commit 37b323c9ac71e2a54f155c722ef64dd41d7429cb Author: 박다현 (Dahyeon Park) Date: Wed Nov 4 20:49:24 2026 +0900 feat: initial make-space full-stack release with weighted multi-provider LLM and Dockerfile diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..aac7a44 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +/target +/.env +/.gemini +.git +node_modules diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..54ede30 --- /dev/null +++ b/.env.example @@ -0,0 +1,27 @@ +# --- Place search --- +KAKAO_REST_API_KEY= +X_NCP_APIGW_API_KEY_ID= +X_NCP_APIGW_API_KEY= + +# --- Storage --- +MONGODB_CONNECTION_STRING=mongodb://localhost:27017 +MONGODB_DB=make_space +MINIO_ENDPOINT=http://localhost:9000 +MINIO_ACCESS_KEY= +MINIO_SECRET_KEY= +MINIO_BUCKET=make-space-photos + +# --- LLM (OpenAI-compatible, weighted multi-provider or single-provider fallback) --- +# JSON array of capacity providers (`PROVIDER`: "strata" | "cpa", `OPENAI_COMPATIBLE_API_ENDPOINT`, `OPENAI_COMPATIBLE_API_KEY`, `MODEL`, `WEIGHT`): +# LLM_PROVIDERS='[{"PROVIDER":"strata","OPENAI_COMPATIBLE_API_ENDPOINT":"http://127.0.0.1:8080","OPENAI_COMPATIBLE_API_KEY":"","MODEL":"qwen3.8-flash-next","WEIGHT":2},{"PROVIDER":"cpa","OPENAI_COMPATIBLE_API_ENDPOINT":"http://126.dahyeon.us:8317","OPENAI_COMPATIBLE_API_KEY":"","MODEL":"gpt-6.1-sol","WEIGHT":1}]' +OPENAI_COMPATIBLE_API_ENDPOINT= +OPENAI_COMPATIBLE_API_KEY= +LLM_MODEL=gpt-6.1-sol + +# --- External browser scraping service (empty = mock) --- +BROWSER_SCRAPER_URL= + +# --- Pipeline tuning --- +MAX_PHOTOS_PER_SOURCE=40 +MAX_PHOTOS_TOTAL=120 +RUST_LOG=info,server=debug,pipeline=debug,providers=debug diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..65586c4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target +.env +*.log +/data diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..d282ea3 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,5005 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "any_spawner" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1384d3fe1eecb464229fcf6eebb72306591c56bf27b373561489458a7c73027d" +dependencies = [ + "futures", + "thiserror 2.0.21", + "tokio", + "wasm-bindgen-futures", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "app" +version = "0.1.0" +dependencies = [ + "domain", + "js-sys", + "leptos", + "leptos_axum", + "leptos_meta", + "leptos_router", + "pipeline", + "providers", + "serde", + "serde_json", + "storage", + "tracing", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "async-compression" +version = "0.4.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459" +dependencies = [ + "compression-codecs", + "compression-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-once-cell" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288f83726785267c6f2ef073a3d83dc3f9b81464e9f99898240cced85fce35a" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "attribute-derive" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f9ef7a68684657ce9da341c934c73b63df7a3585a61e366d84c84ed5d3d167" +dependencies = [ + "attribute-derive-macro", + "manyhow", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "attribute-derive-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300d426e5e73549125bb8e4649bdd5508f82c94ddf898fb0517246e71dfb8e98" +dependencies = [ + "collection_literals", + "interpolator", + "manyhow", + "proc-macro-utils", + "proc-macro2", + "quote", + "quote-use", + "syn 3.0.9", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "multer", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1 0.10.7", + "sync_wrapper", + "tokio", + "tokio-tungstenite", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base16" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27c3610c36aee21ce8ac510e6224498de4228ad772a171ed65643a24693a5a8" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "brotli" +version = "9.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "6.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34c6783f42c21c952ad7112b354f0ba2f10760e9decea5b1b60523d6e270faaf" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bson" +version = "2.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969a9ba84b0ff843813e7249eed1678d9b6607ce5a3b8f0a47af3fcf7978e6e" +dependencies = [ + "ahash", + "base64 0.22.1", + "bitvec", + "getrandom 0.2.17", + "getrandom 0.3.4", + "hex", + "indexmap", + "js-sys", + "once_cell", + "rand 0.9.5", + "serde", + "serde_bytes", + "serde_json", + "time", + "uuid", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "camino" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" + +[[package]] +name = "cc" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "codee" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9dbbdc4b4d349732bc6690de10a9de952bd39ba6a065c586e26600b6b0b91f5" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "collection_literals" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2550f75b8cfac212855f6b1885455df8eaee8fe8e246b647d69146142e016084" + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "compression-codecs" +version = "0.4.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84f840cff84d10085260e460023934d0af699e71212b09b2a41452e8bd9cda43" +dependencies = [ + "brotli", + "compression-core", + "flate2", + "memchr", +] + +[[package]] +name = "compression-core" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" + +[[package]] +name = "config" +version = "0.15.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e9fbc53afcec54441422f1c596cd054655b32e70e1cbac956651b7b175a404" +dependencies = [ + "convert_case 0.6.0", + "pathdiff", + "serde_core", + "toml", + "winnow", +] + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + +[[package]] +name = "const-str" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18f12cc9948ed9604230cdddc7c86e270f9401ccbe3c2e98a4378c5e7632212f" + +[[package]] +name = "const_format" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3decb4d6965448659923544a634a0571ba44cede4e11ef15a5a317126840454" +dependencies = [ + "const_format_proc_macros", + "konst", +] + +[[package]] +name = "const_format_proc_macros" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "941b570269a642506f08cb5b688c04bfa6cfd41a26f8bcdc49db8fd00c0ab659" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "const_str_slice_concat" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f67855af358fcb20fac58f9d714c94e2b228fe5694c1c9b4ead4a366343eda1b" + +[[package]] +name = "convert_case" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "convert_case" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "affbf0190ed2caf063e3def54ff444b449371d55c58e513a95ab98eca50adb49" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "convert_case_extras" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589c70f0faf8aa9d17787557d5eae854d7755cac50f5c3d12c81d3d57661cebb" +dependencies = [ + "convert_case 0.11.0", +] + +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "log", + "publicsuffix", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "cssparser" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e901edd733a1472f944a45116df3f846f54d37e67e68640ac8bb69689aca2aa" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "derive-syn-parse" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d65d7ce8132b7c0e54497a4d9a55a1c2a0912a0d786cf894472ba818fba45762" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive-where" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e2b94854e8576378ccda7c8de8a66ed8b4e8acbd2c50ec3418ea6c8aaf4b567" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "domain" +version = "0.1.0" +dependencies = [ + "serde", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "drain_filter_polyfill" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "669a445ee724c5c69b1b06fe0b63e70a1c84bc9bb7d9696cd4f4e3ec45050408" + +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "ego-tree" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2972feb8dffe7bc8c5463b1dacda1b0dfbed3710e50f977d965429692d74cd8" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "either_of" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5060e0a4cbf26a87550792688ade88e6b8aec9208613631a7a363bda7bc2d4cd" +dependencies = [ + "paste", + "pin-project-lite", +] + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "erased" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1731451909bde27714eacba19c2566362a7f35224f52b153d3f42cf60f72472" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "frontend" +version = "0.1.0" +dependencies = [ + "app", + "console_error_panic_hook", + "leptos", + "wasm-bindgen", +] + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" +dependencies = [ + "mac", + "new_debug_unreachable", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "fxhash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" +dependencies = [ + "byteorder", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getopts" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gloo-net" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06f627b1a58ca3d42b45d6104bf1e1a03799df472df00988b6ba21accc10580" +dependencies = [ + "futures-channel", + "futures-core", + "futures-sink", + "gloo-utils", + "http", + "js-sys", + "pin-project", + "serde", + "serde_json", + "thiserror 1.0.69", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "gloo-utils" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5555354113b18c547c1d3a98fbf7fb32a9ff4f6fa112ce823a21641a0ba3aa" +dependencies = [ + "js-sys", + "serde", + "serde_json", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "guardian" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17e2ac29387b1aa07a1e448f7bb4f35b500787971e965b02842b900afa5c8f6f" + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hickory-net" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d" +dependencies = [ + "async-trait", + "cfg-if", + "data-encoding", + "futures-channel", + "futures-io", + "futures-util", + "hickory-proto", + "idna", + "ipnet", + "jni", + "rand 0.10.3", + "thiserror 2.0.21", + "tinyvec", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "hickory-proto" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d" +dependencies = [ + "data-encoding", + "idna", + "ipnet", + "jni", + "once_cell", + "prefix-trie", + "rand 0.10.3", + "ring", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "url", +] + +[[package]] +name = "hickory-resolver" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981" +dependencies = [ + "cfg-if", + "futures-util", + "hickory-net", + "hickory-proto", + "ipconfig", + "ipnet", + "jni", + "moka", + "ndk-context", + "once_cell", + "parking_lot", + "rand 0.10.3", + "resolv-conf", + "smallvec", + "system-configuration", + "thiserror 2.0.21", + "tokio", + "tracing", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "html-escape" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9356095b4b41197bba32173600e1582792cda618f65d12f68e2e77d273413c5" + +[[package]] +name = "html5ever" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55d958c2f74b664487a2035fe1dadb032c48718a03b63f3ab0b8537db8549ed4" +dependencies = [ + "log", + "markup5ever", + "match_token", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "http-range-header" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hydration_context" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "285b05858fe7d58c5eff059f7b46c228fd86996d996c59eb35fc0340d174f640" +dependencies = [ + "futures", + "js-sys", + "or_poisoned", + "pin-project-lite", + "serde", + "throw_error", + "wasm-bindgen", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-native-certs", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "interpolator" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71dd52191aae121e8611f1e8dc3e324dd0dd1dee1e6dd91d10ee07a3cfb4d9d8" + +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + +[[package]] +name = "ipconfig" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d40460c0ce33d6ce4b0630ad68ff63d6661961c48b6dba35e5a4d81cfb48222" +dependencies = [ + "socket2", + "widestring", + "windows-registry", + "windows-result", + "windows-sys 0.61.2", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +dependencies = [ + "serde", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "konst" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" +dependencies = [ + "konst_macro_rules", +] + +[[package]] +name = "konst_macro_rules" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "leptos" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b0f9f061ff585050a77e18b93a58d6c881c6785f473fc98924c4f77da50d891" +dependencies = [ + "any_spawner", + "base64 0.22.1", + "cfg-if", + "either_of", + "futures", + "getrandom 0.4.3", + "hydration_context", + "leptos_config", + "leptos_dom", + "leptos_hot_reload", + "leptos_macro", + "leptos_server", + "oco_ref", + "or_poisoned", + "paste", + "rand 0.9.5", + "reactive_graph", + "rustc-hash", + "rustc_version", + "send_wrapper", + "serde", + "serde_json", + "serde_qs", + "server_fn", + "slotmap", + "tachys", + "thiserror 2.0.21", + "throw_error", + "typed-builder 0.23.2", + "typed-builder-macro 0.23.2", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm_split_helpers", + "web-sys", +] + +[[package]] +name = "leptos_axum" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513e2dd5fe81512b53304429b9ca77cceb954d23af88921c0c33119380f07cbe" +dependencies = [ + "any_spawner", + "axum", + "futures", + "hydration_context", + "leptos", + "leptos_integration_utils", + "leptos_macro", + "leptos_meta", + "leptos_router", + "or_poisoned", + "server_fn", + "tachys", + "tokio", + "tower", + "tower-http", +] + +[[package]] +name = "leptos_config" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c06f751315bccc0d193fab302ac01d25bcfcd97474d4676440e7e3250dc3fc3" +dependencies = [ + "config", + "regex", + "serde", + "thiserror 2.0.21", + "typed-builder 0.23.2", +] + +[[package]] +name = "leptos_dom" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35742e9ed8f8aaf9e549b454c68a7ac0992536e06856365639b111f72ab07884" +dependencies = [ + "js-sys", + "or_poisoned", + "reactive_graph", + "send_wrapper", + "tachys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "leptos_hot_reload" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d84989bd3d604e66adbfe13a32bec2ea47bdcb6c9fcd643f784facbb32f6ef10" +dependencies = [ + "anyhow", + "camino", + "indexmap", + "or_poisoned", + "proc-macro2", + "quote", + "rstml", + "serde", + "syn 3.0.9", + "walkdir", +] + +[[package]] +name = "leptos_integration_utils" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd93f4fd62ee9845cc50b0925272bccce6fd18e8168c4ad8a4f50eef9a93f747" +dependencies = [ + "futures", + "hydration_context", + "leptos", + "leptos_config", + "leptos_meta", + "leptos_router", + "reactive_graph", +] + +[[package]] +name = "leptos_macro" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0066e6f8003dbedea0900a2d7ad11734ab1a541330718866dd4b9a394a032127" +dependencies = [ + "attribute-derive", + "cfg-if", + "convert_case 0.11.0", + "convert_case_extras", + "html-escape", + "itertools", + "leptos_hot_reload", + "prettyplease", + "proc-macro2", + "quote", + "rstml", + "rustc_version", + "server_fn_macro", + "syn 3.0.9", + "uuid", +] + +[[package]] +name = "leptos_meta" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "987b1a07addba2647da43c0689408cccc0f428236b714ea606127b9e347d35d8" +dependencies = [ + "futures", + "indexmap", + "leptos", + "or_poisoned", + "send_wrapper", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "leptos_router" +version = "0.8.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f92787ebcb5f25af6a67513dacfd75cbffce5bda3f361e2e947c3fc4e3adc14b" +dependencies = [ + "any_spawner", + "either_of", + "futures", + "gloo-net", + "js-sys", + "leptos", + "leptos_router_macro", + "or_poisoned", + "percent-encoding", + "reactive_graph", + "rustc_version", + "send_wrapper", + "tachys", + "thiserror 2.0.21", + "url", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "leptos_router_macro" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bb5c81012dcab0d5cc032a2da0a364a18ce74a0fbeb88f091e9b53a0679bc85" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "leptos_server" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202b2d1261c22d886f307934760a6bb566444f68f39b24f6f10defdc23633049" +dependencies = [ + "any_spawner", + "base64 0.22.1", + "codee", + "futures", + "hydration_context", + "or_poisoned", + "reactive_graph", + "send_wrapper", + "serde", + "serde_json", + "server_fn", + "tachys", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "llm" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64 0.22.1", + "reqwest", + "serde", + "serde_json", + "tokio", + "tracing", +] + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "mac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" + +[[package]] +name = "macro_magic" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc33f9f0351468d26fbc53d9ce00a096c8522ecb42f19b50f34f2c422f76d21d" +dependencies = [ + "macro_magic_core", + "macro_magic_macros", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "macro_magic_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1687dc887e42f352865a393acae7cf79d98fab6351cde1f58e9e057da89bf150" +dependencies = [ + "const-random", + "derive-syn-parse", + "macro_magic_core_macros", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "macro_magic_core_macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b02abfe41815b5bd98dbd4260173db2c116dda171dc0fe7838cb206333b83308" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "macro_magic_macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ea28ee64b88876bf45277ed9a5817c1817df061a74f2b988971a12570e5869" +dependencies = [ + "macro_magic_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "manyhow" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1704b073316272a6785b70599f91f73b49022c2e290b065591ee6b9109ed8c7" +dependencies = [ + "manyhow-macros", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "manyhow-macros" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31601db71f1f5fb6f831a18aa3052d13a62528ee4f2cba7e8c9a5e258d953725" +dependencies = [ + "proc-macro-utils", + "proc-macro2", + "quote", +] + +[[package]] +name = "markup5ever" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "311fe69c934650f8f19652b3946075f0fc41ad8757dbb68f1ca14e7900ecc1c3" +dependencies = [ + "log", + "tendril", + "web_atoms", +] + +[[package]] +name = "match_token" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac84fd3f360fcc43dc5f5d186f02a94192761a080e8bc58621ad4d12296a58cf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest 0.10.7", +] + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moka" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" +dependencies = [ + "crossbeam-channel", + "crossbeam-epoch", + "crossbeam-utils", + "equivalent", + "parking_lot", + "portable-atomic", + "smallvec", + "tagptr", + "uuid", +] + +[[package]] +name = "mongocrypt" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8426a875ded61430d4a811dbfda7633b6b8af0225c547fc6c28b8b0aa7d79a13" +dependencies = [ + "bson", + "mongocrypt-sys", + "once_cell", + "serde", +] + +[[package]] +name = "mongocrypt-sys" +version = "0.1.6+1.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "851fac73f7fe22f6a3ab87f720ce509cae7c9fd08e7dd27866cc232dee07ccf4" + +[[package]] +name = "mongodb" +version = "3.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6466d4601ff396952e1895d88083d1ab03930b812277180eb8258bbe1a10bb0f" +dependencies = [ + "base64 0.22.1", + "bitflags", + "bson", + "derive-where", + "futures-core", + "futures-io", + "futures-util", + "hex", + "hickory-net", + "hickory-proto", + "hickory-resolver", + "hmac", + "macro_magic", + "md-5 0.11.0", + "mongocrypt", + "mongodb-internal-macros", + "pbkdf2", + "percent-encoding", + "rand 0.9.5", + "rustc_version_runtime", + "rustls", + "serde", + "serde_bytes", + "serde_with", + "sha1 0.11.0", + "sha2 0.11.1", + "socket2", + "stringprep", + "strsim", + "take_mut", + "thiserror 2.0.21", + "tokio", + "tokio-rustls", + "tokio-util", + "typed-builder 0.22.0", + "uuid", + "webpki-roots", +] + +[[package]] +name = "mongodb-internal-macros" +version = "3.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "995f1171fab2a793f15afd0e9ba1d84116a9411ff8e3467fe9c167462435033d" +dependencies = [ + "macro_magic", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "next_tuple" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60993920e071b0c9b66f14e2b32740a4e27ffc82854dcd72035887f336a09a28" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "object_store" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbfbfff40aeccab00ec8a910b57ca8ecf4319b335c542f2edcd19dd25a1e2a00" +dependencies = [ + "async-trait", + "base64 0.22.1", + "bytes", + "chrono", + "form_urlencoded", + "futures", + "http", + "http-body-util", + "humantime", + "hyper", + "itertools", + "md-5 0.10.6", + "parking_lot", + "percent-encoding", + "quick-xml", + "rand 0.9.5", + "reqwest", + "ring", + "serde", + "serde_json", + "serde_urlencoded", + "thiserror 2.0.21", + "tokio", + "tracing", + "url", + "walkdir", + "wasm-bindgen-futures", + "web-time", +] + +[[package]] +name = "oco_ref" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed0423ff9973dea4d6bd075934fdda86ebb8c05bdf9d6b0507067d4a1226371d" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +dependencies = [ + "critical-section", + "portable-atomic", +] + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "or_poisoned" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c04f5d74368e4d0dfe06c45c8627c81bd7c317d52762d118fb9b3076f6420fd" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pathdiff" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" + +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand 0.8.8", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pipeline" +version = "0.1.0" +dependencies = [ + "anyhow", + "bytes", + "chrono", + "dashmap", + "domain", + "futures", + "image", + "llm", + "providers", + "reqwest", + "serde", + "serde_json", + "storage", + "tokio", + "tracing", + "uuid", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "prefix-trie" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cf6e3177f0684016a5c209b00882e15f8bdd3f3bb48f0491df10cd102d0c6e7" +dependencies = [ + "either", + "ipnet", + "num-traits", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.9", +] + +[[package]] +name = "proc-macro-utils" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeaf08a13de400bc215877b5bdc088f241b12eb42f0a548d3390dc1c56bb7071" +dependencies = [ + "proc-macro2", + "quote", + "smallvec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df921e1ef974ebc8dd9effdb0c037a96928ae8cbf871438e02d6fd67204b595e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "version_check", +] + +[[package]] +name = "providers" +version = "0.1.0" +dependencies = [ + "anyhow", + "async-trait", + "domain", + "futures", + "regex", + "reqwest", + "scraper", + "serde", + "serde_json", + "tokio", + "tracing", + "url", + "urlencoding", +] + +[[package]] +name = "psl-types" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" + +[[package]] +name = "publicsuffix" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf" +dependencies = [ + "idna", + "psl-types", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "quote-use" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48356e493823dc3c1d7e9fc7b3ff204ecec48afbdd718fc4134091b88eb63f3d" +dependencies = [ + "quote", + "quote-use-macros", +] + +[[package]] +name = "quote-use-macros" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cf1c5de6a7cc231c71e03c77aa4c7019097859ea7029156b54d2894a8430704" +dependencies = [ + "proc-macro-utils", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "reactive_graph" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bcec36a2d1b9a53a4129b3270b19e3df6f6b88c2e7c97ed9404dc9307f137d7" +dependencies = [ + "any_spawner", + "async-lock", + "futures", + "guardian", + "hydration_context", + "indexmap", + "or_poisoned", + "paste", + "pin-project-lite", + "rustc-hash", + "rustc_version", + "send_wrapper", + "serde", + "slotmap", + "thiserror 2.0.21", + "web-sys", +] + +[[package]] +name = "reactive_stores" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a29e469b556f25486678e9f5f65fa21a0351d98affde9a7eea9fee286bf8ebd6" +dependencies = [ + "guardian", + "indexmap", + "itertools", + "or_poisoned", + "paste", + "reactive_graph", + "reactive_stores_macro", + "rustc-hash", + "send_wrapper", +] + +[[package]] +name = "reactive_stores_macro" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d11f1b82859d94577892b8037c35f8a4f066cbb3864583e22e68def0af49a88" +dependencies = [ + "convert_case 0.11.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "cookie", + "cookie_store", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams 0.4.2", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "resolv-conf" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rstml" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6bd1bfba3c4c0b57aae906204d9e5744f3f65800ce6c75bd4cc162f2c26f3aa" +dependencies = [ + "derive-where", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 3.0.9", + "thiserror 2.0.21", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustc_version_runtime" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dd18cd2bae1820af0b6ad5e54f4a51d0f3fcc53b05f845675074efcc7af071d" +dependencies = [ + "rustc_version", + "semver", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scraper" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5f3a24d916e78954af99281a455168d4a9515d65eca99a18da1b813689c4ad9" +dependencies = [ + "cssparser", + "ego-tree", + "getopts", + "html5ever", + "precomputed-hash", + "selectors", + "tendril", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "selectors" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5685b6ae43bfcf7d2e7dfcfb5d8e8f61b46442c902531e41a32a9a8bf0ee0fb6" +dependencies = [ + "bitflags", + "cssparser", + "derive_more", + "fxhash", + "log", + "new_debug_unreachable", + "phf", + "phf_codegen", + "precomputed-hash", + "servo_arc", + "smallvec", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" +dependencies = [ + "futures-core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_qs" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3faaf9e727533a19351a43cc5a8de957372163c7d35cc48c90b75cdda13c352" +dependencies = [ + "percent-encoding", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" +dependencies = [ + "serde_core", + "serde_with_macros", +] + +[[package]] +name = "serde_with_macros" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "server" +version = "0.1.0" +dependencies = [ + "anyhow", + "app", + "axum", + "domain", + "dotenvy", + "futures", + "leptos", + "leptos_axum", + "llm", + "pipeline", + "providers", + "serde_json", + "storage", + "tokio", + "tokio-stream", + "tower-http", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "server_fn" +version = "0.8.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be8559dd05af1b5b7e363a150616589d5a88af5187273f7f331ba0dae8922812" +dependencies = [ + "axum", + "base64 0.22.1", + "bytes", + "const-str", + "const_format", + "futures", + "gloo-net", + "http", + "http-body-util", + "hyper", + "inventory", + "js-sys", + "or_poisoned", + "pin-project-lite", + "rustc_version", + "rustversion", + "send_wrapper", + "serde", + "serde_json", + "serde_qs", + "server_fn_macro_default", + "thiserror 2.0.21", + "throw_error", + "tokio", + "tower", + "tower-layer", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams 0.5.0", + "web-sys", + "xxhash-rust", +] + +[[package]] +name = "server_fn_macro" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce79d7b6ab93f7994e5ff4999eb962f2aea370d7c3b91986eb75da738a8e65f9" +dependencies = [ + "const_format", + "convert_case 0.11.0", + "proc-macro2", + "quote", + "rustc_version", + "syn 3.0.9", + "xxhash-rust", +] + +[[package]] +name = "server_fn_macro_default" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9a4f81a0d855f279c3448243138a55cbfdd9851da9341b9c1e5971b90089e61" +dependencies = [ + "server_fn_macro", + "syn 3.0.9", +] + +[[package]] +name = "servo_arc" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "storage" +version = "0.1.0" +dependencies = [ + "anyhow", + "bytes", + "chrono", + "domain", + "futures", + "mongodb", + "object_store", + "serde", + "tokio", + "tracing", +] + +[[package]] +name = "string_cache" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared", + "precomputed-hash", + "serde", +] + +[[package]] +name = "string_cache_codegen" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", +] + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tachys" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e47e2220bb9d2a3be976a22a0fb7685a0b84499bb11ea5cb3bbc82907675ac68" +dependencies = [ + "any_spawner", + "async-trait", + "const_str_slice_concat", + "drain_filter_polyfill", + "either_of", + "erased", + "futures", + "html-escape", + "indexmap", + "itertools", + "js-sys", + "next_tuple", + "oco_ref", + "or_poisoned", + "paste", + "reactive_graph", + "reactive_stores", + "rustc-hash", + "rustc_version", + "send_wrapper", + "slotmap", + "throw_error", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "tagptr" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" + +[[package]] +name = "take_mut" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60" + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tendril" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" +dependencies = [ + "futf", + "mac", + "utf-8", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "throw_error" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0ed6038fcbc0795aca7c92963ddda636573b956679204e044492d2b13c8f64" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-io", + "futures-sink", + "futures-util", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5ffcdf8f50436dbbfd675c1fe1b8e0854f42b7defea8584bdebe1aee900e561" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "async-compression", + "bitflags", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "http-range-header", + "httpdate", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "tokio", + "tokio-util", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1 0.10.7", + "thiserror 2.0.21", +] + +[[package]] +name = "typed-builder" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "398a3a3c918c96de527dc11e6e846cd549d4508030b8a33e1da12789c856b81a" +dependencies = [ + "typed-builder-macro 0.22.0", +] + +[[package]] +name = "typed-builder" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31aa81521b70f94402501d848ccc0ecaa8f93c8eb6999eb9747e72287757ffda" +dependencies = [ + "typed-builder-macro 0.23.2", +] + +[[package]] +name = "typed-builder-macro" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e48cea23f68d1f78eb7bc092881b6bb88d3d6b5b7e6234f6f9c911da1ffb221" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "typed-builder-macro" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "076a02dc54dd46795c2e9c8282ed40bcfb1e22747e955de9389a1de28190fb26" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasm_split_helpers" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab578aae2fe2916edaea06843187d50f87b0965622da0ceef648edca27b385ba" +dependencies = [ + "async-once-cell", + "wasm_split_macros", +] + +[[package]] +name = "wasm_split_macros" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e653af7ee4a9ef0fce481a9ec6f43cb78de20d0cdb4f4f5862e1dc6e407e6c8" +dependencies = [ + "base16", + "quote", + "sha2 0.10.9", + "syn 2.0.119", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web_atoms" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57ffde1dc01240bdf9992e3205668b235e59421fd085e8a317ed98da0178d414" +dependencies = [ + "phf", + "phf_codegen", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "xxhash-rust" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..de7ca36 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,94 @@ +[workspace] +resolver = "2" +members = [ + "app", + "frontend", + "server", + "crates/domain", + "crates/llm", + "crates/providers", + "crates/storage", + "crates/pipeline", +] + +[workspace.package] +edition = "2021" +version = "0.1.0" + +[workspace.dependencies] +# web +leptos = "0.8" +leptos_meta = "0.8" +leptos_router = "0.8" +leptos_axum = "0.8" +axum = "0.8" +tower-http = { version = "0.6", features = ["fs"] } +wasm-bindgen = "0.2" +web-sys = "0.3" +js-sys = "0.3" +console_error_panic_hook = "0.1" + +# async / runtime +tokio = { version = "1", features = ["full"] } +tokio-stream = { version = "0.1", features = ["sync"] } +futures = "0.3" +async-trait = "0.1" + +# data +serde = { version = "1", features = ["derive"] } +serde_json = "1" +chrono = { version = "0.4", features = ["serde"] } +uuid = { version = "1", features = ["v4"] } + +# infra +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "gzip", "brotli", "deflate", "cookies"] } +scraper = "0.24" +regex = "1" +url = "2" +urlencoding = "2" +mongodb = "3" +object_store = { version = "0.12", features = ["aws"] } +image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif"] } +base64 = "0.22" +bytes = "1" +dashmap = "6" + +# errors / logging / config +anyhow = "1" +thiserror = "2" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +dotenvy = "0.15" + +# internal +domain = { path = "crates/domain" } +llm = { path = "crates/llm" } +providers = { path = "crates/providers" } +storage = { path = "crates/storage" } +pipeline = { path = "crates/pipeline" } +app = { path = "app", default-features = false } + +[profile.wasm-release] +inherits = "release" +opt-level = "z" +lto = true +codegen-units = 1 +panic = "abort" + +[[workspace.metadata.leptos]] +name = "make-space" +bin-package = "server" +bin-target = "server" +lib-package = "frontend" +site-root = "target/site" +site-pkg-dir = "pkg" +style-file = "style/main.css" +assets-dir = "public" +site-addr = "127.0.0.1:3000" +reload-port = 3001 +browserquery = "defaults" +bin-features = [] +bin-default-features = false +lib-features = [] +lib-default-features = false +lib-profile-release = "wasm-release" diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a9be95b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,43 @@ +FROM rust:1.99.1-trixie AS rust-build +WORKDIR /src + +# Install wasm32 target and pinned wasm-bindgen-cli matching Cargo.lock (0.2.130) +RUN rustup target add wasm32-unknown-unknown \ + && cargo install wasm-bindgen-cli --version 0.2.130 --locked + +COPY Cargo.toml Cargo.lock ./ +COPY app ./app +COPY frontend ./frontend +COPY server ./server +COPY crates ./crates +COPY style ./style +COPY public ./public + +# 1. Build Axum SSR server binary +RUN cargo build --release --locked --bin server + +# 2. Build Leptos WASM hydrate bundle and assemble /src/target/site +RUN cargo build --profile wasm-release --locked --target wasm32-unknown-unknown -p frontend \ + && mkdir -p /src/target/site/pkg \ + && wasm-bindgen /src/target/wasm32-unknown-unknown/wasm-release/frontend.wasm \ + --out-dir /src/target/site/pkg \ + --out-name make-space \ + --target web \ + && cp /src/target/site/pkg/make-space_bg.wasm /src/target/site/pkg/make-space.wasm \ + && cp /src/style/main.css /src/target/site/pkg/make-space.css \ + && cp -r /src/public/. /src/target/site/ + +FROM gcr.io/distroless/cc-debian13:nonroot AS runtime +ENV APP_ENV=production \ + HOST=0.0.0.0 \ + PORT=3000 \ + LEPTOS_OUTPUT_NAME=make-space \ + LEPTOS_SITE_ADDR=0.0.0.0:3000 \ + LEPTOS_SITE_ROOT=/app/site \ + LEPTOS_SITE_PKG_DIR=pkg +WORKDIR /app +COPY --from=rust-build --chown=65532:65532 /src/target/release/server /app/make-space +COPY --from=rust-build --chown=65532:65532 /src/target/site /app/site +USER 65532:65532 +EXPOSE 3000 +ENTRYPOINT ["/app/make-space"] diff --git a/app/Cargo.toml b/app/Cargo.toml new file mode 100644 index 0000000..3ffa58d --- /dev/null +++ b/app/Cargo.toml @@ -0,0 +1,41 @@ +[package] +name = "app" +edition.workspace = true +version.workspace = true + +[lib] +crate-type = ["rlib"] + +[dependencies] +domain = { workspace = true } +leptos = { workspace = true } +leptos_meta = { workspace = true } +leptos_router = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } + +# hydrate-only +wasm-bindgen = { workspace = true, optional = true } +js-sys = { workspace = true, optional = true } +web-sys = { workspace = true, optional = true, features = ["EventSource", "MessageEvent", "HtmlCanvasElement", "Event"] } + +# ssr-only +leptos_axum = { workspace = true, optional = true } +pipeline = { workspace = true, optional = true } +storage = { workspace = true, optional = true } +providers = { workspace = true, optional = true } +tracing = { workspace = true, optional = true } + +[features] +default = [] +hydrate = ["leptos/hydrate", "dep:wasm-bindgen", "dep:js-sys", "dep:web-sys"] +ssr = [ + "leptos/ssr", + "leptos_meta/ssr", + "leptos_router/ssr", + "dep:leptos_axum", + "dep:pipeline", + "dep:storage", + "dep:providers", + "dep:tracing", +] diff --git a/app/js/scene.js b/app/js/scene.js new file mode 100644 index 0000000..c247e4d --- /dev/null +++ b/app/js/scene.js @@ -0,0 +1,787 @@ +import * as THREE from "three"; +import { OrbitControls } from "three/addons/controls/OrbitControls.js"; + +const FLOOR_HEIGHT = 3.6; +const WALL_HEIGHT = 2.6; +const WALL_THICK = 0.16; + +// sRGB equivalents of the Aurora light canvas and blue action palette. +const SCENE_COLORS = { + background: 0xeff0f2, + gridMajor: 0xd6d9df, + gridMinor: 0xe3e5e9, + accent: 0x235cc7, +}; + +const ZONE_COLORS = { + seating: 0xe8dfd1, + counter: 0xd4a373, + bar: 0xc89f81, + kitchen: 0xb7b7a4, + restroom: 0xa8dadc, + terrace: 0xccd5ae, + entrance: 0xf4e285, + other: 0xdedbd2, +}; + +const scenes = new Map(); +let nextId = 1; + +function floorIndex(floors, level) { + const sorted = [...floors].sort((a, b) => a.level - b.level); + const idx = sorted.findIndex((f) => f.level === level); + return idx >= 0 ? idx : 0; +} + +function createScene(canvas, layoutJson, onZoneSelect, cleanup) { + const layout = JSON.parse(layoutJson); + if (!layout || !Array.isArray(layout.floors)) throw new Error("Invalid floor layout"); + const coarsePointer = window.matchMedia("(pointer: coarse)"); + const originalTouchAction = canvas.style.touchAction; + const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false }); + cleanup.push(() => renderer.dispose()); + renderer.shadowMap.enabled = true; + renderer.shadowMap.type = THREE.PCFSoftShadowMap; + renderer.setClearColor(SCENE_COLORS.background, 1); + + const scene = new THREE.Scene(); + cleanup.push(() => disposeSceneObjects(scene)); + scene.fog = new THREE.FogExp2(SCENE_COLORS.background, 0.015); + + const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200); + const controls = new OrbitControls(camera, canvas); + cleanup.push(() => { controls.dispose(); canvas.style.touchAction = originalTouchAction; }); + const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)"); + controls.enableDamping = !reducedMotion.matches; + controls.dampingFactor = 0.08; + controls.maxPolarAngle = Math.PI * 0.48; + + const hemi = new THREE.HemisphereLight(0xffffff, 0xaab0ba, 1.05); + scene.add(hemi); + + const dir = new THREE.DirectionalLight(0xffffff, 1.25); + dir.position.set(16, 28, 18); + dir.castShadow = true; + dir.shadow.mapSize.set(2048, 2048); + dir.shadow.camera.near = 1; + dir.shadow.camera.far = 90; + const d = 24; + dir.shadow.camera.left = -d; + dir.shadow.camera.right = d; + dir.shadow.camera.top = d; + dir.shadow.camera.bottom = -d; + scene.add(dir); + + const groundGrid = new THREE.GridHelper(60, 60, SCENE_COLORS.gridMajor, SCENE_COLORS.gridMinor); + groundGrid.position.y = -0.08; + scene.add(groundGrid); + + const floorGroups = new Map(); + const pinMeshes = []; + const floors = layout.floors || []; + + floors.forEach((floor) => { + const idx = floorIndex(floors, floor.level); + const yBase = idx * FLOOR_HEIGHT; + const group = buildFloorGroup(floor, yBase, pinMeshes); + scene.add(group); + floorGroups.set(floor.level, { group, yBase, floor }); + }); + + const maxW = Math.max(10, ...floors.map((f) => f.width_m || 10)); + const maxD = Math.max(10, ...floors.map((f) => f.depth_m || 10)); + const span = Math.max(maxW, maxD); + camera.position.set(span * 1.15, span * 1.05, span * 1.25); + controls.target.set(0, (floors.length - 1) * FLOOR_HEIGHT * 0.35, 0); + controls.update(); + + let hasSize = false; + let visible = true; + let contextLost = false; + let disposed = false; + let raf = 0; + let st; + const requestFrame = () => { + if (!disposed && !contextLost && !document.hidden && visible && hasSize && !raf) { + raf = requestAnimationFrame(animate); + } + }; + let pixelRatio = 0; + const resize = () => { + const rect = canvas.getBoundingClientRect(); + const w = rect.width; + const h = rect.height; + hasSize = w > 0 && h > 0; + if (!hasSize) return; + const nextPixelRatio = Math.min(window.devicePixelRatio || 1, coarsePointer.matches ? 1.5 : 2); + if (nextPixelRatio !== pixelRatio) { + renderer.setPixelRatio(nextPixelRatio); + pixelRatio = nextPixelRatio; + } + renderer.setSize(w, h, false); + camera.aspect = w / h; + // Leave room around the model on portrait and near-square phone viewports. + camera.fov = (2 * Math.atan(Math.tan((42 * Math.PI) / 360) / Math.min(1, camera.aspect / 1.15)) * 180) / Math.PI; + camera.updateProjectionMatrix(); + requestFrame(); + }; + resize(); + const ro = new ResizeObserver(resize); + cleanup.push(() => ro.disconnect()); + ro.observe(canvas); + window.addEventListener("resize", resize); + cleanup.push(() => window.removeEventListener("resize", resize)); + + const raycaster = new THREE.Raycaster(); + const pointer = new THREE.Vector2(); + const activePointers = new Set(); + let downPos = null; + + const syncInteraction = () => { + downPos = null; + controls.enabled = !coarsePointer.matches || canvas.dataset.interactive === "true"; + // OrbitControls sets this to "none" in its constructor, so apply the page-scroll mode afterward. + canvas.style.touchAction = controls.enabled ? "none" : "pan-y"; + }; + syncInteraction(); + const interactionObserver = new MutationObserver(syncInteraction); + cleanup.push(() => interactionObserver.disconnect()); + interactionObserver.observe(canvas, { attributes: true, attributeFilter: ["data-interactive"] }); + const onPointerModeChange = () => { + syncInteraction(); + resize(); + }; + coarsePointer.addEventListener("change", onPointerModeChange); + cleanup.push(() => coarsePointer.removeEventListener("change", onPointerModeChange)); + + const onActivePointerDown = (e) => { + activePointers.add(e.pointerId); + if (activePointers.size > 1) downPos = null; + }; + const onPointerDown = (e) => { + activePointers.add(e.pointerId); + // Pins remain tappable in page-scroll mode; only orbit gestures require opt-in. + if (activePointers.size !== 1 || e.isPrimary === false || e.button !== 0) { + downPos = null; + return; + } + downPos = { pointerId: e.pointerId, x: e.clientX, y: e.clientY, at: performance.now() }; + }; + const onPointerMove = (e) => { + if (downPos?.pointerId === e.pointerId && Math.hypot(e.clientX - downPos.x, e.clientY - downPos.y) > 6) { + downPos = null; + } + }; + const onPointerUp = (e) => { + const wasOnlyPointer = activePointers.size === 1 && activePointers.has(e.pointerId); + activePointers.delete(e.pointerId); + const tap = downPos; + downPos = null; + if (!wasOnlyPointer || tap?.pointerId !== e.pointerId || performance.now() - tap.at > 800) return; + if (Math.hypot(e.clientX - tap.x, e.clientY - tap.y) > 6) return; + const rect = canvas.getBoundingClientRect(); + if (rect.width <= 0 || rect.height <= 0) return; + if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return; + pointer.x = ((e.clientX - rect.left) / rect.width) * 2 - 1; + pointer.y = -((e.clientY - rect.top) / rect.height) * 2 + 1; + raycaster.setFromCamera(pointer, camera); + const selectablePins = pinMeshes.filter((pin) => { + if (st.activeLevel !== 0 && pin.userData.floorLevel !== st.activeLevel) return false; + for (let parent = pin; parent; parent = parent.parent) { + if (!parent.visible) return false; + } + return true; + }); + const hits = raycaster.intersectObjects(selectablePins, true); + let obj = hits[0]?.object; + // The decorative pin is small; use a 44px minimum tap target around its visible center. + if (!obj) { + let distance = 22; + const projected = new THREE.Vector3(); + for (const pin of selectablePins) { + pin.getWorldPosition(projected); + projected.project(camera); + if (projected.z < -1 || projected.z > 1) continue; + const x = rect.left + (projected.x + 1) * rect.width / 2; + const y = rect.top + (1 - projected.y) * rect.height / 2; + const candidateDistance = Math.hypot(e.clientX - x, e.clientY - y); + if (candidateDistance < distance) { + distance = candidateDistance; + obj = pin; + } + } + } + if (obj) { + while (obj && !obj.userData?.photoIds) { + obj = obj.parent; + } + if (obj && obj.userData?.photoIds && typeof onZoneSelect === "function") { + highlightZone(st.id, obj.userData.zoneLabel, JSON.stringify(obj.userData.photoIds)); + onZoneSelect(obj.userData.zoneLabel || "구역", JSON.stringify(obj.userData.photoIds)); + } + } + }; + const onPointerCancel = (e) => { + activePointers.delete(e.pointerId); + downPos = null; + }; + canvas.addEventListener("pointerdown", onPointerDown); + window.addEventListener("pointerdown", onActivePointerDown, true); + window.addEventListener("pointermove", onPointerMove, true); + canvas.addEventListener("lostpointercapture", onPointerCancel); + // Capture release/cancel even when a scrolling or dragged pointer leaves the canvas. + window.addEventListener("pointerup", onPointerUp, true); + window.addEventListener("pointercancel", onPointerCancel, true); + cleanup.push(() => { + canvas.removeEventListener("pointerdown", onPointerDown); + window.removeEventListener("pointerdown", onActivePointerDown, true); + window.removeEventListener("pointermove", onPointerMove, true); + canvas.removeEventListener("lostpointercapture", onPointerCancel); + window.removeEventListener("pointerup", onPointerUp, true); + window.removeEventListener("pointercancel", onPointerCancel, true); + }); + + function animate() { + raf = 0; + if (disposed || contextLost || document.hidden || !visible || !hasSize) return; + const t = performance.now() / 1000; + pinMeshes.forEach((pin, i) => { + pin.position.y = pin.userData.baseY + (reducedMotion.matches ? 0 : Math.sin(t * 2.6 + i) * 0.08); + pin.rotation.y = reducedMotion.matches ? 0 : t * 1.1 + i; + }); + controls.update(); + renderer.render(scene, camera); + if (!reducedMotion.matches) requestFrame(); + } + const stopFrame = () => { + cancelAnimationFrame(raf); + raf = 0; + }; + const onVisibilityChange = () => document.hidden ? stopFrame() : requestFrame(); + document.addEventListener("visibilitychange", onVisibilityChange); + cleanup.push(() => { disposed = true; stopFrame(); document.removeEventListener("visibilitychange", onVisibilityChange); }); + const intersectionObserver = new IntersectionObserver(([entry]) => { + visible = entry.isIntersecting; + visible ? requestFrame() : stopFrame(); + }); + intersectionObserver.observe(canvas); + cleanup.push(() => intersectionObserver.disconnect()); + const onMotionChange = () => { + controls.enableDamping = !reducedMotion.matches; + requestFrame(); + }; + reducedMotion.addEventListener("change", onMotionChange); + controls.addEventListener("change", requestFrame); + cleanup.push(() => { reducedMotion.removeEventListener("change", onMotionChange); controls.removeEventListener("change", requestFrame); }); + const onContextLost = (event) => { + event.preventDefault(); + contextLost = true; + stopFrame(); + reportSceneState(canvas, "공간 화면이 중단됐습니다. 잠시 후 다시 시도해 주세요."); + }; + const onContextRestored = () => { + contextLost = false; + resize(); + requestFrame(); + reportSceneState(canvas, null); + }; + canvas.addEventListener("webglcontextlost", onContextLost); + canvas.addEventListener("webglcontextrestored", onContextRestored); + cleanup.push(() => { canvas.removeEventListener("webglcontextlost", onContextLost); canvas.removeEventListener("webglcontextrestored", onContextRestored); }); + + const id = nextId++; + st = { + id, + renderer, + scene, + camera, + controls, + floorGroups, + pinMeshes, + ro, + interactionObserver, + coarsePointer, + onPointerModeChange, + resize, + requestFrame, + reducedMotion, + onMotionChange, + intersectionObserver, + onVisibilityChange, + onContextLost, + onContextRestored, + stopAnimation: () => { + disposed = true; + stopFrame(); + }, + canvas, + originalTouchAction, + onPointerDown, + onActivePointerDown, + onPointerMove, + onPointerUp, + onPointerCancel, + span, + activeLevel: 0, + viewMode: "3d", + }; + scenes.set(id, st); + resetScene(id); + reportSceneState(canvas, null); + requestFrame(); + return id; +} + +function reportSceneState(canvas, message) { + canvas.dataset.sceneError = message || ""; + canvas.dispatchEvent(new Event(message ? "scene-error" : "scene-ready", { bubbles: true })); +} + +export function mountScene(canvas, layoutJson, onZoneSelect) { + const cleanup = []; + try { + return createScene(canvas, layoutJson, onZoneSelect, cleanup); + } catch (error) { + cleanup.reverse().forEach((dispose) => { try { dispose(); } catch { /* Finish the remaining cleanup. */ } }); + console.warn("Space viewer could not start", error?.message); + reportSceneState(canvas, "공간 화면을 열 수 없습니다. 아래 정보와 사진을 확인하거나 다시 시도해 주세요."); + return 0; + } +} + +export function setFloor(handle, level) { + const st = scenes.get(handle); + if (!st) return; + if (level !== 0 && !st.floorGroups.has(level)) return; + const previousY = floorTarget(st); + st.activeLevel = level; + const offsetY = floorTarget(st) - previousY; + st.camera.position.y += offsetY; + st.controls.target.y += offsetY; + st.floorGroups.forEach(({ group, yBase }, fLevel) => { + if (level === 0) { + group.visible = true; + setGroupOpacity(group, 1.0); + } else if (fLevel === level) { + group.visible = true; + setGroupOpacity(group, 1.0); + } else if (fLevel < level) { + group.visible = st.viewMode !== "plan"; + setGroupOpacity(group, 0.18); + } else { + group.visible = false; + } + }); + st.controls.update(); + st.requestFrame(); +} + +function floorTarget(st) { + return st.floorGroups.get(st.activeLevel)?.yBase ?? Math.max(0, st.floorGroups.size - 1) * FLOOR_HEIGHT * 0.35; +} + +export function setViewMode(handle, mode) { + const st = scenes.get(handle); + if (!st) return; + st.viewMode = mode === "plan" ? "plan" : "3d"; + const plan = st.viewMode === "plan"; + st.controls.enableRotate = !plan; + st.controls.minPolarAngle = 0; + st.controls.maxPolarAngle = plan ? 0 : Math.PI * 0.48; + st.controls.screenSpacePanning = true; + st.controls.mouseButtons.LEFT = plan ? THREE.MOUSE.PAN : THREE.MOUSE.ROTATE; + st.controls.touches.ONE = plan ? THREE.TOUCH.PAN : THREE.TOUCH.ROTATE; + st.controls.touches.TWO = THREE.TOUCH.DOLLY_PAN; + setFloor(handle, st.activeLevel); + resetScene(handle); +} + +export function resetScene(handle) { + const st = scenes.get(handle); + if (!st) return; + const yTarget = floorTarget(st); + const s = st.span; + // Flush accumulated damping so reset and view changes do not inherit a prior gesture. + const damping = st.controls.enableDamping; + st.controls.enableDamping = false; + st.controls.update(); + st.controls.enableDamping = damping; + st.controls.minDistance = Math.max(2, s * 0.18); + st.controls.maxDistance = s * 5; + if (st.viewMode === "plan") { + st.camera.position.set(0, yTarget + s * 1.65, 0.01); + st.controls.target.set(0, yTarget, 0); + } else { + st.camera.position.set(s * 1.15, yTarget + s * 1.0, s * 1.25); + st.controls.target.set(0, yTarget + 0.4, 0); + } + st.controls.update(); + st.requestFrame(); +} + +export function zoomScene(handle, delta) { + const st = scenes.get(handle); + if (!st || !Number.isFinite(delta)) return; + const offset = st.camera.position.clone().sub(st.controls.target); + const distance = THREE.MathUtils.clamp(offset.length() * Math.exp(-delta * 0.18), st.controls.minDistance, st.controls.maxDistance); + st.camera.position.copy(st.controls.target).add(offset.setLength(distance)); + st.controls.update(); + st.requestFrame(); +} + +export function highlightZone(handle, label, photoIdsJson) { + const st = scenes.get(handle); + if (!st) return; + let photoIds = []; + try { photoIds = JSON.parse(photoIdsJson); } catch { /* An empty selection simply clears emphasis. */ } + st.scene.traverse((obj) => { + if (!obj.userData.zoneSurface) return; + const selected = Boolean(label) && obj.userData.zoneLabel === label && + (!photoIds.length || obj.userData.photoIds.some((id) => photoIds.includes(id))); + obj.material.emissive.setHex(selected ? SCENE_COLORS.accent : 0x000000); + obj.material.emissiveIntensity = selected ? 0.23 : 0; + }); + st.pinMeshes.forEach((pin) => { + const selected = Boolean(label) && pin.userData.zoneLabel === label && + (!photoIds.length || pin.userData.photoIds.some((id) => photoIds.includes(id))); + pin.scale.setScalar(selected ? 1.4 : 1); + }); + st.requestFrame(); +} + +export function disposeScene(handle) { + const st = scenes.get(handle); + if (!st) return; + st.stopAnimation(); + st.ro.disconnect(); + st.intersectionObserver.disconnect(); + st.interactionObserver.disconnect(); + st.coarsePointer.removeEventListener("change", st.onPointerModeChange); + st.reducedMotion.removeEventListener("change", st.onMotionChange); + document.removeEventListener("visibilitychange", st.onVisibilityChange); + window.removeEventListener("resize", st.resize); + st.canvas.removeEventListener("pointerdown", st.onPointerDown); + window.removeEventListener("pointerdown", st.onActivePointerDown, true); + window.removeEventListener("pointermove", st.onPointerMove, true); + st.canvas.removeEventListener("lostpointercapture", st.onPointerCancel); + window.removeEventListener("pointerup", st.onPointerUp, true); + window.removeEventListener("pointercancel", st.onPointerCancel, true); + st.canvas.removeEventListener("webglcontextlost", st.onContextLost); + st.canvas.removeEventListener("webglcontextrestored", st.onContextRestored); + st.controls.removeEventListener("change", st.requestFrame); + st.controls.dispose(); + st.canvas.style.touchAction = st.originalTouchAction; + disposeSceneObjects(st.scene); + st.renderer.dispose(); + scenes.delete(handle); +} + +function disposeSceneObjects(scene) { + const geometries = new Set(); + const materials = new Set(); + scene.traverse((obj) => { + if (obj.geometry) geometries.add(obj.geometry); + if (obj.material) (Array.isArray(obj.material) ? obj.material : [obj.material]).forEach((m) => materials.add(m)); + if (obj.shadow) obj.shadow.dispose(); + }); + geometries.forEach((geometry) => geometry.dispose()); + materials.forEach((material) => material.dispose()); +} + +function setGroupOpacity(group, opacity) { + group.traverse((obj) => { + if (obj.isMesh && obj.material) { + const mats = Array.isArray(obj.material) ? obj.material : [obj.material]; + mats.forEach((m) => { + if (m.userData.baseOpacity === undefined) { + m.userData.baseOpacity = m.opacity ?? 1.0; + m.userData.wasTransparent = m.transparent ?? false; + } + if (opacity < 0.99) { + m.transparent = true; + m.opacity = m.userData.baseOpacity * opacity; + } else { + m.transparent = m.userData.wasTransparent; + m.opacity = m.userData.baseOpacity; + } + }); + } + }); +} + +// Convert floor local (x east 0..W, y north 0..D) into Three.js world (x east -W/2..W/2, z south -D/2..D/2) +// Note: local y=0 is SOUTH (front/entrance), which maps to z = +D/2 in Three.js so south faces the viewer. +function toWorldXZ(floor, lx, ly) { + return [lx - floor.width_m / 2, floor.depth_m / 2 - ly]; +} + +function buildFloorGroup(floor, yBase, pinMeshes) { + const group = new THREE.Group(); + group.position.y = yBase; + const W = floor.width_m || 10; + const D = floor.depth_m || 10; + + // Floor slab + const slabGeo = new THREE.BoxGeometry(W, 0.14, D); + const slabMat = new THREE.MeshStandardMaterial({ color: 0xf3ede2, roughness: 0.85 }); + const slab = new THREE.Mesh(slabGeo, slabMat); + slab.position.y = -0.07; + slab.receiveShadow = true; + group.add(slab); + + // Subtle perimeter walls (low cutaway height on South/East so interior is easy to see) + buildWalls(group, floor); + + // Zones + furniture + pins + (floor.zones || []).forEach((zone) => { + const zg = buildZone(floor, zone, pinMeshes); + group.add(zg); + }); + + // Verticals (stairs / elevator) + (floor.verticals || []).forEach((v) => { + group.add(buildVertical(floor, v)); + }); + + return group; +} + +function buildWalls(group, floor) { + const W = floor.width_m; + const D = floor.depth_m; + const wallMat = new THREE.MeshStandardMaterial({ color: 0xd8d2c5, roughness: 0.75 }); + const glassMat = new THREE.MeshStandardMaterial({ + color: 0x8ecae6, + transparent: true, + opacity: 0.32, + roughness: 0.2, + }); + const doorMat = new THREE.MeshStandardMaterial({ color: 0xe76f51, roughness: 0.6 }); + + // Back walls (North & West) full height; front walls (South & East) cutaway 0.9m so camera sees inside + const north = new THREE.Mesh(new THREE.BoxGeometry(W, WALL_HEIGHT, WALL_THICK), wallMat.clone()); + north.position.set(0, WALL_HEIGHT / 2, -D / 2); + north.castShadow = true; + group.add(north); + + const west = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK, WALL_HEIGHT, D), wallMat.clone()); + west.position.set(-W / 2, WALL_HEIGHT / 2, 0); + west.castShadow = true; + group.add(west); + + const lowH = 0.65; + const south = new THREE.Mesh(new THREE.BoxGeometry(W, lowH, WALL_THICK), wallMat.clone()); + south.position.set(0, lowH / 2, D / 2); + group.add(south); + + const east = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK, lowH, D), wallMat.clone()); + east.position.set(W / 2, lowH / 2, 0); + group.add(east); + + // Render openings (windows as glass panels, entrances as welcome mats + arch) + (floor.openings || []).forEach((op) => { + const len = Math.max(0.9, op.length_m || 1.5); + const off = op.offset_m || 1.0; + const isWindow = op.kind === "window"; + const h = isWindow ? 1.5 : 2.1; + const yCenter = isWindow ? 1.3 : h / 2; + const mat = isWindow ? glassMat.clone() : doorMat.clone(); + + let mesh; + if (op.wall === "south" || op.wall === "north") { + mesh = new THREE.Mesh(new THREE.BoxGeometry(len, h, WALL_THICK * 1.3), mat); + const x = -W / 2 + off + len / 2; + const z = op.wall === "south" ? D / 2 : -D / 2; + mesh.position.set(x, yCenter, z); + } else { + mesh = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK * 1.3, h, len), mat); + const z = D / 2 - (off + len / 2); + const x = op.wall === "east" ? W / 2 : -W / 2; + mesh.position.set(x, yCenter, z); + } + group.add(mesh); + }); +} + +function buildZone(floor, zone, pinMeshes) { + const g = new THREE.Group(); + const [wx, wz] = toWorldXZ(floor, zone.x + zone.w / 2, zone.y + zone.d / 2); + g.position.set(wx, 0.02, wz); + + const color = ZONE_COLORS[zone.kind] || ZONE_COLORS.other; + const pad = new THREE.Mesh( + new THREE.BoxGeometry(Math.max(0.8, zone.w - 0.12), 0.04, Math.max(0.8, zone.d - 0.12)), + new THREE.MeshStandardMaterial({ color, roughness: 0.9 }) + ); + pad.receiveShadow = true; + pad.userData = { zoneSurface: true, zoneLabel: zone.label || zone.kind, photoIds: zone.evidence_photos || [] }; + g.add(pad); + + // Place furniture groups inside the zone + (zone.furniture || []).forEach((fg) => { + populateFurniture(g, zone.w, zone.d, fg); + }); + + // If this zone has evidence photos, place a glowing interactive pin above it + if (zone.evidence_photos && zone.evidence_photos.length > 0) { + const pin = buildPin(zone.label || zone.kind, zone.evidence_photos); + pin.position.set(0, 1.65, 0); + pin.userData.baseY = 1.65; + pin.userData.floorLevel = floor.level; + g.add(pin); + pinMeshes.push(pin); + } + return g; +} + +function populateFurniture(zoneGroup, zw, zd, fg) { + const count = Math.min(24, Math.max(1, fg.count || 1)); + const cols = Math.max(1, Math.ceil(Math.sqrt(count * (zw / Math.max(1, zd))))); + const rows = Math.max(1, Math.ceil(count / cols)); + const cellW = (zw * 0.82) / cols; + const cellD = (zd * 0.82) / rows; + + for (let i = 0; i < count; i++) { + const r = Math.floor(i / cols); + const c = i % cols; + const x = -zw * 0.41 + (c + 0.5) * cellW; + const z = -zd * 0.41 + (r + 0.5) * cellD; + const item = buildFurnitureMesh(fg.kind, cellW, cellD); + item.position.set(x, 0.02, z); + zoneGroup.add(item); + } +} + +function buildFurnitureMesh(kind, cellW, cellD) { + const g = new THREE.Group(); + const wood = new THREE.MeshStandardMaterial({ color: 0x8b5e3c, roughness: 0.7 }); + const darkWood = new THREE.MeshStandardMaterial({ color: 0x5c3d28, roughness: 0.75 }); + const chairMat = new THREE.MeshStandardMaterial({ color: 0x3d405b, roughness: 0.8 }); + const sofaMat = new THREE.MeshStandardMaterial({ color: 0x6b705c, roughness: 0.85 }); + const metal = new THREE.MeshStandardMaterial({ color: 0xadb5bd, metalness: 0.5, roughness: 0.4 }); + const leaf = new THREE.MeshStandardMaterial({ color: 0x52b788, roughness: 0.8 }); + + if (kind === "counter_bar") { + const w = Math.min(2.6, Math.max(1.2, cellW * 0.9)); + const d = Math.min(1.0, Math.max(0.65, cellD * 0.6)); + const body = new THREE.Mesh(new THREE.BoxGeometry(w, 0.95, d), darkWood); + body.position.y = 0.475; + body.castShadow = true; + g.add(body); + const machine = new THREE.Mesh(new THREE.BoxGeometry(0.45, 0.35, 0.35), metal); + machine.position.set(-w * 0.2, 1.12, 0); + g.add(machine); + return g; + } + + if (kind === "bar_seat") { + const stool = new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.2, 0.68, 12), chairMat); + stool.position.y = 0.34; + stool.castShadow = true; + g.add(stool); + return g; + } + + if (kind === "sofa") { + const seat = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.42, 0.65), sofaMat); + seat.position.y = 0.21; + seat.castShadow = true; + const back = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.45, 0.16), sofaMat); + back.position.set(0, 0.55, -0.24); + g.add(seat, back); + return g; + } + + if (kind === "plant") { + const pot = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.16, 0.36, 12), darkWood); + pot.position.y = 0.18; + const crown = new THREE.Mesh(new THREE.SphereGeometry(0.36, 12, 10), leaf); + crown.position.y = 0.62; + crown.castShadow = true; + g.add(pot, crown); + return g; + } + + // Tables (table2, table4, table6, communal_table) + const isLarge = kind === "table6" || kind === "communal_table"; + const isFour = kind === "table4"; + const tw = isLarge ? 1.5 : isFour ? 0.95 : 0.68; + const td = isLarge ? 0.8 : 0.68; + const top = new THREE.Mesh(new THREE.BoxGeometry(tw, 0.06, td), wood); + top.position.y = 0.72; + top.castShadow = true; + const leg = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.08, 0.7, 10), metal); + leg.position.y = 0.35; + g.add(top, leg); + + const chairOffsets = isLarge + ? [ + [-0.45, -0.52], + [0, -0.52], + [0.45, -0.52], + [-0.45, 0.52], + [0, 0.52], + [0.45, 0.52], + ] + : isFour + ? [ + [-0.24, -0.48], + [0.24, -0.48], + [-0.24, 0.48], + [0.24, 0.48], + ] + : [ + [0, -0.46], + [0, 0.46], + ]; + + chairOffsets.forEach(([cx, cz]) => { + const ch = new THREE.Mesh(new THREE.BoxGeometry(0.32, 0.44, 0.32), chairMat); + ch.position.set(cx, 0.22, cz); + ch.castShadow = true; + g.add(ch); + }); + return g; +} + +function buildVertical(floor, v) { + const g = new THREE.Group(); + const [wx, wz] = toWorldXZ(floor, v.x + v.w / 2, v.y + v.d / 2); + g.position.set(wx, 0, wz); + const mat = new THREE.MeshStandardMaterial({ color: 0xadb5bd, roughness: 0.6 }); + + if (v.kind === "elevator") { + const box = new THREE.Mesh(new THREE.BoxGeometry(v.w, WALL_HEIGHT, v.d), mat); + box.position.y = WALL_HEIGHT / 2; + g.add(box); + } else { + const steps = 8; + for (let i = 0; i < steps; i++) { + const sh = ((i + 1) / steps) * (WALL_HEIGHT * 0.85); + const step = new THREE.Mesh(new THREE.BoxGeometry(v.w, sh, v.d / steps), mat); + step.position.set(0, sh / 2, -v.d / 2 + ((i + 0.5) * v.d) / steps); + step.castShadow = true; + g.add(step); + } + } + return g; +} + +function buildPin(zoneLabel, photoIds) { + const g = new THREE.Group(); + g.userData = { zoneLabel, photoIds }; + const headMat = new THREE.MeshStandardMaterial({ + color: SCENE_COLORS.accent, + emissive: SCENE_COLORS.accent, + emissiveIntensity: 0.18, + roughness: 0.3, + }); + const head = new THREE.Mesh(new THREE.OctahedronGeometry(0.24, 0), headMat); + head.position.y = 0.2; + const stem = new THREE.Mesh( + new THREE.CylinderGeometry(0.03, 0.03, 0.35, 8), + new THREE.MeshBasicMaterial({ color: SCENE_COLORS.accent }) + ); + g.add(head, stem); + return g; +} diff --git a/app/js/scene.test.mjs b/app/js/scene.test.mjs new file mode 100644 index 0000000..539f6f0 --- /dev/null +++ b/app/js/scene.test.mjs @@ -0,0 +1,184 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import vm from "node:vm"; +import { test } from "node:test"; +import * as Three from "../../public/vendor/three/three.module.js"; + +// Exercise real scene geometry/camera math with a minimal rendering boundary. No DOM or GPU +// is required: these tests cover gesture arbitration and view state, not WebGL rendering. +const source = (await readFile(new URL("./scene.js", import.meta.url), "utf8")) + .replace(/^import .*;\r?\n/gm, "") + .replace(/^export /gm, ""); + +class Surface extends EventTarget { + style = { touchAction: "" }; + dataset = {}; + hidden = false; + getBoundingClientRect() { return { left: 0, top: 0, right: 390, bottom: 460, width: 390, height: 460 }; } +} + +function setup({ reduced = false } = {}) { + const window = new Surface(); + const document = new Surface(); + const canvas = new Surface(); + const frames = new Map(); + let nextFrame = 1; + let failRenderer = false; + class Renderer { + shadowMap = {}; + setClearColor() {} + setPixelRatio() {} + setSize() {} + constructor() { if (failRenderer) throw new Error("GPU unavailable"); } + render(scene, camera) { scene.updateMatrixWorld(true); camera.updateMatrixWorld(true); } + dispose() { this.disposed = true; } + } + class Controls extends Three.EventDispatcher { + target = new Three.Vector3(); + mouseButtons = {}; + touches = {}; + minDistance = 0; + maxDistance = Infinity; + update() {} + dispose() { this.disposed = true; } + } + class Observer { observe() {} disconnect() { this.disconnected = true; } } + window.matchMedia = (query) => Object.assign(new Surface(), { + matches: query === "(pointer: coarse)" || (query.includes("reduced-motion") && reduced), + }); + window.devicePixelRatio = 1; + const context = vm.createContext({ + THREE: { ...Three, WebGLRenderer: Renderer }, OrbitControls: Controls, + window, document, Event, performance, console: { warn() {} }, + ResizeObserver: Observer, MutationObserver: Observer, IntersectionObserver: Observer, + requestAnimationFrame(callback) { const id = nextFrame++; frames.set(id, callback); return id; }, + cancelAnimationFrame(id) { frames.delete(id); }, + }); + vm.runInContext(`${source}\nthis.api = {mountScene,setFloor,setViewMode,resetScene,zoomScene,highlightZone,disposeScene,scenes};`, context); + const api = context.api; + const selected = []; + const layout = JSON.stringify({ floors: [1, 2].map((level) => ({ + level, width_m: 10, depth_m: 10, openings: [], verticals: [], + zones: [{ label: `층${level}`, kind: "seating", x: 1, y: 1, w: 4, d: 4, furniture: [], evidence_photos: [`p${level}`] }], + })) }); + const mount = () => api.mountScene(canvas, layout, (label) => selected.push(label)); + const handle = mount(); + const st = api.scenes.get(handle); + const frame = () => { + const batch = [...frames.values()]; + frames.clear(); + batch.forEach((callback) => callback()); + }; + frame(); + function point(pin = st.pinMeshes[0]) { + st.scene.updateMatrixWorld(true); + st.camera.lookAt(st.controls.target); + st.camera.updateMatrixWorld(true); + const v = pin.getWorldPosition(new Three.Vector3()).project(st.camera); + return { x: (v.x + 1) * 195, y: (1 - v.y) * 230 }; + } + function pointer(target, type, { id = 1, x, y, primary = true } = {}) { + const event = new Event(type, { cancelable: true }); + Object.assign(event, { pointerId: id, clientX: x, clientY: y, isPrimary: primary, button: 0 }); + target.dispatchEvent(event); + } + return { api, canvas, window, document, selected, handle, st, frame, point, pointer, frames, mount, fail: () => { failRenderer = true; } }; +} + +test("photo pins work while page scrolling is enabled", () => { + const t = setup(); + assert.equal(t.canvas.style.touchAction, "pan-y"); + assert.equal(t.st.controls.enabled, false); + t.api.setFloor(t.handle, 1); + const p = t.point(); + t.pointer(t.canvas, "pointerdown", p); + t.pointer(t.window, "pointerup", p); + assert.deepEqual(t.selected, ["층1"]); + t.api.disposeScene(t.handle); +}); + +test("scroll, cancelled, and multi-touch gestures cannot select a pin", () => { + const t = setup(); + const p = t.point(); + t.pointer(t.canvas, "pointerdown", p); + t.pointer(t.window, "pointermove", { x: p.x, y: p.y + 12 }); + t.pointer(t.window, "pointerup", p); + t.pointer(t.canvas, "pointerdown", p); + t.pointer(t.window, "pointercancel", p); + t.pointer(t.window, "pointerup", p); + t.pointer(t.canvas, "pointerdown", p); + t.pointer(t.canvas, "pointerdown", { ...p, id: 2, primary: false }); + t.pointer(t.window, "pointerup", { ...p, id: 2, primary: false }); + t.pointer(t.window, "pointerup", p); + t.pointer(t.canvas, "pointerdown", p); + t.pointer(t.window, "pointerdown", { ...p, id: 2, primary: false }); + t.pointer(t.window, "pointerup", p); + t.pointer(t.window, "pointerup", { ...p, id: 2, primary: false }); + assert.deepEqual(t.selected, []); + t.api.disposeScene(t.handle); +}); + +test("plan mode locks rotation and floor changes preserve its zoom and orientation", () => { + const t = setup(); + t.api.setFloor(t.handle, 1); + t.api.setViewMode(t.handle, "plan"); + assert.equal(t.st.controls.enableRotate, false); + assert.equal(t.st.controls.maxPolarAngle, 0); + assert.equal(t.st.controls.touches.ONE, Three.TOUCH.PAN); + t.api.zoomScene(t.handle, 1); + const offset = t.st.camera.position.clone().sub(t.st.controls.target); + t.api.setFloor(t.handle, 2); + assert.ok(offset.distanceTo(t.st.camera.position.clone().sub(t.st.controls.target)) < 1e-10); + assert.equal(t.st.floorGroups.get(1).group.visible, false); + t.api.setViewMode(t.handle, "3d"); + assert.equal(t.st.controls.enableRotate, true); + assert.equal(t.st.floorGroups.get(1).group.visible, true); + assert.equal(t.st.activeLevel, 2); + t.api.disposeScene(t.handle); +}); + +test("reduced motion renders on demand and freezes decorative pins", () => { + const t = setup({ reduced: true }); + assert.equal(t.st.controls.enableDamping, false); + assert.equal(t.frames.size, 0); + assert.ok(t.st.pinMeshes.every((pin) => pin.rotation.y === 0 && pin.position.y === pin.userData.baseY)); + t.api.zoomScene(t.handle, 1); + assert.equal(t.frames.size, 1); + t.frame(); + assert.equal(t.frames.size, 0); + t.api.disposeScene(t.handle); +}); + +test("context loss reports a recoverable state and disposal cancels work", () => { + const t = setup(); + let errors = 0; + let ready = 0; + t.canvas.addEventListener("scene-error", () => errors++); + t.canvas.addEventListener("scene-ready", () => ready++); + const lost = new Event("webglcontextlost", { cancelable: true }); + t.canvas.dispatchEvent(lost); + assert.equal(lost.defaultPrevented, true); + assert.equal(errors, 1); + assert.ok(t.canvas.dataset.sceneError); + assert.equal(t.frames.size, 0); + t.canvas.dispatchEvent(new Event("webglcontextrestored")); + assert.equal(ready, 1); + assert.equal(t.canvas.dataset.sceneError, ""); + t.api.disposeScene(t.handle); + assert.equal(t.api.scenes.size, 0); + assert.equal(t.frames.size, 0); + assert.equal(t.st.renderer.disposed, true); + assert.equal(t.st.controls.disposed, true); + assert.equal(t.canvas.style.touchAction, ""); + t.canvas.dispatchEvent(new Event("webglcontextlost", { cancelable: true })); + assert.equal(errors, 1); +}); + +test("unavailable WebGL returns an explicit failure handle instead of throwing", () => { + const t = setup(); + t.api.disposeScene(t.handle); + t.fail(); + assert.equal(t.mount(), 0); + assert.ok(t.canvas.dataset.sceneError); + assert.equal(t.api.scenes.size, 0); +}); diff --git a/app/js/ui.js b/app/js/ui.js new file mode 100644 index 0000000..2ba13d0 --- /dev/null +++ b/app/js/ui.js @@ -0,0 +1,186 @@ +// Small browser-only interactions shared by the hydrated views. +const scrollPositions = new Map(); +const dialogs = new Map(); +const watchers = new Map(); +let nextHandle = 1; +let scrollLock = null; +let restoreGeneration = 0; + +export function saveScroll(key) { + restoreGeneration += 1; + scrollPositions.set(key, window.scrollY); +} +export function restoreScroll(destination) { + const target = new URL(destination, location.href); + const top = scrollPositions.get(target.pathname) || 0; + const route = target.pathname + target.search; + const previousRoute = location.pathname + location.search; + const generation = ++restoreGeneration; + let attempts = 0; + const afterCommit = () => { + if (generation !== restoreGeneration) return; + const currentRoute = location.pathname + location.search; + // Leptos constructs the destination before committing the browser URL. + // Wait for that commit, but abandon a canceled or superseded navigation. + if (currentRoute !== route) { + if (currentRoute === previousRoute && ++attempts < 60) requestAnimationFrame(afterCommit); + return; + } + requestAnimationFrame(() => { + if (generation === restoreGeneration && location.pathname + location.search === route) { + window.scrollTo({ top, behavior: "instant" }); + } + }); + }; + requestAnimationFrame(afterCommit); +} +export function focusSearch() { + document.querySelector('input[name="q"]')?.focus({ preventScroll: true }); +} +export function blurActive() { + if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); +} +export function closeMenu(id) { document.getElementById(id)?.removeAttribute("open"); } +export function clearJobQuery() { + const url = new URL(location.href); + if (url.searchParams.has("job")) { + url.searchParams.delete("job"); + history.replaceState(history.state, "", url); + } +} +export function revealSelectedPhoto() { + requestAnimationFrame(() => { + if (isCompact() || document.querySelector('dialog:modal')) return; + const panel = document.getElementById('info-panel'); + if (panel) panel.scrollTop = 0; + panel?.querySelector('.selected-zone-panel')?.scrollIntoView({ block: 'nearest', behavior: 'instant' }); + }); +} +export function isCompact() { + return matchMedia("(max-width: 639px), (max-height: 499px)").matches; +} +export function watchCompact(onChange) { + const handle = nextHandle++; + const media = matchMedia("(max-width: 639px), (max-height: 499px)"); + const listener = () => onChange(media.matches); + media.addEventListener("change", listener); + watchers.set(handle, { media, listener }); + listener(); + return handle; +} +export function releaseWatch(handle) { + const watcher = watchers.get(handle); + if (watcher) watcher.media.removeEventListener("change", watcher.listener); + watchers.delete(handle); +} + +function unlockScroll() { + if (scrollLock && ![...dialogs.values()].some(record => !record.finished)) { + document.documentElement.style.overflow = scrollLock.html; + document.body.style.overflow = scrollLock.body; + scrollLock = null; + } +} +function finishDialog(record, notify = true) { + if (record.finished) return; + record.finished = true; + record.dialog.removeEventListener("cancel", record.cancel); + record.dialog.removeEventListener("close", record.closed); + record.dialog.removeEventListener("click", record.backdrop); + record.dialog.removeAttribute("aria-modal"); + if (record.dialog.open) record.dialog.close(); + if (record.inline && record.dialog.isConnected) record.dialog.show(); + unlockScroll(); + if (location.pathname + location.search === record.route) { + window.scrollTo({ top: record.scrollY, behavior: "instant" }); + if (record.focus?.isConnected) record.focus.focus({ preventScroll: true }); + } + if (notify) queueMicrotask(() => { + if (dialogs.get(record.handle) === record) record.onClose(); + }); +} + +function requestClose(record) { + if (record.finished || record.pending) return; + if (history.state?.spaceOverlay === record.token) { + record.pending = true; + history.back(); + } else { + finishDialog(record); + } +} + +window.addEventListener("popstate", () => { + for (const record of [...dialogs.values()].reverse()) { + if (!record.finished && history.state?.spaceOverlay !== record.token) finishDialog(record); + else if (!record.finished) break; + } +}); + +export function openDialog(id, onClose) { + const dialog = document.getElementById(id); + if (!(dialog instanceof HTMLDialogElement)) return 0; + const existing = [...dialogs.values()].find(record => record.dialog === dialog && !record.finished); + if (existing) { + // The Rust bridge replaces its stored Closure for a reused handle. + existing.onClose = onClose; + return existing.handle; + } + const handle = nextHandle++; + const record = { + handle, dialog, onClose, token: `space-${handle}-${Date.now()}`, + focus: document.activeElement instanceof HTMLElement ? document.activeElement : null, + inline: dialog.hasAttribute("data-inline-dialog"), + scrollY: window.scrollY, route: location.pathname + location.search, + finished: false, pending: false, + }; + record.cancel = event => { event.preventDefault(); requestClose(record); }; + record.closed = () => { + // close() before showModal() queues an event; ignore it while the new modal is open. + if (!dialog.open && !record.finished) requestClose(record); + }; + record.backdrop = event => { + if (event.target !== dialog) return; + const rect = dialog.getBoundingClientRect(); + if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) requestClose(record); + }; + if (!scrollLock) { + scrollLock = { html: document.documentElement.style.overflow, body: document.body.style.overflow }; + document.documentElement.style.overflow = "hidden"; + document.body.style.overflow = "hidden"; + } + dialogs.set(handle, record); + if (dialog.open) dialog.close(); + try { + dialog.showModal(); + } catch { + dialogs.delete(handle); + if (record.inline && dialog.isConnected) dialog.show(); + unlockScroll(); + return 0; + } + dialog.setAttribute("aria-modal", "true"); + dialog.addEventListener("cancel", record.cancel); + dialog.addEventListener("close", record.closed); + dialog.addEventListener("click", record.backdrop); + history.pushState({ ...history.state, spaceOverlay: record.token }, ""); + const focusTarget = dialog.querySelector("[autofocus], button:not([disabled]), [href], [tabindex='0']"); + focusTarget?.focus({ preventScroll: true }); + return handle; +} +export function closeDialog(id) { + const record = [...dialogs.values()].reverse().find(entry => entry.dialog.id === id && !entry.finished); + if (record) requestClose(record); +} +export function releaseDialog(handle) { + const record = dialogs.get(handle); + if (!record) return; + // Route disposal must not initiate a second navigation. Explicit close consumes history. + finishDialog(record, false); + dialogs.delete(handle); +} + +export function copyText(value, onResult) { + if (!navigator.clipboard?.writeText) { onResult(false); return; } + navigator.clipboard.writeText(value).then(() => onResult(true), () => onResult(false)); +} diff --git a/app/js/ui.test.mjs b/app/js/ui.test.mjs new file mode 100644 index 0000000..325b412 --- /dev/null +++ b/app/js/ui.test.mjs @@ -0,0 +1,306 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; + +const source = readFileSync(new URL("./ui.js", import.meta.url), "utf8"); + +// The fake environment models asynchronous close/popstate delivery deliberately: +// it catches lifetime mistakes hidden by a synchronous history.back() stub. +function setup() { + const tasks = []; + const microtasks = []; + const frames = []; + const elements = new Map(); + const scrollCalls = []; + const document = { + activeElement: null, + documentElement: { style: { overflow: "auto" } }, + body: { style: { overflow: "" } }, + getElementById: id => elements.get(id), + querySelector: () => null, + }; + class Element extends EventTarget { + isConnected = true; + focusCount = 0; + focus() { this.focusCount += 1; document.activeElement = this; } + blur() { if (document.activeElement === this) document.activeElement = null; } + } + class Dialog extends Element { + constructor(id, { inline = false } = {}) { + super(); + this.id = id; + this.open = inline; + this.modal = false; + this.attributes = new Map(inline ? [["data-inline-dialog", "true"]] : []); + this.firstButton = new Element(); + elements.set(id, this); + } + hasAttribute(name) { return this.attributes.has(name); } + setAttribute(name, value) { this.attributes.set(name, value); } + removeAttribute(name) { this.attributes.delete(name); } + querySelector() { return this.firstButton; } + show() { this.open = true; this.modal = false; } + showModal() { + if (this.open) throw new Error("A nonmodal dialog must be closed first"); + this.open = true; + this.modal = true; + } + close() { + if (!this.open) return; + this.open = false; + this.modal = false; + tasks.push(() => this.dispatchEvent(new Event("close"))); + } + getBoundingClientRect() { return { left: 10, top: 10, right: 300, bottom: 500 }; } + } + const window = new EventTarget(); + window.scrollY = 340; + window.scrollTo = options => { + window.scrollY = options.top; + scrollCalls.push(options.top); + }; + const location = new URL("http://localhost/place/kakao:123?from=%2Frecent"); + const entries = [{ router: "base" }]; + let historyIndex = 0; + const history = { + backCalls: 0, + get state() { return entries[historyIndex]; }, + pushState(state) { + entries.splice(historyIndex + 1); + entries.push(state); + historyIndex += 1; + }, + replaceState(state) { entries[historyIndex] = state; }, + back() { + this.backCalls += 1; + tasks.push(() => { + if (historyIndex === 0) return; + historyIndex -= 1; + window.dispatchEvent(new Event("popstate")); + }); + }, + }; + const context = { + window, document, location, history, URL, Event, + HTMLElement: Element, HTMLDialogElement: Dialog, + navigator: {}, + queueMicrotask: callback => microtasks.push(callback), + requestAnimationFrame: callback => frames.push(callback), + matchMedia: () => Object.assign(new EventTarget(), { matches: false }), + }; + const exports = ["saveScroll", "restoreScroll", "openDialog", "closeDialog", "releaseDialog"]; + const api = vm.runInNewContext( + `${source.replace(/^export /gm, "")}\n({ ${exports.join(", ")} })`, + context, + { filename: "ui.js" }, + ); + function flush() { + while (tasks.length || microtasks.length) { + while (microtasks.length) microtasks.shift()(); + if (tasks.length) tasks.shift()(); + } + } + function flushFrames() { + while (frames.length) frames.shift()(); + } + function nextFrame() { frames.shift()?.(); } + return { api, Dialog, Element, document, window, location, history, entries, scrollCalls, flush, flushFrames, nextFrame }; +} + +test("nested modal close consumes only the inner history entry and retains the outer scroll lock", () => { + const env = setup(); + const { api, document, history, flush } = env; + const opener = new env.Element(); + opener.focus(); + const scene = new env.Dialog("scene", { inline: true }); + const photo = new env.Dialog("photo"); + let sceneClosed = 0; + let photoClosed = 0; + api.openDialog("scene", () => sceneClosed++); + const innerOpener = new env.Element(); + innerOpener.focus(); + api.openDialog("photo", () => photoClosed++); + + api.closeDialog("photo"); + assert.equal(photo.open, true, "close is pending its history traversal"); + flush(); + assert.equal(photo.open, false); + assert.equal(photoClosed, 1); + assert.equal(sceneClosed, 0); + assert.equal(scene.open, true); + assert.equal(scene.modal, true); + assert.equal(document.body.style.overflow, "hidden"); + assert.equal(document.activeElement, innerOpener); + assert.equal(history.state.spaceOverlay, env.entries[1].spaceOverlay); + + api.closeDialog("scene"); + flush(); + assert.equal(sceneClosed, 1); + assert.equal(scene.open, true, "the inline canvas remains rendered"); + assert.equal(scene.modal, false); + assert.equal(document.body.style.overflow, ""); + assert.equal(document.documentElement.style.overflow, "auto"); + assert.equal(document.activeElement, opener); + assert.equal(history.backCalls, 2); +}); + +test("the queued close event from promoting an inline dialog does not dismiss its modal", () => { + const env = setup(); + const dialog = new env.Dialog("scene", { inline: true }); + let closed = 0; + env.api.openDialog("scene", () => closed++); + env.flush(); + assert.equal(dialog.modal, true); + assert.equal(dialog.open, true); + assert.equal(closed, 0); + assert.equal(env.history.backCalls, 0); + + const cancel = new Event("cancel", { cancelable: true }); + dialog.dispatchEvent(cancel); + assert.equal(cancel.defaultPrevented, true); + env.flush(); + assert.equal(dialog.open, true); + assert.equal(dialog.modal, false); + assert.equal(closed, 1); +}); + +test("reopening an already open dialog replaces the callback without adding history", () => { + const env = setup(); + new env.Dialog("photo"); + let oldCalls = 0; + let newCalls = 0; + const first = env.api.openDialog("photo", () => oldCalls++); + const second = env.api.openDialog("photo", () => newCalls++); + assert.equal(second, first); + assert.equal(env.entries.length, 2); + env.api.closeDialog("photo"); + env.flush(); + assert.equal(oldCalls, 0, "the old Rust Closure can safely be dropped"); + assert.equal(newCalls, 1); +}); + +test("component release restores inline content without navigating history or notifying disposed state", () => { + const env = setup(); + const scene = new env.Dialog("scene", { inline: true }); + let closed = 0; + const handle = env.api.openDialog("scene", () => closed++); + // The URL can still be the old route while a router disposes its component. + env.api.releaseDialog(handle); + env.flush(); + assert.equal(env.history.backCalls, 0); + assert.equal(scene.open, true); + assert.equal(scene.modal, false); + assert.equal(env.document.body.style.overflow, ""); + assert.equal(closed, 0); +}); + +test("close followed by immediate release cannot call a dropped callback after popstate", () => { + const env = setup(); + const photo = new env.Dialog("photo"); + const handle = env.api.openDialog("photo", () => assert.fail("disposed callback invoked")); + env.api.closeDialog("photo"); + env.api.releaseDialog(handle); + env.flush(); + assert.equal(env.history.backCalls, 1); + assert.equal(photo.open, false); + assert.equal(env.document.body.style.overflow, ""); +}); + +test("browser back closes nested dialogs from top to bottom", () => { + const env = setup(); + const scene = new env.Dialog("scene", { inline: true }); + const photo = new env.Dialog("photo"); + const notifications = []; + env.api.openDialog("scene", () => notifications.push("scene")); + env.api.openDialog("photo", () => notifications.push("photo")); + env.history.back(); + env.flush(); + assert.deepEqual(notifications, ["photo"]); + assert.equal(photo.open, false); + assert.equal(scene.modal, true); + env.history.back(); + env.flush(); + assert.deepEqual(notifications, ["photo", "scene"]); + assert.equal(scene.open, true); + assert.equal(scene.modal, false); +}); + +test("native dialog close still consumes overlay history once", () => { + const env = setup(); + const photo = new env.Dialog("photo"); + let closed = 0; + env.api.openDialog("photo", () => closed++); + photo.close(); + env.flush(); + assert.equal(env.history.backCalls, 1); + assert.equal(closed, 1); + assert.equal(env.document.body.style.overflow, ""); +}); + +test("a deferred search scroll restore cannot affect a different query on the same route", () => { + const env = setup(); + env.location.pathname = "/"; + env.location.search = "?q=first"; + env.window.scrollY = 620; + env.api.saveScroll("/"); + env.window.scrollY = 0; + env.api.restoreScroll("/?q=first"); + env.location.search = "?q=second"; + env.flushFrames(); + assert.deepEqual(env.scrollCalls, []); + + env.location.search = "?q=first"; + env.api.restoreScroll("/?q=first"); + env.flushFrames(); + assert.deepEqual(env.scrollCalls, [620]); +}); + +test("search restoration waits for the router's destination URL commit", () => { + const env = setup(); + env.location.pathname = "/"; + env.location.search = "?q=first"; + env.window.scrollY = 89; + env.api.saveScroll("/"); + env.location.pathname = "/recent"; + env.location.search = ""; + env.window.scrollY = 0; + // The new Home component exists while browser location still says /recent. + env.api.restoreScroll("/?q=first"); + env.nextFrame(); + assert.deepEqual(env.scrollCalls, []); + env.location.pathname = "/"; + env.location.search = "?q=first"; + env.flushFrames(); + assert.deepEqual(env.scrollCalls, [89]); +}); + +test("a newer navigation cancels a pending restoration before its URL commits", () => { + const env = setup(); + env.window.scrollY = 89; + env.api.saveScroll("/"); + env.location.pathname = "/recent"; + env.location.search = ""; + env.api.restoreScroll("/?q=first"); + env.nextFrame(); + env.api.saveScroll("/recent"); + env.location.pathname = "/"; + env.location.search = "?q=first"; + env.flushFrames(); + assert.deepEqual(env.scrollCalls, []); +}); + +test("releasing a dialog after route change does not restore focus or scroll into the old page", () => { + const env = setup(); + const opener = new env.Element(); + opener.focus(); + new env.Dialog("photo"); + const handle = env.api.openDialog("photo", () => assert.fail("disposed callback invoked")); + env.location.pathname = "/recent"; + env.location.search = ""; + env.api.releaseDialog(handle); + env.flush(); + assert.equal(opener.focusCount, 1); + assert.deepEqual(env.scrollCalls, []); + assert.equal(env.history.backCalls, 0); +}); diff --git a/app/src/detail.rs b/app/src/detail.rs new file mode 100644 index 0000000..64c36b8 --- /dev/null +++ b/app/src/detail.rs @@ -0,0 +1,300 @@ +use crate::{ + discovery::DiscoveryState, get_place_view, scene_bridge, trigger_reanalyze, ui_bridge, + workspace::WorkspaceView, Icon, +}; +use domain::JobEvent; +use leptos::prelude::*; +use leptos_router::hooks::{use_params_map, use_query_map}; + +pub(crate) fn return_destination(value: Option<&str>) -> String { + match value { + Some("/recent") => "/recent".into(), + Some(value) + if (value == "/" || value.starts_with("/?q=")) + && value.len() <= 4096 + && !value.contains(['\r', '\n', '#']) => + { + value.into() + } + _ => "/".into(), + } +} + +#[component] +pub(crate) fn PlacePage() -> impl IntoView { + let params = use_params_map(); + view! { {move || { + let id = params.read().get("id").unwrap_or_default(); + view! { } + }} } +} + +#[component] +fn PlaceDetail(place_id: String) -> impl IntoView { + let discovery = use_context::(); + let query = use_query_map(); + let initial_job = query.read_untracked().get("job"); + let id = StoredValue::new(place_id); + let active_job = RwSignal::new(initial_job); + let events = RwSignal::new(Vec::::new()); + let settled_jobs = RwSignal::new(Vec::::new()); + let refresh_tick = RwSignal::new(0u32); + let pending = RwSignal::new(false); + let analysis_error = RwSignal::new(None::<&'static str>); + let copy_status = RwSignal::new(String::new()); + let back = Memo::new(move |_| return_destination(query.read().get("from").as_deref())); + let place_res = Resource::new( + move || refresh_tick.get(), + move |_| get_place_view(id.get_value()), + ); + + Effect::new(move |_| { + if let Some(Ok(Some(place))) = place_res.get() { + if active_job.get_untracked().is_none() { + if let Some(job) = place.running_job { + if !settled_jobs.get_untracked().contains(&job) { + active_job.set(Some(job)); + } + } + } + } + }); + + Effect::new(move |_| { + let Some(job) = active_job.get() else { + return; + }; + events.set(Vec::new()); + analysis_error.set(None); + let subscribed_job = job.clone(); + let subscription = scene_bridge::subscribe_job_events(&job, move |event| { + let terminal = event.is_terminal(); + let succeeded = matches!(event, JobEvent::Done { .. }); + if matches!(event, JobEvent::Error { .. }) { + analysis_error.set(Some("분석을 완료하지 못했습니다. 다시 시도해 주세요.")); + } + events.update(|all| all.push(event)); + if terminal { + settled_jobs.update(|all| all.push(subscribed_job.clone())); + active_job.set(None); + ui_bridge::clear_job_query(); + if succeeded { + if let Some(state) = discovery { + state.invalidate_recent(); + } + refresh_tick.update(|n| *n += 1); + } + } + }); + #[cfg(feature = "hydrate")] + if subscription.is_none() { + analysis_error.set(Some( + "분석 진행 상태에 연결하지 못했습니다. 다시 시도해 주세요.", + )); + settled_jobs.update(|all| all.push(job)); + active_job.set(None); + } + on_cleanup(move || { + if let Some(handle) = subscription { + scene_bridge::close_job_events(handle); + } + }); + }); + + let analyze = Action::new(move |_: &()| async move { + if pending.get_untracked() || active_job.get_untracked().is_some() { + return; + } + pending.set(true); + analysis_error.set(None); + ui_bridge::close_menu("place-menu"); + match trigger_reanalyze(id.get_value()).await { + Ok(job) => { + if let Some(state) = discovery { + state.invalidate_recent(); + } + active_job.set(Some(job)); + } + Err(_) => analysis_error.set(Some( + "분석을 시작하지 못했습니다. 잠시 후 다시 시도해 주세요.", + )), + } + pending.set(false); + }); + + view! { +
+ "장소를 불러오는 중…"
}> + {move || place_res.get().map(|result| match result { + Ok(Some(place)) => { + let address = if place.place.road_address.is_empty() { place.place.address.clone() } else { place.place.road_address.clone() }; + let copy_address = address.clone(); + let parcel_address = (!place.place.road_address.is_empty() + && !place.place.address.is_empty() + && place.place.address != place.place.road_address) + .then(|| place.place.address.clone()); + let has_layout = place.layout.is_some(); + view! { +
+ + +

{place.place.name.clone()}

+
+ +
+ +

{address}

+ + {parcel_address.map(|address| { + let copy_parcel = address.clone(); + view! { +

"지번 "{address}

+ + } + })} +

{move || copy_status.get()}

+ {(!place.place.phone.is_empty()).then(|| view! { "전화 "{place.place.phone.clone()} })} + {(!place.place.place_url.is_empty()).then(|| view! { "장소 원문 보기" })} + +
+
+
+ {move || analysis_error.get().map(|message| view! { + + })} + {move || active_job.get().is_some().then(|| view! { })} + {match place.layout.clone() { + Some(layout) => view! { }.into_any(), + None => view! { +

"분석이 끝나면 공간 배치와 사진이 표시됩니다."

"분석 완료된 장소 보기" + }> +
+

"아직 공간 정보가 없습니다."

+

"장소 사진을 분석하면 공간 배치와 좌석 정보를 확인할 수 있습니다."

+ +
+
+ }.into_any(), + }} + }.into_any() + }, + Ok(None) => view! {

"장소를 찾을 수 없습니다."

"목록으로 돌아가기"
}.into_any(), + Err(_) => view! { }.into_any(), + })} + + + } +} + +fn progress_phase(events: &[JobEvent]) -> usize { + if events + .iter() + .any(|event| matches!(event, JobEvent::Done { .. })) + { + 2 + } else if events.iter().any(|event| { + matches!( + event, + JobEvent::Classified { .. } + | JobEvent::FloorsDetected { .. } + | JobEvent::LayoutDraft { .. } + ) + }) { + 1 + } else { + 0 + } +} + +fn progress_detail(event: &JobEvent) -> Option { + match event { + JobEvent::PlaceResolved { .. } => Some("장소를 확인했습니다.".into()), + JobEvent::SourceDone { + source, + photos, + error, + .. + } => Some(if error.is_some() { + format!("{}의 일부 자료를 가져오지 못했습니다.", source.label()) + } else { + format!("{} 사진 {}장을 확인했습니다.", source.label(), photos) + }), + JobEvent::PhotosStored { stored, .. } => Some(format!("사진 {}장을 준비했습니다.", stored)), + JobEvent::Classified { + interior, exterior, .. + } => Some(format!( + "실내 사진 {}장 · 외관 사진 {}장을 확인했습니다.", + interior, exterior + )), + JobEvent::FloorsDetected { floors } => { + Some(format!("{}개 층 후보를 검토하고 있습니다.", floors.len())) + } + JobEvent::LayoutDraft { .. } => { + Some("사진을 바탕으로 공간 배치를 구성하고 있습니다.".into()) + } + _ => None, + } +} + +#[component] +fn ProgressPanel(events: RwSignal>) -> impl IntoView { + view! { +
+
{move || if progress_phase(&events.get()) == 0 { "사진과 리뷰를 확인하고 있습니다" } else { "공간 배치를 구성하고 있습니다" }}
+
    {["자료 수집", "공간 분석", "완료"].into_iter().enumerate().map(|(index, label)| view! { +
  1. index { "complete" } else { "" } } aria-current=move || (progress_phase(&events.get()) == index).then_some("step")>{label}
  2. + }).collect_view()}
+
"진행 내용"
    {move || events.get().iter().filter_map(progress_detail).map(|message| view! {
  • {message}
  • }).collect_view()}
+
+ } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn return_paths_stay_in_known_local_views() { + assert_eq!(return_destination(Some("/recent")), "/recent"); + assert_eq!( + return_destination(Some("/?q=%EC%84%B1%EC%88%98")), + "/?q=%EC%84%B1%EC%88%98" + ); + for value in [ + "//evil.example", + "https://evil.example", + "/place/x", + "/?q=x\n", + "/?q=x#photo", + ] { + assert_eq!(return_destination(Some(value)), "/"); + } + } + #[test] + fn phases_follow_actual_events_without_inventing_percentage() { + assert_eq!(progress_phase(&[]), 0); + assert_eq!(progress_phase(&[JobEvent::LayoutDraft { attempt: 2 }]), 1); + assert_eq!( + progress_phase(&[JobEvent::Done { + place_id: "x".into() + }]), + 2 + ); + assert_eq!( + progress_detail(&JobEvent::Log { + message: "internal p_123".into() + }), + None + ); + } +} diff --git a/app/src/discovery.rs b/app/src/discovery.rs new file mode 100644 index 0000000..3db9cf9 --- /dev/null +++ b/app/src/discovery.rs @@ -0,0 +1,549 @@ +//! Search and saved-analysis discovery. State belongs to the app so opening a +//! place does not discard the list that led to it. + +use crate::{encode_path_segment, get_recent_places, search_places, select_place, Icon}; +use domain::{PlaceCandidate, RecentPlace}; +use leptos::prelude::*; +use leptos_router::hooks::{use_location, use_navigate, use_query_map}; + +#[derive(Clone, Copy)] +pub(crate) struct DiscoveryState { + pub draft: RwSignal, + pub search_href: RwSignal, + applied_query: RwSignal, + cached_search: RwSignal)>>, + cached_recent: RwSignal>>, + restore_search: RwSignal, + restore_recent: RwSignal, + reuse_recent: RwSignal, +} + +impl Default for DiscoveryState { + fn default() -> Self { + Self { + draft: RwSignal::new(String::new()), + search_href: RwSignal::new("/".to_string()), + applied_query: RwSignal::new(String::new()), + cached_search: RwSignal::new(None), + cached_recent: RwSignal::new(None), + restore_search: RwSignal::new(false), + restore_recent: RwSignal::new(false), + reuse_recent: RwSignal::new(false), + } + } +} + +impl DiscoveryState { + /// Set the return intent before routing starts; disposal can run after the + /// destination's first effect and is too late as the only signal source. + pub(crate) fn remember_scroll(self, pathname: &str) { + crate::ui_bridge::save_scroll(pathname); + match pathname { + "/" => self.restore_search.set(true), + "/recent" => self.restore_recent.set(true), + _ => {} + } + } + + /// Call when an analysis starts or finishes so returning to its source list + /// does not reuse a snapshot from before the analysis. + pub(crate) fn invalidate_recent(self) { + self.cached_recent.set(None); + } +} + +/// RFC 3986 query component encoding; in particular, nested return URLs must +/// encode their `?`, `&`, `+`, and `=` delimiters instead of becoming parameters. +pub(crate) fn encode_query_component(value: &str) -> String { + use std::fmt::Write; + value.bytes().fold(String::new(), |mut encoded, byte| { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') { + encoded.push(byte as char); + } else { + let _ = write!(encoded, "%{byte:02X}"); + } + encoded + }) +} + +pub(crate) fn search_href(query: &str) -> String { + let query = query.trim(); + if query.is_empty() { + "/".to_string() + } else { + format!("/?q={}", encode_query_component(query)) + } +} + +#[component] +pub(crate) fn HomePage() -> impl IntoView { + let state = expect_context::(); + // An outgoing click sets the app's return intent before native link + // navigation runs. Only the next mounted page may consume that intent. + let (restore_on_entry, set_restore_on_entry) = signal(state.restore_search.get_untracked()); + let params = use_query_map(); + let location = use_location(); + let location_search = location.search; + let pathname = location.pathname; + let initial_query = params + .get_untracked() + .get("q") + .unwrap_or_default() + .trim() + .to_string(); + if state.applied_query.get_untracked() != initial_query { + state.draft.set(initial_query.clone()); + state.applied_query.set(initial_query.clone()); + } + state.search_href.set(search_href(&initial_query)); + // Topbar records the actual position before navigation. Only mark it here: + // saving during disposal can overwrite it after the router scrolls to top. + #[cfg(feature = "hydrate")] + on_cleanup(move || state.restore_search.set(true)); + + let submitted = Memo::new(move |_| { + params + .read() + .get("q") + .unwrap_or_default() + .trim() + .to_string() + }); + let (refresh, set_refresh) = signal(0u32); + let (selecting, set_selecting) = signal(Option::::None); + let (selection_error, set_selection_error) = signal(false); + let (last_selection, set_last_selection) = signal(Option::::None); + let (search_pending, set_search_pending) = signal(false); + let navigate = use_navigate(); + + Effect::new(move |_| { + let query = submitted.get(); + // Do not replace an unsubmitted draft when returning from a place. + if state.applied_query.get_untracked() != query { + state.draft.set(query.clone()); + state.applied_query.set(query.clone()); + } + state.search_href.set(search_href(&query)); + }); + + let search_res = Resource::new( + move || (submitted.get(), refresh.get()), + move |(query, refresh)| async move { + if query.trim().is_empty() { + return Ok(Vec::new()); + } + if refresh == 0 { + if let Some((cached_query, list)) = state.cached_search.get_untracked() { + if cached_query == query { + return Ok(list); + } + } + } + let result = search_places(query.clone()).await; + if let Ok(list) = &result { + state.cached_search.set(Some((query, list.clone()))); + } + result + }, + ); + // The existing API provides up to 50 positively identified analyses. An + // absent ID is intentionally left unlabelled, rather than called "new". + let analyzed_res = Resource::new( + || (), + move |_| async move { + // Refresh these small status summaries on each visit. An analysis + // may have completed while this search route was not mounted. + let result = get_recent_places().await; + if let Ok(list) = &result { + state.cached_recent.set(Some(list.clone())); + } + result + }, + ); + Effect::new(move |_| { + // The ready-status resource is also read inside the results Transition. + // Cached results alone do not mean its DOM has enough height to restore. + if pathname.get() == "/" + && matches!(search_res.get(), Some(Ok(_))) + && analyzed_res.get().is_some() + && !search_pending.get() + && restore_on_entry.get() + { + let search = location_search.get_untracked(); + let destination = if search.is_empty() { + "/".into() + } else { + format!("/?{search}") + }; + crate::ui_bridge::restore_scroll(&destination); + set_restore_on_entry.set(false); + state.restore_search.set(false); + } + }); + + let nav_select = navigate.clone(); + let pick_action = Action::new(move |candidate: &PlaceCandidate| { + let candidate = candidate.clone(); + let nav = nav_select.clone(); + let from = search_href(&submitted.get_untracked()); + async move { + set_selecting.set(Some(candidate.place_id())); + set_last_selection.set(Some(candidate.clone())); + set_selection_error.set(false); + match select_place(candidate, false).await { + Ok((place_id, job)) => { + state.remember_scroll("/"); + let mut href = format!( + "/place/{}?from={}", + encode_path_segment(&place_id), + encode_query_component(&from) + ); + if let Some(job_id) = job { + state.invalidate_recent(); + href.push_str("&job="); + href.push_str(&encode_query_component(&job_id)); + } + nav(&href, Default::default()); + } + Err(_) => { + set_selection_error.set(true); + set_selecting.set(None); + } + } + } + }); + let nav_submit = navigate.clone(); + let submit = move || { + let query = state.draft.get_untracked().trim().to_string(); + if query.is_empty() || selecting.get_untracked().is_some() { + return; + } + state.draft.set(query.clone()); + state.search_href.set(search_href(&query)); + state.restore_search.set(false); + set_selection_error.set(false); + crate::ui_bridge::blur_active(); + if submitted.get_untracked() == query { + set_refresh.update(|tick| *tick += 1); + } else { + set_refresh.set(0); + nav_submit(&search_href(&query), Default::default()); + } + }; + + view! { +
+
+ +
+

"장소 검색"

+

"상호명 또는 주소를 입력하세요."

+
+
+
+ + +
+ "검색 예시" + {["성수 대림창고", "어니언 성수", "블루보틀 성수"].into_iter().map(|query| { + let nav = navigate.clone(); + view! { + + } + }).collect_view()} +
+
+
+
+ +
+ + + +
+ +
+

"검색 결과"

+ + + {move || if search_pending.get() { "검색 중…".to_string() } else { + search_res.get().and_then(Result::ok).map(|list| format!("{}개", list.len())).unwrap_or_default() + }} + + +
+ +

{move || format!("‘{}’ 검색 결과입니다. 변경한 검색어는 검색을 눌러 적용하세요.", submitted.get())}

+
+
+ "장소를 찾는 중…"
+ }> + {move || search_res.get().map(|result| match result { + Ok(list) if list.is_empty() && !submitted.get().trim().is_empty() => view! { +
+

"검색 결과가 없습니다."

+

"지점명이나 도로명 주소로 다시 검색해 주세요."

+
+ }.into_any(), + Ok(list) => view! { +
+ {list.into_iter().map(|candidate| { + let place_id = candidate.place_id(); + let selecting_id = place_id.clone(); + let ready_id = place_id.clone(); + let status_id = place_id.clone(); + let address = if candidate.road_address.is_empty() { candidate.address.clone() } else { candidate.road_address.clone() }; + let aria_name = format!("{} · {} 공간 보기", candidate.name, address); + let for_click = candidate.clone(); + view! { + + } + }).collect_view()} +
+ }.into_any(), + Err(_) => view! { + + }.into_any(), + })} + + +
+ "이용 방법" +
    +
  1. "장소를 검색하고 목록에서 선택합니다."
  2. +
  3. "분석된 공간의 층별 구조와 좌석 배치를 확인합니다."
  4. +
  5. "사진 핀이나 구역을 눌러 해당 사진을 봅니다."
  6. +
+

"사진과 리뷰로 추정한 결과로, 실제 배치와 다를 수 있습니다."

+
+
+ + } +} + +#[component] +pub(crate) fn RecentPlacesPage() -> impl IntoView { + let state = expect_context::(); + let (restore_on_entry, set_restore_on_entry) = signal(state.restore_recent.get_untracked()); + let reuse_on_entry = state.reuse_recent.get_untracked(); + let pathname = use_location().pathname; + #[cfg(feature = "hydrate")] + on_cleanup(move || state.restore_recent.set(true)); + let (refresh, set_refresh) = signal(0u32); + let (pending, set_pending) = signal(false); + let recent_res = Resource::new( + move || refresh.get(), + move |refresh| async move { + // Keep order only for a direct detail round trip. A tab visit must + // refresh the shared list even when its scroll position is restored. + if refresh == 0 && reuse_on_entry { + if let Some(list) = state.cached_recent.get_untracked() { + return Ok(list); + } + } + let result = get_recent_places().await; + if let Ok(list) = &result { + state.cached_recent.set(Some(list.clone())); + } + result + }, + ); + Effect::new(move |_| { + if pathname.get() == "/recent" + && matches!(recent_res.get(), Some(Ok(_))) + && !pending.get() + && restore_on_entry.get() + { + crate::ui_bridge::restore_scroll("/recent"); + set_restore_on_entry.set(false); + state.restore_recent.set(false); + state.reuse_recent.set(false); + } + }); + + view! { +
+
+
+

"분석 완료" + + + {move || recent_res.get().and_then(Result::ok).map(|places| format!(" {}", places.len()))} + + +

+

"공용 목록 · 최근 열어본 순"

+
+ +
+
+ "장소를 불러오는 중…"
+ }> + {move || recent_res.get().map(|result| match result { + Ok(places) if places.is_empty() => view! { +
+

"아직 분석이 완료된 장소가 없습니다."

+

"장소를 검색하고 분석을 마치면 여기에서 다시 볼 수 있습니다."

+ "장소 검색" +
+ }.into_any(), + Ok(places) => { + let count = places.len(); + view! { +
+ {places.into_iter().map(|entry| { + let place = entry.place; + let address = if place.road_address.is_empty() { place.address } else { place.road_address }; + let floor_count = entry.floor_labels.len(); + let analyzed_date = format_analysis_date(&entry.analyzed_at); + let aria_name = format!("{} · {} 공간 보기", place.name, address); + view! { + + + {place.name} + {place.category} + {address} + + {(floor_count > 0).then(|| view! { {format!("추정 {}개 층", floor_count)} })} + {(entry.seat_estimate > 0).then(|| view! { {format!("약 {}석", entry.seat_estimate)} })} + + {analyzed_date.map(|date| view! { {format!("분석 {date}")} })} + + + + } + }).collect_view()} +
+ {(count == 50).then(|| view! {

"최근 50개 장소를 표시합니다."

})} + }.into_any() + }, + Err(_) => view! { + + }.into_any(), + })} + + + + } +} + +/// Display the supplied ISO calendar date without guessing the user's timezone. +/// Invalid/unknown timestamps are omitted rather than shown as a made-up date. +fn format_analysis_date(value: &str) -> Option { + let date = value.get(..10)?; + let bytes = date.as_bytes(); + if bytes[4] != b'-' + || bytes[7] != b'-' + || !bytes + .iter() + .enumerate() + .all(|(i, byte)| i == 4 || i == 7 || byte.is_ascii_digit()) + { + return None; + } + let month = date[5..7].parse::().ok()?; + let day = date[8..10].parse::().ok()?; + if !(1..=12).contains(&month) || !(1..=31).contains(&day) { + return None; + } + Some(date.replace('-', ".")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nested_return_url_encodes_delimiters_and_unicode() { + let search = search_href(" 카페 A&B+점 "); + assert_eq!(search, "/?q=%EC%B9%B4%ED%8E%98%20A%26B%2B%EC%A0%90"); + let from = encode_query_component(&search); + assert!(from.starts_with("%2F%3Fq%3D")); + assert!(!from.contains('&')); + assert!(!from.contains('+')); + assert!(from.contains("%2526")); + assert_eq!(search_href(" "), "/"); + } + + #[test] + fn analysis_dates_handle_short_and_non_ascii_inputs() { + assert_eq!( + format_analysis_date("2026-11-04T09:00:00Z"), + Some("2026.11.04".to_string()) + ); + assert_eq!(format_analysis_date("미확인"), None); + assert_eq!(format_analysis_date("2026-99-12T09:00:00Z"), None); + assert_eq!(format_analysis_date(""), None); + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs new file mode 100644 index 0000000..16c5ffa --- /dev/null +++ b/app/src/lib.rs @@ -0,0 +1,183 @@ +#![recursion_limit = "256"] + +mod detail; +mod discovery; +pub mod scene_bridge; +pub mod ui_bridge; +mod workspace; + +use detail::PlacePage; +use discovery::{DiscoveryState, HomePage, RecentPlacesPage}; +use domain::{PlaceCandidate, PlaceView, RecentPlace}; +use leptos::prelude::*; +use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title}; +use leptos_router::components::{Route, Router, Routes}; +use leptos_router::hooks::use_location; +use leptos_router::path; + +/// HTML shell rendered on the server (`ssr`), including the ES-module import map for Three.js. +pub fn shell(options: LeptosOptions) -> impl IntoView { + let import_map = r#"{ + "imports": { + "three": "/vendor/three/three.module.js", + "three/addons/controls/OrbitControls.js": "/vendor/three/OrbitControls.js" + } + }"#; + view! { + + + + + + + + + + + + + + + + } +} + +// ============================================================================ +// Server Functions +// ============================================================================ + +#[cfg(feature = "ssr")] +fn pipeline_ctx() -> Result { + use_context::() + .ok_or_else(|| ServerFnError::new("Pipeline context missing")) +} + +#[server(SearchPlaces, "/api")] +pub async fn search_places(query: String) -> Result, ServerFnError> { + let pl = pipeline_ctx()?; + pl.search_places(&query) + .await + .map_err(|e| ServerFnError::new(e.to_string())) +} + +#[server(SelectPlace, "/api")] +pub async fn select_place( + candidate: PlaceCandidate, + force: bool, +) -> Result<(String, Option), ServerFnError> { + let pl = pipeline_ctx()?; + pl.select_or_analyze(candidate, force) + .await + .map_err(|e| ServerFnError::new(e.to_string())) +} + +#[server(GetPlaceView, "/api")] +pub async fn get_place_view(place_id: String) -> Result, ServerFnError> { + let pl = pipeline_ctx()?; + pl.get_place_view(&place_id) + .await + .map_err(|e| ServerFnError::new(e.to_string())) +} + +#[server(TriggerReanalyze, "/api")] +pub async fn trigger_reanalyze(place_id: String) -> Result { + let pl = pipeline_ctx()?; + pl.reanalyze(&place_id) + .await + .map_err(|e| ServerFnError::new(e.to_string())) +} + +#[server(GetRecentPlaces, "/api")] +pub async fn get_recent_places() -> Result, ServerFnError> { + pipeline_ctx()? + .recent_places() + .await + .map_err(|e| ServerFnError::new(e.to_string())) +} + +// ============================================================================ +// Root App & Router +// ============================================================================ + +#[component] +pub fn App() -> impl IntoView { + provide_meta_context(); + provide_context(DiscoveryState::default()); + + view! { + + + <Router> + <div class="app-shell"> + <Topbar/> + <main class="main-body" id="main-content"> + <Routes fallback=|| view! { <div class="empty-box">"페이지를 찾을 수 없습니다."</div> }> + <Route path=path!("") view=HomePage/> + <Route path=path!("/recent") view=RecentPlacesPage/> + <Route path=path!("/place/:id") view=PlacePage/> + </Routes> + </main> + </div> + </Router> + } +} + +#[component] +fn Topbar() -> impl IntoView { + let pathname = use_location().pathname; + let state = expect_context::<DiscoveryState>(); + view! { + <a class="skip-link" href="#main-content">"본문으로 이동"</a> + <Show when=move || !pathname.get().starts_with("/place/")> + <header class="topbar"> + <a href=move || state.search_href.get() class="brand" aria-label="Make-Space 장소 검색" on:click=move |_| state.remember_scroll(&pathname.get())> + <span class="brand-mark"><Icon name="cube"/></span> + <span class="brand-title">"Make-Space"</span> + </a> + <nav class="topbar-nav" aria-label="주 메뉴"> + <a href=move || state.search_href.get() on:click=move |_| state.remember_scroll(&pathname.get()) aria-current=move || (pathname.get() == "/").then_some("page")>"검색"</a> + <a href="/recent" on:click=move |_| state.remember_scroll(&pathname.get()) aria-current=move || (pathname.get() == "/recent").then_some("page")>"분석 완료"</a> + </nav> + </header> + </Show> + } +} + +#[component] +fn Icon(name: &'static str) -> impl IntoView { + let path = match name { + "search" => "M21 21l-4.4-4.4M19 10.5a8.5 8.5 0 1 1-17 0 8.5 8.5 0 0 1 17 0", + "cube" => "m12 3 9 5v9l-9 5-9-5V8l9-5Zm0 10 9-5M12 13 3 8m9 5v9M7.5 5.5l9 5", + "layers" => "m12 3 10 5-10 5L2 8l10-5ZM2 12l10 5 10-5M2 16l10 5 10-5", + "info" => "M12 11v6m0-10v.01M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0", + "back" => "M20 12H4m6-6-6 6 6 6", + "photo" => "M4 3h16a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1ZM3 16l5-5 4 4 4-6 5 7M8 7h.01", + "refresh" => "M20 7v5h-5M4 17v-5h5M5.3 7a8 8 0 0 1 13.2-1L20 9M4 15l1.5 3A8 8 0 0 0 18.7 17", + "close" => "m6 6 12 12M6 18 18 6", + "more" => "M5 12h.01M12 12h.01M19 12h.01", + "copy" => "M9 9h12v12H9zM15 9V3H3v12h6", + "external" => "M14 3h7v7m0-7L10 14M10 3H3v18h18v-7", + "chevron" => "m9 6 6 6-6 6", + "expand" => "M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5", + "plus" => "M12 5v14M5 12h14", + "minus" => "M5 12h14", + _ => "M5 12l4 4L19 6", + }; + view! { + <svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d=path/> + </svg> + } +} + +fn encode_path_segment(value: &str) -> String { + value.bytes().fold(String::new(), |mut encoded, byte| { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~' | b':') { + encoded.push(byte as char); + } else { + use std::fmt::Write; + let _ = write!(encoded, "%{byte:02X}"); + } + encoded + }) +} diff --git a/app/src/scene_bridge.rs b/app/src/scene_bridge.rs new file mode 100644 index 0000000..437df4a --- /dev/null +++ b/app/src/scene_bridge.rs @@ -0,0 +1,274 @@ +//! Browser-only bridges (`hydrate` feature): +//! 1. `wasm-bindgen` bindings to `/js/scene.js` (Three.js renderer) +//! 2. `EventSource` SSE subscriber for `/api/jobs/:id/events` +//! +//! JS closures and `EventSource` objects are kept in a `thread_local!` table and referenced by `u32` +//! so handles are `Copy + Send + Sync` and work directly with Leptos `on_cleanup`. + +use domain::JobEvent; + +#[cfg(feature = "hydrate")] +mod imp { + use super::*; + use std::cell::{Cell, RefCell}; + use std::collections::HashMap; + use std::rc::Rc; + use wasm_bindgen::closure::Closure; + use wasm_bindgen::prelude::*; + use wasm_bindgen::JsCast; + + #[wasm_bindgen(module = "/js/scene.js")] + extern "C" { + #[wasm_bindgen(catch, js_name = mountScene)] + fn js_mount_scene( + canvas: &web_sys::HtmlCanvasElement, + layout_json: &str, + on_zone_select: &js_sys::Function, + ) -> Result<u32, JsValue>; + + #[wasm_bindgen(js_name = setFloor)] + fn js_set_floor(handle: u32, level: i32); + + #[wasm_bindgen(js_name = setViewMode)] + fn js_set_view_mode(handle: u32, mode: &str); + + #[wasm_bindgen(js_name = resetScene)] + fn js_reset_scene(handle: u32); + + #[wasm_bindgen(js_name = zoomScene)] + fn js_zoom_scene(handle: u32, delta: f64); + + #[wasm_bindgen(js_name = highlightZone)] + fn js_highlight_zone(handle: u32, label: &str, photo_ids_json: &str); + + #[wasm_bindgen(js_name = disposeScene)] + fn js_dispose_scene(handle: u32); + } + + struct SseEntry { + es: web_sys::EventSource, + _on_msg: Closure<dyn FnMut(web_sys::MessageEvent)>, + _on_error: Closure<dyn FnMut(web_sys::Event)>, + } + + struct SceneWatch { + canvas: web_sys::HtmlCanvasElement, + callback: Closure<dyn FnMut(web_sys::Event)>, + } + + thread_local! { + static SCENE_CBS: RefCell<HashMap<u32, Closure<dyn FnMut(String, String)>>> = RefCell::new(HashMap::new()); + static SSE_MAP: RefCell<HashMap<u32, SseEntry>> = RefCell::new(HashMap::new()); + static NEXT_SSE_ID: RefCell<u32> = const { RefCell::new(1) }; + static SCENE_WATCHES: RefCell<HashMap<u32, SceneWatch>> = RefCell::new(HashMap::new()); + static NEXT_WATCH_ID: Cell<u32> = const { Cell::new(1) }; + } + + pub fn mount_scene( + canvas: web_sys::HtmlCanvasElement, + layout_json: &str, + mut on_select: impl FnMut(String, Vec<String>) + 'static, + ) -> u32 { + let cb = Closure::wrap(Box::new(move |label: String, ids_json: String| { + let ids: Vec<String> = serde_json::from_str(&ids_json).unwrap_or_default(); + on_select(label, ids); + }) as Box<dyn FnMut(String, String)>); + let id = js_mount_scene(&canvas, layout_json, cb.as_ref().unchecked_ref()).unwrap_or(0); + if id != 0 { + SCENE_CBS.with(|m| { + m.borrow_mut().insert(id, cb); + }); + } + id + } + + pub fn set_floor(handle: u32, level: i32) { + js_set_floor(handle, level); + } + + pub fn set_view_mode(handle: u32, mode: &str) { + js_set_view_mode(handle, mode); + } + + pub fn reset_scene(handle: u32) { + js_reset_scene(handle); + } + + /// Positive deltas zoom in; negative deltas zoom out. + pub fn zoom_scene(handle: u32, delta: f64) { + js_zoom_scene(handle, delta); + } + + pub fn highlight_zone(handle: u32, label: &str, photo_ids: &[String]) { + let ids_json = serde_json::to_string(photo_ids).unwrap_or_else(|_| "[]".to_string()); + js_highlight_zone(handle, label, &ids_json); + } + + /// Observe initial mount failures and later context loss without replacing the canvas. + pub fn watch_scene( + canvas: web_sys::HtmlCanvasElement, + mut on_state: impl FnMut(Option<String>) + 'static, + ) -> Option<u32> { + let read_error = |canvas: &web_sys::HtmlCanvasElement| { + canvas + .get_attribute("data-scene-error") + .filter(|message| !message.is_empty()) + }; + on_state(read_error(&canvas)); + let observed_canvas = canvas.clone(); + let callback = Closure::wrap(Box::new(move |_: web_sys::Event| { + on_state(read_error(&observed_canvas)); + }) as Box<dyn FnMut(web_sys::Event)>); + canvas + .add_event_listener_with_callback("scene-error", callback.as_ref().unchecked_ref()) + .ok()?; + if canvas + .add_event_listener_with_callback("scene-ready", callback.as_ref().unchecked_ref()) + .is_err() + { + let _ = canvas.remove_event_listener_with_callback( + "scene-error", + callback.as_ref().unchecked_ref(), + ); + return None; + } + let id = NEXT_WATCH_ID.with(|next| { + let id = next.get(); + next.set(id + 1); + id + }); + SCENE_WATCHES.with(|watches| { + watches + .borrow_mut() + .insert(id, SceneWatch { canvas, callback }); + }); + Some(id) + } + + pub fn unwatch_scene(id: u32) { + SCENE_WATCHES.with(|watches| { + if let Some(watch) = watches.borrow_mut().remove(&id) { + let _ = watch.canvas.remove_event_listener_with_callback( + "scene-error", + watch.callback.as_ref().unchecked_ref(), + ); + let _ = watch.canvas.remove_event_listener_with_callback( + "scene-ready", + watch.callback.as_ref().unchecked_ref(), + ); + } + }); + } + + pub fn dispose_scene(handle: u32) { + js_dispose_scene(handle); + SCENE_CBS.with(|m| { + m.borrow_mut().remove(&handle); + }); + } + + pub fn subscribe_job_events( + job_id: &str, + mut on_event: impl FnMut(JobEvent) + 'static, + ) -> Option<u32> { + let url = format!("/api/jobs/{job_id}/events"); + let es = match web_sys::EventSource::new(&url) { + Ok(es) => es, + Err(_) => { + on_event(JobEvent::Error { + message: + "분석 진행 상태에 연결할 수 없습니다. 연결을 확인하고 다시 시도해 주세요." + .to_string(), + }); + return None; + } + }; + let on_event = Rc::new(RefCell::new(on_event)); + let failures = Rc::new(Cell::new(0_u8)); + let terminal = Rc::new(Cell::new(false)); + let es_clone = es.clone(); + let message_callback = on_event.clone(); + let message_failures = failures.clone(); + let message_terminal = terminal.clone(); + let on_msg = Closure::wrap(Box::new(move |e: web_sys::MessageEvent| { + if message_terminal.get() { + return; + } + if let Some(txt) = e.data().as_string() { + if let Ok(ev) = serde_json::from_str::<JobEvent>(&txt) { + message_failures.set(0); + let done = ev.is_terminal(); + if done { + message_terminal.set(true); + es_clone.set_onmessage(None); + es_clone.set_onerror(None); + es_clone.close(); + } + (message_callback.borrow_mut())(ev); + } + } + }) as Box<dyn FnMut(web_sys::MessageEvent)>); + let error_es = es.clone(); + let on_error = Closure::wrap(Box::new(move |_: web_sys::Event| { + if terminal.get() { + return; + } + failures.set(failures.get().saturating_add(1)); + // EventSource handles a short transient disconnect itself. Bound reconnect attempts + // so a permanently unavailable stream cannot leave the UI in a loading state. + if error_es.ready_state() == web_sys::EventSource::CLOSED || failures.get() >= 4 { + terminal.set(true); + error_es.set_onmessage(None); + error_es.set_onerror(None); + error_es.close(); + (on_event.borrow_mut())(JobEvent::Error { + message: "분석 상태 연결이 끊겼습니다. 잠시 후 결과를 새로고침해 주세요." + .to_string(), + }); + } + }) as Box<dyn FnMut(web_sys::Event)>); + es.set_onmessage(Some(on_msg.as_ref().unchecked_ref())); + es.set_onerror(Some(on_error.as_ref().unchecked_ref())); + let id = NEXT_SSE_ID.with(|n| { + let mut b = n.borrow_mut(); + let v = *b; + *b += 1; + v + }); + SSE_MAP.with(|m| { + m.borrow_mut().insert( + id, + SseEntry { + es, + _on_msg: on_msg, + _on_error: on_error, + }, + ); + }); + Some(id) + } + + pub fn close_job_events(id: u32) { + SSE_MAP.with(|m| { + if let Some(entry) = m.borrow_mut().remove(&id) { + entry.es.set_onmessage(None); + entry.es.set_onerror(None); + entry.es.close(); + } + }); + } +} + +#[cfg(feature = "hydrate")] +pub use imp::*; + +#[cfg(not(feature = "hydrate"))] +pub fn subscribe_job_events( + _job_id: &str, + _on_event: impl FnMut(JobEvent) + 'static, +) -> Option<u32> { + None +} + +#[cfg(not(feature = "hydrate"))] +pub fn close_job_events(_id: u32) {} diff --git a/app/src/ui_bridge.rs b/app/src/ui_bridge.rs new file mode 100644 index 0000000..71b5d81 --- /dev/null +++ b/app/src/ui_bridge.rs @@ -0,0 +1,124 @@ +//! UI-only browser operations; SSR uses inert counterparts. +#[cfg(feature = "hydrate")] +mod imp { + use std::{cell::RefCell, collections::HashMap}; + use wasm_bindgen::{closure::Closure, prelude::*, JsCast}; + + #[wasm_bindgen(module = "/js/ui.js")] + extern "C" { + #[wasm_bindgen(js_name = saveScroll)] + fn js_save_scroll(key: &str); + #[wasm_bindgen(js_name = restoreScroll)] + fn js_restore_scroll(key: &str); + #[wasm_bindgen(js_name = focusSearch)] + fn js_focus_search(); + #[wasm_bindgen(js_name = blurActive)] + fn js_blur_active(); + #[wasm_bindgen(js_name = closeMenu)] + fn js_close_menu(id: &str); + #[wasm_bindgen(js_name = clearJobQuery)] + fn js_clear_job_query(); + #[wasm_bindgen(js_name = revealSelectedPhoto)] + fn js_reveal_selected_photo(); + #[wasm_bindgen(js_name = isCompact)] + fn js_is_compact() -> bool; + #[wasm_bindgen(js_name = watchCompact)] + fn js_watch_compact(callback: &js_sys::Function) -> u32; + #[wasm_bindgen(js_name = releaseWatch)] + fn js_release_watch(handle: u32); + #[wasm_bindgen(js_name = openDialog)] + fn js_open_dialog(id: &str, callback: &js_sys::Function) -> u32; + #[wasm_bindgen(js_name = closeDialog)] + fn js_close_dialog(id: &str); + #[wasm_bindgen(js_name = releaseDialog)] + fn js_release_dialog(handle: u32); + #[wasm_bindgen(js_name = copyText)] + fn js_copy_text(value: &str, callback: &js_sys::Function); + } + thread_local! { + static DIALOG_CALLBACKS: RefCell<HashMap<u32, Closure<dyn FnMut()>>> = RefCell::new(HashMap::new()); + static WATCH_CALLBACKS: RefCell<HashMap<u32, Closure<dyn FnMut(bool)>>> = RefCell::new(HashMap::new()); + } + pub fn save_scroll(key: &str) { + js_save_scroll(key); + } + pub fn restore_scroll(key: &str) { + js_restore_scroll(key); + } + pub fn focus_search() { + js_focus_search(); + } + pub fn blur_active() { + js_blur_active(); + } + pub fn close_menu(id: &str) { + js_close_menu(id); + } + pub fn clear_job_query() { + js_clear_job_query(); + } + pub fn reveal_selected_photo() { + js_reveal_selected_photo(); + } + pub fn is_compact() -> bool { + js_is_compact() + } + pub fn watch_compact(callback: impl FnMut(bool) + 'static) -> Option<u32> { + let cb = Closure::wrap(Box::new(callback) as Box<dyn FnMut(bool)>); + let id = js_watch_compact(cb.as_ref().unchecked_ref()); + WATCH_CALLBACKS.with(|map| map.borrow_mut().insert(id, cb)); + Some(id) + } + pub fn release_watch(handle: u32) { + js_release_watch(handle); + WATCH_CALLBACKS.with(|map| map.borrow_mut().remove(&handle)); + } + pub fn open_dialog(id: &str, callback: impl FnMut() + 'static) -> Option<u32> { + let cb = Closure::wrap(Box::new(callback) as Box<dyn FnMut()>); + let handle = js_open_dialog(id, cb.as_ref().unchecked_ref()); + if handle == 0 { + return None; + } + DIALOG_CALLBACKS.with(|map| map.borrow_mut().insert(handle, cb)); + Some(handle) + } + pub fn close_dialog(id: &str) { + js_close_dialog(id); + } + pub fn release_dialog(handle: u32) { + js_release_dialog(handle); + DIALOG_CALLBACKS.with(|map| map.borrow_mut().remove(&handle)); + } + pub fn copy_text(value: &str, callback: impl FnOnce(bool) + 'static) { + let cb = Closure::once_into_js(callback); + js_copy_text(value, cb.unchecked_ref()); + } +} +#[cfg(feature = "hydrate")] +pub use imp::*; + +#[cfg(not(feature = "hydrate"))] +mod imp_ssr { + pub fn save_scroll(_: &str) {} + pub fn restore_scroll(_: &str) {} + pub fn focus_search() {} + pub fn blur_active() {} + pub fn close_menu(_: &str) {} + pub fn clear_job_query() {} + pub fn reveal_selected_photo() {} + pub fn is_compact() -> bool { + false + } + pub fn watch_compact(_: impl FnMut(bool) + 'static) -> Option<u32> { + None + } + pub fn release_watch(_: u32) {} + pub fn open_dialog(_: &str, _: impl FnMut() + 'static) -> Option<u32> { + None + } + pub fn close_dialog(_: &str) {} + pub fn release_dialog(_: u32) {} + pub fn copy_text(_: &str, _: impl FnOnce(bool) + 'static) {} +} +#[cfg(not(feature = "hydrate"))] +pub use imp_ssr::*; diff --git a/app/src/workspace.rs b/app/src/workspace.rs new file mode 100644 index 0000000..d4ee521 --- /dev/null +++ b/app/src/workspace.rs @@ -0,0 +1,849 @@ +//! The responsive place workspace keeps the scene and its selection mounted across widths. + +use crate::Icon; +#[cfg(feature = "hydrate")] +use crate::{scene_bridge, ui_bridge}; +use domain::{Floor, Layout, PhotoKind, PhotoSummary, Tri, ROOFTOP_LEVEL}; +use leptos::prelude::*; + +#[derive(Clone, Debug)] +struct PhotoSelection { + title: String, + photos: Vec<PhotoSummary>, + zone: Option<(i32, String)>, +} + +fn short_floor_label(floor: &Floor) -> String { + let base = match floor.level { + ROOFTOP_LEVEL => "옥상".to_string(), + n if n < 0 => format!("B{}", n.unsigned_abs()), + 0 => "층 미확인".to_string(), + n => format!("{n}층"), + }; + if floor_is_uncertain(floor) { + format!("{base}(추정)") + } else { + base + } +} + +fn floor_is_uncertain(floor: &Floor) -> bool { + let uncertain = |text: &str| { + [ + "임시", + "추정", + "미확인", + "확인되지", + "확인 안", + "불명", + "가정", + "가능성", + "알 수 없", + "증거 없", + ] + .iter() + .any(|word| text.contains(word)) + }; + if uncertain(&floor.label) { + return true; + } + floor.notes.split(['.', '。', '\n', ';']).any(|sentence| { + // Uncertain window positions or room dimensions do not make the floor number uncertain. + let floor_assignment = sentence.contains('층') + && [ + "촬영", + "배정", + "층수", + "층 위치", + "층 정보", + "어느 층", + "실제 층", + "층인지", + "상층", + ] + .iter() + .any(|word| sentence.contains(word)); + floor_assignment && uncertain(sentence) + }) +} + +/// Replace implementation IDs without removing the surrounding evidence or warnings. +fn readable_evidence(text: &str, photos: &[PhotoSummary]) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while !rest.is_empty() { + if rest.starts_with("p_") { + let end = rest + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-')) + .unwrap_or(rest.len()); + let token = &rest[..end]; + if token.len() > 2 { + if let Some(photo) = photos.iter().find(|p| p.id == token) { + out.push_str(&format!("{} 참고 사진", photo.source.label())); + } else { + out.push_str("참고 사진"); + } + rest = &rest[end..]; + continue; + } + } + let ch = rest.chars().next().expect("nonempty text"); + out.push(ch); + rest = &rest[ch.len_utf8()..]; + } + out +} + +fn unique_text(items: Vec<String>, photos: &[PhotoSummary]) -> Vec<String> { + let mut seen = std::collections::HashSet::new(); + items + .into_iter() + .map(|s| readable_evidence(s.trim(), photos)) + .filter(|s| !s.is_empty()) + .filter(|s| { + let key: String = s + .chars() + .filter(|c| !c.is_whitespace() && !matches!(c, '·' | ',' | '.' | '-')) + .flat_map(char::to_lowercase) + .collect(); + seen.insert(key) + }) + .collect() +} + +fn brief(text: &str, max: usize) -> String { + if text.chars().count() <= max { + text.to_string() + } else { + format!("{}…", text.chars().take(max).collect::<String>().trim_end()) + } +} + +fn photo_caption(photo: &PhotoSummary) -> String { + if !photo.description.trim().is_empty() { + photo.description.clone() + } else if !photo.caption.trim().is_empty() { + photo.caption.clone() + } else { + match photo.kind { + Some(PhotoKind::Exterior) => "건물 외관 사진".to_string(), + Some(PhotoKind::Interior) => "공간 내부 사진".to_string(), + _ => "공간 확인에 사용된 사진".to_string(), + } + } +} + +fn source_url(photo: &PhotoSummary) -> Option<String> { + (photo.page_url.starts_with("https://") || photo.page_url.starts_with("http://")) + .then(|| photo.page_url.clone()) +} + +fn accessibility_label(value: Tri) -> &'static str { + match value { + Tri::Unknown => "미확인", + Tri::Likely => "있을 가능성 · 확인 필요", + Tri::Yes => "있음", + Tri::No => "없음", + } +} + +#[component] +fn PhotoImage( + photo: PhotoSummary, + #[prop(default = "lazy")] loading: &'static str, +) -> impl IntoView { + let (failed, set_failed) = signal(false); + let alt = brief(&photo_caption(&photo), 120); + view! { + <div class="image-shell"> + <img + src=format!("/api/photos/{}", photo.id) + alt=alt + loading=loading + decoding="async" + hidden=move || failed.get() + on:error=move |_| set_failed.set(true) + /> + <span class="image-fallback" hidden=move || !failed.get()> + <Icon name="photo"/>"사진을 불러오지 못했습니다." + </span> + </div> + } +} + +#[component] +fn PhotoCaption(photo: PhotoSummary) -> impl IntoView { + let caption = photo_caption(&photo); + let has_more = caption.chars().count() > 90; + view! { + <div class="photo-caption"> + <p>{brief(&caption, 90)}</p> + {has_more.then(|| view! { + <details class="photo-description"> + <summary>"설명 더 보기"</summary> + <p>{caption}</p> + </details> + })} + {match source_url(&photo) { + Some(url) => view! { + <a class="photo-source" href=url target="_blank" rel="noopener noreferrer"> + {format!("원문 보기 · {}", photo.source.label())} + <span class="sr-only">" (새 탭)"</span> + </a> + }.into_any(), + None => view! { <span class="photo-source">{photo.source.label()}</span> }.into_any(), + }} + </div> + } +} + +#[component] +pub(crate) fn WorkspaceView(layout: Layout, photos: Vec<PhotoSummary>) -> impl IntoView { + let (active_floor, set_active_floor) = signal(0i32); + let (view_mode, set_view_mode) = signal("iso"); + let (mobile_panel, set_mobile_panel) = signal("layout"); + let (scene_interactive, set_scene_interactive) = signal(false); + let (scene_error, set_scene_error) = signal(Option::<String>::None); + let (scene_retry, set_scene_retry) = signal(0u32); + let (scene_fullscreen, set_scene_fullscreen) = signal(false); + let (selection, set_selection) = signal(Option::<PhotoSelection>::None); + let (photo_index, set_photo_index) = signal(0usize); + let (photo_open, set_photo_open) = signal(false); + let canvas_ref = NodeRef::<leptos::html::Canvas>::new(); + + let clean_photos = photos + .iter() + .cloned() + .map(|mut p| { + p.description = readable_evidence(&p.description, &photos); + p.caption = readable_evidence(&p.caption, &photos); + p + }) + .collect::<Vec<_>>(); + let photo_store = StoredValue::new(clean_photos.clone()); + let floor_store = StoredValue::new(layout.floors.clone()); + let interior_photos = clean_photos + .iter() + .filter(|p| { + matches!( + p.kind, + Some(PhotoKind::Interior | PhotoKind::Exterior) | None + ) + }) + .cloned() + .collect::<Vec<_>>(); + let gallery_store = StoredValue::new(interior_photos.clone()); + + let choose_zone = Callback::new(move |(level, label, ids): (i32, String, Vec<String>)| { + let photos = photo_store.with_value(|all| { + all.iter() + .filter(|p| ids.contains(&p.id)) + .cloned() + .collect::<Vec<_>>() + }); + set_selection.set(Some(PhotoSelection { + title: label.clone(), + photos, + zone: Some((level, label)), + })); + set_photo_index.set(0); + #[cfg(feature = "hydrate")] + { + if ui_bridge::is_compact() || scene_fullscreen.get_untracked() { + set_photo_open.set(true); + } else { + ui_bridge::reveal_selected_photo(); + } + } + }); + + let choose_floor = Callback::new(move |level: i32| { + set_active_floor.set(level); + let keep = selection.with_untracked(|current| { + current + .as_ref() + .and_then(|s| s.zone.as_ref()) + .is_none_or(|(selected_level, _)| level == 0 || *selected_level == level) + }); + if !keep { + set_selection.set(None); + set_photo_open.set(false); + } + }); + + let show_gallery = Callback::new(move |index: usize| { + set_selection.set(Some(PhotoSelection { + title: "공간 사진".into(), + photos: gallery_store.get_value(), + zone: None, + })); + set_photo_index.set(index); + set_photo_open.set(true); + }); + + #[cfg(feature = "hydrate")] + let (scene_id, set_scene_id) = signal(Option::<u32>::None); + #[cfg(feature = "hydrate")] + { + let layout_json = serde_json::to_string(&layout).unwrap_or_default(); + Effect::new(move |_| { + let _ = scene_retry.get(); + let Some(canvas) = canvas_ref.get() else { + return; + }; + set_scene_error.set(None); + let id = scene_bridge::mount_scene(canvas.clone(), &layout_json, move |label, ids| { + let level = floor_store.with_value(|floors| { + floors + .iter() + .filter(|f| { + active_floor.get_untracked() == 0 + || f.level == active_floor.get_untracked() + }) + .find(|f| { + f.zones + .iter() + .any(|z| z.label == label && z.evidence_photos == ids) + }) + .or_else(|| { + floors + .iter() + .find(|f| f.zones.iter().any(|z| z.label == label)) + }) + .map_or(0, |f| f.level) + }); + choose_zone.run((level, label, ids)); + }); + if id == 0 { + set_scene_error.set(Some("공간 화면을 불러오지 못했습니다.".into())); + set_scene_id.set(None); + } else { + set_scene_id.set(Some(id)); + // These are untracked so changing a control does not recreate the renderer. + scene_bridge::set_floor(id, active_floor.get_untracked()); + scene_bridge::set_view_mode(id, view_mode.get_untracked()); + } + let watch = scene_bridge::watch_scene(canvas, move |error| set_scene_error.set(error)); + on_cleanup(move || { + if let Some(watch) = watch { + scene_bridge::unwatch_scene(watch); + } + if id != 0 { + scene_bridge::dispose_scene(id); + } + }); + }); + Effect::new(move |_| { + let level = active_floor.get(); + if let Some(id) = scene_id.get() { + scene_bridge::set_floor(id, level); + } + }); + Effect::new(move |_| { + let mode = view_mode.get(); + if let Some(id) = scene_id.get() { + scene_bridge::set_view_mode(id, mode); + } + }); + Effect::new(move |_| { + let current = selection.get(); + if let Some(id) = scene_id.get() { + if let Some(s) = current.filter(|s| s.zone.is_some()) { + let ids = s.photos.iter().map(|p| p.id.clone()).collect::<Vec<_>>(); + scene_bridge::highlight_zone(id, &s.title, &ids); + } else { + scene_bridge::highlight_zone(id, "", &[]); + } + } + }); + + let photo_handle = StoredValue::new(None::<u32>); + Effect::new(move |_| { + if photo_open.get() { + if photo_handle.get_value().is_none() { + let handle = ui_bridge::open_dialog("space-photo-dialog", move || { + set_photo_open.set(false) + }); + photo_handle.set_value(handle); + } + } else if let Some(handle) = photo_handle.get_value() { + ui_bridge::close_dialog("space-photo-dialog"); + ui_bridge::release_dialog(handle); + photo_handle.set_value(None); + } + }); + let scene_handle = StoredValue::new(None::<u32>); + Effect::new(move |_| { + if scene_fullscreen.get() { + if scene_handle.get_value().is_none() { + let handle = ui_bridge::open_dialog("space-scene-dialog", move || { + set_scene_fullscreen.set(false) + }); + scene_handle.set_value(handle); + } + } else if let Some(handle) = scene_handle.get_value() { + ui_bridge::close_dialog("space-scene-dialog"); + ui_bridge::release_dialog(handle); + scene_handle.set_value(None); + } + }); + let resize_watch = ui_bridge::watch_compact(move |compact| { + if !compact + && !scene_fullscreen.get_untracked() + && selection.with_untracked(|s| s.as_ref().is_some_and(|s| s.zone.is_some())) + { + set_photo_open.set(false); + } + }); + on_cleanup(move || { + if let Some(handle) = photo_handle.get_value() { + ui_bridge::release_dialog(handle); + } + if let Some(handle) = scene_handle.get_value() { + ui_bridge::release_dialog(handle); + } + if let Some(handle) = resize_watch { + ui_bridge::release_watch(handle); + } + }); + } + #[cfg(not(feature = "hydrate"))] + let _ = ( + scene_retry, + set_scene_error, + photo_open, + scene_fullscreen, + floor_store, + ); + + let floors_for_tabs = layout.floors.clone(); + let floors_for_notes = layout.floors.clone(); + let many_floors = floors_for_tabs.len() > 4; + let caveats = unique_text(layout.summary.caveats.clone(), &photos); + let all_evidence = format!( + "{} {}", + caveats.join(" "), + layout + .floors + .iter() + .map(|f| f.notes.as_str()) + .collect::<Vec<_>>() + .join(" ") + ); + let uncertain_branch = [ + "다른 지점", + "타 지점", + "타지점", + "지점 혼", + "지점 불일치", + "지점이 불명", + ] + .iter() + .any(|s| all_evidence.contains(s)); + let uncertain_floor = layout.floors.iter().any(floor_is_uncertain); + let warning = match (uncertain_branch, uncertain_floor) { + (true, true) => "층·지점 정보 확인 필요 · 추정 배치", + (true, false) => "지점 정보 확인 필요 · 추정 배치", + (false, true) => "층 정보 확인 필요 · 추정 배치", + (false, false) => "사진·리뷰로 추정한 배치", + }; + let seat_types = unique_text(layout.summary.seat_types.clone(), &photos); + let highlights = unique_text(layout.summary.highlights.clone(), &photos); + let more_highlights = highlights.iter().skip(3).cloned().collect::<Vec<_>>(); + let brief_highlights = highlights.iter().take(3).cloned().collect::<Vec<_>>(); + let floor_count = layout.floors.len(); + let floor_summary = layout + .floors + .iter() + .map(short_floor_label) + .collect::<Vec<_>>() + .join(" · "); + let confidence = if layout.confidence.is_finite() { + format!( + "분석 모델이 보고한 신뢰도 {:.0}%", + layout.confidence.clamp(0.0, 1.0) * 100.0 + ) + } else { + "분석 모델 신뢰도 미제공".into() + }; + let gallery_total = interior_photos.len(); + + view! { + <div class="workspace-switcher" role="group" aria-label="공간 보기"> + <button type="button" aria-controls="layout-panel" + aria-pressed=move || (mobile_panel.get() == "layout").to_string() + on:click=move |_| set_mobile_panel.set("layout")>"공간 배치"</button> + <button type="button" aria-controls="info-panel" + aria-pressed=move || (mobile_panel.get() == "info").to_string() + on:click=move |_| { set_mobile_panel.set("info"); set_scene_interactive.set(false); }>"공간 정보"</button> + </div> + <p class="workspace-warning"><Icon name="info"/>{warning}</p> + <div class="workspace-grid" data-mobile-panel=move || mobile_panel.get()> + <section class="viewport-col" id="layout-panel" aria-label="공간 배치"> + <div class="viewport-toolbar"> + {if many_floors { + view! { + <label class="floor-select-label"><span class="sr-only">"표시할 층"</span> + <select class="floor-select" prop:value=move || active_floor.get().to_string() + on:change=move |ev| choose_floor.run(event_target_value(&ev).parse().unwrap_or(0))> + <option value="0">"전체 층"</option> + {floors_for_tabs.iter().map(|f| view! { + <option value=f.level.to_string()>{short_floor_label(f)}</option> + }).collect_view()} + </select> + </label> + }.into_any() + } else { + view! { + <div class="floor-tabs" role="group" aria-label="표시할 층"> + <button type="button" class="tab" aria-pressed=move || (active_floor.get() == 0).to_string() + on:click=move |_| choose_floor.run(0)>"전체"</button> + {floors_for_tabs.iter().map(|f| { + let level = f.level; + view! { + <button type="button" class="tab" aria-pressed=move || (active_floor.get() == level).to_string() + on:click=move |_| choose_floor.run(level)>{short_floor_label(f)}</button> + } + }).collect_view()} + </div> + }.into_any() + }} + <div class="view-modes" role="group" aria-label="보기 방식"> + <button type="button" class="tab" aria-pressed=move || (view_mode.get() == "iso").to_string() + on:click=move |_| set_view_mode.set("iso")>"3D"</button> + <button type="button" class="tab" aria-pressed=move || (view_mode.get() == "plan").to_string() + on:click=move |_| set_view_mode.set("plan")>"평면도"</button> + </div> + </div> + + <dialog id="space-scene-dialog" class="scene-dialog" open data-inline-dialog="true" + role=move || if scene_fullscreen.get() { "dialog" } else { "region" } + aria-label="공간 배치 화면"> + <div class="scene-dialog-header" hidden=move || !scene_fullscreen.get()> + <strong>{move || if view_mode.get() == "plan" { "평면도" } else { "3D 공간" }}</strong> + <button type="button" class="btn-close" on:click=move |_| set_scene_fullscreen.set(false)>"전체 화면 닫기"<Icon name="close"/></button> + </div> + <div class="canvas-holder" data-scene-failed=move || scene_error.get().is_some().to_string()> + <canvas node_ref=canvas_ref class="scene-canvas" + data-interactive=move || scene_interactive.get().to_string() + aria-label=move || if view_mode.get() == "plan" { + "층별 평면도. 아래 구역 버튼에서도 사진을 확인할 수 있습니다." + } else { + "층별 3D 공간. 아래 구역 버튼에서도 사진을 확인할 수 있습니다." + }></canvas> + <div class="scene-tools" role="group" aria-label="공간 화면 조절" hidden=move || scene_error.get().is_some()> + <button type="button" class="scene-tool" aria-label="확대" title="확대" on:click=move |_| { + #[cfg(feature = "hydrate")] + if let Some(id) = scene_id.get_untracked() { scene_bridge::zoom_scene(id, 1.0); } + }>"+"</button> + <button type="button" class="scene-tool" aria-label="축소" title="축소" on:click=move |_| { + #[cfg(feature = "hydrate")] + if let Some(id) = scene_id.get_untracked() { scene_bridge::zoom_scene(id, -1.0); } + }>"−"</button> + <button type="button" class="scene-tool" aria-label="시점 초기화" title="시점 초기화" on:click=move |_| { + #[cfg(feature = "hydrate")] + if let Some(id) = scene_id.get_untracked() { scene_bridge::reset_scene(id); } + }><Icon name="refresh"/></button> + <button type="button" class="scene-tool scene-expand" aria-label=move || if scene_fullscreen.get() { "전체 화면 닫기" } else { "전체 화면 보기" } + on:click=move |_| set_scene_fullscreen.update(|open| *open = !*open)> + {move || if scene_fullscreen.get() { "축소 보기" } else { "전체 화면" }} + </button> + </div> + <button type="button" class="scene-interaction-toggle" + hidden=move || scene_error.get().is_some() + aria-pressed=move || scene_interactive.get().to_string() + on:click=move |_| set_scene_interactive.update(|active| *active = !*active)> + {move || if scene_interactive.get() { "조작 종료" } else if view_mode.get() == "plan" { "이동·확대" } else { "회전·확대" }} + </button> + <div class="canvas-hint" hidden=move || scene_error.get().is_some()> + <span class="hint-pointer">{move || if view_mode.get() == "plan" { + "드래그로 이동 · 휠로 확대 · 핀으로 사진" + } else { "드래그로 회전 · 휠로 확대 · 핀으로 사진" }}</span> + <span class="hint-touch">{move || match (scene_interactive.get(), view_mode.get()) { + (true, "plan") => "한 손가락 이동 · 두 손가락 확대", + (true, _) => "한 손가락 회전 · 두 손가락 확대·이동", + (false, _) if scene_fullscreen.get() => "핀을 누르면 사진 · 조작 버튼으로 이동·확대", + (false, _) => "핀을 누르면 사진 · 위아래로 화면 스크롤", + }}</span> + </div> + {move || scene_error.get().map(|_| view! { + <div class="scene-failure" role="status"> + <strong>"공간 화면을 불러오지 못했습니다."</strong> + <p>"사진과 공간 정보는 계속 확인할 수 있습니다."</p> + <div> + <button type="button" class="btn-secondary" on:click=move |_| set_scene_retry.update(|n| *n += 1)>"다시 불러오기"</button> + <button type="button" class="btn-secondary" on:click=move |_| { + set_scene_fullscreen.set(false); + set_mobile_panel.set("info"); + }>"공간 정보 보기"</button> + </div> + </div> + })} + </div> + </dialog> + + {move || selection.get().map(|s| view! { + <button type="button" class="selected-zone-mobile" on:click=move |_| set_photo_open.set(true)> + <Icon name="photo"/> + <span>{format!("{} · 사진 {}장", brief(&s.title, 24), s.photos.len())}</span> + <span>"보기"</span> + </button> + })} + + <div class="floor-notes" aria-label="층별 구역"> + {floors_for_notes.into_iter().map(|floor| { + let level = floor.level; + let notes = readable_evidence(&floor.notes, &photos); + let original_label = readable_evidence(&floor.label, &photos); + let short_label = short_floor_label(&floor); + let show_original = original_label != short_label && original_label != format!("{}F", level); + view! { + <section class="floor-note-card" hidden=move || active_floor.get() != 0 && active_floor.get() != level> + <div class="floor-note-head"> + <h3>{short_label}</h3> + <span>{format!("약 {:.0}m × {:.0}m", floor.width_m, floor.depth_m)}</span> + </div> + <div class="zone-chips"> + {floor.zones.into_iter().map(|zone| { + let label = zone.label.clone(); + let label_for_selected = label.clone(); + let ids = zone.evidence_photos; + let has_photos = clean_photos.iter().any(|p| ids.contains(&p.id)); + if has_photos { + view! { + <button type="button" class="zone-chip" + aria-pressed=move || selection.with(|s| s.as_ref().and_then(|s| s.zone.as_ref()).is_some_and(|(l, name)| *l == level && name == &label_for_selected)).to_string() + on:click=move |_| choose_zone.run((level, label.clone(), ids.clone()))> + {zone.label}<Icon name="photo"/> + </button> + }.into_any() + } else { + view! { <span class="zone-empty">{zone.label}<span>"사진 없음"</span></span> }.into_any() + } + }).collect_view()} + </div> + {(!notes.is_empty() || show_original).then(|| view! { + <details class="summary-details floor-details"> + <summary>"층 정보와 추정 근거"</summary> + {show_original.then(|| view! { <p>{original_label}</p> })} + {(!notes.is_empty()).then(|| view! { <p>{notes}</p> })} + <p class="confidence-explanation">{format!("분석 모델이 보고한 층 신뢰도 {:.0}%. 실제 정확도를 검증한 확률은 아닙니다.", floor.confidence.clamp(0.0, 1.0) * 100.0)}</p> + </details> + })} + </section> + } + }).collect_view()} + </div> + </section> + + <aside class="summary-col" id="info-panel" aria-label="공간 정보"> + {move || selection.get().map(|s| { + let total = s.photos.len(); + let selected_photos = StoredValue::new(s.photos.clone()); + view! { + <section class="summary-card selected-zone-panel" aria-label="선택한 구역 사진"> + <div class="pin-drawer-head"> + <h3>{s.title.clone()}</h3> + <button type="button" class="btn-close" aria-label="선택한 사진 닫기" on:click=move |_| set_selection.set(None)><Icon name="close"/></button> + </div> + <p class="photo-count">{format!("사진 {}장", total)}</p> + <button type="button" class="selected-photo-preview" aria-label="선택한 사진 크게 보기" hidden=total == 0 on:click=move |_| set_photo_open.set(true)> + {move || selected_photos.with_value(|photos| photos.get(photo_index.get()).cloned()).map(|p| view! { <PhotoImage photo=p loading="eager"/> })} + </button> + {move || selected_photos.with_value(|photos| photos.get(photo_index.get()).cloned()).map(|p| view! { <PhotoCaption photo=p/> })} + {(total > 1).then(|| view! { + <div class="photo-navigation"> + <button type="button" class="btn-secondary" disabled=move || photo_index.get() == 0 on:click=move |_| set_photo_index.update(|n| *n = n.saturating_sub(1))>"이전"</button> + <span>{move || format!("{} / {}", photo_index.get() + 1, total)}</span> + <button type="button" class="btn-secondary" disabled=move || { photo_index.get() + 1 >= total } on:click=move |_| set_photo_index.update(|n| *n = (*n + 1).min(total.saturating_sub(1)))>"다음"</button> + </div> + })} + {(total == 0).then(|| view! { <p class="photo-empty">"이 구역에 연결된 사진이 없습니다."</p> })} + </section> + } + })} + + <section class="summary-card"> + <h3>"공간 정보"</h3> + <div class="metric-grid"> + <div class="metric"><span class="metric-label">"추정 면적"</span> + <strong class="metric-val">{if layout.summary.area_pyeong_max > 0.0 { + format!("약 {:.0}~{:.0}평", layout.summary.area_pyeong_min, layout.summary.area_pyeong_max) + } else { "미확인".into() }}</strong> + </div> + <div class="metric"><span class="metric-label">"추정 좌석 수"</span> + <strong class="metric-val">{if layout.summary.seat_estimate > 0 { + format!("약 {}석", layout.summary.seat_estimate) + } else { "미확인".into() }}</strong> + </div> + </div> + <div class="summary-floor-count"><strong>{format!("추정 {}개 층", floor_count)}</strong><span>{floor_summary}</span></div> + <div class="summary-section"> + <h4>"확인할 정보"</h4> + <p class="evidence-warning">{warning}"입니다. 실제 배치와 다를 수 있습니다."</p> + <details class="summary-details"> + <summary>"참고사항과 분석 근거"</summary> + {(!caveats.is_empty()).then(|| view! { + <ul class="bullet-list">{caveats.into_iter().map(|c| view! { <li>{c}</li> }).collect_view()}</ul> + })} + <p>{confidence}</p> + <p class="confidence-explanation">"이 수치는 분석 모델의 자체 평가입니다. 현장 실측으로 보정한 정확도나 실제 배치가 맞을 확률이 아닙니다."</p> + </details> + </div> + {(!seat_types.is_empty()).then(|| view! { + <div class="summary-section"><h4>"좌석 구성 · 전체 층"</h4> + <div class="tag-row">{seat_types.into_iter().map(|s| view! { <span class="badge">{s}</span> }).collect_view()}</div> + </div> + })} + <div class="summary-section"> + <h4>"접근성"</h4> + <dl class="fact-list"> + <div><dt>"엘리베이터"</dt><dd>{accessibility_label(layout.summary.accessibility.elevator)}</dd></div> + <div><dt>"무단차 출입구"</dt><dd>{accessibility_label(layout.summary.accessibility.step_free_entrance)}</dd></div> + </dl> + <p class="accessibility-note">"미확인은 시설이 없다는 뜻이 아닙니다. 방문 전 장소에 확인해 주세요."</p> + </div> + {(!brief_highlights.is_empty()).then(|| view! { + <div class="summary-section"><h4>"공간 특징"</h4> + <ul class="bullet-list">{brief_highlights.into_iter().map(|h| view! { <li>{brief(&h, 100)}</li> }).collect_view()}</ul> + {(!more_highlights.is_empty() || highlights.iter().any(|h| h.chars().count() > 100)).then(|| view! { + <details class="summary-details"><summary>"특징 전체 보기"</summary> + <ul class="bullet-list">{highlights.into_iter().map(|h| view! { <li>{h}</li> }).collect_view()}</ul> + </details> + })} + </div> + })} + </section> + + {(gallery_total > 0).then(|| view! { + <section class="summary-card gallery-card"> + <div class="gallery-heading"><h3>"공간 사진"</h3><span>{format!("{}장", gallery_total)}</span></div> + <div class="gallery-grid"> + {interior_photos.into_iter().take(6).enumerate().map(|(index, photo)| { + let source = photo.source.label(); + view! { + <button type="button" class="gallery-item" aria-label=format!("공간 사진 {} 크게 보기", index + 1) + on:click=move |_| show_gallery.run(index)> + <PhotoImage photo=photo/> + <span class="gallery-source">{source}</span> + </button> + } + }).collect_view()} + </div> + {(gallery_total > 6).then(|| view! { + <button type="button" class="gallery-all btn-secondary" on:click=move |_| show_gallery.run(0)>{format!("사진 {}장 모두 보기", gallery_total)}</button> + })} + </section> + })} + </aside> + </div> + + <dialog id="space-photo-dialog" class="photo-dialog" aria-labelledby="space-photo-title" + on:keydown=move |ev| { + if ev.key() == "ArrowLeft" { + ev.prevent_default(); + set_photo_index.update(|n| *n = n.saturating_sub(1)); + } + if ev.key() == "ArrowRight" { + ev.prevent_default(); + let count = selection.with_untracked(|s| s.as_ref().map_or(0, |s| s.photos.len())); + set_photo_index.update(|n| *n = (*n + 1).min(count.saturating_sub(1))); + } + }> + <div class="dialog-header"> + <h2 id="space-photo-title">{move || selection.get().map_or_else(|| "공간 사진".into(), |s| s.title)}</h2> + <button type="button" class="btn-close" aria-label="사진 닫기" on:click=move |_| set_photo_open.set(false)>"닫기"<Icon name="close"/></button> + </div> + <div class="photo-dialog-body"> + {move || selection.get().map(|s| { + let total = s.photos.len(); + let selected_photos = StoredValue::new(s.photos.clone()); + view! { + {move || selected_photos.with_value(|photos| photos.get(photo_index.get()).cloned()).map(|photo| view! { + <div class="photo-viewer"><PhotoImage photo=photo.clone() loading="eager"/></div> + <PhotoCaption photo=photo/> + })} + {(total > 0).then(|| view! { + <div class="photo-navigation"> + <button type="button" class="btn-secondary" aria-label="이전 사진" disabled=move || photo_index.get() == 0 + on:click=move |_| set_photo_index.update(|n| *n = n.saturating_sub(1))>"이전"</button> + <span role="status" aria-live="polite">{move || format!("{} / {}", photo_index.get() + 1, total)}</span> + <button type="button" class="btn-secondary" aria-label="다음 사진" disabled=move || { photo_index.get() + 1 >= total } + on:click=move |_| set_photo_index.update(|n| *n = (*n + 1).min(total.saturating_sub(1)))>"다음"</button> + </div> + })} + {(total > 1).then(|| view! { + <div class="photo-thumbnails" role="group" aria-label="사진 선택"> + {s.photos.into_iter().enumerate().map(|(i, photo)| view! { + <button type="button" aria-label=format!("{}번째 사진", i + 1) aria-pressed=move || (i == photo_index.get()).to_string() + on:click=move |_| set_photo_index.set(i)><PhotoImage photo=photo/></button> + }).collect_view()} + </div> + })} + {(total == 0).then(|| view! { <p class="photo-empty">"이 구역에 연결된 사진이 없습니다."</p> })} + } + })} + </div> + </dialog> + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn floor(label: &str, notes: &str, level: i32) -> Floor { + Floor { + level, + label: label.into(), + confidence: 0.5, + width_m: 10.0, + depth_m: 8.0, + openings: vec![], + zones: vec![], + verticals: vec![], + notes: notes.into(), + } + } + + #[test] + fn floor_labels_distinguish_assignment_from_dimension_uncertainty() { + assert_eq!( + short_floor_label(&floor("1층", "치수와 방위는 가정입니다.", 1)), + "1층" + ); + assert_eq!( + short_floor_label(&floor("상층 좌석 공간 · 2층으로 임시 배정", "", 2)), + "2층(추정)" + ); + assert_eq!( + short_floor_label(&floor("2층", "사진의 촬영 층은 미확인입니다.", 2)), + "2층(추정)" + ); + assert_eq!(short_floor_label(&floor("지하", "", -1)), "B1"); + assert_eq!( + short_floor_label(&floor("루프탑", "", ROOFTOP_LEVEL)), + "옥상" + ); + } + + #[test] + fn evidence_ids_are_replaced_without_losing_caveats() { + let text = "p_ab123, p_other: 다른 지점 사진일 가능성이 있어 층은 미확인."; + assert_eq!( + readable_evidence(text, &[]), + "참고 사진, 참고 사진: 다른 지점 사진일 가능성이 있어 층은 미확인." + ); + } + + #[test] + fn equivalent_tags_are_not_repeated() { + assert_eq!( + unique_text( + vec!["바 좌석".into(), "바좌석".into(), "소파".into(), "".into()], + &[] + ), + vec!["바 좌석", "소파"] + ); + } +} diff --git a/crates/domain/Cargo.toml b/crates/domain/Cargo.toml new file mode 100644 index 0000000..8cb2459 --- /dev/null +++ b/crates/domain/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "domain" +edition.workspace = true +version.workspace = true + +[dependencies] +serde = { workspace = true } diff --git a/crates/domain/src/layout.rs b/crates/domain/src/layout.rs new file mode 100644 index 0000000..5132ace --- /dev/null +++ b/crates/domain/src/layout.rs @@ -0,0 +1,174 @@ +//! Layout JSON: the central artifact rendered by three.js. +//! +//! Coordinate system per floor (meters): origin at the south-west corner, +//! `x` grows east (0..width_m), `y` grows north (0..depth_m). +//! The street/entrance side is conventionally south. + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Layout { + pub place_id: String, + pub generated_at: String, + pub model: String, + pub confidence: f32, + pub floors: Vec<Floor>, + pub summary: Summary, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Floor { + pub level: i32, + pub label: String, + pub confidence: f32, + pub width_m: f32, + pub depth_m: f32, + pub openings: Vec<Opening>, + pub zones: Vec<Zone>, + pub verticals: Vec<Vertical>, + pub notes: String, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Wall { + North, + South, + East, + West, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum OpeningKind { + Entrance, + Window, + Door, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Opening { + pub kind: OpeningKind, + pub wall: Wall, + /// Distance from the wall's start (west end for N/S walls, south end for E/W walls). + pub offset_m: f32, + pub length_m: f32, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ZoneKind { + Seating, + Counter, + Bar, + Kitchen, + Restroom, + Terrace, + Entrance, + Other, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Zone { + pub kind: ZoneKind, + pub label: String, + pub x: f32, + pub y: f32, + pub w: f32, + pub d: f32, + pub furniture: Vec<FurnitureGroup>, + pub evidence_photos: Vec<String>, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +pub enum FurnitureKind { + Table2, + Table4, + Table6, + CommunalTable, + BarSeat, + Sofa, + CounterBar, + Plant, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Arrangement { + Grid, + AlongWall, + Row, + Cluster, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct FurnitureGroup { + pub kind: FurnitureKind, + pub count: u32, + pub arrangement: Arrangement, + pub along_wall: Option<Wall>, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum VerticalKind { + Stairs, + Elevator, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Vertical { + pub kind: VerticalKind, + pub x: f32, + pub y: f32, + pub w: f32, + pub d: f32, + pub to_level: i32, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Tri { + Yes, + Likely, + No, + Unknown, +} + +impl Tri { + pub fn label(&self) -> &'static str { + match self { + Tri::Yes => "있음", + Tri::Likely => "있을 가능성 높음", + Tri::No => "없음", + Tri::Unknown => "확인 안 됨", + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Accessibility { + pub elevator: Tri, + pub step_free_entrance: Tri, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Summary { + pub area_pyeong_min: f32, + pub area_pyeong_max: f32, + pub seat_estimate: u32, + pub seat_types: Vec<String>, + pub highlights: Vec<String>, + pub accessibility: Accessibility, + pub caveats: Vec<String>, +} + +/// Everything the place page needs in one round-trip. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PlaceView { + pub place: crate::Place, + pub layout: Option<Layout>, + pub photos: Vec<crate::PhotoSummary>, + pub running_job: Option<String>, +} diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs new file mode 100644 index 0000000..644a624 --- /dev/null +++ b/crates/domain/src/lib.rs @@ -0,0 +1,63 @@ +//! Shared domain types. Compiles for both native (server) and wasm32 (hydrate), +//! so keep dependencies limited to `serde`. + +mod layout; +mod photo; +mod place; + +pub use layout::*; +pub use photo::*; +pub use place::*; + +use serde::{Deserialize, Serialize}; + +/// Progress events streamed to the browser over SSE while a place is analyzed. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum JobEvent { + Started { place_id: String }, + PlaceResolved { name: String, naver_place_id: Option<String> }, + SourceDone { source: PhotoSourceId, photos: usize, texts: usize, error: Option<String> }, + PhotosStored { stored: usize, duplicates: usize, failed: usize }, + Classified { interior: usize, exterior: usize, food: usize, other: usize }, + FloorsDetected { floors: Vec<FloorEvidence> }, + LayoutDraft { attempt: u32 }, + Log { message: String }, + Done { place_id: String }, + Error { message: String }, +} + +impl JobEvent { + pub fn is_terminal(&self) -> bool { + matches!(self, JobEvent::Done { .. } | JobEvent::Error { .. }) + } +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum JobStatus { + Running, + Done, + Failed, +} + +/// Aggregated evidence that a given floor exists. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct FloorEvidence { + /// 1 = ground floor, 2 = second floor, -1 = B1, 99 = rooftop. + pub level: i32, + pub label: String, + pub score: f32, + pub photo_ids: Vec<String>, + pub text_snippets: Vec<String>, +} + +pub const ROOFTOP_LEVEL: i32 = 99; + +pub fn floor_label(level: i32) -> String { + match level { + ROOFTOP_LEVEL => "루프탑".to_string(), + l if l < 0 => format!("B{}", -l), + l => format!("{l}F"), + } +} diff --git a/crates/domain/src/photo.rs b/crates/domain/src/photo.rs new file mode 100644 index 0000000..d400f8f --- /dev/null +++ b/crates/domain/src/photo.rs @@ -0,0 +1,144 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +pub enum PhotoSourceId { + NaverPlace, + NaverBlog, + KakaoPlace, + GoogleMaps, + Instagram, + User, +} + +impl PhotoSourceId { + pub fn label(&self) -> &'static str { + match self { + Self::NaverPlace => "네이버 플레이스", + Self::NaverBlog => "네이버 블로그", + Self::KakaoPlace => "카카오맵", + Self::GoogleMaps => "구글 지도", + Self::Instagram => "인스타그램", + Self::User => "사용자 업로드", + } + } +} + +/// A photo reference returned by a source before download. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct RawPhoto { + pub source: PhotoSourceId, + /// Direct image URL. + pub image_url: String, + /// Page where the image was found (for attribution). + pub page_url: String, + /// Text directly associated with the image (alt, caption, nearby paragraph). + pub caption: String, + /// Referer header required by some CDNs (e.g. postfiles.pstatic.net). + pub referer: Option<String>, +} + +/// Free text found by a source (blog body, place description, reviews). +/// Used as evidence for floors / seating. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct TextSnippet { + pub source: PhotoSourceId, + pub url: String, + pub text: String, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +pub struct SourceOutput { + pub photos: Vec<RawPhoto>, + pub texts: Vec<TextSnippet>, +} + +/// Stored photo (MongoDB `photos`). Bytes live in MinIO under `object_key`. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Photo { + #[serde(rename = "_id")] + pub id: String, + pub place_id: String, + pub source: PhotoSourceId, + pub image_url: String, + pub page_url: String, + pub caption: String, + pub object_key: String, + /// 64-bit difference hash, hex encoded (BSON has no u64). + pub dhash: String, + pub width: u32, + pub height: u32, + pub tag: Option<PhotoTag>, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +pub enum PhotoKind { + Interior, + Exterior, + Food, + Menu, + Person, + Other, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +pub enum PhotoZone { + Entrance, + Counter, + Hall, + WindowSide, + Terrace, + Restroom, + Stairs, + Kitchen, + Unknown, +} + +/// VLM classification of one photo. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PhotoTag { + pub kind: PhotoKind, + pub zone: PhotoZone, + /// Same convention as `FloorEvidence::level`; `None` = unknown. + pub floor_level: Option<i32>, + pub floor_evidence: String, + pub furniture: Vec<FurnitureCount>, + pub quality: f32, + pub description: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct FurnitureCount { + pub kind: crate::FurnitureKind, + pub count: u32, +} + +/// Lightweight photo info sent to the UI. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PhotoSummary { + pub id: String, + pub source: PhotoSourceId, + pub page_url: String, + pub caption: String, + pub kind: Option<PhotoKind>, + pub zone: Option<PhotoZone>, + pub floor_level: Option<i32>, + pub description: String, +} + +impl From<&Photo> for PhotoSummary { + fn from(p: &Photo) -> Self { + Self { + id: p.id.clone(), + source: p.source, + page_url: p.page_url.clone(), + caption: p.caption.clone(), + kind: p.tag.as_ref().map(|t| t.kind), + zone: p.tag.as_ref().map(|t| t.zone), + floor_level: p.tag.as_ref().and_then(|t| t.floor_level), + description: p.tag.as_ref().map(|t| t.description.clone()).unwrap_or_default(), + } + } +} diff --git a/crates/domain/src/place.rs b/crates/domain/src/place.rs new file mode 100644 index 0000000..ca011ca --- /dev/null +++ b/crates/domain/src/place.rs @@ -0,0 +1,81 @@ +use serde::{Deserialize, Serialize}; + +/// A search result shown to the user before they confirm the place. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PlaceCandidate { + /// Provider that produced this candidate (`kakao`, `naver`). + pub provider: String, + /// Provider-native id (Kakao place id, Naver place id). + pub provider_id: String, + pub name: String, + pub category: String, + pub address: String, + pub road_address: String, + pub phone: String, + pub lat: f64, + pub lng: f64, + pub place_url: String, +} + +impl PlaceCandidate { + /// Stable internal id, e.g. `kakao:12345`. + pub fn place_id(&self) -> String { + format!("{}:{}", self.provider, self.provider_id) + } +} + +/// Canonical, normalized place persisted in MongoDB. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Place { + #[serde(rename = "_id")] + pub id: String, + pub kakao_id: Option<String>, + pub naver_place_id: Option<String>, + pub name: String, + pub category: String, + pub address: String, + pub road_address: String, + pub phone: String, + pub lat: f64, + pub lng: f64, + pub place_url: String, +} + +/// A saved analysis that can be reopened without starting another analysis job. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct RecentPlace { + pub place: Place, + pub analyzed_at: String, + pub last_viewed_at: Option<String>, + pub floor_labels: Vec<String>, + pub seat_estimate: u32, +} + +impl Place { + pub fn from_candidate(c: &PlaceCandidate) -> Self { + let (kakao_id, naver_place_id) = match c.provider.as_str() { + "kakao" => (Some(c.provider_id.clone()), None), + "naver" => (None, Some(c.provider_id.clone())), + _ => (None, None), + }; + Self { + id: c.place_id(), + kakao_id, + naver_place_id, + name: c.name.clone(), + category: c.category.clone(), + address: c.address.clone(), + road_address: c.road_address.clone(), + phone: c.phone.clone(), + lat: c.lat, + lng: c.lng, + place_url: c.place_url.clone(), + } + } + + /// Short region hint (e.g. "성동구 성수동") used to disambiguate web searches. + pub fn region_hint(&self) -> String { + let addr = if self.address.is_empty() { &self.road_address } else { &self.address }; + addr.split_whitespace().skip(1).take(2).collect::<Vec<_>>().join(" ") + } +} diff --git a/crates/llm/Cargo.toml b/crates/llm/Cargo.toml new file mode 100644 index 0000000..b4d0356 --- /dev/null +++ b/crates/llm/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "llm" +edition.workspace = true +version.workspace = true + +[dependencies] +reqwest = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +anyhow = { workspace = true } +tracing = { workspace = true } +base64 = { workspace = true } +tokio = { workspace = true } diff --git a/crates/llm/src/lib.rs b/crates/llm/src/lib.rs new file mode 100644 index 0000000..82b100c --- /dev/null +++ b/crates/llm/src/lib.rs @@ -0,0 +1,746 @@ +//! OpenAI-compatible chat client with vision input, strict JSON-schema output, +//! weighted multi-provider routing (`strata` / `cpa`), and automatic failover. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use base64::Engine; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +/// Health probe result for a single configured LLM provider. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ProviderHealth { + pub provider: ProviderKind, + pub endpoint: String, + pub model: String, + pub weight: u32, + pub healthy: bool, + pub latency_ms: u64, + pub detail: String, +} + +/// Identifier for the underlying LLM inference backend. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ProviderKind { + /// Local/self-hosted Strata inference engine (Niko1221/Strata). + Strata, + /// CLIProxyAPI (`cpa`) OpenAI-compatible proxy. + #[serde(alias = "cliproxy", alias = "cli-proxy")] + Cpa, + /// Fallback for any other custom OpenAI-compatible provider name. + #[serde(untagged)] + Custom(String), +} + +impl ProviderKind { + pub fn as_str(&self) -> &str { + match self { + ProviderKind::Strata => "strata", + ProviderKind::Cpa => "cpa", + ProviderKind::Custom(s) => s.as_str(), + } + } +} + +impl Default for ProviderKind { + fn default() -> Self { + ProviderKind::Cpa + } +} + +/// Configuration for a single weighted LLM capacity provider. +/// Accepts both uppercase env-style keys (`PROVIDER`, `OPENAI_COMPATIBLE_API_ENDPOINT`, +/// `OPENAI_COMPATIBLE_API_KEY`, `MODEL`, `WEIGHT`) and lowercase keys (`provider`, +/// `endpoint`, `api_key`, `model`, `weight`). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LlmProviderConfig { + #[serde(default, alias = "PROVIDER", alias = "provider")] + pub provider: ProviderKind, + #[serde( + alias = "OPENAI_COMPATIBLE_API_ENDPOINT", + alias = "endpoint", + alias = "ENDPOINT", + alias = "url" + )] + pub endpoint: String, + #[serde( + default, + alias = "OPENAI_COMPATIBLE_API_KEY", + alias = "api_key", + alias = "API_KEY", + alias = "key", + alias = "KEY" + )] + pub api_key: String, + #[serde(alias = "MODEL", alias = "LLM_MODEL", alias = "model")] + pub model: String, + #[serde(default = "default_weight", alias = "WEIGHT", alias = "weight")] + pub weight: u32, +} + +fn default_weight() -> u32 { + 1 +} + +impl LlmProviderConfig { + /// Display tag such as `strata/qwen3.8-flash-next` or `cpa/gpt-6.1-sol`. + pub fn display_model(&self) -> String { + format!("{}/{}", self.provider.as_str(), self.model) + } + + fn normalized(mut self) -> Self { + let ep = self.endpoint.trim().trim_end_matches('/'); + self.endpoint = ep.strip_suffix("/v1").unwrap_or(ep).to_string(); + self.api_key = self.api_key.trim().to_string(); + self.model = self.model.trim().to_string(); + self + } +} + +/// Successful JSON response together with the provider/model that served it. +#[derive(Debug, Clone)] +pub struct ChatJsonOutput<T> { + pub data: T, + pub provider: ProviderKind, + pub model: String, +} + +impl<T> ChatJsonOutput<T> { + /// Formatted tag (`{provider}/{model}`) suitable for storing in `Layout.model`. + pub fn model_tag(&self) -> String { + format!("{}/{}", self.provider.as_str(), self.model) + } +} + +#[derive(Clone)] +pub struct LlmClient { + client: reqwest::Client, + providers: Arc<Vec<LlmProviderConfig>>, + /// Latest known health flag per provider (`true` = healthy, initialized to `true`). + health_flags: Arc<Vec<AtomicBool>>, + /// Weighted schedule table of indices into `providers` (e.g. `[0, 0, 1]` for weights 2, 1). + schedule: Arc<Vec<usize>>, + cursor: Arc<AtomicUsize>, + /// Primary model name kept for backwards compatibility (`{provider}/{model}`). + pub model: String, +} + +/// One part of a multimodal user message. +#[derive(Debug, Clone)] +pub enum Part { + Text(String), + /// Raw image bytes + mime type; sent as a base64 data URL. + Image { bytes: Vec<u8>, mime: String }, +} + +impl Part { + pub fn text(s: impl Into<String>) -> Self { + Part::Text(s.into()) + } + + fn to_json(&self) -> Value { + match self { + Part::Text(t) => json!({ "type": "text", "text": t }), + Part::Image { bytes, mime } => { + let b64 = base64::engine::general_purpose::STANDARD.encode(bytes); + json!({ "type": "image_url", "image_url": { "url": format!("data:{mime};base64,{b64}") } }) + } + } + } +} + +#[derive(Debug, Serialize, Clone)] +struct Message { + role: &'static str, + content: Value, +} + +impl LlmClient { + /// Construct a single-provider client (weight = 1). + pub fn new(endpoint: impl Into<String>, key: impl Into<String>, model: impl Into<String>) -> Self { + Self::from_providers(vec![LlmProviderConfig { + provider: ProviderKind::Cpa, + endpoint: endpoint.into(), + api_key: key.into(), + model: model.into(), + weight: 1, + }]) + .expect("single provider config is always non-empty") + } + + /// Construct a weighted multi-provider client from a list of `LlmProviderConfig`s. + /// Providers with `weight == 0` are kept only as failover backups unless all weights are 0. + pub fn from_providers(configs: Vec<LlmProviderConfig>) -> anyhow::Result<Self> { + let providers: Vec<LlmProviderConfig> = configs + .into_iter() + .map(LlmProviderConfig::normalized) + .filter(|p| !p.endpoint.is_empty() && !p.model.is_empty()) + .collect(); + if providers.is_empty() { + anyhow::bail!("at least one valid LLM provider must be configured"); + } + + let schedule = build_interleaved_schedule(&providers); + let primary_idx = schedule.first().copied().unwrap_or(0); + let model = providers[primary_idx].display_model(); + let health_flags = providers.iter().map(|_| AtomicBool::new(true)).collect(); + + Ok(Self { + client: reqwest::Client::builder() + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(240)) + .build() + .expect("reqwest client"), + providers: Arc::new(providers), + health_flags: Arc::new(health_flags), + schedule: Arc::new(schedule), + cursor: Arc::new(AtomicUsize::new(0)), + model, + }) + } + + /// Parse a JSON array string of `LlmProviderConfig`s. + pub fn from_json_str(raw: &str) -> anyhow::Result<Self> { + let configs: Vec<LlmProviderConfig> = serde_json::from_str(raw.trim()) + .map_err(|e| anyhow::anyhow!("invalid LLM_PROVIDERS JSON: {e}"))?; + Self::from_providers(configs) + } + + pub fn providers(&self) -> &[LlmProviderConfig] { + &self.providers + } + + /// Run provider-specific health checks across all configured LLM providers in parallel + /// and update their internal health flags used by weighted routing: + /// - `strata`: probes `GET {endpoint}/health` (verifies `status == "ok"` and `loaded != false`, + /// with fallback to `GET {endpoint}/v1/models` if `/health` returns 404). + /// - `cpa` (CLIProxyAPI) / custom: probes `GET {endpoint}/v1/models` with Bearer token + /// (verifies HTTP 2xx and checks whether the configured model is registered). + pub async fn health_check_all(&self) -> Vec<ProviderHealth> { + let mut results = Vec::with_capacity(self.providers.len()); + for (idx, provider) in self.providers.iter().enumerate() { + let status = self.check_provider_health(provider).await; + self.health_flags[idx].store(status.healthy, Ordering::Relaxed); + results.push(status); + } + results + } + + /// Probe a single provider's health according to its `ProviderKind`. + pub async fn check_provider_health(&self, provider: &LlmProviderConfig) -> ProviderHealth { + let started = Instant::now(); + let probe_res = match provider.provider { + ProviderKind::Strata => self.probe_strata_health(provider).await, + ProviderKind::Cpa | ProviderKind::Custom(_) => self.probe_cpa_health(provider).await, + }; + let latency_ms = started.elapsed().as_millis() as u64; + match probe_res { + Ok(detail) => ProviderHealth { + provider: provider.provider.clone(), + endpoint: provider.endpoint.clone(), + model: provider.model.clone(), + weight: provider.weight, + healthy: true, + latency_ms, + detail, + }, + Err(err) => ProviderHealth { + provider: provider.provider.clone(), + endpoint: provider.endpoint.clone(), + model: provider.model.clone(), + weight: provider.weight, + healthy: false, + latency_ms, + detail: err.to_string(), + }, + } + } + + /// Strata health check: + /// 1. `GET {endpoint}/health` (Strata native endpoint returning `{"status":"ok","loaded":true,"model":...,"images":true}`) + /// 2. Falls back to `/v1/models` if `/health` is not exposed (404). + async fn probe_strata_health(&self, provider: &LlmProviderConfig) -> anyhow::Result<String> { + let url = format!("{}/health", provider.endpoint); + let mut req = self.client.get(&url).timeout(Duration::from_secs(5)); + if !provider.api_key.is_empty() { + req = req.bearer_auth(&provider.api_key); + } + let resp = req.send().await.map_err(|e| anyhow::anyhow!("Strata /health unreachable: {e}"))?; + let status = resp.status(); + if status == reqwest::StatusCode::NOT_FOUND { + return self.probe_cpa_health(provider).await; + } + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + anyhow::bail!("Strata /health HTTP {status}: {}", truncate(&text, 200)); + } + if let Ok(v) = serde_json::from_str::<Value>(&text) { + if let Some(st) = v["status"].as_str() { + if !st.eq_ignore_ascii_case("ok") && !st.eq_ignore_ascii_case("healthy") && !st.eq_ignore_ascii_case("ready") { + anyhow::bail!("Strata status is '{st}': {}", truncate(&text, 200)); + } + } + if v["loaded"].as_bool() == Some(false) { + anyhow::bail!("Strata engine running but model not loaded yet (loaded=false)"); + } + let engine_model = v["model"].as_str().unwrap_or(&provider.model); + let vision = v["images"].as_bool().map(|b| format!(", images={b}")).unwrap_or_default(); + return Ok(format!("Strata ready (model={engine_model}{vision})")); + } + Ok("Strata /health ok".into()) + } + + /// CLIProxyAPI (`cpa`) health check: + /// Queries `GET {endpoint}/v1/models` with Bearer auth and verifies the model list response. + async fn probe_cpa_health(&self, provider: &LlmProviderConfig) -> anyhow::Result<String> { + let url = format!("{}/v1/models", provider.endpoint); + let mut req = self.client.get(&url).timeout(Duration::from_secs(5)); + if !provider.api_key.is_empty() { + req = req.bearer_auth(&provider.api_key); + } + let resp = req.send().await.map_err(|e| { + anyhow::anyhow!("{} /v1/models unreachable: {e}", provider.provider.as_str()) + })?; + let status = resp.status(); + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + anyhow::bail!( + "{} /v1/models HTTP {status}: {}", + provider.provider.as_str(), + truncate(&text, 200) + ); + } + if let Ok(v) = serde_json::from_str::<Value>(&text) { + if let Some(arr) = v["data"].as_array() { + let ids: Vec<&str> = arr.iter().filter_map(|m| m["id"].as_str()).collect(); + if !ids.is_empty() && !ids.iter().any(|&id| id == provider.model) { + return Ok(format!( + "/v1/models ok ({} models online; '{}' not listed in registry, will route directly)", + ids.len(), + provider.model + )); + } + return Ok(format!("/v1/models ok ({} models, '{}' available)", ids.len(), provider.model)); + } + } + Ok("/v1/models ok".into()) + } + + /// Pick the ordered list of provider indices to try for the next request: + /// starts with the weighted round-robin winner among currently healthy providers, + /// followed by remaining healthy providers, and finally any unhealthy providers as last-resort failover. + fn pick_provider_order(&self) -> Vec<usize> { + let step = self.cursor.fetch_add(1, Ordering::Relaxed); + let mut healthy_order = Vec::with_capacity(self.providers.len()); + let mut unhealthy_order = Vec::new(); + + // Walk the weighted schedule starting from `step` so the 2:1 ratio is preserved. + for offset in 0..self.schedule.len() { + let idx = self.schedule[(step + offset) % self.schedule.len()]; + if self.health_flags[idx].load(Ordering::Relaxed) { + if !healthy_order.contains(&idx) { + healthy_order.push(idx); + } + } else if !unhealthy_order.contains(&idx) { + unhealthy_order.push(idx); + } + } + // Include any 0-weight backup providers not present in `schedule`. + for idx in 0..self.providers.len() { + if self.health_flags[idx].load(Ordering::Relaxed) { + if !healthy_order.contains(&idx) { + healthy_order.push(idx); + } + } else if !unhealthy_order.contains(&idx) { + unhealthy_order.push(idx); + } + } + healthy_order.extend(unhealthy_order); + healthy_order + } + + /// Send `system` + multimodal `user` parts and parse the reply into `T` + /// using a strict JSON schema. + pub async fn chat_json<T: DeserializeOwned>( + &self, + system: &str, + user: &[Part], + schema_name: &str, + schema: &Value, + ) -> anyhow::Result<T> { + Ok(self + .chat_json_with_meta(system, user, schema_name, schema) + .await? + .data) + } + + /// Same as `chat_json`, but also returns which provider (`strata` / `cpa`) and model served the request. + /// Automatically fails over to the next configured provider if the chosen provider fails. + pub async fn chat_json_with_meta<T: DeserializeOwned>( + &self, + system: &str, + user: &[Part], + schema_name: &str, + schema: &Value, + ) -> anyhow::Result<ChatJsonOutput<T>> { + let order = self.pick_provider_order(); + let mut last_err: Option<anyhow::Error> = None; + + for (attempt_idx, &prov_idx) in order.iter().enumerate() { + let provider = &self.providers[prov_idx]; + match self + .chat_json_on_provider::<T>(provider, system, user, schema_name, schema) + .await + { + Ok(data) => { + self.health_flags[prov_idx].store(true, Ordering::Relaxed); + return Ok(ChatJsonOutput { + data, + provider: provider.provider.clone(), + model: provider.model.clone(), + }); + } + Err(err) => { + self.health_flags[prov_idx].store(false, Ordering::Relaxed); + if attempt_idx + 1 < order.len() { + let next_prov = &self.providers[order[attempt_idx + 1]]; + tracing::warn!( + failed_provider = provider.provider.as_str(), + failed_model = %provider.model, + failover_provider = next_prov.provider.as_str(), + failover_model = %next_prov.model, + error = %err, + "LLM provider call failed, failing over to next provider" + ); + } + last_err = Some(err); + } + } + } + + Err(last_err.unwrap_or_else(|| anyhow::anyhow!("no LLM providers available"))) + } + + async fn chat_json_on_provider<T: DeserializeOwned>( + &self, + provider: &LlmProviderConfig, + system: &str, + user: &[Part], + schema_name: &str, + schema: &Value, + ) -> anyhow::Result<T> { + let messages = vec![ + Message { + role: "system", + content: Value::String(system.to_string()), + }, + Message { + role: "user", + content: Value::Array(user.iter().map(Part::to_json).collect()), + }, + ]; + let strict = json!({ + "type": "json_schema", + "json_schema": { "name": schema_name, "strict": true, "schema": schema } + }); + let raw = match self.complete(provider, &messages, Some(strict)).await { + Ok(r) => r, + Err(e) if should_fallback_response_format(&e, &provider.provider) => { + tracing::warn!( + provider = provider.provider.as_str(), + model = %provider.model, + "json_schema unsupported, falling back to json_object / prompt schema: {e}" + ); + let mut msgs = messages; + msgs[0].content = Value::String(format!( + "{system}\n\nRespond ONLY with valid JSON matching this schema (no markdown fences, no extra prose):\n{}", + serde_json::to_string(schema)? + )); + match self + .complete(provider, &msgs, Some(json!({ "type": "json_object" }))) + .await + { + Ok(r) => r, + Err(e2) if should_fallback_response_format(&e2, &provider.provider) => { + self.complete(provider, &msgs, None).await? + } + Err(e2) => return Err(e2), + } + } + Err(e) => return Err(e), + }; + let cleaned = strip_fences(&raw); + serde_json::from_str(cleaned).map_err(|e| { + anyhow::anyhow!( + "LLM JSON parse error ({}/{}): {e}; raw: {}", + provider.provider.as_str(), + provider.model, + truncate(&raw, 500) + ) + }) + } + + async fn complete( + &self, + provider: &LlmProviderConfig, + messages: &[Message], + response_format: Option<Value>, + ) -> anyhow::Result<String> { + let mut body = json!({ + "model": provider.model, + "messages": messages, + }); + if let Some(rf) = response_format { + body["response_format"] = rf; + } + let started = std::time::Instant::now(); + let mut req = self + .client + .post(format!("{}/v1/chat/completions", provider.endpoint)) + .json(&body); + if !provider.api_key.is_empty() { + req = req.bearer_auth(&provider.api_key); + } + let resp = req.send().await?; + let status = resp.status(); + let text = resp.text().await?; + if !status.is_success() { + anyhow::bail!( + "LLM HTTP {status} ({}/{}): {}", + provider.provider.as_str(), + provider.model, + truncate(&text, 800) + ); + } + let v: Value = serde_json::from_str(&text)?; + let raw_content = v["choices"][0]["message"]["content"] + .as_str() + .ok_or_else(|| { + anyhow::anyhow!( + "LLM response without content ({}/{}): {}", + provider.provider.as_str(), + provider.model, + truncate(&text, 500) + ) + })?; + let content = strip_thinking_blocks(raw_content).to_string(); + tracing::debug!( + provider = provider.provider.as_str(), + model = %provider.model, + elapsed_ms = started.elapsed().as_millis() as u64, + prompt_tokens = v["usage"]["prompt_tokens"].as_u64(), + completion_tokens = v["usage"]["completion_tokens"].as_u64(), + "llm completion" + ); + Ok(content) + } +} + +fn should_fallback_response_format(err: &anyhow::Error, provider: &ProviderKind) -> bool { + let msg = err.to_string().to_lowercase(); + msg.contains("response_format") + || msg.contains("json_schema") + || msg.contains("structured") + || (matches!(provider, ProviderKind::Strata) + && (msg.contains("http 400") || msg.contains("http 422") || msg.contains("unsupported"))) +} + +/// Build a smooth interleaved weighted schedule (Smooth Weighted Round-Robin) +/// so e.g. weights `[2, 1]` produce `[0, 0, 1]` and `[4, 2]` produce `[0, 0, 1]` (reduced by GCD). +fn build_interleaved_schedule(providers: &[LlmProviderConfig]) -> Vec<usize> { + let mut weights: Vec<u32> = providers.iter().map(|p| p.weight.min(100)).collect(); + let total: u32 = weights.iter().sum(); + if total == 0 { + return (0..providers.len()).collect(); + } + let g = weights.iter().copied().fold(0u32, gcd); + if g > 1 { + for w in &mut weights { + *w /= g; + } + } + let total_steps: usize = weights.iter().map(|&w| w as usize).sum(); + let total_w = total_steps as i64; + let mut current = vec![0i64; providers.len()]; + let mut schedule = Vec::with_capacity(total_steps); + + for _ in 0..total_steps { + let mut best_idx = 0; + for (i, &w) in weights.iter().enumerate() { + if w == 0 { + continue; + } + current[i] += w as i64; + if weights[best_idx] == 0 || current[i] > current[best_idx] { + best_idx = i; + } + } + current[best_idx] -= total_w; + schedule.push(best_idx); + } + schedule +} + +fn gcd(a: u32, b: u32) -> u32 { + if b == 0 { + a + } else { + gcd(b, a % b) + } +} + +/// Strip `<think>...</think>` blocks that local reasoning/MoE models (e.g. Qwen3.8 on Strata) may emit. +fn strip_thinking_blocks(s: &str) -> &str { + let mut rest = s.trim(); + while let Some(start) = rest.find("<think>") { + if start == 0 { + if let Some(end) = rest.find("</think>") { + rest = rest[end + "</think>".len()..].trim(); + continue; + } + } + break; + } + rest +} + +fn strip_fences(s: &str) -> &str { + let t = strip_thinking_blocks(s); + let t = t.strip_prefix("```json").or_else(|| t.strip_prefix("```")).unwrap_or(t); + t.strip_suffix("```").unwrap_or(t).trim() +} + +fn truncate(s: &str, n: usize) -> String { + if s.chars().count() <= n { + s.to_string() + } else { + format!("{}…", s.chars().take(n).collect::<String>()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fences_and_thinking() { + assert_eq!(super::strip_fences("```json\n{\"a\":1}\n```"), "{\"a\":1}"); + assert_eq!(super::strip_fences("{\"a\":1}"), "{\"a\":1}"); + assert_eq!( + super::strip_fences("<think>\nreasoning...\n</think>\n```json\n{\"a\":1}\n```"), + "{\"a\":1}" + ); + } + + #[test] + fn parse_uppercase_and_lowercase_provider_json() { + let raw = r#"[ + { + "PROVIDER": "strata", + "OPENAI_COMPATIBLE_API_ENDPOINT": "http://127.0.0.1:8080/v1/", + "OPENAI_COMPATIBLE_API_KEY": "", + "MODEL": "qwen3.8-flash-next", + "WEIGHT": 2 + }, + { + "provider": "cpa", + "endpoint": "http://126.dahyeon.us:8317", + "api_key": "secret-jwt", + "model": "gpt-6.1-sol", + "weight": 1 + } + ]"#; + let client = LlmClient::from_json_str(raw).expect("valid json"); + assert_eq!(client.providers().len(), 2); + assert_eq!(client.providers()[0].provider, ProviderKind::Strata); + assert_eq!(client.providers()[0].endpoint, "http://127.0.0.1:8080"); + assert_eq!(client.providers()[0].weight, 2); + assert_eq!(client.providers()[1].provider, ProviderKind::Cpa); + assert_eq!(client.providers()[1].weight, 1); + + // Weighted 2:1 schedule should pick provider 0 twice and provider 1 once every 3 calls. + let picks: Vec<usize> = (0..6) + .map(|_| client.pick_provider_order()[0]) + .collect(); + let count_0 = picks.iter().filter(|&&i| i == 0).count(); + let count_1 = picks.iter().filter(|&&i| i == 1).count(); + assert_eq!(count_0, 4); + assert_eq!(count_1, 2); + + // If provider 0 (strata) is marked unhealthy, pick_provider_order should promote provider 1 (cpa) first + // while keeping provider 0 at the end as last-resort failover. + client.health_flags[0].store(false, Ordering::Relaxed); + let failover_order = client.pick_provider_order(); + assert_eq!(failover_order, vec![1, 0]); + } + + #[tokio::test] + #[ignore] + async fn live_env_providers_health_and_routing() -> anyhow::Result<()> { + let env_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.env"); + let content = std::fs::read_to_string(&env_path)?; + let mut raw_providers = String::new(); + for line in content.lines() { + let line = line.trim(); + if let Some(rest) = line.strip_prefix("LLM_PROVIDERS=") { + raw_providers = rest.trim_matches('\'').trim_matches('"').to_string(); + } + } + assert!(!raw_providers.is_empty(), "LLM_PROVIDERS not found in .env"); + let client = LlmClient::from_json_str(&raw_providers)?; + println!("Loaded {} providers from .env", client.providers().len()); + + let health = client.health_check_all().await; + for h in &health { + println!( + "[HEALTH] provider={} endpoint={} model={} weight={} healthy={} latency={}ms detail={}", + h.provider.as_str(), + h.endpoint, + h.model, + h.weight, + h.healthy, + h.latency_ms, + h.detail + ); + } + assert!(health.iter().all(|h| h.healthy), "Expected all providers to be healthy"); + + #[derive(Debug, Deserialize)] + struct PingResp { + ok: bool, + provider_echo: String, + } + let schema = serde_json::json!({ + "type": "object", + "additionalProperties": false, + "required": ["ok", "provider_echo"], + "properties": { + "ok": { "type": "boolean" }, + "provider_echo": { "type": "string" } + } + }); + + for i in 1..=3 { + let out: ChatJsonOutput<PingResp> = client + .chat_json_with_meta( + "Respond with JSON matching the schema. Set ok=true and provider_echo='pong'.", + &[Part::text("ping")], + "ping_check", + &schema, + ) + .await?; + println!( + "[CALL #{i}] served_by={} ({}) -> ok={}, echo={}", + out.provider.as_str(), + out.model, + out.data.ok, + out.data.provider_echo + ); + } + Ok(()) + } +} diff --git a/crates/pipeline/Cargo.toml b/crates/pipeline/Cargo.toml new file mode 100644 index 0000000..a95c04d --- /dev/null +++ b/crates/pipeline/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "pipeline" +edition.workspace = true +version.workspace = true + +[dependencies] +domain = { workspace = true } +llm = { workspace = true } +providers = { workspace = true } +storage = { workspace = true } +reqwest = { workspace = true } +image = { workspace = true } +bytes = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true } +futures = { workspace = true } +dashmap = { workspace = true } +uuid = { workspace = true } +chrono = { workspace = true } +anyhow = { workspace = true } +tracing = { workspace = true } diff --git a/crates/pipeline/src/classify.rs b/crates/pipeline/src/classify.rs new file mode 100644 index 0000000..9d2d9b2 --- /dev/null +++ b/crates/pipeline/src/classify.rs @@ -0,0 +1,250 @@ +//! Step 4 & 5 of the pipeline: +//! - VLM batch photo classification (`PhotoTag` per photo) +//! - Multi-evidence floor voting (photo `floor_level` + text `floor_mentions`) + +use std::collections::BTreeMap; + +use domain::{ + floor_label, FloorEvidence, FurnitureCount, FurnitureKind, Photo, PhotoKind, PhotoTag, + PhotoZone, +}; +use llm::{LlmClient, Part}; +use providers::text::floor_mentions; +use serde::Deserialize; +use serde_json::{json, Value}; +use storage::TextDoc; + +const SYSTEM_PROMPT: &str = "\ +당신은 한국 식당·카페의 사진을 분류하고 공간 단서를 추출하는 비전 분석가입니다. +주어진 각 사진(index 0..N-1)과 캡션 단서를 보고 다음을 판별하세요: +- kind: interior(실내 공간/좌석/카운터/계단), exterior(건물 외관/간판), food(음식/음료 클로즈업), menu(메뉴판/가격표), person(인물 위주), other +- zone: entrance, counter, hall, window_side, terrace, restroom, stairs, kitchen, unknown +- floor_level: 사진이나 캡션에서 층수가 확인되면 정수(1=1층, 2=2층, -1=지하1층, 99=루프탑/옥상), 알 수 없으면 null +- floor_evidence: 층수를 판단한 근거(계단, 표지판, 캡션 문구 등, 없으면 빈 문자열) +- furniture: 사진에 보이는 가구 종류(table2, table4, table6, communal_table, bar_seat, sofa, counter_bar, plant)와 대략적 개수 +- quality: 공간 배치 파악에 도움이 되는 정도 (0.0~1.0) +- description: 공간 구조/좌석/창문/계단 중심 한국어 1문장 요약"; + +pub async fn classify_batch( + llm: &LlmClient, + batch: &[(&Photo, Vec<u8>)], +) -> anyhow::Result<Vec<(String, PhotoTag)>> { + if batch.is_empty() { + return Ok(Vec::new()); + } + let mut parts = Vec::with_capacity(batch.len() * 2 + 1); + parts.push(Part::text(format!( + "총 {}장의 사진입니다. 각 사진의 index(0..{})에 맞춰 분류 결과를 반환하세요.", + batch.len(), + batch.len() - 1 + ))); + for (idx, (photo, bytes)) in batch.iter().enumerate() { + parts.push(Part::text(format!( + "Photo index={idx}, id={}, source={:?}, caption={:?}", + photo.id, photo.source, photo.caption + ))); + parts.push(Part::Image { + bytes: bytes.clone(), + mime: "image/jpeg".into(), + }); + } + + let resp: BatchResp = llm + .chat_json(SYSTEM_PROMPT, &parts, "photo_classification", &schema()) + .await?; + + let mut out = Vec::new(); + for item in resp.items { + if let Some((photo, _)) = batch.get(item.index) { + out.push(( + photo.id.clone(), + PhotoTag { + kind: item.kind, + zone: item.zone, + floor_level: item.floor_level.filter(|&l| l == 99 || (-5..=20).contains(&l) && l != 0), + floor_evidence: item.floor_evidence, + furniture: item.furniture, + quality: item.quality.clamp(0.0, 1.0), + description: item.description, + }, + )); + } + } + Ok(out) +} + +#[derive(Deserialize)] +struct BatchResp { + items: Vec<BatchItem>, +} + +#[derive(Deserialize)] +struct BatchItem { + index: usize, + kind: PhotoKind, + zone: PhotoZone, + floor_level: Option<i32>, + floor_evidence: String, + furniture: Vec<FurnitureCount>, + quality: f32, + description: String, +} + +fn schema() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["items"], + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["index", "kind", "zone", "floor_level", "floor_evidence", "furniture", "quality", "description"], + "properties": { + "index": { "type": "integer" }, + "kind": { "type": "string", "enum": ["interior", "exterior", "food", "menu", "person", "other"] }, + "zone": { "type": "string", "enum": ["entrance", "counter", "hall", "window_side", "terrace", "restroom", "stairs", "kitchen", "unknown"] }, + "floor_level": { "type": ["integer", "null"] }, + "floor_evidence": { "type": "string" }, + "furniture": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "count"], + "properties": { + "kind": { "type": "string", "enum": ["table2", "table4", "table6", "communal_table", "bar_seat", "sofa", "counter_bar", "plant"] }, + "count": { "type": "integer" } + } + } + }, + "quality": { "type": "number" }, + "description": { "type": "string" } + } + } + } + } + }) +} + +/// Combine photo `floor_level` hints, photo captions, and text snippets into a ranked list of floors. +/// Always includes at least `1F` so single-floor venues have a ground floor. +pub fn detect_floors(photos: &[Photo], texts: &[TextDoc]) -> Vec<FloorEvidence> { + let mut map: BTreeMap<i32, FloorEvidence> = BTreeMap::new(); + let ensure = |map: &mut BTreeMap<i32, FloorEvidence>, level: i32| { + map.entry(level).or_insert_with(|| FloorEvidence { + level, + label: floor_label(level), + score: 0.0, + photo_ids: Vec::new(), + text_snippets: Vec::new(), + }); + }; + + for p in photos { + if let Some(tag) = &p.tag { + if let Some(lvl) = tag.floor_level { + ensure(&mut map, lvl); + let entry = map.get_mut(&lvl).unwrap(); + entry.score += if tag.kind == PhotoKind::Interior { 1.5 } else { 0.8 }; + if !entry.photo_ids.contains(&p.id) { + entry.photo_ids.push(p.id.clone()); + } + if !tag.floor_evidence.is_empty() && entry.text_snippets.len() < 4 { + entry.text_snippets.push(tag.floor_evidence.clone()); + } + } + } + for (lvl, snip) in floor_mentions(&p.caption) { + ensure(&mut map, lvl); + let entry = map.get_mut(&lvl).unwrap(); + entry.score += 0.7; + if !entry.photo_ids.contains(&p.id) { + entry.photo_ids.push(p.id.clone()); + } + if entry.text_snippets.len() < 4 && !entry.text_snippets.contains(&snip) { + entry.text_snippets.push(snip); + } + } + } + + for t in texts { + for (lvl, snip) in floor_mentions(&t.text) { + ensure(&mut map, lvl); + let entry = map.get_mut(&lvl).unwrap(); + entry.score += 0.5; + if entry.text_snippets.len() < 4 && !entry.text_snippets.contains(&snip) { + entry.text_snippets.push(snip); + } + } + } + + // Filter out weak stray mentions (e.g., a single "3층" referring to another tenant in the building) + // unless it's 1F. + let mut floors: Vec<FloorEvidence> = map + .into_values() + .filter(|f| f.level == 1 || f.score >= 1.0) + .collect(); + + if floors.is_empty() { + floors.push(FloorEvidence { + level: 1, + label: "1F".into(), + score: 1.0, + photo_ids: photos + .iter() + .filter(|p| p.tag.as_ref().map(|t| t.kind == PhotoKind::Interior).unwrap_or(false)) + .take(4) + .map(|p| p.id.clone()) + .collect(), + text_snippets: Vec::new(), + }); + } + + floors.sort_by_key(|f| f.level); + let _ = FurnitureKind::Table2; + floors +} + +#[cfg(test)] +mod tests { + use super::*; + use domain::PhotoSourceId; + + #[test] + fn floor_voting_combines_photo_and_text() { + let p = Photo { + id: "p1".into(), + place_id: "kakao:1".into(), + source: PhotoSourceId::NaverBlog, + image_url: String::new(), + page_url: String::new(), + caption: "2층 창가석".into(), + object_key: String::new(), + dhash: String::new(), + width: 800, + height: 600, + tag: Some(PhotoTag { + kind: PhotoKind::Interior, + zone: PhotoZone::WindowSide, + floor_level: Some(2), + floor_evidence: "계단 위 2층 홀".into(), + furniture: vec![], + quality: 0.9, + description: "2층 창가".into(), + }), + }; + let t = TextDoc { + place_id: "kakao:1".into(), + source: PhotoSourceId::NaverBlog, + url: String::new(), + text: "1층에서 주문하고 2층으로 올라가면 루프탑도 있어요. 루프탑 뷰가 최고".into(), + }; + let floors = detect_floors(&[p], &[t]); + let levels: Vec<i32> = floors.iter().map(|f| f.level).collect(); + assert!(levels.contains(&2)); + assert!(levels.contains(&domain::ROOFTOP_LEVEL)); + } +} diff --git a/crates/pipeline/src/dhash.rs b/crates/pipeline/src/dhash.rs new file mode 100644 index 0000000..cfb71f0 --- /dev/null +++ b/crates/pipeline/src/dhash.rs @@ -0,0 +1,79 @@ +//! Image decoding, resizing, and 64-bit perceptual difference hash (dHash). + +use image::imageops::FilterType; +use image::{DynamicImage, GenericImageView}; +use std::io::Cursor; + +pub struct ProcessedImage { + pub jpeg_bytes: Vec<u8>, + pub width: u32, + pub height: u32, + pub dhash: u64, +} + +/// Decode raw image bytes, reject tiny icons (< 160px), downscale to at most `max_dim` +/// on the longest side, re-encode as JPEG, and compute a 9x8 dHash. +pub fn process_image(bytes: &[u8], max_dim: u32) -> anyhow::Result<ProcessedImage> { + let img = image::load_from_memory(bytes)?; + let (w, h) = img.dimensions(); + if w < 160 || h < 160 { + anyhow::bail!("image too small ({w}x{h})"); + } + let dhash = compute_dhash(&img); + let resized = if w > max_dim || h > max_dim { + img.resize(max_dim, max_dim, FilterType::Triangle) + } else { + img + }; + let (rw, rh) = resized.dimensions(); + let mut out = Vec::new(); + resized.to_rgb8().write_to(&mut Cursor::new(&mut out), image::ImageFormat::Jpeg)?; + Ok(ProcessedImage { + jpeg_bytes: out, + width: rw, + height: rh, + dhash, + }) +} + +pub fn compute_dhash(img: &DynamicImage) -> u64 { + let gray = img.resize_exact(9, 8, FilterType::Triangle).to_luma8(); + let mut hash = 0u64; + let mut bit = 0; + for y in 0..8 { + for x in 0..8 { + if gray.get_pixel(x, y)[0] > gray.get_pixel(x + 1, y)[0] { + hash |= 1u64 << bit; + } + bit += 1; + } + } + hash +} + +pub fn hamming(a: u64, b: u64) -> u32 { + (a ^ b).count_ones() +} + +pub fn is_near_duplicate(existing: &[u64], candidate: u64) -> bool { + existing.iter().any(|&h| hamming(h, candidate) <= 6) +} + +#[cfg(test)] +mod tests { + use super::*; + use image::{Rgb, RgbImage}; + + #[test] + fn identical_images_match() { + let mut buf = RgbImage::new(200, 200); + for (x, y, p) in buf.enumerate_pixels_mut() { + *p = Rgb([(x % 255) as u8, (y % 255) as u8, 120]); + } + let dyn_img = DynamicImage::ImageRgb8(buf); + let h1 = compute_dhash(&dyn_img); + let h2 = compute_dhash(&dyn_img); + assert_eq!(hamming(h1, h2), 0); + assert!(is_near_duplicate(&[h1], h2)); + } +} diff --git a/crates/pipeline/src/layout_gen.rs b/crates/pipeline/src/layout_gen.rs new file mode 100644 index 0000000..9f5b048 --- /dev/null +++ b/crates/pipeline/src/layout_gen.rs @@ -0,0 +1,430 @@ +//! Step 6 & 7 of the pipeline: +//! - VLM spatial layout inference -> `domain::Layout` +//! - Validation & clamping (bounds, non-zero dimensions, valid `evidence_photos` IDs) +//! - Single retry with validation feedback if needed + +use std::collections::HashSet; + +use domain::{ + floor_label, Accessibility, Arrangement, Floor, FloorEvidence, FurnitureGroup, FurnitureKind, + Layout, Opening, OpeningKind, Photo, PhotoKind, Place, Summary, Tri, Vertical, VerticalKind, + Wall, Zone, ZoneKind, +}; +use llm::{LlmClient, Part}; +use serde::Deserialize; +use serde_json::{json, Value}; +use storage::TextDoc; + +const SYSTEM_PROMPT: &str = "\ +당신은 식당·카페의 실내 사진들과 텍스트 리뷰를 종합해 three.js 미니어처 3D 뷰어용 공간 배치(Layout JSON)를 추론하는 공간 건축 AI입니다. + +좌표 규칙 (층별 미터 단위): +- 각 층은 직사각형 바닥(width_m: 동서 폭, depth_m: 남북 깊이, 보통 6~22m 범위)입니다. +- 원점 (0, 0)은 남서쪽(South-West) 모서리이며, x는 동쪽(0..width_m), y는 북쪽(0..depth_m)으로 증가합니다. +- 주 출입구(entrance)는 기본적으로 south 벽에 두되, 사진 단서에 맞게 조정하세요. +- 각 zone(구역)의 직사각형 (x, y, w, d)는 바닥 범위(0 <= x, x+w <= width_m, 0 <= y, y+d <= depth_m) 안에 있어야 하며 서로 과도하게 겹치지 않게 배치하세요. +- evidence_photos 배열에는 반드시 입력으로 주어진 사진 id만 넣으세요 (절대 없는 id를 만들지 마세요). +- 다층 건물인 경우 층간 이동 수단(stairs 또는 elevator)을 verticals에 포함하세요. +- summary에는 예상 평수 범위, 예상 좌석 수, 좌석 종류, 방문 전 핵심 체크 포인트(highlights), 주의사항(caveats)을 한국어로 작성하세요."; + +pub async fn generate_layout( + llm: &LlmClient, + place: &Place, + photos_with_bytes: &[(&Photo, Vec<u8>)], + floors: &[FloorEvidence], + texts: &[TextDoc], + mut on_attempt: impl FnMut(u32), +) -> anyhow::Result<Layout> { + let valid_ids: HashSet<String> = photos_with_bytes.iter().map(|(p, _)| p.id.clone()).collect(); + let mut feedback: Option<String> = None; + + for attempt in 1..=2 { + on_attempt(attempt); + let parts = build_prompt_parts(place, photos_with_bytes, floors, texts, feedback.as_deref()); + match llm + .chat_json_with_meta::<DraftLayout>(SYSTEM_PROMPT, &parts, "space_layout", &schema()) + .await + { + Ok(out) => { + let model_tag = out.model_tag(); + let mut layout = into_layout(place, &model_tag, out.data, &valid_ids); + match validate_and_clamp(&mut layout) { + Ok(()) => return Ok(layout), + Err(err) if attempt == 1 => { + tracing::warn!(attempt, %err, "layout validation failed, retrying once"); + feedback = Some(err); + } + Err(err) => { + tracing::warn!(attempt, %err, "layout validation failed on second attempt, using clamped layout"); + return Ok(layout); + } + } + } + Err(err) if attempt == 1 => { + tracing::warn!(attempt, %err, "layout LLM call failed, retrying once"); + feedback = Some(format!("이전 응답 파싱 실패: {err}")); + } + Err(err) => { + tracing::warn!(%err, "layout LLM call failed twice, using fallback layout"); + return Ok(fallback_layout(place, &llm.model, photos_with_bytes, floors)); + } + } + } + Ok(fallback_layout(place, &llm.model, photos_with_bytes, floors)) +} + +fn build_prompt_parts( + place: &Place, + photos_with_bytes: &[(&Photo, Vec<u8>)], + floors: &[FloorEvidence], + texts: &[TextDoc], + feedback: Option<&str>, +) -> Vec<Part> { + let mut header = format!( + "장소명: {}\n카테고리: {}\n주소: {} ({})\n\n[감지된 층 단서]\n", + place.name, place.category, place.road_address, place.address + ); + for f in floors { + header.push_str(&format!( + "- {} (level={}, 점수={:.1}, 관련 사진={:?}, 텍스트 단서={:?})\n", + f.label, f.level, f.score, f.photo_ids, f.text_snippets + )); + } + header.push_str("\n[수집된 텍스트/리뷰 발췌]\n"); + for t in texts.iter().take(6) { + let excerpt: String = t.text.chars().take(450).collect(); + header.push_str(&format!("({:?}) {}\n---\n", t.source, excerpt)); + } + if let Some(fb) = feedback { + header.push_str(&format!( + "\n[이전 생성 결과 오류 - 반드시 수정하세요]\n{fb}\n" + )); + } + header.push_str("\n[실내/외관 핵심 사진 목록 — evidence_photos에는 아래 photo_id만 사용하세요]\n"); + + let mut parts = vec![Part::text(header)]; + for (p, bytes) in photos_with_bytes.iter().take(12) { + let tag_desc = p + .tag + .as_ref() + .map(|t| { + format!( + "kind={:?}, zone={:?}, floor={:?}, desc={}, furniture={:?}", + t.kind, t.zone, t.floor_level, t.description, t.furniture + ) + }) + .unwrap_or_default(); + parts.push(Part::text(format!( + "photo_id=\"{}\" | caption={:?} | {tag_desc}", + p.id, p.caption + ))); + parts.push(Part::Image { + bytes: bytes.clone(), + mime: "image/jpeg".into(), + }); + } + parts +} + +fn into_layout( + place: &Place, + model: &str, + draft: DraftLayout, + valid_ids: &HashSet<String>, +) -> Layout { + let floors = draft + .floors + .into_iter() + .map(|mut f| { + if f.label.trim().is_empty() { + f.label = floor_label(f.level); + } + for z in &mut f.zones { + z.evidence_photos.retain(|id| valid_ids.contains(id)); + } + f + }) + .collect(); + Layout { + place_id: place.id.clone(), + generated_at: chrono::Utc::now().to_rfc3339(), + model: model.to_string(), + confidence: draft.confidence.clamp(0.1, 0.98), + floors, + summary: draft.summary, + } +} + +/// Clamp coordinates into valid ranges and return `Err` if the layout had structural issues worth retrying. +pub fn validate_and_clamp(layout: &mut Layout) -> Result<(), String> { + if layout.floors.is_empty() { + return Err("floors 배열이 비어 있습니다. 최소 1개 층(1F)을 포함해야 합니다.".into()); + } + let mut issues = Vec::new(); + for f in &mut layout.floors { + if f.width_m < 4.0 || f.width_m > 40.0 { + issues.push(format!("층 {} width_m({})가 비정상 범위", f.label, f.width_m)); + f.width_m = f.width_m.clamp(5.0, 28.0); + } + if f.depth_m < 4.0 || f.depth_m > 40.0 { + issues.push(format!("층 {} depth_m({})가 비정상 범위", f.label, f.depth_m)); + f.depth_m = f.depth_m.clamp(5.0, 28.0); + } + f.confidence = f.confidence.clamp(0.1, 0.99); + if f.zones.is_empty() { + issues.push(format!("층 {}에 zones가 비어 있습니다.", f.label)); + } + for z in &mut f.zones { + z.w = z.w.clamp(1.2, f.width_m); + z.d = z.d.clamp(1.2, f.depth_m); + z.x = z.x.clamp(0.0, (f.width_m - z.w).max(0.0)); + z.y = z.y.clamp(0.0, (f.depth_m - z.d).max(0.0)); + for fg in &mut z.furniture { + fg.count = fg.count.clamp(1, 30); + } + } + for o in &mut f.openings { + let wall_len = match o.wall { + Wall::North | Wall::South => f.width_m, + Wall::East | Wall::West => f.depth_m, + }; + o.length_m = o.length_m.clamp(0.8, (wall_len - 0.4).max(0.8)); + o.offset_m = o.offset_m.clamp(0.2, (wall_len - o.length_m - 0.2).max(0.2)); + } + for v in &mut f.verticals { + v.w = v.w.clamp(1.0, 3.5); + v.d = v.d.clamp(1.2, 4.0); + v.x = v.x.clamp(0.0, (f.width_m - v.w).max(0.0)); + v.y = v.y.clamp(0.0, (f.depth_m - v.d).max(0.0)); + } + } + layout.floors.sort_by_key(|f| f.level); + if issues.is_empty() { + Ok(()) + } else { + Err(issues.join("; ")) + } +} + +pub fn fallback_layout( + place: &Place, + model: &str, + photos_with_bytes: &[(&Photo, Vec<u8>)], + floors: &[FloorEvidence], +) -> Layout { + let evidence: Vec<String> = photos_with_bytes.iter().take(4).map(|(p, _)| p.id.clone()).collect(); + let levels: Vec<i32> = if floors.is_empty() { + vec![1] + } else { + floors.iter().map(|f| f.level).collect() + }; + let built_floors = levels + .iter() + .map(|&lvl| Floor { + level: lvl, + label: floor_label(lvl), + confidence: 0.45, + width_m: 10.0, + depth_m: 12.0, + openings: if lvl == 1 { + vec![ + Opening { kind: OpeningKind::Entrance, wall: Wall::South, offset_m: 1.5, length_m: 1.6 }, + Opening { kind: OpeningKind::Window, wall: Wall::South, offset_m: 4.0, length_m: 4.5 }, + ] + } else { + vec![Opening { kind: OpeningKind::Window, wall: Wall::South, offset_m: 2.0, length_m: 6.0 }] + }, + zones: vec![ + Zone { + kind: if lvl == 1 { ZoneKind::Counter } else { ZoneKind::Seating }, + label: if lvl == 1 { "주문 카운터".into() } else { "창가 좌석".into() }, + x: 0.6, + y: if lvl == 1 { 8.2 } else { 0.6 }, + w: 4.2, + d: 3.0, + furniture: vec![FurnitureGroup { + kind: if lvl == 1 { FurnitureKind::CounterBar } else { FurnitureKind::BarSeat }, + count: if lvl == 1 { 1 } else { 5 }, + arrangement: Arrangement::AlongWall, + along_wall: Some(if lvl == 1 { Wall::North } else { Wall::South }), + }], + evidence_photos: evidence.clone(), + }, + Zone { + kind: ZoneKind::Seating, + label: "메인 홀 좌석".into(), + x: 0.8, + y: if lvl == 1 { 1.0 } else { 4.2 }, + w: 8.4, + d: 6.5, + furniture: vec![ + FurnitureGroup { + kind: FurnitureKind::Table2, + count: 5, + arrangement: Arrangement::Grid, + along_wall: None, + }, + FurnitureGroup { + kind: FurnitureKind::Table4, + count: 3, + arrangement: Arrangement::Grid, + along_wall: None, + }, + ], + evidence_photos: evidence.clone(), + }, + ], + verticals: if levels.len() > 1 { + vec![Vertical { + kind: VerticalKind::Stairs, + x: 7.8, + y: 9.2, + w: 1.6, + d: 2.2, + to_level: if lvl == 1 { levels.get(1).copied().unwrap_or(2) } else { 1 }, + }] + } else { + vec![] + }, + notes: "수집된 사진을 기반으로 생성한 기본 추정 배치입니다.".into(), + }) + .collect(); + + let _ = PhotoKind::Interior; + Layout { + place_id: place.id.clone(), + generated_at: chrono::Utc::now().to_rfc3339(), + model: model.to_string(), + confidence: 0.45, + floors: built_floors, + summary: Summary { + area_pyeong_min: 18.0, + area_pyeong_max: 28.0, + seat_estimate: 26, + seat_types: vec!["2인 테이블".into(), "4인 테이블".into(), "바 좌석".into()], + highlights: vec![format!("{} 공간 배치 추정 완료", place.name)], + accessibility: Accessibility { + elevator: Tri::Unknown, + step_free_entrance: Tri::Likely, + }, + caveats: vec!["실내 사진 수량이 제한적이어서 일부 구역은 표준 배치로 추정되었습니다.".into()], + }, + } +} + +#[derive(Deserialize)] +struct DraftLayout { + confidence: f32, + floors: Vec<Floor>, + summary: Summary, +} + +fn schema() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["confidence", "floors", "summary"], + "properties": { + "confidence": { "type": "number" }, + "floors": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["level", "label", "confidence", "width_m", "depth_m", "openings", "zones", "verticals", "notes"], + "properties": { + "level": { "type": "integer" }, + "label": { "type": "string" }, + "confidence": { "type": "number" }, + "width_m": { "type": "number" }, + "depth_m": { "type": "number" }, + "openings": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "wall", "offset_m", "length_m"], + "properties": { + "kind": { "type": "string", "enum": ["entrance", "window", "door"] }, + "wall": { "type": "string", "enum": ["north", "south", "east", "west"] }, + "offset_m": { "type": "number" }, + "length_m": { "type": "number" } + } + } + }, + "zones": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "label", "x", "y", "w", "d", "furniture", "evidence_photos"], + "properties": { + "kind": { "type": "string", "enum": ["seating", "counter", "bar", "kitchen", "restroom", "terrace", "entrance", "other"] }, + "label": { "type": "string" }, + "x": { "type": "number" }, + "y": { "type": "number" }, + "w": { "type": "number" }, + "d": { "type": "number" }, + "furniture": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "count", "arrangement", "along_wall"], + "properties": { + "kind": { "type": "string", "enum": ["table2", "table4", "table6", "communal_table", "bar_seat", "sofa", "counter_bar", "plant"] }, + "count": { "type": "integer" }, + "arrangement": { "type": "string", "enum": ["grid", "along_wall", "row", "cluster"] }, + "along_wall": { "type": ["string", "null"], "enum": ["north", "south", "east", "west", null] } + } + } + }, + "evidence_photos": { "type": "array", "items": { "type": "string" } } + } + } + }, + "verticals": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "x", "y", "w", "d", "to_level"], + "properties": { + "kind": { "type": "string", "enum": ["stairs", "elevator"] }, + "x": { "type": "number" }, + "y": { "type": "number" }, + "w": { "type": "number" }, + "d": { "type": "number" }, + "to_level": { "type": "integer" } + } + } + }, + "notes": { "type": "string" } + } + } + }, + "summary": { + "type": "object", + "additionalProperties": false, + "required": ["area_pyeong_min", "area_pyeong_max", "seat_estimate", "seat_types", "highlights", "accessibility", "caveats"], + "properties": { + "area_pyeong_min": { "type": "number" }, + "area_pyeong_max": { "type": "number" }, + "seat_estimate": { "type": "integer" }, + "seat_types": { "type": "array", "items": { "type": "string" } }, + "highlights": { "type": "array", "items": { "type": "string" } }, + "accessibility": { + "type": "object", + "additionalProperties": false, + "required": ["elevator", "step_free_entrance"], + "properties": { + "elevator": { "type": "string", "enum": ["yes", "likely", "no", "unknown"] }, + "step_free_entrance": { "type": "string", "enum": ["yes", "likely", "no", "unknown"] } + } + }, + "caveats": { "type": "array", "items": { "type": "string" } } + } + } + } + }) +} diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs new file mode 100644 index 0000000..59fd8ab --- /dev/null +++ b/crates/pipeline/src/lib.rs @@ -0,0 +1,482 @@ +#![recursion_limit = "256"] +//! End-to-end place analysis pipeline: +//! 1. Normalize place (Kakao candidate + NCP Geocode address verification + Naver place ID resolution) +//! 2. Collect photos & texts in parallel across all `PhotoSource`s (per-source timeout) +//! 3. Download images, deduplicate with 64-bit dHash, store JPEG blobs in MinIO & metadata in MongoDB +//! 4. Classify photos in batches with the VLM (`PhotoTag`) +//! 5. Vote on floors (`FloorEvidence`) from photo tags, captions, and text snippets +//! 6. Generate 3D `Layout` JSON with the VLM +//! 7. Validate & clamp layout (retry once on structural issues) and save to MongoDB + +pub mod classify; +pub mod dhash; +pub mod layout_gen; + +use std::sync::Arc; +use std::time::Duration; + +use bytes::Bytes; +use dashmap::DashMap; +use domain::{ + JobEvent, Photo, PhotoKind, PhotoSummary, Place, PlaceCandidate, PlaceView, RawPhoto, RecentPlace, +}; +use futures::stream::{self, StreamExt}; +use llm::LlmClient; +use providers::browser::{browser_source, BrowserSource}; +use providers::kakao_local::KakaoLocal; +use providers::kakao_place::KakaoPlacePhotos; +use providers::naver_blog::NaverBlog; +use providers::naver_map::NaverMapSearch; +use providers::naver_place::NaverPlacePhotos; +use providers::ncp_geocode::NcpGeocode; +use providers::{PhotoSource, PlaceSearch}; +use storage::{Store, TextDoc}; +use tokio::sync::broadcast; + +#[derive(Clone)] +pub struct PipelineConfig { + pub kakao_api_key: String, + pub ncp_client_id: String, + pub ncp_client_secret: String, + pub browser_scraper_url: Option<String>, + pub max_photos_per_source: usize, + pub max_photos_total: usize, +} + +#[derive(Clone)] +pub struct Pipeline { + pub store: Store, + pub llm: LlmClient, + kakao: Arc<KakaoLocal>, + naver_map: Arc<NaverMapSearch>, + ncp: Option<Arc<NcpGeocode>>, + sources: Arc<Vec<Box<dyn PhotoSource>>>, + http: reqwest::Client, + cfg: PipelineConfig, + /// Active job event broadcasters keyed by `job_id`. + jobs: Arc<DashMap<String, broadcast::Sender<JobEvent>>>, + /// Map `place_id` -> currently running `job_id` so concurrent visitors share one job. + running_by_place: Arc<DashMap<String, String>>, +} + +impl Pipeline { + pub fn new(store: Store, llm: LlmClient, cfg: PipelineConfig) -> Self { + let kakao = Arc::new(KakaoLocal::new(&cfg.kakao_api_key)); + let naver_map = Arc::new(NaverMapSearch::new()); + let ncp = if !cfg.ncp_client_id.trim().is_empty() && !cfg.ncp_client_secret.trim().is_empty() { + Some(Arc::new(NcpGeocode::new(&cfg.ncp_client_id, &cfg.ncp_client_secret))) + } else { + None + }; + let sources: Vec<Box<dyn PhotoSource>> = vec![ + Box::new(NaverPlacePhotos::new()), + Box::new(KakaoPlacePhotos::new()), + Box::new(NaverBlog::new()), + browser_source(cfg.browser_scraper_url.as_deref(), BrowserSource::GoogleMaps), + browser_source(cfg.browser_scraper_url.as_deref(), BrowserSource::Instagram), + ]; + Self { + store, + llm, + kakao, + naver_map, + ncp, + sources: Arc::new(sources), + http: providers::http::scraping_client(), + cfg, + jobs: Arc::new(DashMap::new()), + running_by_place: Arc::new(DashMap::new()), + } + } + + /// Search place candidates by free text (Kakao primary, Naver Map fallback). + pub async fn search_places(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>> { + let q = query.trim(); + if q.is_empty() { + return Ok(Vec::new()); + } + let mut results = self.kakao.search(q).await.unwrap_or_default(); + if results.is_empty() { + results = self.naver_map.search(q).await.unwrap_or_default(); + } + Ok(results) + } + + /// Saved analyses ordered by their most recent view (or analysis time for older records). + pub async fn recent_places(&self) -> anyhow::Result<Vec<RecentPlace>> { + self.store.recent_places().await + } + + /// Return current `PlaceView` (place + latest cached layout + stored photos + running job id). + pub async fn get_place_view(&self, place_id: &str) -> anyhow::Result<Option<PlaceView>> { + let Some(place) = self.store.get_place(place_id).await? else { + return Ok(None); + }; + let layout = self.store.latest_layout(place_id).await?.map(|d| d.layout); + let photos = self + .store + .photos_for_place(place_id) + .await? + .iter() + .map(PhotoSummary::from) + .collect(); + let running_job = self.running_by_place.get(place_id).map(|v| v.value().clone()); + if layout.is_some() { + if let Err(error) = self.store.record_place_view(place_id).await { + tracing::warn!(%place_id, %error, "could not record place view"); + } + } + Ok(Some(PlaceView { + place, + layout, + photos, + running_job, + })) + } + + /// Subscribe to live events for `job_id`, plus any events already recorded in MongoDB. + pub async fn subscribe_job( + &self, + job_id: &str, + ) -> anyhow::Result<(Vec<JobEvent>, Option<broadcast::Receiver<JobEvent>>)> { + let rx = self.jobs.get(job_id).map(|s| s.value().subscribe()); + let past = self + .store + .get_job(job_id) + .await? + .map(|j| j.events) + .unwrap_or_default(); + Ok((past, rx)) + } + + /// Ensure the candidate's `Place` exists in MongoDB; if no cached layout exists (or `force_reanalyze` is true), + /// spawn the analysis job in the background and return `(place_id, Option<job_id>)`. + pub async fn select_or_analyze( + &self, + candidate: PlaceCandidate, + force_reanalyze: bool, + ) -> anyhow::Result<(String, Option<String>)> { + let place_id = candidate.place_id(); + let mut place = match self.store.get_place(&place_id).await? { + Some(existing) => existing, + None => { + let p = Place::from_candidate(&candidate); + self.store.upsert_place(&p).await?; + p + } + }; + + if !force_reanalyze { + if let Some( job_id ) = self.running_by_place.get(&place_id).map(|r| r.value().clone()) { + return Ok((place_id, Some(job_id))); + } + if self.store.latest_layout(&place_id).await?.is_some() { + return Ok((place_id, None)); + } + } + + let job_id = self.spawn_job(place_id.clone(), place.clone(), force_reanalyze).await?; + let _ = &mut place; + Ok((place_id, Some(job_id))) + } + + /// Trigger reanalysis for an already-stored `place_id`. + pub async fn reanalyze(&self, place_id: &str) -> anyhow::Result<String> { + if let Some(existing) = self.running_by_place.get(place_id) { + return Ok(existing.value().clone()); + } + let place = self + .store + .get_place(place_id) + .await? + .ok_or_else(|| anyhow::anyhow!("장소를 찾을 수 없습니다: {place_id}"))?; + self.spawn_job(place_id.to_string(), place, true).await + } + + async fn spawn_job( + &self, + place_id: String, + place: Place, + clear_existing_photos: bool, + ) -> anyhow::Result<String> { + let job_id = uuid::Uuid::new_v4().to_string(); + self.store.create_job(&job_id, &place_id).await?; + let (tx, _) = broadcast::channel(64); + self.jobs.insert(job_id.clone(), tx.clone()); + self.running_by_place.insert(place_id.clone(), job_id.clone()); + + let this = self.clone(); + let jid = job_id.clone(); + let pid = place_id.clone(); + tokio::spawn(async move { + if let Err(err) = this.run_job(&jid, place, clear_existing_photos, &tx).await { + tracing::error!(job_id = %jid, place_id = %pid, "pipeline job failed: {err:#}"); + this.emit(&jid, &tx, JobEvent::Error { message: err.to_string() }).await; + } + this.running_by_place.remove(&pid); + // Keep channel briefly so SSE clients receive the terminal event, then drop. + tokio::time::sleep(Duration::from_secs(5)).await; + this.jobs.remove(&jid); + }); + + Ok(job_id) + } + + /// Run a place analysis synchronously (used by `precompute` CLI and `spawn_job`). + pub async fn run_sync(&self, place: Place) -> anyhow::Result<domain::Layout> { + let job_id = uuid::Uuid::new_v4().to_string(); + self.store.upsert_place(&place).await?; + self.store.create_job(&job_id, &place.id).await?; + let (tx, _) = broadcast::channel(64); + self.run_job(&job_id, place.clone(), false, &tx).await?; + let doc = self + .store + .latest_layout(&place.id) + .await? + .ok_or_else(|| anyhow::anyhow!("layout not saved"))?; + Ok(doc.layout) + } + + async fn emit(&self, job_id: &str, tx: &broadcast::Sender<JobEvent>, ev: JobEvent) { + let _ = self.store.push_job_event(job_id, &ev).await; + let _ = tx.send(ev); + } + + async fn run_job( + &self, + job_id: &str, + mut place: Place, + clear_existing_photos: bool, + tx: &broadcast::Sender<JobEvent>, + ) -> anyhow::Result<()> { + self.emit(job_id, tx, JobEvent::Started { place_id: place.id.clone() }).await; + + // 1. Address verification (NCP Geocode) + Naver Place ID matching + if let Some(ncp) = &self.ncp { + let addr_query = if !place.road_address.is_empty() { + place.road_address.clone() + } else { + place.address.clone() + }; + if !addr_query.is_empty() { + if let Ok(Some(geo)) = ncp.geocode(&addr_query).await { + if place.road_address.is_empty() && !geo.road_address.is_empty() { + place.road_address = geo.road_address; + } + if place.address.is_empty() && !geo.jibun_address.is_empty() { + place.address = geo.jibun_address; + } + } + } + } + if place.naver_place_id.is_none() { + if let Ok(Some(nid)) = self.naver_map.resolve_place_id(&place).await { + place.naver_place_id = Some(nid); + } + } + self.store.upsert_place(&place).await?; + self.emit( + job_id, + tx, + JobEvent::PlaceResolved { + name: place.name.clone(), + naver_place_id: place.naver_place_id.clone(), + }, + ) + .await; + + // 2. Collect photos & text snippets from all sources in parallel + let per_source = self.cfg.max_photos_per_source; + let source_futs = self.sources.iter().map(|src| { + let place_ref = &place; + async move { + let id = src.id(); + let res = tokio::time::timeout(Duration::from_secs(30), src.collect(place_ref, per_source)).await; + match res { + Ok(Ok(out)) => (id, out, None), + Ok(Err(e)) => (id, Default::default(), Some(e.to_string())), + Err(_) => (id, Default::default(), Some("시간 초과 (30s)".into())), + } + } + }); + let collected = futures::future::join_all(source_futs).await; + + let mut raw_photos: Vec<RawPhoto> = Vec::new(); + let mut text_docs: Vec<TextDoc> = Vec::new(); + for (source, out, error) in collected { + self.emit( + job_id, + tx, + JobEvent::SourceDone { + source, + photos: out.photos.len(), + texts: out.texts.len(), + error, + }, + ) + .await; + raw_photos.extend(out.photos); + for t in out.texts { + text_docs.push(TextDoc { + place_id: place.id.clone(), + source: t.source, + url: t.url, + text: t.text, + }); + } + } + let _ = self.store.replace_texts(&place.id, &text_docs).await; + raw_photos.truncate(self.cfg.max_photos_total); + + // 3. Download, deduplicate (dHash), and store in MinIO + MongoDB + if clear_existing_photos { + let _ = self.store.delete_photos_for_place(&place.id).await; + } + let downloaded: Vec<Option<(RawPhoto, dhash::ProcessedImage)>> = stream::iter(raw_photos) + .map(|raw| { + let client = self.http.clone(); + async move { + let mut req = client.get(&raw.image_url); + if let Some(r) = &raw.referer { + req = req.header(reqwest::header::REFERER, r); + } + let bytes = tokio::time::timeout(Duration::from_secs(15), async { + Ok::<_, anyhow::Error>(req.send().await?.error_for_status()?.bytes().await?) + }) + .await + .ok()? + .ok()?; + let processed = dhash::process_image(&bytes, 1024).ok()?; + Some((raw, processed)) + } + }) + .buffer_unordered(8) + .collect() + .await; + + let mut seen_hashes: Vec<u64> = Vec::new(); + let mut stored_photos: Vec<(Photo, Vec<u8>)> = Vec::new(); + let mut duplicates = 0usize; + let mut failed = 0usize; + + for item in downloaded { + let Some((raw, proc_img)) = item else { + failed += 1; + continue; + }; + if dhash::is_near_duplicate(&seen_hashes, proc_img.dhash) { + duplicates += 1; + continue; + } + seen_hashes.push(proc_img.dhash); + let photo_id = format!("p_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]); + let object_key = format!("places/{}/{photo_id}.jpg", place.id.replace(':', "_")); + if let Err(e) = self.store.put_blob(&object_key, Bytes::from(proc_img.jpeg_bytes.clone())).await { + tracing::warn!(%e, "minio put_blob failed"); + failed += 1; + continue; + } + let photo = Photo { + id: photo_id, + place_id: place.id.clone(), + source: raw.source, + image_url: raw.image_url, + page_url: raw.page_url, + caption: raw.caption, + object_key, + dhash: format!("{:016x}", proc_img.dhash), + width: proc_img.width, + height: proc_img.height, + tag: None, + }; + self.store.insert_photo(&photo).await?; + stored_photos.push((photo, proc_img.jpeg_bytes)); + } + + self.emit( + job_id, + tx, + JobEvent::PhotosStored { + stored: stored_photos.len(), + duplicates, + failed, + }, + ) + .await; + + // 4. Classify photos in batches of 6 via VLM + let to_classify_len = stored_photos.len().min(36); + for chunk in stored_photos[..to_classify_len].chunks_mut(6) { + let refs: Vec<(&Photo, Vec<u8>)> = chunk.iter().map(|(p, b)| (p, b.clone())).collect(); + match classify::classify_batch(&self.llm, &refs).await { + Ok(tags) => { + for (pid, tag) in tags { + let _ = self.store.set_photo_tag(&pid, &tag).await; + if let Some((p, _)) = chunk.iter_mut().find(|(p, _)| p.id == pid) { + p.tag = Some(tag); + } + } + } + Err(e) => { + tracing::warn!(%e, "photo batch classification failed"); + } + } + } + + let mut interior = 0usize; + let mut exterior = 0usize; + let mut food = 0usize; + let mut other = 0usize; + for (p, _) in &stored_photos { + match p.tag.as_ref().map(|t| t.kind) { + Some(PhotoKind::Interior) => interior += 1, + Some(PhotoKind::Exterior) => exterior += 1, + Some(PhotoKind::Food) => food += 1, + _ => other += 1, + } + } + self.emit(job_id, tx, JobEvent::Classified { interior, exterior, food, other }).await; + + // 5. Floor detection + let all_photos: Vec<Photo> = stored_photos.iter().map(|(p, _)| p.clone()).collect(); + let floors = classify::detect_floors(&all_photos, &text_docs); + self.emit(job_id, tx, JobEvent::FloorsDetected { floors: floors.clone() }).await; + + // 6 & 7. Select top interior/exterior photos and infer 3D layout + let mut ranked: Vec<(&Photo, Vec<u8>)> = stored_photos + .iter() + .filter(|(p, _)| { + matches!( + p.tag.as_ref().map(|t| t.kind), + Some(PhotoKind::Interior | PhotoKind::Exterior) | None + ) + }) + .map(|(p, b)| (p, b.clone())) + .collect(); + ranked.sort_by(|(a, _), (b, _)| { + let score = |p: &Photo| match &p.tag { + Some(t) if t.kind == PhotoKind::Interior => 2.0 + t.quality, + Some(t) if t.kind == PhotoKind::Exterior => 1.0 + t.quality, + Some(t) => t.quality, + None => 0.5, + }; + score(b).total_cmp(&score(a)) + }); + ranked.truncate(12); + + self.emit(job_id, tx, JobEvent::LayoutDraft { attempt: 1 }).await; + let layout = layout_gen::generate_layout( + &self.llm, + &place, + &ranked, + &floors, + &text_docs, + |_attempt| {}, + ) + .await?; + + self.store.save_layout(&layout).await?; + self.emit(job_id, tx, JobEvent::Done { place_id: place.id.clone() }).await; + Ok(()) + } +} diff --git a/crates/providers/Cargo.toml b/crates/providers/Cargo.toml new file mode 100644 index 0000000..c7113be --- /dev/null +++ b/crates/providers/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "providers" +edition.workspace = true +version.workspace = true + +[dependencies] +domain = { workspace = true } +async-trait = { workspace = true } +reqwest = { workspace = true } +scraper = { workspace = true } +regex = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +url = { workspace = true } +urlencoding = { workspace = true } +tokio = { workspace = true } +futures = { workspace = true } +anyhow = { workspace = true } +tracing = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true } diff --git a/crates/providers/src/browser.rs b/crates/providers/src/browser.rs new file mode 100644 index 0000000..47be70e --- /dev/null +++ b/crates/providers/src/browser.rs @@ -0,0 +1,224 @@ +//! Client for the external browser-scraping microservice (Google Maps, Instagram, ...). +//! +//! The service is not implemented yet. Contract (async job API): +//! +//! ```text +//! POST {BASE}/jobs +//! { "source": "google_maps" | "instagram", +//! "place": { "name", "address", "lat", "lng" }, +//! "limit": 50, +//! "callback_url": null } +//! -> 202 { "job_id": "..." } +//! +//! GET {BASE}/jobs/{job_id} +//! -> { "status": "queued" | "running" | "done" | "failed", +//! "items": [ { "image_url", "caption", "source_url", "taken_at" } ], +//! "texts": [ { "text", "source_url" } ], +//! "error": null } +//! ``` +//! +//! When `BROWSER_SCRAPER_URL` is unset, [`MockBrowserScraper`] is used instead. + +use std::time::Duration; + +use async_trait::async_trait; +use domain::{PhotoSourceId, Place, RawPhoto, SourceOutput, TextSnippet}; +use serde::{Deserialize, Serialize}; + +use crate::PhotoSource; + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum BrowserSource { + GoogleMaps, + Instagram, +} + +impl BrowserSource { + pub fn photo_source_id(self) -> PhotoSourceId { + match self { + BrowserSource::GoogleMaps => PhotoSourceId::GoogleMaps, + BrowserSource::Instagram => PhotoSourceId::Instagram, + } + } +} + +#[derive(Debug, Serialize)] +pub struct JobRequest<'a> { + pub source: BrowserSource, + pub place: JobPlace<'a>, + pub limit: usize, + pub callback_url: Option<String>, +} + +#[derive(Debug, Serialize)] +pub struct JobPlace<'a> { + pub name: &'a str, + pub address: &'a str, + pub lat: f64, + pub lng: f64, +} + +#[derive(Debug, Deserialize)] +pub struct JobCreated { + pub job_id: String, +} + +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum JobState { + Queued, + Running, + Done, + Failed, +} + +#[derive(Debug, Deserialize)] +pub struct JobResult { + pub status: JobState, + #[serde(default)] + pub items: Vec<JobItem>, + #[serde(default)] + pub texts: Vec<JobText>, + pub error: Option<String>, +} + +#[derive(Debug, Deserialize)] +pub struct JobItem { + pub image_url: String, + #[serde(default)] + pub caption: String, + #[serde(default)] + pub source_url: String, + pub taken_at: Option<String>, +} + +#[derive(Debug, Deserialize)] +pub struct JobText { + pub text: String, + #[serde(default)] + pub source_url: String, +} + +/// HTTP client for the real service. +pub struct BrowserScraperClient { + client: reqwest::Client, + base: String, + source: BrowserSource, + poll_every: Duration, + timeout: Duration, +} + +impl BrowserScraperClient { + pub fn new(base: impl Into<String>, source: BrowserSource) -> Self { + Self { + client: crate::http::api_client(), + base: base.into().trim_end_matches('/').to_string(), + source, + poll_every: Duration::from_secs(2), + timeout: Duration::from_secs(120), + } + } +} + +#[async_trait] +impl PhotoSource for BrowserScraperClient { + fn id(&self) -> PhotoSourceId { + self.source.photo_source_id() + } + + async fn collect(&self, place: &Place, limit: usize) -> anyhow::Result<SourceOutput> { + let req = JobRequest { + source: self.source, + place: JobPlace { + name: &place.name, + address: if place.road_address.is_empty() { &place.address } else { &place.road_address }, + lat: place.lat, + lng: place.lng, + }, + limit, + callback_url: None, + }; + let created: JobCreated = self + .client + .post(format!("{}/jobs", self.base)) + .json(&req) + .send() + .await? + .error_for_status()? + .json() + .await?; + + let deadline = tokio::time::Instant::now() + self.timeout; + loop { + tokio::time::sleep(self.poll_every).await; + let r: JobResult = self + .client + .get(format!("{}/jobs/{}", self.base, created.job_id)) + .send() + .await? + .error_for_status()? + .json() + .await?; + match r.status { + JobState::Done => return Ok(to_output(self.id(), r)), + JobState::Failed => anyhow::bail!("browser scraper failed: {}", r.error.unwrap_or_default()), + _ if tokio::time::Instant::now() > deadline => anyhow::bail!("browser scraper timed out"), + _ => {} + } + } + } +} + +fn to_output(source: PhotoSourceId, r: JobResult) -> SourceOutput { + SourceOutput { + photos: r + .items + .into_iter() + .map(|i| RawPhoto { + source, + image_url: i.image_url, + page_url: i.source_url, + caption: i.caption, + referer: None, + }) + .collect(), + texts: r + .texts + .into_iter() + .map(|t| TextSnippet { source, url: t.source_url, text: t.text }) + .collect(), + } +} + +/// Stand-in used until the browser service exists. Returns nothing (but succeeds) +/// so the pipeline treats the source as "empty" rather than failed. +pub struct MockBrowserScraper { + source: BrowserSource, +} + +impl MockBrowserScraper { + pub fn new(source: BrowserSource) -> Self { + Self { source } + } +} + +#[async_trait] +impl PhotoSource for MockBrowserScraper { + fn id(&self) -> PhotoSourceId { + self.source.photo_source_id() + } + + async fn collect(&self, place: &Place, _limit: usize) -> anyhow::Result<SourceOutput> { + tracing::info!(source = ?self.source, place = %place.name, "browser scraper not configured (mock): returning no results"); + Ok(SourceOutput::default()) + } +} + +/// Pick the real client or the mock depending on configuration. +pub fn browser_source(base_url: Option<&str>, source: BrowserSource) -> Box<dyn PhotoSource> { + match base_url.filter(|u| !u.trim().is_empty()) { + Some(u) => Box::new(BrowserScraperClient::new(u, source)), + None => Box::new(MockBrowserScraper::new(source)), + } +} diff --git a/crates/providers/src/http.rs b/crates/providers/src/http.rs new file mode 100644 index 0000000..a12641e --- /dev/null +++ b/crates/providers/src/http.rs @@ -0,0 +1,60 @@ +use std::time::Duration; + +use regex::Regex; + +pub const DESKTOP_UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"; +pub const MOBILE_UA: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1"; + +/// Shared HTTP client for scraping: browser UA, cookies, gzip, sane timeouts. +pub fn scraping_client() -> reqwest::Client { + reqwest::Client::builder() + .user_agent(DESKTOP_UA) + .cookie_store(true) + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(25)) + .default_headers({ + let mut h = reqwest::header::HeaderMap::new(); + h.insert(reqwest::header::ACCEPT_LANGUAGE, "ko-KR,ko;q=0.9,en;q=0.8".parse().unwrap()); + h + }) + .build() + .expect("reqwest client") +} + +/// Client for official JSON APIs. +pub fn api_client() -> reqwest::Client { + reqwest::Client::builder() + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(20)) + .build() + .expect("reqwest client") +} + +/// Extract image URLs from arbitrary text (HTML, embedded JSON) whose host matches +/// one of `host_patterns` (regex fragments). Handles `\/` and `\u002F` escaping. +pub fn extract_image_urls(body: &str, host_patterns: &[&str]) -> Vec<String> { + let unescaped = body.replace("\\u002F", "/").replace("\\/", "/").replace("&", "&"); + let hosts = host_patterns.join("|"); + let re = Regex::new(&format!( + r#"https?://(?:{hosts})[^\s"'<>\\)]*?\.(?:jpe?g|png|webp|JPE?G|PNG|WEBP)(?:\?[^\s"'<>\\)]*)?"# + )) + .expect("valid regex"); + let mut seen = std::collections::HashSet::new(); + re.find_iter(&unescaped) + .map(|m| m.as_str().to_string()) + .filter(|u| seen.insert(u.clone())) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extracts_escaped_urls() { + let body = r#"{"a":"https:\/\/ldb-phinf.pstatic.net\/2024\/abc.jpg","b":"https:\u002F\u002Fldb-phinf.pstatic.net\u002Fx\u002Fy.JPG?type=w750"}"#; + let urls = extract_image_urls(body, &[r"ldb-phinf\.pstatic\.net"]); + assert_eq!(urls.len(), 2); + assert!(urls[1].ends_with("?type=w750")); + } +} diff --git a/crates/providers/src/kakao_local.rs b/crates/providers/src/kakao_local.rs new file mode 100644 index 0000000..60faa9e --- /dev/null +++ b/crates/providers/src/kakao_local.rs @@ -0,0 +1,253 @@ +//! Kakao Local REST API (official) with a keyless web-search fallback (`search.map.kakao.com`). +//! Docs: https://developers.kakao.com/docs/latest/ko/local/dev-guide + +use async_trait::async_trait; +use domain::PlaceCandidate; +use serde::Deserialize; + +use crate::PlaceSearch; + +const BASE: &str = "https://dapi.kakao.com/v2/local"; +const WEB_SEARCH: &str = "https://search.map.kakao.com/mapsearch/map.daum"; + +pub struct KakaoLocal { + client: reqwest::Client, + scrape_client: reqwest::Client, + key: String, +} + +impl KakaoLocal { + pub fn new(key: impl Into<String>) -> Self { + Self { + client: crate::http::api_client(), + scrape_client: crate::http::scraping_client(), + key: key.into().trim().to_string(), + } + } + + pub fn has_api_key(&self) -> bool { + !self.key.is_empty() + } + + async fn get<T: for<'de> Deserialize<'de>>(&self, path: &str, query: &[(&str, String)]) -> anyhow::Result<T> { + let resp = self + .client + .get(format!("{BASE}/{path}")) + .header("Authorization", format!("KakaoAK {}", self.key)) + .query(query) + .send() + .await?; + let status = resp.status(); + if !status.is_success() { + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!("kakao {path} {status}: {body}"); + } + Ok(resp.json().await?) + } + + pub async fn keyword(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>> { + let r: KeywordResp = self.get("search/keyword.json", &[("query", query.to_string()), ("size", "15".into())]).await?; + Ok(r.documents.into_iter().map(Into::into).collect()) + } + + /// Places of category (FD6 음식점, CE7 카페) around a coordinate. + pub async fn category_near(&self, code: &str, lat: f64, lng: f64, radius_m: u32) -> anyhow::Result<Vec<PlaceCandidate>> { + let r: KeywordResp = self + .get( + "search/category.json", + &[ + ("category_group_code", code.to_string()), + ("x", lng.to_string()), + ("y", lat.to_string()), + ("radius", radius_m.to_string()), + ("sort", "distance".into()), + ], + ) + .await?; + Ok(r.documents.into_iter().map(Into::into).collect()) + } + + /// Address → coordinates (first match). + pub async fn address(&self, query: &str) -> anyhow::Result<Option<(f64, f64, String)>> { + let r: AddressResp = self.get("search/address.json", &[("query", query.to_string())]).await?; + Ok(r.documents.into_iter().next().and_then(|d| { + Some((d.y.parse().ok()?, d.x.parse().ok()?, d.address_name)) + })) + } + + /// Keyless fallback via Kakao Map's web JSONP endpoint (`search.map.kakao.com/mapsearch/map.daum`). + pub async fn web_search(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>> { + let text = self + .scrape_client + .get(WEB_SEARCH) + .header(reqwest::header::REFERER, "https://map.kakao.com/") + .query(&[("callback", "j"), ("q", query), ("msFlag", "A"), ("sort", "0")]) + .send() + .await? + .error_for_status()? + .text() + .await?; + parse_web_search_jsonp(&text) + } +} + +pub fn parse_web_search_jsonp(text: &str) -> anyhow::Result<Vec<PlaceCandidate>> { + let start = text.find('{').ok_or_else(|| anyhow::anyhow!("kakao web search: missing JSON object"))?; + let end = text.rfind('}').ok_or_else(|| anyhow::anyhow!("kakao web search: missing closing brace"))?; + let r: WebSearchResp = serde_json::from_str(&text[start..=end])?; + Ok(r.place + .into_iter() + .filter(|p| !p.confirmid.is_empty() && p.lat != 0.0 && p.lon != 0.0) + .map(|p| PlaceCandidate { + provider: "kakao".into(), + place_url: format!("https://place.map.kakao.com/{}", p.confirmid), + provider_id: p.confirmid, + name: p.name, + category: p.last_cate_name, + address: p.address, + road_address: p.new_address, + phone: p.tel, + lat: p.lat, + lng: p.lon, + }) + .collect()) +} + +#[async_trait] +impl PlaceSearch for KakaoLocal { + fn name(&self) -> &'static str { + "kakao" + } + + /// Uses official REST API when `KAKAO_REST_API_KEY` is set; otherwise falls back + /// to Kakao Map's web search so development works without an API key. + async fn search(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>> { + if !self.has_api_key() { + return self.web_search(query).await; + } + match self.keyword(query).await { + Ok(mut out) => { + if out.is_empty() || looks_like_address(query) { + if let Some((lat, lng, _)) = self.address(query).await.ok().flatten() { + for code in ["FD6", "CE7"] { + for c in self.category_near(code, lat, lng, 40).await.unwrap_or_default() { + if !out.iter().any(|o| o.provider_id == c.provider_id) { + out.push(c); + } + } + } + } + } + Ok(out) + } + Err(e) => { + tracing::warn!("kakao REST search failed ({e}), falling back to web search"); + self.web_search(query).await + } + } + } +} + +pub fn looks_like_address(q: &str) -> bool { + let re = regex::Regex::new(r"(로|길|동|읍|면|리)\s*\d+(-\d+)?").unwrap(); + re.is_match(q) +} + +#[derive(Deserialize)] +struct KeywordResp { + documents: Vec<KakaoPlaceDoc>, +} + +#[derive(Deserialize)] +struct KakaoPlaceDoc { + id: String, + place_name: String, + #[serde(default)] + category_name: String, + #[serde(default)] + phone: String, + #[serde(default)] + address_name: String, + #[serde(default)] + road_address_name: String, + x: String, + y: String, + #[serde(default)] + place_url: String, +} + +impl From<KakaoPlaceDoc> for PlaceCandidate { + fn from(d: KakaoPlaceDoc) -> Self { + PlaceCandidate { + provider: "kakao".into(), + provider_id: d.id, + name: d.place_name, + category: d.category_name.rsplit(" > ").next().unwrap_or_default().to_string(), + address: d.address_name, + road_address: d.road_address_name, + phone: d.phone, + lat: d.y.parse().unwrap_or_default(), + lng: d.x.parse().unwrap_or_default(), + place_url: d.place_url, + } + } +} + +#[derive(Deserialize)] +struct AddressResp { + documents: Vec<AddressDoc>, +} + +#[derive(Deserialize)] +struct AddressDoc { + address_name: String, + x: String, + y: String, +} + +#[derive(Deserialize)] +struct WebSearchResp { + #[serde(default)] + place: Vec<WebPlaceDoc>, +} + +#[derive(Deserialize)] +struct WebPlaceDoc { + #[serde(default)] + confirmid: String, + #[serde(default)] + name: String, + #[serde(default)] + last_cate_name: String, + #[serde(default)] + address: String, + #[serde(default)] + new_address: String, + #[serde(default)] + tel: String, + #[serde(default)] + lat: f64, + #[serde(default)] + lon: f64, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn address_detection() { + assert!(looks_like_address("서울 성동구 성수이로 78")); + assert!(looks_like_address("연무장길 5-1")); + assert!(!looks_like_address("대림창고")); + } + + #[test] + fn parses_jsonp() { + let raw = r#"/**/j({"place":[{"confirmid":"1128989913","name":"대림창고","last_cate_name":"갤러리카페","address":"서울 성동구 성수동2가 322-32 1층","new_address":"서울 성동구 성수이로 78","tel":"0507-1390-9669","lat":37.5417,"lon":127.0562}]});"#; + let list = parse_web_search_jsonp(raw).unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].provider_id, "1128989913"); + assert_eq!(list[0].name, "대림창고"); + } +} diff --git a/crates/providers/src/kakao_place.rs b/crates/providers/src/kakao_place.rs new file mode 100644 index 0000000..b55e572 --- /dev/null +++ b/crates/providers/src/kakao_place.rs @@ -0,0 +1,203 @@ +//! Kakao Map place panel + photos (unofficial, verified 2026-11-04). +//! +//! Endpoint: `https://place-api.map.kakao.com/places/panel3/{kakao_id}` +//! Required headers: `pf: web`, `Referer: https://place.map.kakao.com/{kakao_id}`. + +use std::collections::HashSet; + +use async_trait::async_trait; +use domain::{PhotoSourceId, Place, RawPhoto, SourceOutput, TextSnippet}; +use serde_json::Value; + +use crate::{http, PhotoSource}; + +pub struct KakaoPlacePhotos { + client: reqwest::Client, +} + +impl Default for KakaoPlacePhotos { + fn default() -> Self { + Self::new() + } +} + +impl KakaoPlacePhotos { + pub fn new() -> Self { + Self { client: http::scraping_client() } + } +} + +#[async_trait] +impl PhotoSource for KakaoPlacePhotos { + fn id(&self) -> PhotoSourceId { + PhotoSourceId::KakaoPlace + } + + async fn collect(&self, place: &Place, limit: usize) -> anyhow::Result<SourceOutput> { + let Some(id) = place.kakao_id.as_deref() else { + anyhow::bail!("kakao place id missing"); + }; + let url = format!("https://place-api.map.kakao.com/places/panel3/{id}"); + let referer = format!("https://place.map.kakao.com/{id}"); + let text = self + .client + .get(&url) + .header("pf", "web") + .header(reqwest::header::REFERER, &referer) + .header(reqwest::header::ACCEPT, "application/json") + .send() + .await? + .error_for_status()? + .text() + .await?; + parse_panel3_json(&text, &referer, limit) + } +} + +pub fn parse_panel3_json(raw: &str, page_url: &str, limit: usize) -> anyhow::Result<SourceOutput> { + let v: Value = serde_json::from_str(raw)?; + let mut seen = HashSet::new(); + let mut photos = Vec::new(); + let mut text_parts = Vec::new(); + + // Address detail often contains explicit floor info, e.g. "서울 성동구 성수이로 78 1층". + if let Some(disp) = v.pointer("/summary/address/disp").and_then(Value::as_str) { + text_parts.push(format!("주소: {disp}")); + } + if let Some(detail) = v.pointer("/summary/address/address_detail_part").and_then(Value::as_str) { + if !detail.is_empty() { + text_parts.push(format!("층/호수 정보: {detail}")); + } + } + if let Some(tags) = v.pointer("/place_add_info/tags").and_then(Value::as_array) { + let t: Vec<&str> = tags.iter().filter_map(Value::as_str).collect(); + if !t.is_empty() { + text_parts.push(format!("태그: {}", t.join(", "))); + } + } + if let Some(ai_summary) = v.pointer("/ai_mate/bottom_sheet/summary").and_then(Value::as_str) { + text_parts.push(ai_summary.to_string()); + } + if let Some(infos) = v.pointer("/place_add_info/full_detail_infos").and_then(Value::as_array) { + for info in infos { + let title = info.get("title").and_then(Value::as_str).unwrap_or_default(); + let items: Vec<&str> = info + .get("items") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|i| i.pointer("/icon/text").and_then(Value::as_str)) + .collect(); + if !items.is_empty() { + text_parts.push(format!("{title}: {}", items.join(", "))); + } + } + } + + // Structured photo list + if let Some(arr) = v.pointer("/photos/photos").and_then(Value::as_array) { + for item in arr { + if photos.len() >= limit { + break; + } + if let Some(u) = item.get("url").and_then(Value::as_str) { + let clean = unwrap_kakao_thumb(u); + if seen.insert(clean.clone()) { + let caption = item.get("title").and_then(Value::as_str).unwrap_or_default().to_string(); + photos.push(RawPhoto { + source: PhotoSourceId::KakaoPlace, + image_url: clean, + page_url: page_url.to_string(), + caption, + referer: Some("https://place.map.kakao.com/".into()), + }); + } + } + } + } + + // Review texts + review photos + for review_path in ["/kakaomap_review/reviews", "/blog_review/reviews"] { + if let Some(reviews) = v.pointer(review_path).and_then(Value::as_array) { + for r in reviews { + let contents = r + .get("contents") + .or_else(|| r.get("Summary")) + .or_else(|| r.get("title")) + .and_then(Value::as_str) + .unwrap_or_default(); + if contents.chars().count() >= 6 { + text_parts.push(contents.to_string()); + } + if let Some(p_arr) = r.get("photos").or_else(|| r.get("photo_list")).and_then(Value::as_array) { + for p in p_arr { + if photos.len() >= limit { + break; + } + if let Some(u) = p.get("url").or_else(|| p.get("orgurl")).and_then(Value::as_str) { + let clean = unwrap_kakao_thumb(u); + if seen.insert(clean.clone()) { + photos.push(RawPhoto { + source: PhotoSourceId::KakaoPlace, + image_url: clean, + page_url: page_url.to_string(), + caption: contents.chars().take(180).collect(), + referer: Some("https://place.map.kakao.com/".into()), + }); + } + } + } + } + } + } + } + + let mut texts = Vec::new(); + if !text_parts.is_empty() { + let joined: String = text_parts.join("\n").chars().take(3000).collect(); + texts.push(TextSnippet { + source: PhotoSourceId::KakaoPlace, + url: page_url.to_string(), + text: joined, + }); + } + Ok(SourceOutput { photos, texts }) +} + +/// Unwrap Kakao's thumbnail proxy (`?fname=https%3A%2F%2F...`) and upgrade `http://` to `https://`. +pub fn unwrap_kakao_thumb(u: &str) -> String { + if let Some(idx) = u.find("fname=") { + let encoded = &u[idx + 6..]; + let end = encoded.find('&').unwrap_or(encoded.len()); + if let Ok(decoded) = urlencoding::decode(&encoded[..end]) { + if decoded.starts_with("http") { + return decoded.into_owned().replace("http://", "https://"); + } + } + } + u.replace("http://", "https://") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unwraps_fname_proxy() { + let u = "https://img1.kakaocdn.net/cthumb/local/R0x420/?fname=http%3A%2F%2Ft1.daumcdn.net%2Flocal%2Fabc.jpg"; + assert_eq!(unwrap_kakao_thumb(u), "https://t1.daumcdn.net/local/abc.jpg"); + } + + #[test] + fn parses_panel_sample() { + let sample = r#"{ + "summary":{"address":{"disp":"서울 성동구 성수이로 78 1층","address_detail_part":"1층"}}, + "place_add_info":{"tags":["갤러리카페","루프탑있는"]}, + "photos":{"photos":[{"url":"http://t1.kakaocdn.net/local/kakaomapPhoto/review/abc?original","title":"실내"}]} + }"#; + let out = parse_panel3_json(sample, "https://place.map.kakao.com/1128989913", 10).unwrap(); + assert_eq!(out.photos.len(), 1); + assert!(out.photos[0].image_url.starts_with("https://")); + assert!(out.texts[0].text.contains("루프탑있는")); + } +} diff --git a/crates/providers/src/lib.rs b/crates/providers/src/lib.rs new file mode 100644 index 0000000..9b97602 --- /dev/null +++ b/crates/providers/src/lib.rs @@ -0,0 +1,32 @@ +//! External data providers: place search, geocoding and photo/text sources. +//! +//! * Official APIs: [`kakao_local`], [`ncp_geocode`] +//! * In-process scrapers: [`naver_map`], [`naver_place`], [`naver_blog`], [`kakao_place`] +//! * Delegated to the external browser scraping service: [`browser`] (Google Maps, Instagram) + +pub mod browser; +pub mod http; +pub mod kakao_local; +pub mod kakao_place; +pub mod naver_blog; +pub mod naver_map; +pub mod naver_place; +pub mod ncp_geocode; +pub mod text; + +use async_trait::async_trait; +use domain::{PhotoSourceId, Place, PlaceCandidate, SourceOutput}; + +/// Free-text place search (상호명 / 주소 → candidates). +#[async_trait] +pub trait PlaceSearch: Send + Sync { + fn name(&self) -> &'static str; + async fn search(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>>; +} + +/// A source of photos and text evidence for a resolved place. +#[async_trait] +pub trait PhotoSource: Send + Sync { + fn id(&self) -> PhotoSourceId; + async fn collect(&self, place: &Place, limit: usize) -> anyhow::Result<SourceOutput>; +} diff --git a/crates/providers/src/naver_blog.rs b/crates/providers/src/naver_blog.rs new file mode 100644 index 0000000..389f763 --- /dev/null +++ b/crates/providers/src/naver_blog.rs @@ -0,0 +1,244 @@ +//! Naver Blog posts about the place: inline images + body text (unofficial, verified 2026-11-04). +//! +//! 1. Search `https://search.naver.com/search.naver?ssc=tab.blog.all&query=...` for `blog.naver.com/{blogId}/{logNo}` links. +//! 2. Fetch each post via `https://blog.naver.com/PostView.naver?blogId=...&logNo=...` (bypasses outer iframe). +//! 3. Parse SmartEditor (`.se-main-container`) paragraphs and `postfiles.pstatic.net` images, pairing each image +//! with nearby paragraph text as its caption. + +use std::collections::HashSet; + +use async_trait::async_trait; +use domain::{PhotoSourceId, Place, RawPhoto, SourceOutput, TextSnippet}; +use futures::stream::{self, StreamExt}; +use regex::Regex; +use scraper::{Html, Selector}; + +use crate::{http, PhotoSource}; + +const SEARCH_URL: &str = "https://search.naver.com/search.naver"; +const POST_VIEW_URL: &str = "https://blog.naver.com/PostView.naver"; + +pub struct NaverBlog { + client: reqwest::Client, + max_posts: usize, +} + +impl Default for NaverBlog { + fn default() -> Self { + Self::new() + } +} + +impl NaverBlog { + pub fn new() -> Self { + Self { client: http::scraping_client(), max_posts: 8 } + } + + async fn search_post_ids(&self, query: &str) -> anyhow::Result<Vec<(String, String)>> { + let html = self + .client + .get(SEARCH_URL) + .header(reqwest::header::REFERER, "https://search.naver.com/") + .query(&[("ssc", "tab.blog.all"), ("query", query)]) + .send() + .await? + .error_for_status()? + .text() + .await?; + Ok(extract_blog_post_ids(&html)) + } + + async fn fetch_post(&self, blog_id: &str, log_no: &str) -> anyhow::Result<SourceOutput> { + let page_url = format!("https://blog.naver.com/{blog_id}/{log_no}"); + let html = self + .client + .get(POST_VIEW_URL) + .header(reqwest::header::REFERER, "https://blog.naver.com/") + .query(&[("blogId", blog_id), ("logNo", log_no)]) + .send() + .await? + .error_for_status()? + .text() + .await?; + Ok(parse_blog_post_html(&html, &page_url)) + } +} + +#[async_trait] +impl PhotoSource for NaverBlog { + fn id(&self) -> PhotoSourceId { + PhotoSourceId::NaverBlog + } + + async fn collect(&self, place: &Place, limit: usize) -> anyhow::Result<SourceOutput> { + let region = place.region_hint(); + let q1 = format!("{} {} 내부 좌석", region, place.name); + let q2 = format!("{} {}", region, place.name); + + let mut post_ids = self.search_post_ids(q1.trim()).await.unwrap_or_default(); + if post_ids.len() < self.max_posts { + for id in self.search_post_ids(q2.trim()).await.unwrap_or_default() { + if !post_ids.contains(&id) { + post_ids.push(id); + } + } + } + post_ids.truncate(self.max_posts); + + let results: Vec<SourceOutput> = stream::iter(post_ids) + .map(|(b, l)| async move { self.fetch_post(&b, &l).await.ok() }) + .buffer_unordered(4) + .filter_map(|x| async move { x }) + .collect() + .await; + + let mut seen = HashSet::new(); + let mut photos = Vec::new(); + let mut texts = Vec::new(); + for r in results { + texts.extend(r.texts); + for p in r.photos { + if photos.len() >= limit { + break; + } + if seen.insert(p.image_url.clone()) { + photos.push(p); + } + } + } + Ok(SourceOutput { photos, texts }) + } +} + +pub fn extract_blog_post_ids(html: &str) -> Vec<(String, String)> { + let re = Regex::new(r"https?://(?:m\.)?blog\.naver\.com/([a-zA-Z0-9_\-]+)/(\d{10,15})").unwrap(); + let mut seen = HashSet::new(); + let mut out = Vec::new(); + for c in re.captures_iter(html) { + let pair = (c[1].to_string(), c[2].to_string()); + if seen.insert(pair.clone()) { + out.push(pair); + } + } + out +} + +pub fn parse_blog_post_html(html: &str, page_url: &str) -> SourceOutput { + let doc = Html::parse_document(html); + let container_sel = Selector::parse(".se-main-container, #postViewArea").unwrap(); + let p_sel = Selector::parse(".se-text-paragraph, p").unwrap(); + let img_sel = Selector::parse("img").unwrap(); + + let mut paragraphs = Vec::new(); + for container in doc.select(&container_sel) { + for p in container.select(&p_sel) { + let t = p.text().collect::<Vec<_>>().join(" "); + let clean = t.split_whitespace().collect::<Vec<_>>().join(" "); + if clean.chars().count() >= 4 { + paragraphs.push(clean); + } + } + } + if paragraphs.is_empty() { + for p in doc.select(&p_sel) { + let clean = p.text().collect::<Vec<_>>().join(" ").split_whitespace().collect::<Vec<_>>().join(" "); + if clean.chars().count() >= 4 { + paragraphs.push(clean); + } + } + } + + let full_text: String = paragraphs.join("\n").chars().take(3000).collect(); + let mut texts = Vec::new(); + if !full_text.is_empty() { + texts.push(TextSnippet { + source: PhotoSourceId::NaverBlog, + url: page_url.to_string(), + text: full_text.clone(), + }); + } + + let mut seen = HashSet::new(); + let mut photos = Vec::new(); + for img in doc.select(&img_sel) { + let v = img.value(); + let src = v + .attr("data-lazy-src") + .or_else(|| v.attr("data-src")) + .or_else(|| v.attr("src")) + .unwrap_or_default(); + if let Some(url) = normalize_blog_image_url(src) { + if seen.insert(url.clone()) { + photos.push(RawPhoto { + source: PhotoSourceId::NaverBlog, + image_url: url, + page_url: page_url.to_string(), + caption: String::new(), + referer: Some("https://blog.naver.com/".into()), + }); + } + } + } + // Fallback regex scan if DOM attributes differed + if photos.is_empty() { + for u in http::extract_image_urls(html, &[r"postfiles\.pstatic\.net", r"blogfiles\.pstatic\.net"]) { + if let Some(url) = normalize_blog_image_url(&u) { + if seen.insert(url.clone()) { + photos.push(RawPhoto { + source: PhotoSourceId::NaverBlog, + image_url: url, + page_url: page_url.to_string(), + caption: String::new(), + referer: Some("https://blog.naver.com/".into()), + }); + } + } + } + } + + // Spread paragraph context across photos proportionally + if !paragraphs.is_empty() && !photos.is_empty() { + let n_p = paragraphs.len(); + let n_img = photos.len(); + for (i, photo) in photos.iter_mut().enumerate() { + let center = (i * n_p) / n_img; + let start = center.saturating_sub(1); + let end = (center + 2).min(n_p); + photo.caption = paragraphs[start..end].join(" ").chars().take(220).collect(); + } + } + + SourceOutput { photos, texts } +} + +fn normalize_blog_image_url(raw: &str) -> Option<String> { + let u = raw.replace("&", "&"); + if !(u.contains("postfiles.pstatic.net") || u.contains("blogfiles.pstatic.net")) { + return None; + } + let lower = u.to_ascii_lowercase(); + if lower.contains("sticker") || lower.contains("emoticon") || lower.contains("profile") || lower.contains(".gif") { + return None; + } + let base = u.split('?').next().unwrap_or(&u); + Some(format!("{base}?type=w966")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_blog_html() { + let html = r#"<div class="se-main-container"> + <p class="se-text-paragraph">1층에서 주문하고 2층으로 올라갔어요</p> + <img data-lazy-src="https://postfiles.pstatic.net/2026/img1.JPEG?type=w80_blur"/> + <p class="se-text-paragraph">창가 바 좌석이 6자리 정도 있어요</p> + </div>"#; + let out = parse_blog_post_html(html, "https://blog.naver.com/a/123456789012"); + assert_eq!(out.photos.len(), 1); + assert_eq!(out.photos[0].image_url, "https://postfiles.pstatic.net/2026/img1.JPEG?type=w966"); + assert!(out.photos[0].caption.contains("2층")); + assert_eq!(out.texts.len(), 1); + } +} diff --git a/crates/providers/src/naver_map.rs b/crates/providers/src/naver_map.rs new file mode 100644 index 0000000..fdb5a22 --- /dev/null +++ b/crates/providers/src/naver_map.rs @@ -0,0 +1,231 @@ +//! Naver Map web search (unofficial, verified 2026-11-04). +//! +//! Primary endpoint: `https://map.naver.com/p/api/search/instant-search?query=...&coords=lat,lng` +//! Fallback endpoint: `https://m.place.naver.com/place/list?query=...&x=lng&y=lat` (parses `window.__APOLLO_STATE__`). + +use async_trait::async_trait; +use domain::{Place, PlaceCandidate}; +use serde::Deserialize; +use serde_json::Value; + +use crate::{http, text, PlaceSearch}; + +const INSTANT_URL: &str = "https://map.naver.com/p/api/search/instant-search"; +const MPLACE_LIST_URL: &str = "https://m.place.naver.com/place/list"; + +pub struct NaverMapSearch { + client: reqwest::Client, +} + +impl Default for NaverMapSearch { + fn default() -> Self { + Self::new() + } +} + +impl NaverMapSearch { + pub fn new() -> Self { + Self { client: http::scraping_client() } + } + + /// Search places on Naver Map, optionally biased around `(lat, lng)`. + pub async fn search_near(&self, query: &str, near: Option<(f64, f64)>) -> anyhow::Result<Vec<PlaceCandidate>> { + let mut out = self.instant_search(query, near).await.unwrap_or_default(); + if out.is_empty() { + if let Ok(fallback) = self.mobile_list_search(query, near).await { + out = fallback; + } + } + Ok(out) + } + + async fn instant_search(&self, query: &str, near: Option<(f64, f64)>) -> anyhow::Result<Vec<PlaceCandidate>> { + let (lat, lng) = near.unwrap_or((37.5665, 126.9780)); + let coords = format!("{lat},{lng}"); + let resp = self + .client + .get(INSTANT_URL) + .header(reqwest::header::REFERER, "https://map.naver.com/") + .query(&[("query", query), ("coords", &coords)]) + .send() + .await? + .error_for_status()?; + let body: InstantResp = resp.json().await?; + Ok(parse_instant(body)) + } + + async fn mobile_list_search(&self, query: &str, near: Option<(f64, f64)>) -> anyhow::Result<Vec<PlaceCandidate>> { + let (lat, lng) = near.unwrap_or((37.5665, 126.9780)); + let html = self + .client + .get(MPLACE_LIST_URL) + .header(reqwest::header::USER_AGENT, http::MOBILE_UA) + .query(&[("query", query), ("x", &lng.to_string()), ("y", &lat.to_string())]) + .send() + .await? + .error_for_status()? + .text() + .await?; + Ok(parse_apollo_place_list(&html)) + } + + /// Find the Naver place id matching `place` (name similarity + coordinate distance). + pub async fn resolve_place_id(&self, place: &Place) -> anyhow::Result<Option<String>> { + let queries = [ + format!("{} {}", place.name, place.region_hint()), + place.name.clone(), + ]; + for q in queries { + let candidates = self.search_near(q.trim(), Some((place.lat, place.lng))).await.unwrap_or_default(); + if let Some(id) = pick_best_match(place, &candidates) { + tracing::debug!(place = %place.name, naver_id = %id, "resolved naver place id"); + return Ok(Some(id)); + } + } + Ok(None) + } +} + +pub fn pick_best_match(place: &Place, candidates: &[PlaceCandidate]) -> Option<String> { + candidates + .iter() + .filter_map(|c| { + let sim = text::name_similarity(&place.name, &c.name); + let dist = text::haversine_m(place.lat, place.lng, c.lat, c.lng); + // Accept either strong name similarity within 200m, or very close (<50m) with moderate name match. + if (sim >= 0.55 && dist <= 200.0) || (sim >= 0.35 && dist <= 50.0) { + let score = sim * 100.0 - (dist as f32) * 0.2; + Some((score, c.provider_id.clone())) + } else { + None + } + }) + .max_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, id)| id) +} + +fn parse_instant(body: InstantResp) -> Vec<PlaceCandidate> { + body.place + .into_iter() + .filter_map(|p| { + let lat: f64 = p.y.parse().ok()?; + let lng: f64 = p.x.parse().ok()?; + Some(PlaceCandidate { + provider: "naver".into(), + place_url: format!("https://m.place.naver.com/place/{}/home", p.id), + provider_id: p.id, + name: p.title, + category: p.ctg, + address: p.jibun_address, + road_address: p.road_address, + phone: String::new(), + lat, + lng, + }) + }) + .collect() +} + +pub fn parse_apollo_place_list(html: &str) -> Vec<PlaceCandidate> { + let Some(state) = extract_apollo_state(html) else { + return Vec::new(); + }; + let Some(obj) = state.as_object() else { + return Vec::new(); + }; + let mut out = Vec::new(); + for (k, v) in obj { + if !k.starts_with("PlaceListBusinessesItem:") && !k.starts_with("PlaceSummary:") { + continue; + } + let Some(id) = v.get("id").and_then(Value::as_str) else { continue }; + let Some(name) = v.get("name").and_then(Value::as_str) else { continue }; + let lat: f64 = v.get("y").and_then(Value::as_str).and_then(|s| s.parse().ok()).unwrap_or_default(); + let lng: f64 = v.get("x").and_then(Value::as_str).and_then(|s| s.parse().ok()).unwrap_or_default(); + if lat == 0.0 || lng == 0.0 { + continue; + } + let category = v.get("category").and_then(Value::as_str).unwrap_or_default().to_string(); + let address = v + .get("fullAddress") + .or_else(|| v.get("address")) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let road_address = v.get("roadAddress").and_then(Value::as_str).unwrap_or_default().to_string(); + let phone = v + .get("phone") + .or_else(|| v.get("virtualPhone")) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + out.push(PlaceCandidate { + provider: "naver".into(), + provider_id: id.to_string(), + name: name.to_string(), + category, + address, + road_address, + phone, + lat, + lng, + place_url: format!("https://m.place.naver.com/place/{id}/home"), + }); + } + out +} + +/// Extract the first JSON object assigned to `__APOLLO_STATE__`. +pub fn extract_apollo_state(html: &str) -> Option<Value> { + let marker = "__APOLLO_STATE__"; + let idx = html.find(marker)?; + let rest = &html[idx + marker.len()..]; + let brace = rest.find('{')?; + let mut de = serde_json::Deserializer::from_str(&rest[brace..]).into_iter::<Value>(); + de.next()?.ok() +} + +#[async_trait] +impl PlaceSearch for NaverMapSearch { + fn name(&self) -> &'static str { + "naver" + } + + async fn search(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>> { + self.search_near(query, None).await + } +} + +#[derive(Deserialize)] +struct InstantResp { + #[serde(default)] + place: Vec<InstantPlace>, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct InstantPlace { + id: String, + title: String, + #[serde(default)] + ctg: String, + #[serde(default)] + jibun_address: String, + #[serde(default)] + road_address: String, + x: String, + y: String, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_apollo_snippet() { + let html = r#"<script>window.__APOLLO_STATE__ = {"PlaceListBusinessesItem:37910590":{"id":"37910590","name":"성수동대림창고갤러리","category":"카페,디저트","fullAddress":"서울특별시 성동구 성수이로 78","roadAddress":"성수이로 78","virtualPhone":"0507-1390-9669","x":"127.0563952","y":"37.5417036"}};</script>"#; + let list = parse_apollo_place_list(html); + assert_eq!(list.len(), 1); + assert_eq!(list[0].provider_id, "37910590"); + } +} diff --git a/crates/providers/src/naver_place.rs b/crates/providers/src/naver_place.rs new file mode 100644 index 0000000..93199a4 --- /dev/null +++ b/crates/providers/src/naver_place.rs @@ -0,0 +1,209 @@ +//! Naver Place photos + info/review text (unofficial, verified 2026-11-04). +//! +//! Fetches `https://m.place.naver.com/place/{id}/{home,photo,review/visitor}` (follows 302 to +//! `/restaurant/{id}/...` or `/cafe/{id}/...`) and extracts image URLs on `*-phinf.pstatic.net` +//! plus descriptive text from `window.__APOLLO_STATE__`. + +use std::collections::HashSet; + +use async_trait::async_trait; +use domain::{PhotoSourceId, Place, RawPhoto, SourceOutput, TextSnippet}; +use serde_json::Value; + +use crate::{http, naver_map, PhotoSource}; + +const PHINF_HOSTS: &[&str] = &[ + r"ldb-phinf\.pstatic\.net", + r"pup-review-phinf\.pstatic\.net", + r"naverbooking-phinf\.pstatic\.net", +]; + +pub struct NaverPlacePhotos { + client: reqwest::Client, +} + +impl Default for NaverPlacePhotos { + fn default() -> Self { + Self::new() + } +} + +impl NaverPlacePhotos { + pub fn new() -> Self { + Self { client: http::scraping_client() } + } + + async fn fetch_tab(&self, place_id: &str, tab: &str) -> anyhow::Result<(String, String)> { + let url = format!("https://m.place.naver.com/place/{place_id}/{tab}"); + let resp = self + .client + .get(&url) + .header(reqwest::header::USER_AGENT, http::MOBILE_UA) + .header(reqwest::header::REFERER, "https://m.place.naver.com/") + .send() + .await? + .error_for_status()?; + let final_url = resp.url().to_string(); + Ok((final_url, resp.text().await?)) + } +} + +#[async_trait] +impl PhotoSource for NaverPlacePhotos { + fn id(&self) -> PhotoSourceId { + PhotoSourceId::NaverPlace + } + + async fn collect(&self, place: &Place, limit: usize) -> anyhow::Result<SourceOutput> { + let Some(place_id) = place.naver_place_id.as_deref() else { + anyhow::bail!("naver place id not resolved"); + }; + let mut seen = HashSet::new(); + let mut photos = Vec::new(); + let mut texts = Vec::new(); + + for tab in ["photo", "review/visitor", "information", "home"] { + if photos.len() >= limit { + break; + } + let (page_url, html) = match self.fetch_tab(place_id, tab).await { + Ok(v) => v, + Err(e) => { + tracing::debug!(place_id, tab, "naver place tab failed: {e}"); + continue; + } + }; + parse_naver_place_html(&html, &page_url, limit, &mut seen, &mut photos, &mut texts); + } + + Ok(SourceOutput { photos, texts }) + } +} + +pub fn parse_naver_place_html( + html: &str, + page_url: &str, + limit: usize, + seen: &mut HashSet<String>, + photos: &mut Vec<RawPhoto>, + texts: &mut Vec<TextSnippet>, +) { + if let Some(state) = naver_map::extract_apollo_state(html) { + extract_apollo_texts_and_photos(&state, page_url, limit, seen, photos, texts); + } + for raw_url in http::extract_image_urls(html, PHINF_HOSTS) { + if photos.len() >= limit { + break; + } + if is_noise_image(&raw_url) { + continue; + } + let clean = normalize_phinf_url(&raw_url); + if seen.insert(clean.clone()) { + photos.push(RawPhoto { + source: PhotoSourceId::NaverPlace, + image_url: upgrade_phinf_size(&clean), + page_url: page_url.to_string(), + caption: String::new(), + referer: Some("https://m.place.naver.com/".into()), + }); + } + } +} + +fn extract_apollo_texts_and_photos( + state: &Value, + page_url: &str, + limit: usize, + seen: &mut HashSet<String>, + photos: &mut Vec<RawPhoto>, + texts: &mut Vec<TextSnippet>, +) { + let Some(obj) = state.as_object() else { return }; + let mut text_lines = Vec::new(); + for (_k, v) in obj { + let Some(map) = v.as_object() else { continue }; + for field in ["description", "introduction", "conveniences", "parking", "direction", "body", "text"] { + if let Some(val) = map.get(field) { + match val { + Value::String(s) if s.chars().count() >= 6 => text_lines.push(s.clone()), + Value::Array(arr) => { + let joined: Vec<&str> = arr.iter().filter_map(Value::as_str).collect(); + if !joined.is_empty() { + text_lines.push(joined.join(", ")); + } + } + _ => {} + } + } + } + // Review or photo entries often carry both `body`/`text` and `media`/`originUrl`. + if photos.len() < limit { + if let Some(url) = map + .get("originUrl") + .or_else(|| map.get("imageUrl")) + .and_then(Value::as_str) + .filter(|u| u.contains("-phinf.pstatic.net") && !is_noise_image(u)) + { + let clean = normalize_phinf_url(url); + if seen.insert(clean.clone()) { + let caption = map + .get("body") + .or_else(|| map.get("text")) + .or_else(|| map.get("description")) + .and_then(Value::as_str) + .unwrap_or_default() + .chars() + .take(200) + .collect(); + photos.push(RawPhoto { + source: PhotoSourceId::NaverPlace, + image_url: upgrade_phinf_size(&clean), + page_url: page_url.to_string(), + caption, + referer: Some("https://m.place.naver.com/".into()), + }); + } + } + } + } + if !text_lines.is_empty() { + text_lines.dedup(); + let combined: String = text_lines.join("\n").chars().take(3000).collect(); + texts.push(TextSnippet { + source: PhotoSourceId::NaverPlace, + url: page_url.to_string(), + text: combined, + }); + } +} + +fn normalize_phinf_url(u: &str) -> String { + u.split('?').next().unwrap_or(u).to_string() +} + +fn upgrade_phinf_size(clean_url: &str) -> String { + format!("{clean_url}?type=w1200_60_sharpen") +} + +fn is_noise_image(u: &str) -> bool { + let lower = u.to_ascii_lowercase(); + lower.contains("profile") || lower.contains("icon") || lower.contains("logo") || lower.contains(" default") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extracts_apollo_and_regex_photos() { + let html = r#"<script>window.__APOLLO_STATE__ = {"VisitorReview:1":{"body":"2층 창가 자리가 넓어요","originUrl":"https:\u002F\u002Fpup-review-phinf.pstatic.net\u002F2026\u002Fa.jpg?type=w300"}};</script><img src="https://ldb-phinf.pstatic.net/2025/b.jpg"/>"#; + let mut seen = HashSet::new(); + let mut photos = Vec::new(); + let mut texts = Vec::new(); + parse_naver_place_html(html, "https://m.place.naver.com/place/1/photo", 10, &mut seen, &mut photos, &mut texts); + assert_eq!(photos.len(), 2); + assert_eq!(photos[0].caption, "2층 창가 자리가 넓어요"); + assert_eq!(texts.len(), 1); + } +} diff --git a/crates/providers/src/ncp_geocode.rs b/crates/providers/src/ncp_geocode.rs new file mode 100644 index 0000000..f68146a --- /dev/null +++ b/crates/providers/src/ncp_geocode.rs @@ -0,0 +1,66 @@ +//! Naver Cloud Platform Maps — Geocoding (official). Address normalization/verification only. +//! Docs: https://api.ncloud-docs.com/docs/application-maps-geocoding + +use serde::Deserialize; + +const URL: &str = "https://maps.apigw.ntruss.com/map-geocode/v2/geocode"; + +pub struct NcpGeocode { + client: reqwest::Client, + id: String, + secret: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct GeocodeResult { + pub road_address: String, + pub jibun_address: String, + pub lat: f64, + pub lng: f64, +} + +impl NcpGeocode { + pub fn new(id: impl Into<String>, secret: impl Into<String>) -> Self { + Self { client: crate::http::api_client(), id: id.into(), secret: secret.into() } + } + + pub async fn geocode(&self, query: &str) -> anyhow::Result<Option<GeocodeResult>> { + let resp = self + .client + .get(URL) + .header("x-ncp-apigw-api-key-id", &self.id) + .header("x-ncp-apigw-api-key", &self.secret) + .header("Accept", "application/json") + .query(&[("query", query)]) + .send() + .await?; + let status = resp.status(); + if !status.is_success() { + anyhow::bail!("ncp geocode {status}: {}", resp.text().await.unwrap_or_default()); + } + let r: Resp = resp.json().await?; + Ok(r.addresses.into_iter().next().map(|a| GeocodeResult { + road_address: a.road_address, + jibun_address: a.jibun_address, + lat: a.y.parse().unwrap_or_default(), + lng: a.x.parse().unwrap_or_default(), + })) + } +} + +#[derive(Deserialize)] +struct Resp { + #[serde(default)] + addresses: Vec<Addr>, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Addr { + #[serde(default)] + road_address: String, + #[serde(default)] + jibun_address: String, + x: String, + y: String, +} diff --git a/crates/providers/src/text.rs b/crates/providers/src/text.rs new file mode 100644 index 0000000..49faef6 --- /dev/null +++ b/crates/providers/src/text.rs @@ -0,0 +1,139 @@ +//! Text helpers: name normalization/similarity, distance, floor keyword extraction. + +use regex::Regex; +use std::sync::LazyLock; + +/// Lowercase, strip whitespace/punctuation so "스타벅스 성수점" ≈ "스타벅스성수점". +pub fn normalize_name(s: &str) -> String { + s.chars() + .filter(|c| c.is_alphanumeric()) + .flat_map(|c| c.to_lowercase()) + .collect() +} + +/// Similarity in 0..=1 based on character bigram Dice coefficient. +pub fn name_similarity(a: &str, b: &str) -> f32 { + let a = normalize_name(a); + let b = normalize_name(b); + if a.is_empty() || b.is_empty() { + return 0.0; + } + if a == b { + return 1.0; + } + if a.contains(&b) || b.contains(&a) { + return 0.9; + } + let bigrams = |s: &str| -> Vec<(char, char)> { + let cs: Vec<char> = s.chars().collect(); + cs.windows(2).map(|w| (w[0], w[1])).collect() + }; + let ba = bigrams(&a); + let mut bb = bigrams(&b); + if ba.is_empty() || bb.is_empty() { + return 0.0; + } + let total = ba.len() + bb.len(); + let mut hits = 0; + for g in &ba { + if let Some(pos) = bb.iter().position(|x| x == g) { + bb.swap_remove(pos); + hits += 1; + } + } + (2 * hits) as f32 / total as f32 +} + +/// Great-circle distance in meters. +pub fn haversine_m(lat1: f64, lng1: f64, lat2: f64, lng2: f64) -> f64 { + let r = 6_371_000.0_f64; + let (p1, p2) = (lat1.to_radians(), lat2.to_radians()); + let dp = (lat2 - lat1).to_radians(); + let dl = (lng2 - lng1).to_radians(); + let a = (dp / 2.0).sin().powi(2) + p1.cos() * p2.cos() * (dl / 2.0).sin().powi(2); + 2.0 * r * a.sqrt().asin() +} + +static FLOOR_RE: LazyLock<Regex> = LazyLock::new(|| { + Regex::new(r"(?x) + (?P<b>지하\s*(?P<bn>\d)\s*층|B(?P<bn2>\d)\b|지하층) + | (?P<n>\d{1,2})\s*(?:층|F\b|f\b) + | (?P<roof>루프탑|옥상) + ").unwrap() +}); + +/// Floor mentions found in text: (level, snippet). Rooftop = `domain::ROOFTOP_LEVEL`. +pub fn floor_mentions(text: &str) -> Vec<(i32, String)> { + let mut out = Vec::new(); + for caps in FLOOR_RE.captures_iter(text) { + let m = caps.get(0).unwrap(); + let level = if caps.name("b").is_some() { + caps.name("bn") + .or(caps.name("bn2")) + .and_then(|x| x.as_str().parse::<i32>().ok()) + .map(|n| -n) + .unwrap_or(-1) + } else if let Some(n) = caps.name("n") { + match n.as_str().parse::<i32>() { + Ok(n) if (1..=20).contains(&n) => n, + _ => continue, + } + } else if caps.name("roof").is_some() { + domain::ROOFTOP_LEVEL + } else { + continue; + }; + out.push((level, snippet_around(text, m.start(), m.end(), 40))); + } + out +} + +/// Text window of roughly `radius` chars around a byte range, on char boundaries. +pub fn snippet_around(text: &str, start: usize, end: usize, radius: usize) -> String { + let mut s = start; + for _ in 0..radius { + if s == 0 { + break; + } + s -= 1; + while !text.is_char_boundary(s) { + s -= 1; + } + } + let mut e = end; + for _ in 0..radius { + if e >= text.len() { + break; + } + e += 1; + while e < text.len() && !text.is_char_boundary(e) { + e += 1; + } + } + text[s..e].split_whitespace().collect::<Vec<_>>().join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn similarity() { + assert!(name_similarity("스타벅스 성수점", "스타벅스성수점") > 0.99); + assert!(name_similarity("대림창고", "대림창고 갤러리컬럼") >= 0.9); + assert!(name_similarity("블루보틀", "스타벅스") < 0.2); + } + + #[test] + fn floors() { + let m = floor_mentions("1층은 주문, 2층 좌석이 넓고 루프탑도 있어요. 지하 1층 화장실"); + let levels: Vec<i32> = m.iter().map(|x| x.0).collect(); + assert_eq!(levels, vec![1, 2, domain::ROOFTOP_LEVEL, -1]); + } + + #[test] + fn distance() { + let d = haversine_m(37.5446, 127.0557, 37.5450, 127.0557); + assert!((d - 44.5).abs() < 2.0); + } +} diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml new file mode 100644 index 0000000..fc160d7 --- /dev/null +++ b/crates/storage/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "storage" +edition.workspace = true +version.workspace = true + +[dependencies] +domain = { workspace = true } +mongodb = { workspace = true } +object_store = { workspace = true } +bytes = { workspace = true } +serde = { workspace = true } +futures = { workspace = true } +anyhow = { workspace = true } +tracing = { workspace = true } +chrono = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true } diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs new file mode 100644 index 0000000..b05eaa8 --- /dev/null +++ b/crates/storage/src/lib.rs @@ -0,0 +1,557 @@ +//! MongoDB repositories + MinIO (S3) blob store, with automatic in-memory fallback +//! when MongoDB or MinIO is not yet configured/reachable in local development. + +use std::collections::HashMap; +use std::sync::{Arc, RwLock}; +use std::time::Duration; + +use bytes::Bytes; +use domain::{JobEvent, JobStatus, Layout, Photo, PhotoTag, Place, RecentPlace}; +use futures::TryStreamExt; +use mongodb::bson::{self, doc}; +use mongodb::options::ClientOptions; +use mongodb::{Collection, Database}; +use object_store::aws::AmazonS3Builder; +use object_store::memory::InMemory; +use object_store::path::Path as ObjPath; +use object_store::{ObjectStore, PutPayload}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone)] +pub struct StorageConfig { + pub mongodb_uri: String, + pub mongodb_db: String, + pub minio_endpoint: String, + pub minio_access_key: String, + pub minio_secret_key: String, + pub minio_bucket: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LayoutDoc { + #[serde(rename = "_id")] + pub id: String, + pub place_id: String, + pub version: i64, + pub created_at: String, + pub layout: Layout, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct JobDoc { + #[serde(rename = "_id")] + pub id: String, + pub place_id: String, + pub status: JobStatus, + pub events: Vec<JobEvent>, + pub created_at: String, + pub updated_at: String, +} + +/// Text evidence persisted per place (blog bodies, place info). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TextDoc { + pub place_id: String, + pub source: domain::PhotoSourceId, + pub url: String, + pub text: String, +} + +/// View history is separate from place metadata, which analysis may replace. +#[derive(Debug, Clone, Serialize, Deserialize)] +struct PlaceViewDoc { + #[serde(rename = "_id")] + place_id: String, + last_viewed_at: String, +} + +const RECENT_PLACES_LIMIT: usize = 50; + +#[derive(Default)] +struct MemDb { + places: HashMap<String, Place>, + place_views: HashMap<String, String>, + photos: HashMap<String, Photo>, + layouts: HashMap<String, Vec<LayoutDoc>>, + jobs: HashMap<String, JobDoc>, + texts: HashMap<String, Vec<TextDoc>>, +} + +#[derive(Clone)] +pub struct Store { + db: Option<Database>, + mem: Arc<RwLock<MemDb>>, + blobs: Arc<dyn ObjectStore>, + mem_blobs: Arc<InMemory>, +} + +fn now() -> String { + chrono::Utc::now().to_rfc3339() +} + +fn recent_places_from_memory(mem: &MemDb) -> Vec<RecentPlace> { + let mut places: Vec<_> = mem + .layouts + .iter() + .filter_map(|(place_id, versions)| { + let place = mem.places.get(place_id)?.clone(); + let latest = versions.iter().max_by(|a, b| { + a.version.cmp(&b.version).then(a.created_at.cmp(&b.created_at)) + })?; + Some(RecentPlace { + place, + analyzed_at: latest.created_at.clone(), + last_viewed_at: mem.place_views.get(place_id).cloned(), + floor_labels: latest.layout.floors.iter().map(|f| f.label.clone()).collect(), + seat_estimate: latest.layout.summary.seat_estimate, + }) + }) + .collect(); + // MongoDB dates have millisecond precision. Match that ordering in fallback mode. + let sort_time = |place: &RecentPlace| { + chrono::DateTime::parse_from_rfc3339( + place.last_viewed_at.as_deref().unwrap_or(&place.analyzed_at), + ) + .map(|time| time.timestamp_millis()) + .unwrap_or(0) + }; + places.sort_by(|a, b| sort_time(b).cmp(&sort_time(a)).then(a.place.id.cmp(&b.place.id))); + places.truncate(RECENT_PLACES_LIMIT); + places +} + +fn recent_sort_time() -> bson::Document { + // Older records use chrono's micro/nanosecond RFC3339 output. Normalize only + // fractional precision because MongoDB's date parser accepts milliseconds. + doc! { "$let": { + "vars": { "raw": { "$ifNull": ["$last_viewed_at", "$analyzed_at"] } }, + "in": { "$let": { + "vars": { "precise": { "$regexFind": { + "input": "$$raw", + "regex": r"^(.*\.\d{3})\d+(Z|[+-]\d{2}:\d{2})$" + } } }, + "in": { "$convert": { + "input": { "$cond": [ + { "$ne": ["$$precise", bson::Bson::Null] }, + { "$concat": [ + { "$arrayElemAt": ["$$precise.captures", 0] }, + { "$arrayElemAt": ["$$precise.captures", 1] } + ] }, + "$$raw" + ] }, + "to": "date", + "onError": bson::DateTime::from_millis(0), + "onNull": bson::DateTime::from_millis(0) + } } + } } + } } +} + +impl Store { + pub async fn connect(cfg: &StorageConfig) -> anyhow::Result<Self> { + let mut opts = ClientOptions::parse(&cfg.mongodb_uri).await?; + opts.server_selection_timeout = Some(Duration::from_secs(3)); + opts.connect_timeout = Some(Duration::from_secs(3)); + let client = mongodb::Client::with_options(opts)?; + let candidate_db = client.database(&cfg.mongodb_db); + let db = match candidate_db.run_command(doc! { "ping": 1 }).await { + Ok(_) => { + tracing::info!(uri = %cfg.mongodb_uri, db = %cfg.mongodb_db, "connected to MongoDB"); + Some(candidate_db) + } + Err(e) => { + tracing::warn!("MongoDB unreachable ({e}); using in-memory store until MongoDB is available"); + None + } + }; + + let mem_blobs = Arc::new(InMemory::new()); + let blobs: Arc<dyn ObjectStore> = if !cfg.minio_access_key.trim().is_empty() + && !cfg.minio_secret_key.trim().is_empty() + { + let s3 = AmazonS3Builder::new() + .with_endpoint(&cfg.minio_endpoint) + .with_bucket_name(&cfg.minio_bucket) + .with_access_key_id(&cfg.minio_access_key) + .with_secret_access_key(&cfg.minio_secret_key) + .with_region("us-east-1") + .with_allow_http(true) + .with_virtual_hosted_style_request(false) + .build()?; + let probe = ObjPath::from("_health/probe.txt"); + match s3.put(&probe, PutPayload::from_static(b"ok")).await { + Ok(_) => { + tracing::info!(endpoint = %cfg.minio_endpoint, bucket = %cfg.minio_bucket, "connected to MinIO/S3"); + Arc::new(s3) + } + Err(e) => { + tracing::warn!("MinIO bucket '{}' not reachable ({e}); falling back to in-memory blob store", cfg.minio_bucket); + mem_blobs.clone() + } + } + } else { + tracing::warn!("MINIO_ACCESS_KEY/MINIO_SECRET_KEY empty; using in-memory blob store"); + mem_blobs.clone() + }; + + Ok(Self { + db, + mem: Arc::new(RwLock::new(MemDb::default())), + blobs, + mem_blobs, + }) + } + + pub async fn health_check(&self) -> anyhow::Result<()> { + if let Some(db) = &self.db { + db.run_command(doc! { "ping": 1 }).await?; + } + let probe = ObjPath::from("_health/probe.txt"); + self.blobs.put(&probe, PutPayload::from_static(b"ok")).await?; + self.blobs.get(&probe).await?.bytes().await?; + Ok(()) + } + + pub async fn ensure_indexes(&self) -> anyhow::Result<()> { + let Some(db) = &self.db else { return Ok(()) }; + use mongodb::IndexModel; + db.collection::<Photo>("photos") + .create_index(IndexModel::builder().keys(doc! { "place_id": 1 }).build()) + .await?; + db.collection::<LayoutDoc>("layouts") + .create_index(IndexModel::builder().keys(doc! { "place_id": 1, "version": -1 }).build()) + .await?; + db.collection::<JobDoc>("jobs") + .create_index(IndexModel::builder().keys(doc! { "place_id": 1, "created_at": -1 }).build()) + .await?; + db.collection::<TextDoc>("texts") + .create_index(IndexModel::builder().keys(doc! { "place_id": 1 }).build()) + .await?; + Ok(()) + } + + fn places(&self) -> Option<Collection<Place>> { + self.db.as_ref().map(|d| d.collection("places")) + } + fn photos(&self) -> Option<Collection<Photo>> { + self.db.as_ref().map(|d| d.collection("photos")) + } + fn layouts(&self) -> Option<Collection<LayoutDoc>> { + self.db.as_ref().map(|d| d.collection("layouts")) + } + fn jobs(&self) -> Option<Collection<JobDoc>> { + self.db.as_ref().map(|d| d.collection("jobs")) + } + fn texts(&self) -> Option<Collection<TextDoc>> { + self.db.as_ref().map(|d| d.collection("texts")) + } + + // ---------- places ---------- + + pub async fn upsert_place(&self, place: &Place) -> anyhow::Result<()> { + self.mem.write().unwrap().places.insert(place.id.clone(), place.clone()); + if let Some(col) = self.places() { + col.replace_one(doc! { "_id": &place.id }, place).upsert(true).await?; + } + Ok(()) + } + + pub async fn get_place(&self, id: &str) -> anyhow::Result<Option<Place>> { + if let Some(col) = self.places() { + if let Ok(Some(p)) = col.find_one(doc! { "_id": id }).await { + return Ok(Some(p)); + } + } + Ok(self.mem.read().unwrap().places.get(id).cloned()) + } + + pub async fn record_place_view(&self, place_id: &str) -> anyhow::Result<()> { + let viewed_at = now(); + self.mem + .write() + .unwrap() + .place_views + .insert(place_id.to_string(), viewed_at.clone()); + if let Some(db) = &self.db { + db.collection::<PlaceViewDoc>("place_views") + .update_one( + doc! { "_id": place_id }, + doc! { "$set": { "last_viewed_at": viewed_at } }, + ) + .upsert(true) + .await?; + } + Ok(()) + } + + /// Latest saved analyses, including analyses created before view tracking existed. + pub async fn recent_places(&self) -> anyhow::Result<Vec<RecentPlace>> { + if let Some(col) = self.layouts() { + // Project only card data rather than loading every historical 3D layout. + let pipeline = vec![ + doc! { "$sort": { "place_id": 1, "version": -1, "created_at": -1, "_id": 1 } }, + doc! { "$group": { "_id": "$place_id", "latest": { "$first": "$$ROOT" } } }, + doc! { "$lookup": { + "from": "places", "localField": "_id", "foreignField": "_id", "as": "place" + } }, + doc! { "$unwind": "$place" }, + doc! { "$lookup": { + "from": "place_views", "localField": "_id", "foreignField": "_id", "as": "views" + } }, + doc! { "$project": { + "_id": 0, + "place": 1, + "analyzed_at": "$latest.created_at", + "last_viewed_at": { "$ifNull": [ + { "$arrayElemAt": ["$views.last_viewed_at", 0] }, bson::Bson::Null + ] }, + "floor_labels": "$latest.layout.floors.label", + "seat_estimate": "$latest.layout.summary.seat_estimate" + } }, + doc! { "$set": { "sort_time": recent_sort_time() } }, + doc! { "$sort": { "sort_time": -1, "place._id": 1 } }, + doc! { "$limit": RECENT_PLACES_LIMIT as i64 }, + doc! { "$unset": "sort_time" }, + ]; + let result = async { + let docs = col.aggregate(pipeline).await?.try_collect::<Vec<_>>().await?; + docs.into_iter() + .map(bson::from_document::<RecentPlace>) + .collect::<Result<Vec<_>, _>>() + .map_err(anyhow::Error::from) + } + .await; + match result { + Ok(list) if !list.is_empty() => return Ok(list), + Err(error) => { + let fallback = recent_places_from_memory(&self.mem.read().unwrap()); + if fallback.is_empty() { + return Err(error); + } + tracing::warn!(%error, "recent places query failed; using in-memory history"); + return Ok(fallback); + } + _ => {} + } + } + Ok(recent_places_from_memory(&self.mem.read().unwrap())) + } + + // ---------- photos ---------- + + pub async fn insert_photo(&self, photo: &Photo) -> anyhow::Result<()> { + self.mem.write().unwrap().photos.insert(photo.id.clone(), photo.clone()); + if let Some(col) = self.photos() { + col.replace_one(doc! { "_id": &photo.id }, photo).upsert(true).await?; + } + Ok(()) + } + + pub async fn photos_for_place(&self, place_id: &str) -> anyhow::Result<Vec<Photo>> { + if let Some(col) = self.photos() { + if let Ok(cur) = col.find(doc! { "place_id": place_id }).await { + if let Ok(list) = cur.try_collect::<Vec<Photo>>().await { + if !list.is_empty() { + return Ok(list); + } + } + } + } + Ok(self + .mem + .read() + .unwrap() + .photos + .values() + .filter(|p| p.place_id == place_id) + .cloned() + .collect()) + } + + pub async fn get_photo(&self, id: &str) -> anyhow::Result<Option<Photo>> { + if let Some(col) = self.photos() { + if let Ok(Some(p)) = col.find_one(doc! { "_id": id }).await { + return Ok(Some(p)); + } + } + Ok(self.mem.read().unwrap().photos.get(id).cloned()) + } + + pub async fn set_photo_tag(&self, id: &str, tag: &PhotoTag) -> anyhow::Result<()> { + if let Some(p) = self.mem.write().unwrap().photos.get_mut(id) { + p.tag = Some(tag.clone()); + } + if let Some(col) = self.photos() { + col.update_one(doc! { "_id": id }, doc! { "$set": { "tag": bson::to_bson(tag)? } }) + .await?; + } + Ok(()) + } + + pub async fn delete_photos_for_place(&self, place_id: &str) -> anyhow::Result<()> { + self.mem.write().unwrap().photos.retain(|_, p| p.place_id != place_id); + if let Some(col) = self.photos() { + col.delete_many(doc! { "place_id": place_id }).await?; + } + Ok(()) + } + + // ---------- texts ---------- + + pub async fn replace_texts(&self, place_id: &str, texts: &[TextDoc]) -> anyhow::Result<()> { + self.mem + .write() + .unwrap() + .texts + .insert(place_id.to_string(), texts.to_vec()); + if let Some(col) = self.texts() { + col.delete_many(doc! { "place_id": place_id }).await?; + if !texts.is_empty() { + col.insert_many(texts).await?; + } + } + Ok(()) + } + + pub async fn texts_for_place(&self, place_id: &str) -> anyhow::Result<Vec<TextDoc>> { + if let Some(col) = self.texts() { + if let Ok(cur) = col.find(doc! { "place_id": place_id }).await { + if let Ok(list) = cur.try_collect::<Vec<TextDoc>>().await { + if !list.is_empty() { + return Ok(list); + } + } + } + } + Ok(self + .mem + .read() + .unwrap() + .texts + .get(place_id) + .cloned() + .unwrap_or_default()) + } + + // ---------- layouts ---------- + + pub async fn save_layout(&self, layout: &Layout) -> anyhow::Result<LayoutDoc> { + let version = self.latest_layout(&layout.place_id).await?.map(|d| d.version + 1).unwrap_or(1); + let d = LayoutDoc { + id: format!("{}#v{version}", layout.place_id), + place_id: layout.place_id.clone(), + version, + created_at: now(), + layout: layout.clone(), + }; + self.mem + .write() + .unwrap() + .layouts + .entry(layout.place_id.clone()) + .or_default() + .push(d.clone()); + if let Some(col) = self.layouts() { + col.insert_one(&d).await?; + } + Ok(d) + } + + pub async fn latest_layout(&self, place_id: &str) -> anyhow::Result<Option<LayoutDoc>> { + if let Some(col) = self.layouts() { + if let Ok(Some(d)) = col + .find_one(doc! { "place_id": place_id }) + .sort(doc! { "version": -1 }) + .await + { + return Ok(Some(d)); + } + } + Ok(self + .mem + .read() + .unwrap() + .layouts + .get(place_id) + .and_then(|v| v.last().cloned())) + } + + // ---------- jobs ---------- + + pub async fn create_job(&self, id: &str, place_id: &str) -> anyhow::Result<()> { + let t = now(); + let doc = JobDoc { + id: id.to_string(), + place_id: place_id.to_string(), + status: JobStatus::Running, + events: vec![], + created_at: t.clone(), + updated_at: t, + }; + self.mem.write().unwrap().jobs.insert(id.to_string(), doc.clone()); + if let Some(col) = self.jobs() { + col.insert_one(doc).await?; + } + Ok(()) + } + + pub async fn push_job_event(&self, id: &str, ev: &JobEvent) -> anyhow::Result<()> { + if let Some(j) = self.mem.write().unwrap().jobs.get_mut(id) { + j.updated_at = now(); + if matches!(ev, JobEvent::Done { .. }) { + j.status = JobStatus::Done; + } else if matches!(ev, JobEvent::Error { .. }) { + j.status = JobStatus::Failed; + } + j.events.push(ev.clone()); + } + if let Some(col) = self.jobs() { + let mut set = doc! { "updated_at": now() }; + match ev { + JobEvent::Done { .. } => { + set.insert("status", bson::to_bson(&JobStatus::Done)?); + } + JobEvent::Error { .. } => { + set.insert("status", bson::to_bson(&JobStatus::Failed)?); + } + _ => {} + } + col.update_one( + doc! { "_id": id }, + doc! { "$push": { "events": bson::to_bson(ev)? }, "$set": set }, + ) + .await?; + } + Ok(()) + } + + pub async fn get_job(&self, id: &str) -> anyhow::Result<Option<JobDoc>> { + if let Some(col) = self.jobs() { + if let Ok(Some(j)) = col.find_one(doc! { "_id": id }).await { + return Ok(Some(j)); + } + } + Ok(self.mem.read().unwrap().jobs.get(id).cloned()) + } + + // ---------- blobs ---------- + + pub async fn put_blob(&self, key: &str, bytes: Bytes) -> anyhow::Result<()> { + let p = ObjPath::from(key); + if self.blobs.put(&p, PutPayload::from(bytes.clone())).await.is_err() { + self.mem_blobs.put(&p, PutPayload::from(bytes)).await?; + } + Ok(()) + } + + pub async fn get_blob(&self, key: &str) -> anyhow::Result<Bytes> { + let p = ObjPath::from(key); + match self.blobs.get(&p).await { + Ok(r) => Ok(r.bytes().await?), + Err(_) => Ok(self.mem_blobs.get(&p).await?.bytes().await?), + } + } +} + +#[cfg(test)] +mod recent_tests; diff --git a/crates/storage/src/recent_tests.rs b/crates/storage/src/recent_tests.rs new file mode 100644 index 0000000..a49c4af --- /dev/null +++ b/crates/storage/src/recent_tests.rs @@ -0,0 +1,136 @@ +use super::*; +use domain::{Accessibility, Floor, Summary, Tri}; + +fn store() -> Store { + let blobs = Arc::new(InMemory::new()); + Store { + db: None, + mem: Arc::new(RwLock::new(MemDb::default())), + blobs: blobs.clone(), + mem_blobs: blobs, + } +} + +fn place(id: &str) -> Place { + Place { + id: id.into(), + kakao_id: None, + naver_place_id: None, + name: id.into(), + category: "카페".into(), + address: String::new(), + road_address: String::new(), + phone: String::new(), + lat: 0.0, + lng: 0.0, + place_url: String::new(), + } +} + +fn layout(id: &str, label: &str, seats: u32) -> Layout { + Layout { + place_id: id.into(), + generated_at: "2024-01-01T00:00:00Z".into(), + model: "test".into(), + confidence: 0.5, + floors: vec![Floor { + level: 1, + label: label.into(), + confidence: 0.5, + width_m: 10.0, + depth_m: 10.0, + openings: vec![], + zones: vec![], + verticals: vec![], + notes: String::new(), + }], + summary: Summary { + area_pyeong_min: 20.0, + area_pyeong_max: 30.0, + seat_estimate: seats, + seat_types: vec![], + highlights: vec![], + accessibility: Accessibility { + elevator: Tri::Unknown, + step_free_entrance: Tri::Unknown, + }, + caveats: vec![], + }, + } +} + +async fn saved_place(store: &Store, id: &str, created_at: &str) { + store.upsert_place(&place(id)).await.unwrap(); + store.save_layout(&layout(id, "1F", 20)).await.unwrap(); + store.mem.write().unwrap().layouts.get_mut(id).unwrap()[0].created_at = created_at.into(); +} + +#[tokio::test] +async fn recent_places_require_metadata_and_saved_layout() { + let store = store(); + store.upsert_place(&place("unfinished")).await.unwrap(); + store.record_place_view("unfinished").await.unwrap(); + store.save_layout(&layout("orphaned-layout", "1F", 20)).await.unwrap(); + saved_place(&store, "completed", "2024-01-01T00:00:00Z").await; + + let recent = store.recent_places().await.unwrap(); + assert_eq!(recent.len(), 1); + assert_eq!(recent[0].place.id, "completed"); + // Cached records created before this feature need no view-history migration. + assert_eq!(recent[0].last_viewed_at, None); + assert_eq!(recent[0].analyzed_at, "2024-01-01T00:00:00Z"); +} + +#[tokio::test] +async fn recent_places_use_latest_version_summary_once() { + let store = store(); + saved_place(&store, "revised", "2024-01-01T00:00:00Z").await; + let latest = store.save_layout(&layout("revised", "2F", 42)).await.unwrap(); + // The list must select the highest version even if the fallback entries are reordered. + store.mem.write().unwrap().layouts.get_mut("revised").unwrap().reverse(); + + let recent = store.recent_places().await.unwrap(); + assert_eq!(recent.len(), 1); + assert_eq!(recent[0].floor_labels, ["2F"]); + assert_eq!(recent[0].seat_estimate, 42); + assert_eq!(recent[0].analyzed_at, latest.created_at); +} + +#[tokio::test] +async fn revisiting_updates_order_and_survives_place_refresh() { + let store = store(); + saved_place(&store, "older", "2024-01-01T00:00:00Z").await; + saved_place(&store, "newer", "2025-01-01T00:00:00Z").await; + assert_eq!(store.recent_places().await.unwrap()[0].place.id, "newer"); + + store.record_place_view("older").await.unwrap(); + let mut updated = place("older"); + updated.name = "Updated name".into(); + store.upsert_place(&updated).await.unwrap(); + + let recent = store.recent_places().await.unwrap(); + assert_eq!(recent[0].place.name, "Updated name"); + assert_eq!(recent[0].place.id, "older"); + assert!(recent[0].last_viewed_at.is_some()); + assert_eq!(recent[0].analyzed_at, "2024-01-01T00:00:00Z"); +} + +#[tokio::test] +async fn recent_places_are_bounded_and_stable_on_timestamp_ties() { + let store = store(); + for number in (0..55).rev() { + // Equivalent instants expressed with different offsets still tie. + let at = if number % 2 == 0 { + "2024-01-01T00:00:00Z" + } else { + "2024-01-01T09:00:00+09:00" + }; + saved_place(&store, &format!("place-{number:02}"), at).await; + } + + let recent = store.recent_places().await.unwrap(); + assert_eq!(recent.len(), 50); + let ids: Vec<_> = recent.iter().map(|row| row.place.id.clone()).collect(); + let expected: Vec<_> = (0..50).map(|number| format!("place-{number:02}")).collect(); + assert_eq!(ids, expected); +} diff --git a/frontend/Cargo.toml b/frontend/Cargo.toml new file mode 100644 index 0000000..181e5ad --- /dev/null +++ b/frontend/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "frontend" +edition.workspace = true +version.workspace = true + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +app = { workspace = true, features = ["hydrate"] } +leptos = { workspace = true, features = ["hydrate"] } +console_error_panic_hook = { workspace = true } +wasm-bindgen = { workspace = true } diff --git a/frontend/src/lib.rs b/frontend/src/lib.rs new file mode 100644 index 0000000..c91f67f --- /dev/null +++ b/frontend/src/lib.rs @@ -0,0 +1,7 @@ +#![recursion_limit = "256"] + +#[wasm_bindgen::prelude::wasm_bindgen] +pub fn hydrate() { + console_error_panic_hook::set_once(); + leptos::mount::hydrate_body(app::App); +} diff --git a/js/scene.js b/js/scene.js new file mode 100644 index 0000000..c247e4d --- /dev/null +++ b/js/scene.js @@ -0,0 +1,787 @@ +import * as THREE from "three"; +import { OrbitControls } from "three/addons/controls/OrbitControls.js"; + +const FLOOR_HEIGHT = 3.6; +const WALL_HEIGHT = 2.6; +const WALL_THICK = 0.16; + +// sRGB equivalents of the Aurora light canvas and blue action palette. +const SCENE_COLORS = { + background: 0xeff0f2, + gridMajor: 0xd6d9df, + gridMinor: 0xe3e5e9, + accent: 0x235cc7, +}; + +const ZONE_COLORS = { + seating: 0xe8dfd1, + counter: 0xd4a373, + bar: 0xc89f81, + kitchen: 0xb7b7a4, + restroom: 0xa8dadc, + terrace: 0xccd5ae, + entrance: 0xf4e285, + other: 0xdedbd2, +}; + +const scenes = new Map(); +let nextId = 1; + +function floorIndex(floors, level) { + const sorted = [...floors].sort((a, b) => a.level - b.level); + const idx = sorted.findIndex((f) => f.level === level); + return idx >= 0 ? idx : 0; +} + +function createScene(canvas, layoutJson, onZoneSelect, cleanup) { + const layout = JSON.parse(layoutJson); + if (!layout || !Array.isArray(layout.floors)) throw new Error("Invalid floor layout"); + const coarsePointer = window.matchMedia("(pointer: coarse)"); + const originalTouchAction = canvas.style.touchAction; + const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false }); + cleanup.push(() => renderer.dispose()); + renderer.shadowMap.enabled = true; + renderer.shadowMap.type = THREE.PCFSoftShadowMap; + renderer.setClearColor(SCENE_COLORS.background, 1); + + const scene = new THREE.Scene(); + cleanup.push(() => disposeSceneObjects(scene)); + scene.fog = new THREE.FogExp2(SCENE_COLORS.background, 0.015); + + const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200); + const controls = new OrbitControls(camera, canvas); + cleanup.push(() => { controls.dispose(); canvas.style.touchAction = originalTouchAction; }); + const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)"); + controls.enableDamping = !reducedMotion.matches; + controls.dampingFactor = 0.08; + controls.maxPolarAngle = Math.PI * 0.48; + + const hemi = new THREE.HemisphereLight(0xffffff, 0xaab0ba, 1.05); + scene.add(hemi); + + const dir = new THREE.DirectionalLight(0xffffff, 1.25); + dir.position.set(16, 28, 18); + dir.castShadow = true; + dir.shadow.mapSize.set(2048, 2048); + dir.shadow.camera.near = 1; + dir.shadow.camera.far = 90; + const d = 24; + dir.shadow.camera.left = -d; + dir.shadow.camera.right = d; + dir.shadow.camera.top = d; + dir.shadow.camera.bottom = -d; + scene.add(dir); + + const groundGrid = new THREE.GridHelper(60, 60, SCENE_COLORS.gridMajor, SCENE_COLORS.gridMinor); + groundGrid.position.y = -0.08; + scene.add(groundGrid); + + const floorGroups = new Map(); + const pinMeshes = []; + const floors = layout.floors || []; + + floors.forEach((floor) => { + const idx = floorIndex(floors, floor.level); + const yBase = idx * FLOOR_HEIGHT; + const group = buildFloorGroup(floor, yBase, pinMeshes); + scene.add(group); + floorGroups.set(floor.level, { group, yBase, floor }); + }); + + const maxW = Math.max(10, ...floors.map((f) => f.width_m || 10)); + const maxD = Math.max(10, ...floors.map((f) => f.depth_m || 10)); + const span = Math.max(maxW, maxD); + camera.position.set(span * 1.15, span * 1.05, span * 1.25); + controls.target.set(0, (floors.length - 1) * FLOOR_HEIGHT * 0.35, 0); + controls.update(); + + let hasSize = false; + let visible = true; + let contextLost = false; + let disposed = false; + let raf = 0; + let st; + const requestFrame = () => { + if (!disposed && !contextLost && !document.hidden && visible && hasSize && !raf) { + raf = requestAnimationFrame(animate); + } + }; + let pixelRatio = 0; + const resize = () => { + const rect = canvas.getBoundingClientRect(); + const w = rect.width; + const h = rect.height; + hasSize = w > 0 && h > 0; + if (!hasSize) return; + const nextPixelRatio = Math.min(window.devicePixelRatio || 1, coarsePointer.matches ? 1.5 : 2); + if (nextPixelRatio !== pixelRatio) { + renderer.setPixelRatio(nextPixelRatio); + pixelRatio = nextPixelRatio; + } + renderer.setSize(w, h, false); + camera.aspect = w / h; + // Leave room around the model on portrait and near-square phone viewports. + camera.fov = (2 * Math.atan(Math.tan((42 * Math.PI) / 360) / Math.min(1, camera.aspect / 1.15)) * 180) / Math.PI; + camera.updateProjectionMatrix(); + requestFrame(); + }; + resize(); + const ro = new ResizeObserver(resize); + cleanup.push(() => ro.disconnect()); + ro.observe(canvas); + window.addEventListener("resize", resize); + cleanup.push(() => window.removeEventListener("resize", resize)); + + const raycaster = new THREE.Raycaster(); + const pointer = new THREE.Vector2(); + const activePointers = new Set(); + let downPos = null; + + const syncInteraction = () => { + downPos = null; + controls.enabled = !coarsePointer.matches || canvas.dataset.interactive === "true"; + // OrbitControls sets this to "none" in its constructor, so apply the page-scroll mode afterward. + canvas.style.touchAction = controls.enabled ? "none" : "pan-y"; + }; + syncInteraction(); + const interactionObserver = new MutationObserver(syncInteraction); + cleanup.push(() => interactionObserver.disconnect()); + interactionObserver.observe(canvas, { attributes: true, attributeFilter: ["data-interactive"] }); + const onPointerModeChange = () => { + syncInteraction(); + resize(); + }; + coarsePointer.addEventListener("change", onPointerModeChange); + cleanup.push(() => coarsePointer.removeEventListener("change", onPointerModeChange)); + + const onActivePointerDown = (e) => { + activePointers.add(e.pointerId); + if (activePointers.size > 1) downPos = null; + }; + const onPointerDown = (e) => { + activePointers.add(e.pointerId); + // Pins remain tappable in page-scroll mode; only orbit gestures require opt-in. + if (activePointers.size !== 1 || e.isPrimary === false || e.button !== 0) { + downPos = null; + return; + } + downPos = { pointerId: e.pointerId, x: e.clientX, y: e.clientY, at: performance.now() }; + }; + const onPointerMove = (e) => { + if (downPos?.pointerId === e.pointerId && Math.hypot(e.clientX - downPos.x, e.clientY - downPos.y) > 6) { + downPos = null; + } + }; + const onPointerUp = (e) => { + const wasOnlyPointer = activePointers.size === 1 && activePointers.has(e.pointerId); + activePointers.delete(e.pointerId); + const tap = downPos; + downPos = null; + if (!wasOnlyPointer || tap?.pointerId !== e.pointerId || performance.now() - tap.at > 800) return; + if (Math.hypot(e.clientX - tap.x, e.clientY - tap.y) > 6) return; + const rect = canvas.getBoundingClientRect(); + if (rect.width <= 0 || rect.height <= 0) return; + if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return; + pointer.x = ((e.clientX - rect.left) / rect.width) * 2 - 1; + pointer.y = -((e.clientY - rect.top) / rect.height) * 2 + 1; + raycaster.setFromCamera(pointer, camera); + const selectablePins = pinMeshes.filter((pin) => { + if (st.activeLevel !== 0 && pin.userData.floorLevel !== st.activeLevel) return false; + for (let parent = pin; parent; parent = parent.parent) { + if (!parent.visible) return false; + } + return true; + }); + const hits = raycaster.intersectObjects(selectablePins, true); + let obj = hits[0]?.object; + // The decorative pin is small; use a 44px minimum tap target around its visible center. + if (!obj) { + let distance = 22; + const projected = new THREE.Vector3(); + for (const pin of selectablePins) { + pin.getWorldPosition(projected); + projected.project(camera); + if (projected.z < -1 || projected.z > 1) continue; + const x = rect.left + (projected.x + 1) * rect.width / 2; + const y = rect.top + (1 - projected.y) * rect.height / 2; + const candidateDistance = Math.hypot(e.clientX - x, e.clientY - y); + if (candidateDistance < distance) { + distance = candidateDistance; + obj = pin; + } + } + } + if (obj) { + while (obj && !obj.userData?.photoIds) { + obj = obj.parent; + } + if (obj && obj.userData?.photoIds && typeof onZoneSelect === "function") { + highlightZone(st.id, obj.userData.zoneLabel, JSON.stringify(obj.userData.photoIds)); + onZoneSelect(obj.userData.zoneLabel || "구역", JSON.stringify(obj.userData.photoIds)); + } + } + }; + const onPointerCancel = (e) => { + activePointers.delete(e.pointerId); + downPos = null; + }; + canvas.addEventListener("pointerdown", onPointerDown); + window.addEventListener("pointerdown", onActivePointerDown, true); + window.addEventListener("pointermove", onPointerMove, true); + canvas.addEventListener("lostpointercapture", onPointerCancel); + // Capture release/cancel even when a scrolling or dragged pointer leaves the canvas. + window.addEventListener("pointerup", onPointerUp, true); + window.addEventListener("pointercancel", onPointerCancel, true); + cleanup.push(() => { + canvas.removeEventListener("pointerdown", onPointerDown); + window.removeEventListener("pointerdown", onActivePointerDown, true); + window.removeEventListener("pointermove", onPointerMove, true); + canvas.removeEventListener("lostpointercapture", onPointerCancel); + window.removeEventListener("pointerup", onPointerUp, true); + window.removeEventListener("pointercancel", onPointerCancel, true); + }); + + function animate() { + raf = 0; + if (disposed || contextLost || document.hidden || !visible || !hasSize) return; + const t = performance.now() / 1000; + pinMeshes.forEach((pin, i) => { + pin.position.y = pin.userData.baseY + (reducedMotion.matches ? 0 : Math.sin(t * 2.6 + i) * 0.08); + pin.rotation.y = reducedMotion.matches ? 0 : t * 1.1 + i; + }); + controls.update(); + renderer.render(scene, camera); + if (!reducedMotion.matches) requestFrame(); + } + const stopFrame = () => { + cancelAnimationFrame(raf); + raf = 0; + }; + const onVisibilityChange = () => document.hidden ? stopFrame() : requestFrame(); + document.addEventListener("visibilitychange", onVisibilityChange); + cleanup.push(() => { disposed = true; stopFrame(); document.removeEventListener("visibilitychange", onVisibilityChange); }); + const intersectionObserver = new IntersectionObserver(([entry]) => { + visible = entry.isIntersecting; + visible ? requestFrame() : stopFrame(); + }); + intersectionObserver.observe(canvas); + cleanup.push(() => intersectionObserver.disconnect()); + const onMotionChange = () => { + controls.enableDamping = !reducedMotion.matches; + requestFrame(); + }; + reducedMotion.addEventListener("change", onMotionChange); + controls.addEventListener("change", requestFrame); + cleanup.push(() => { reducedMotion.removeEventListener("change", onMotionChange); controls.removeEventListener("change", requestFrame); }); + const onContextLost = (event) => { + event.preventDefault(); + contextLost = true; + stopFrame(); + reportSceneState(canvas, "공간 화면이 중단됐습니다. 잠시 후 다시 시도해 주세요."); + }; + const onContextRestored = () => { + contextLost = false; + resize(); + requestFrame(); + reportSceneState(canvas, null); + }; + canvas.addEventListener("webglcontextlost", onContextLost); + canvas.addEventListener("webglcontextrestored", onContextRestored); + cleanup.push(() => { canvas.removeEventListener("webglcontextlost", onContextLost); canvas.removeEventListener("webglcontextrestored", onContextRestored); }); + + const id = nextId++; + st = { + id, + renderer, + scene, + camera, + controls, + floorGroups, + pinMeshes, + ro, + interactionObserver, + coarsePointer, + onPointerModeChange, + resize, + requestFrame, + reducedMotion, + onMotionChange, + intersectionObserver, + onVisibilityChange, + onContextLost, + onContextRestored, + stopAnimation: () => { + disposed = true; + stopFrame(); + }, + canvas, + originalTouchAction, + onPointerDown, + onActivePointerDown, + onPointerMove, + onPointerUp, + onPointerCancel, + span, + activeLevel: 0, + viewMode: "3d", + }; + scenes.set(id, st); + resetScene(id); + reportSceneState(canvas, null); + requestFrame(); + return id; +} + +function reportSceneState(canvas, message) { + canvas.dataset.sceneError = message || ""; + canvas.dispatchEvent(new Event(message ? "scene-error" : "scene-ready", { bubbles: true })); +} + +export function mountScene(canvas, layoutJson, onZoneSelect) { + const cleanup = []; + try { + return createScene(canvas, layoutJson, onZoneSelect, cleanup); + } catch (error) { + cleanup.reverse().forEach((dispose) => { try { dispose(); } catch { /* Finish the remaining cleanup. */ } }); + console.warn("Space viewer could not start", error?.message); + reportSceneState(canvas, "공간 화면을 열 수 없습니다. 아래 정보와 사진을 확인하거나 다시 시도해 주세요."); + return 0; + } +} + +export function setFloor(handle, level) { + const st = scenes.get(handle); + if (!st) return; + if (level !== 0 && !st.floorGroups.has(level)) return; + const previousY = floorTarget(st); + st.activeLevel = level; + const offsetY = floorTarget(st) - previousY; + st.camera.position.y += offsetY; + st.controls.target.y += offsetY; + st.floorGroups.forEach(({ group, yBase }, fLevel) => { + if (level === 0) { + group.visible = true; + setGroupOpacity(group, 1.0); + } else if (fLevel === level) { + group.visible = true; + setGroupOpacity(group, 1.0); + } else if (fLevel < level) { + group.visible = st.viewMode !== "plan"; + setGroupOpacity(group, 0.18); + } else { + group.visible = false; + } + }); + st.controls.update(); + st.requestFrame(); +} + +function floorTarget(st) { + return st.floorGroups.get(st.activeLevel)?.yBase ?? Math.max(0, st.floorGroups.size - 1) * FLOOR_HEIGHT * 0.35; +} + +export function setViewMode(handle, mode) { + const st = scenes.get(handle); + if (!st) return; + st.viewMode = mode === "plan" ? "plan" : "3d"; + const plan = st.viewMode === "plan"; + st.controls.enableRotate = !plan; + st.controls.minPolarAngle = 0; + st.controls.maxPolarAngle = plan ? 0 : Math.PI * 0.48; + st.controls.screenSpacePanning = true; + st.controls.mouseButtons.LEFT = plan ? THREE.MOUSE.PAN : THREE.MOUSE.ROTATE; + st.controls.touches.ONE = plan ? THREE.TOUCH.PAN : THREE.TOUCH.ROTATE; + st.controls.touches.TWO = THREE.TOUCH.DOLLY_PAN; + setFloor(handle, st.activeLevel); + resetScene(handle); +} + +export function resetScene(handle) { + const st = scenes.get(handle); + if (!st) return; + const yTarget = floorTarget(st); + const s = st.span; + // Flush accumulated damping so reset and view changes do not inherit a prior gesture. + const damping = st.controls.enableDamping; + st.controls.enableDamping = false; + st.controls.update(); + st.controls.enableDamping = damping; + st.controls.minDistance = Math.max(2, s * 0.18); + st.controls.maxDistance = s * 5; + if (st.viewMode === "plan") { + st.camera.position.set(0, yTarget + s * 1.65, 0.01); + st.controls.target.set(0, yTarget, 0); + } else { + st.camera.position.set(s * 1.15, yTarget + s * 1.0, s * 1.25); + st.controls.target.set(0, yTarget + 0.4, 0); + } + st.controls.update(); + st.requestFrame(); +} + +export function zoomScene(handle, delta) { + const st = scenes.get(handle); + if (!st || !Number.isFinite(delta)) return; + const offset = st.camera.position.clone().sub(st.controls.target); + const distance = THREE.MathUtils.clamp(offset.length() * Math.exp(-delta * 0.18), st.controls.minDistance, st.controls.maxDistance); + st.camera.position.copy(st.controls.target).add(offset.setLength(distance)); + st.controls.update(); + st.requestFrame(); +} + +export function highlightZone(handle, label, photoIdsJson) { + const st = scenes.get(handle); + if (!st) return; + let photoIds = []; + try { photoIds = JSON.parse(photoIdsJson); } catch { /* An empty selection simply clears emphasis. */ } + st.scene.traverse((obj) => { + if (!obj.userData.zoneSurface) return; + const selected = Boolean(label) && obj.userData.zoneLabel === label && + (!photoIds.length || obj.userData.photoIds.some((id) => photoIds.includes(id))); + obj.material.emissive.setHex(selected ? SCENE_COLORS.accent : 0x000000); + obj.material.emissiveIntensity = selected ? 0.23 : 0; + }); + st.pinMeshes.forEach((pin) => { + const selected = Boolean(label) && pin.userData.zoneLabel === label && + (!photoIds.length || pin.userData.photoIds.some((id) => photoIds.includes(id))); + pin.scale.setScalar(selected ? 1.4 : 1); + }); + st.requestFrame(); +} + +export function disposeScene(handle) { + const st = scenes.get(handle); + if (!st) return; + st.stopAnimation(); + st.ro.disconnect(); + st.intersectionObserver.disconnect(); + st.interactionObserver.disconnect(); + st.coarsePointer.removeEventListener("change", st.onPointerModeChange); + st.reducedMotion.removeEventListener("change", st.onMotionChange); + document.removeEventListener("visibilitychange", st.onVisibilityChange); + window.removeEventListener("resize", st.resize); + st.canvas.removeEventListener("pointerdown", st.onPointerDown); + window.removeEventListener("pointerdown", st.onActivePointerDown, true); + window.removeEventListener("pointermove", st.onPointerMove, true); + st.canvas.removeEventListener("lostpointercapture", st.onPointerCancel); + window.removeEventListener("pointerup", st.onPointerUp, true); + window.removeEventListener("pointercancel", st.onPointerCancel, true); + st.canvas.removeEventListener("webglcontextlost", st.onContextLost); + st.canvas.removeEventListener("webglcontextrestored", st.onContextRestored); + st.controls.removeEventListener("change", st.requestFrame); + st.controls.dispose(); + st.canvas.style.touchAction = st.originalTouchAction; + disposeSceneObjects(st.scene); + st.renderer.dispose(); + scenes.delete(handle); +} + +function disposeSceneObjects(scene) { + const geometries = new Set(); + const materials = new Set(); + scene.traverse((obj) => { + if (obj.geometry) geometries.add(obj.geometry); + if (obj.material) (Array.isArray(obj.material) ? obj.material : [obj.material]).forEach((m) => materials.add(m)); + if (obj.shadow) obj.shadow.dispose(); + }); + geometries.forEach((geometry) => geometry.dispose()); + materials.forEach((material) => material.dispose()); +} + +function setGroupOpacity(group, opacity) { + group.traverse((obj) => { + if (obj.isMesh && obj.material) { + const mats = Array.isArray(obj.material) ? obj.material : [obj.material]; + mats.forEach((m) => { + if (m.userData.baseOpacity === undefined) { + m.userData.baseOpacity = m.opacity ?? 1.0; + m.userData.wasTransparent = m.transparent ?? false; + } + if (opacity < 0.99) { + m.transparent = true; + m.opacity = m.userData.baseOpacity * opacity; + } else { + m.transparent = m.userData.wasTransparent; + m.opacity = m.userData.baseOpacity; + } + }); + } + }); +} + +// Convert floor local (x east 0..W, y north 0..D) into Three.js world (x east -W/2..W/2, z south -D/2..D/2) +// Note: local y=0 is SOUTH (front/entrance), which maps to z = +D/2 in Three.js so south faces the viewer. +function toWorldXZ(floor, lx, ly) { + return [lx - floor.width_m / 2, floor.depth_m / 2 - ly]; +} + +function buildFloorGroup(floor, yBase, pinMeshes) { + const group = new THREE.Group(); + group.position.y = yBase; + const W = floor.width_m || 10; + const D = floor.depth_m || 10; + + // Floor slab + const slabGeo = new THREE.BoxGeometry(W, 0.14, D); + const slabMat = new THREE.MeshStandardMaterial({ color: 0xf3ede2, roughness: 0.85 }); + const slab = new THREE.Mesh(slabGeo, slabMat); + slab.position.y = -0.07; + slab.receiveShadow = true; + group.add(slab); + + // Subtle perimeter walls (low cutaway height on South/East so interior is easy to see) + buildWalls(group, floor); + + // Zones + furniture + pins + (floor.zones || []).forEach((zone) => { + const zg = buildZone(floor, zone, pinMeshes); + group.add(zg); + }); + + // Verticals (stairs / elevator) + (floor.verticals || []).forEach((v) => { + group.add(buildVertical(floor, v)); + }); + + return group; +} + +function buildWalls(group, floor) { + const W = floor.width_m; + const D = floor.depth_m; + const wallMat = new THREE.MeshStandardMaterial({ color: 0xd8d2c5, roughness: 0.75 }); + const glassMat = new THREE.MeshStandardMaterial({ + color: 0x8ecae6, + transparent: true, + opacity: 0.32, + roughness: 0.2, + }); + const doorMat = new THREE.MeshStandardMaterial({ color: 0xe76f51, roughness: 0.6 }); + + // Back walls (North & West) full height; front walls (South & East) cutaway 0.9m so camera sees inside + const north = new THREE.Mesh(new THREE.BoxGeometry(W, WALL_HEIGHT, WALL_THICK), wallMat.clone()); + north.position.set(0, WALL_HEIGHT / 2, -D / 2); + north.castShadow = true; + group.add(north); + + const west = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK, WALL_HEIGHT, D), wallMat.clone()); + west.position.set(-W / 2, WALL_HEIGHT / 2, 0); + west.castShadow = true; + group.add(west); + + const lowH = 0.65; + const south = new THREE.Mesh(new THREE.BoxGeometry(W, lowH, WALL_THICK), wallMat.clone()); + south.position.set(0, lowH / 2, D / 2); + group.add(south); + + const east = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK, lowH, D), wallMat.clone()); + east.position.set(W / 2, lowH / 2, 0); + group.add(east); + + // Render openings (windows as glass panels, entrances as welcome mats + arch) + (floor.openings || []).forEach((op) => { + const len = Math.max(0.9, op.length_m || 1.5); + const off = op.offset_m || 1.0; + const isWindow = op.kind === "window"; + const h = isWindow ? 1.5 : 2.1; + const yCenter = isWindow ? 1.3 : h / 2; + const mat = isWindow ? glassMat.clone() : doorMat.clone(); + + let mesh; + if (op.wall === "south" || op.wall === "north") { + mesh = new THREE.Mesh(new THREE.BoxGeometry(len, h, WALL_THICK * 1.3), mat); + const x = -W / 2 + off + len / 2; + const z = op.wall === "south" ? D / 2 : -D / 2; + mesh.position.set(x, yCenter, z); + } else { + mesh = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK * 1.3, h, len), mat); + const z = D / 2 - (off + len / 2); + const x = op.wall === "east" ? W / 2 : -W / 2; + mesh.position.set(x, yCenter, z); + } + group.add(mesh); + }); +} + +function buildZone(floor, zone, pinMeshes) { + const g = new THREE.Group(); + const [wx, wz] = toWorldXZ(floor, zone.x + zone.w / 2, zone.y + zone.d / 2); + g.position.set(wx, 0.02, wz); + + const color = ZONE_COLORS[zone.kind] || ZONE_COLORS.other; + const pad = new THREE.Mesh( + new THREE.BoxGeometry(Math.max(0.8, zone.w - 0.12), 0.04, Math.max(0.8, zone.d - 0.12)), + new THREE.MeshStandardMaterial({ color, roughness: 0.9 }) + ); + pad.receiveShadow = true; + pad.userData = { zoneSurface: true, zoneLabel: zone.label || zone.kind, photoIds: zone.evidence_photos || [] }; + g.add(pad); + + // Place furniture groups inside the zone + (zone.furniture || []).forEach((fg) => { + populateFurniture(g, zone.w, zone.d, fg); + }); + + // If this zone has evidence photos, place a glowing interactive pin above it + if (zone.evidence_photos && zone.evidence_photos.length > 0) { + const pin = buildPin(zone.label || zone.kind, zone.evidence_photos); + pin.position.set(0, 1.65, 0); + pin.userData.baseY = 1.65; + pin.userData.floorLevel = floor.level; + g.add(pin); + pinMeshes.push(pin); + } + return g; +} + +function populateFurniture(zoneGroup, zw, zd, fg) { + const count = Math.min(24, Math.max(1, fg.count || 1)); + const cols = Math.max(1, Math.ceil(Math.sqrt(count * (zw / Math.max(1, zd))))); + const rows = Math.max(1, Math.ceil(count / cols)); + const cellW = (zw * 0.82) / cols; + const cellD = (zd * 0.82) / rows; + + for (let i = 0; i < count; i++) { + const r = Math.floor(i / cols); + const c = i % cols; + const x = -zw * 0.41 + (c + 0.5) * cellW; + const z = -zd * 0.41 + (r + 0.5) * cellD; + const item = buildFurnitureMesh(fg.kind, cellW, cellD); + item.position.set(x, 0.02, z); + zoneGroup.add(item); + } +} + +function buildFurnitureMesh(kind, cellW, cellD) { + const g = new THREE.Group(); + const wood = new THREE.MeshStandardMaterial({ color: 0x8b5e3c, roughness: 0.7 }); + const darkWood = new THREE.MeshStandardMaterial({ color: 0x5c3d28, roughness: 0.75 }); + const chairMat = new THREE.MeshStandardMaterial({ color: 0x3d405b, roughness: 0.8 }); + const sofaMat = new THREE.MeshStandardMaterial({ color: 0x6b705c, roughness: 0.85 }); + const metal = new THREE.MeshStandardMaterial({ color: 0xadb5bd, metalness: 0.5, roughness: 0.4 }); + const leaf = new THREE.MeshStandardMaterial({ color: 0x52b788, roughness: 0.8 }); + + if (kind === "counter_bar") { + const w = Math.min(2.6, Math.max(1.2, cellW * 0.9)); + const d = Math.min(1.0, Math.max(0.65, cellD * 0.6)); + const body = new THREE.Mesh(new THREE.BoxGeometry(w, 0.95, d), darkWood); + body.position.y = 0.475; + body.castShadow = true; + g.add(body); + const machine = new THREE.Mesh(new THREE.BoxGeometry(0.45, 0.35, 0.35), metal); + machine.position.set(-w * 0.2, 1.12, 0); + g.add(machine); + return g; + } + + if (kind === "bar_seat") { + const stool = new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.2, 0.68, 12), chairMat); + stool.position.y = 0.34; + stool.castShadow = true; + g.add(stool); + return g; + } + + if (kind === "sofa") { + const seat = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.42, 0.65), sofaMat); + seat.position.y = 0.21; + seat.castShadow = true; + const back = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.45, 0.16), sofaMat); + back.position.set(0, 0.55, -0.24); + g.add(seat, back); + return g; + } + + if (kind === "plant") { + const pot = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.16, 0.36, 12), darkWood); + pot.position.y = 0.18; + const crown = new THREE.Mesh(new THREE.SphereGeometry(0.36, 12, 10), leaf); + crown.position.y = 0.62; + crown.castShadow = true; + g.add(pot, crown); + return g; + } + + // Tables (table2, table4, table6, communal_table) + const isLarge = kind === "table6" || kind === "communal_table"; + const isFour = kind === "table4"; + const tw = isLarge ? 1.5 : isFour ? 0.95 : 0.68; + const td = isLarge ? 0.8 : 0.68; + const top = new THREE.Mesh(new THREE.BoxGeometry(tw, 0.06, td), wood); + top.position.y = 0.72; + top.castShadow = true; + const leg = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.08, 0.7, 10), metal); + leg.position.y = 0.35; + g.add(top, leg); + + const chairOffsets = isLarge + ? [ + [-0.45, -0.52], + [0, -0.52], + [0.45, -0.52], + [-0.45, 0.52], + [0, 0.52], + [0.45, 0.52], + ] + : isFour + ? [ + [-0.24, -0.48], + [0.24, -0.48], + [-0.24, 0.48], + [0.24, 0.48], + ] + : [ + [0, -0.46], + [0, 0.46], + ]; + + chairOffsets.forEach(([cx, cz]) => { + const ch = new THREE.Mesh(new THREE.BoxGeometry(0.32, 0.44, 0.32), chairMat); + ch.position.set(cx, 0.22, cz); + ch.castShadow = true; + g.add(ch); + }); + return g; +} + +function buildVertical(floor, v) { + const g = new THREE.Group(); + const [wx, wz] = toWorldXZ(floor, v.x + v.w / 2, v.y + v.d / 2); + g.position.set(wx, 0, wz); + const mat = new THREE.MeshStandardMaterial({ color: 0xadb5bd, roughness: 0.6 }); + + if (v.kind === "elevator") { + const box = new THREE.Mesh(new THREE.BoxGeometry(v.w, WALL_HEIGHT, v.d), mat); + box.position.y = WALL_HEIGHT / 2; + g.add(box); + } else { + const steps = 8; + for (let i = 0; i < steps; i++) { + const sh = ((i + 1) / steps) * (WALL_HEIGHT * 0.85); + const step = new THREE.Mesh(new THREE.BoxGeometry(v.w, sh, v.d / steps), mat); + step.position.set(0, sh / 2, -v.d / 2 + ((i + 0.5) * v.d) / steps); + step.castShadow = true; + g.add(step); + } + } + return g; +} + +function buildPin(zoneLabel, photoIds) { + const g = new THREE.Group(); + g.userData = { zoneLabel, photoIds }; + const headMat = new THREE.MeshStandardMaterial({ + color: SCENE_COLORS.accent, + emissive: SCENE_COLORS.accent, + emissiveIntensity: 0.18, + roughness: 0.3, + }); + const head = new THREE.Mesh(new THREE.OctahedronGeometry(0.24, 0), headMat); + head.position.y = 0.2; + const stem = new THREE.Mesh( + new THREE.CylinderGeometry(0.03, 0.03, 0.35, 8), + new THREE.MeshBasicMaterial({ color: SCENE_COLORS.accent }) + ); + g.add(head, stem); + return g; +} diff --git a/public/fonts/LICENSE-SUIT.txt b/public/fonts/LICENSE-SUIT.txt new file mode 100644 index 0000000..7ee44cf --- /dev/null +++ b/public/fonts/LICENSE-SUIT.txt @@ -0,0 +1,94 @@ +Copyright (c) 2022, SUNN (http://sun.fo/suit), +with Reserved Font Name SUIT. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/public/fonts/SUIT-Variable.woff2 b/public/fonts/SUIT-Variable.woff2 new file mode 100644 index 0000000..89d7e4c Binary files /dev/null and b/public/fonts/SUIT-Variable.woff2 differ diff --git a/public/vendor/three/OrbitControls.js b/public/vendor/three/OrbitControls.js new file mode 100644 index 0000000..7360aab --- /dev/null +++ b/public/vendor/three/OrbitControls.js @@ -0,0 +1,1523 @@ +import { + Controls, + MOUSE, + Quaternion, + Spherical, + TOUCH, + Vector2, + Vector3, + Plane, + Ray, + MathUtils +} from 'three'; + +// OrbitControls performs orbiting, dollying (zooming), and panning. +// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). +// +// Orbit - left mouse / touch: one-finger move +// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish +// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move + +const _changeEvent = { type: 'change' }; +const _startEvent = { type: 'start' }; +const _endEvent = { type: 'end' }; +const _ray = new Ray(); +const _plane = new Plane(); +const _TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD ); + +const _v = new Vector3(); +const _twoPI = 2 * Math.PI; + +const _STATE = { + NONE: - 1, + ROTATE: 0, + DOLLY: 1, + PAN: 2, + TOUCH_ROTATE: 3, + TOUCH_PAN: 4, + TOUCH_DOLLY_PAN: 5, + TOUCH_DOLLY_ROTATE: 6 +}; +const _EPS = 0.000001; + +class OrbitControls extends Controls { + + constructor( object, domElement = null ) { + + super( object, domElement ); + + this.state = _STATE.NONE; + + // Set to false to disable this control + this.enabled = true; + + // "target" sets the location of focus, where the object orbits around + this.target = new Vector3(); + + // Sets the 3D cursor (similar to Blender), from which the maxTargetRadius takes effect + this.cursor = new Vector3(); + + // How far you can dolly in and out ( PerspectiveCamera only ) + this.minDistance = 0; + this.maxDistance = Infinity; + + // How far you can zoom in and out ( OrthographicCamera only ) + this.minZoom = 0; + this.maxZoom = Infinity; + + // Limit camera target within a spherical area around the cursor + this.minTargetRadius = 0; + this.maxTargetRadius = Infinity; + + // How far you can orbit vertically, upper and lower limits. + // Range is 0 to Math.PI radians. + this.minPolarAngle = 0; // radians + this.maxPolarAngle = Math.PI; // radians + + // How far you can orbit horizontally, upper and lower limits. + // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) + this.minAzimuthAngle = - Infinity; // radians + this.maxAzimuthAngle = Infinity; // radians + + // Set to true to enable damping (inertia) + // If damping is enabled, you must call controls.update() in your animation loop + this.enableDamping = false; + this.dampingFactor = 0.05; + + // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. + // Set to false to disable zooming + this.enableZoom = true; + this.zoomSpeed = 1.0; + + // Set to false to disable rotating + this.enableRotate = true; + this.rotateSpeed = 1.0; + + // Set to false to disable panning + this.enablePan = true; + this.panSpeed = 1.0; + this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up + this.keyPanSpeed = 7.0; // pixels moved per arrow key push + this.zoomToCursor = false; + + // Set to true to automatically rotate around the target + // If auto-rotate is enabled, you must call controls.update() in your animation loop + this.autoRotate = false; + this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 + + // The four arrow keys + this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; + + // Mouse buttons + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + + // Touch fingers + this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; + + // for reset + this.target0 = this.target.clone(); + this.position0 = this.object.position.clone(); + this.zoom0 = this.object.zoom; + + // the target DOM element for key events + this._domElementKeyEvents = null; + + // internals + + this._lastPosition = new Vector3(); + this._lastQuaternion = new Quaternion(); + this._lastTargetPosition = new Vector3(); + + // so camera.up is the orbit axis + this._quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); + this._quatInverse = this._quat.clone().invert(); + + // current position in spherical coordinates + this._spherical = new Spherical(); + this._sphericalDelta = new Spherical(); + + this._scale = 1; + this._panOffset = new Vector3(); + + this._rotateStart = new Vector2(); + this._rotateEnd = new Vector2(); + this._rotateDelta = new Vector2(); + + this._panStart = new Vector2(); + this._panEnd = new Vector2(); + this._panDelta = new Vector2(); + + this._dollyStart = new Vector2(); + this._dollyEnd = new Vector2(); + this._dollyDelta = new Vector2(); + + this._dollyDirection = new Vector3(); + this._mouse = new Vector2(); + this._performCursorZoom = false; + + this._pointers = []; + this._pointerPositions = {}; + + this._controlActive = false; + + // event listeners + + this._onPointerMove = onPointerMove.bind( this ); + this._onPointerDown = onPointerDown.bind( this ); + this._onPointerUp = onPointerUp.bind( this ); + this._onContextMenu = onContextMenu.bind( this ); + this._onMouseWheel = onMouseWheel.bind( this ); + this._onKeyDown = onKeyDown.bind( this ); + + this._onTouchStart = onTouchStart.bind( this ); + this._onTouchMove = onTouchMove.bind( this ); + + this._onMouseDown = onMouseDown.bind( this ); + this._onMouseMove = onMouseMove.bind( this ); + + this._interceptControlDown = interceptControlDown.bind( this ); + this._interceptControlUp = interceptControlUp.bind( this ); + + // + + if ( this.domElement !== null ) { + + this.connect(); + + } + + this.update(); + + } + + connect() { + + this.domElement.addEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.addEventListener( 'pointercancel', this._onPointerUp ); + + this.domElement.addEventListener( 'contextmenu', this._onContextMenu ); + this.domElement.addEventListener( 'wheel', this._onMouseWheel, { passive: false } ); + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + document.addEventListener( 'keydown', this._interceptControlDown, { passive: true, capture: true } ); + + this.domElement.style.touchAction = 'none'; // disable touch scroll + + } + + disconnect() { + + this.domElement.removeEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.removeEventListener( 'pointermove', this._onPointerMove ); + this.domElement.removeEventListener( 'pointerup', this._onPointerUp ); + this.domElement.removeEventListener( 'pointercancel', this._onPointerUp ); + + this.domElement.removeEventListener( 'wheel', this._onMouseWheel ); + this.domElement.removeEventListener( 'contextmenu', this._onContextMenu ); + + this.stopListenToKeyEvents(); + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + document.removeEventListener( 'keydown', this._interceptControlDown, { capture: true } ); + + this.domElement.style.touchAction = 'auto'; + + } + + dispose() { + + this.disconnect(); + + } + + getPolarAngle() { + + return this._spherical.phi; + + } + + getAzimuthalAngle() { + + return this._spherical.theta; + + } + + getDistance() { + + return this.object.position.distanceTo( this.target ); + + } + + listenToKeyEvents( domElement ) { + + domElement.addEventListener( 'keydown', this._onKeyDown ); + this._domElementKeyEvents = domElement; + + } + + stopListenToKeyEvents() { + + if ( this._domElementKeyEvents !== null ) { + + this._domElementKeyEvents.removeEventListener( 'keydown', this._onKeyDown ); + this._domElementKeyEvents = null; + + } + + } + + saveState() { + + this.target0.copy( this.target ); + this.position0.copy( this.object.position ); + this.zoom0 = this.object.zoom; + + } + + reset() { + + this.target.copy( this.target0 ); + this.object.position.copy( this.position0 ); + this.object.zoom = this.zoom0; + + this.object.updateProjectionMatrix(); + this.dispatchEvent( _changeEvent ); + + this.update(); + + this.state = _STATE.NONE; + + } + + update( deltaTime = null ) { + + const position = this.object.position; + + _v.copy( position ).sub( this.target ); + + // rotate offset to "y-axis-is-up" space + _v.applyQuaternion( this._quat ); + + // angle from z-axis around y-axis + this._spherical.setFromVector3( _v ); + + if ( this.autoRotate && this.state === _STATE.NONE ) { + + this._rotateLeft( this._getAutoRotationAngle( deltaTime ) ); + + } + + if ( this.enableDamping ) { + + this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor; + this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor; + + } else { + + this._spherical.theta += this._sphericalDelta.theta; + this._spherical.phi += this._sphericalDelta.phi; + + } + + // restrict theta to be between desired limits + + let min = this.minAzimuthAngle; + let max = this.maxAzimuthAngle; + + if ( isFinite( min ) && isFinite( max ) ) { + + if ( min < - Math.PI ) min += _twoPI; else if ( min > Math.PI ) min -= _twoPI; + + if ( max < - Math.PI ) max += _twoPI; else if ( max > Math.PI ) max -= _twoPI; + + if ( min <= max ) { + + this._spherical.theta = Math.max( min, Math.min( max, this._spherical.theta ) ); + + } else { + + this._spherical.theta = ( this._spherical.theta > ( min + max ) / 2 ) ? + Math.max( min, this._spherical.theta ) : + Math.min( max, this._spherical.theta ); + + } + + } + + // restrict phi to be between desired limits + this._spherical.phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, this._spherical.phi ) ); + + this._spherical.makeSafe(); + + + // move target to panned location + + if ( this.enableDamping === true ) { + + this.target.addScaledVector( this._panOffset, this.dampingFactor ); + + } else { + + this.target.add( this._panOffset ); + + } + + // Limit the target distance from the cursor to create a sphere around the center of interest + this.target.sub( this.cursor ); + this.target.clampLength( this.minTargetRadius, this.maxTargetRadius ); + this.target.add( this.cursor ); + + let zoomChanged = false; + // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera + // we adjust zoom later in these cases + if ( this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera ) { + + this._spherical.radius = this._clampDistance( this._spherical.radius ); + + } else { + + const prevRadius = this._spherical.radius; + this._spherical.radius = this._clampDistance( this._spherical.radius * this._scale ); + zoomChanged = prevRadius != this._spherical.radius; + + } + + _v.setFromSpherical( this._spherical ); + + // rotate offset back to "camera-up-vector-is-up" space + _v.applyQuaternion( this._quatInverse ); + + position.copy( this.target ).add( _v ); + + this.object.lookAt( this.target ); + + if ( this.enableDamping === true ) { + + this._sphericalDelta.theta *= ( 1 - this.dampingFactor ); + this._sphericalDelta.phi *= ( 1 - this.dampingFactor ); + + this._panOffset.multiplyScalar( 1 - this.dampingFactor ); + + } else { + + this._sphericalDelta.set( 0, 0, 0 ); + + this._panOffset.set( 0, 0, 0 ); + + } + + // adjust camera position + if ( this.zoomToCursor && this._performCursorZoom ) { + + let newRadius = null; + if ( this.object.isPerspectiveCamera ) { + + // move the camera down the pointer ray + // this method avoids floating point error + const prevRadius = _v.length(); + newRadius = this._clampDistance( prevRadius * this._scale ); + + const radiusDelta = prevRadius - newRadius; + this.object.position.addScaledVector( this._dollyDirection, radiusDelta ); + this.object.updateMatrixWorld(); + + zoomChanged = !! radiusDelta; + + } else if ( this.object.isOrthographicCamera ) { + + // adjust the ortho camera position based on zoom changes + const mouseBefore = new Vector3( this._mouse.x, this._mouse.y, 0 ); + mouseBefore.unproject( this.object ); + + const prevZoom = this.object.zoom; + this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) ); + this.object.updateProjectionMatrix(); + + zoomChanged = prevZoom !== this.object.zoom; + + const mouseAfter = new Vector3( this._mouse.x, this._mouse.y, 0 ); + mouseAfter.unproject( this.object ); + + this.object.position.sub( mouseAfter ).add( mouseBefore ); + this.object.updateMatrixWorld(); + + newRadius = _v.length(); + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' ); + this.zoomToCursor = false; + + } + + // handle the placement of the target + if ( newRadius !== null ) { + + if ( this.screenSpacePanning ) { + + // position the orbit target in front of the new camera position + this.target.set( 0, 0, - 1 ) + .transformDirection( this.object.matrix ) + .multiplyScalar( newRadius ) + .add( this.object.position ); + + } else { + + // get the ray and translation plane to compute target + _ray.origin.copy( this.object.position ); + _ray.direction.set( 0, 0, - 1 ).transformDirection( this.object.matrix ); + + // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid + // extremely large values + if ( Math.abs( this.object.up.dot( _ray.direction ) ) < _TILT_LIMIT ) { + + this.object.lookAt( this.target ); + + } else { + + _plane.setFromNormalAndCoplanarPoint( this.object.up, this.target ); + _ray.intersectPlane( _plane, this.target ); + + } + + } + + } + + } else if ( this.object.isOrthographicCamera ) { + + const prevZoom = this.object.zoom; + this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) ); + + if ( prevZoom !== this.object.zoom ) { + + this.object.updateProjectionMatrix(); + zoomChanged = true; + + } + + } + + this._scale = 1; + this._performCursorZoom = false; + + // update condition is: + // min(camera displacement, camera rotation in radians)^2 > EPS + // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + + if ( zoomChanged || + this._lastPosition.distanceToSquared( this.object.position ) > _EPS || + 8 * ( 1 - this._lastQuaternion.dot( this.object.quaternion ) ) > _EPS || + this._lastTargetPosition.distanceToSquared( this.target ) > _EPS ) { + + this.dispatchEvent( _changeEvent ); + + this._lastPosition.copy( this.object.position ); + this._lastQuaternion.copy( this.object.quaternion ); + this._lastTargetPosition.copy( this.target ); + + return true; + + } + + return false; + + } + + _getAutoRotationAngle( deltaTime ) { + + if ( deltaTime !== null ) { + + return ( _twoPI / 60 * this.autoRotateSpeed ) * deltaTime; + + } else { + + return _twoPI / 60 / 60 * this.autoRotateSpeed; + + } + + } + + _getZoomScale( delta ) { + + const normalizedDelta = Math.abs( delta * 0.01 ); + return Math.pow( 0.95, this.zoomSpeed * normalizedDelta ); + + } + + _rotateLeft( angle ) { + + this._sphericalDelta.theta -= angle; + + } + + _rotateUp( angle ) { + + this._sphericalDelta.phi -= angle; + + } + + _panLeft( distance, objectMatrix ) { + + _v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix + _v.multiplyScalar( - distance ); + + this._panOffset.add( _v ); + + } + + _panUp( distance, objectMatrix ) { + + if ( this.screenSpacePanning === true ) { + + _v.setFromMatrixColumn( objectMatrix, 1 ); + + } else { + + _v.setFromMatrixColumn( objectMatrix, 0 ); + _v.crossVectors( this.object.up, _v ); + + } + + _v.multiplyScalar( distance ); + + this._panOffset.add( _v ); + + } + + // deltaX and deltaY are in pixels; right and down are positive + _pan( deltaX, deltaY ) { + + const element = this.domElement; + + if ( this.object.isPerspectiveCamera ) { + + // perspective + const position = this.object.position; + _v.copy( position ).sub( this.target ); + let targetDistance = _v.length(); + + // half of the fov is center to top of screen + targetDistance *= Math.tan( ( this.object.fov / 2 ) * Math.PI / 180.0 ); + + // we use only clientHeight here so aspect ratio does not distort speed + this._panLeft( 2 * deltaX * targetDistance / element.clientHeight, this.object.matrix ); + this._panUp( 2 * deltaY * targetDistance / element.clientHeight, this.object.matrix ); + + } else if ( this.object.isOrthographicCamera ) { + + // orthographic + this._panLeft( deltaX * ( this.object.right - this.object.left ) / this.object.zoom / element.clientWidth, this.object.matrix ); + this._panUp( deltaY * ( this.object.top - this.object.bottom ) / this.object.zoom / element.clientHeight, this.object.matrix ); + + } else { + + // camera neither orthographic nor perspective + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); + this.enablePan = false; + + } + + } + + _dollyOut( dollyScale ) { + + if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) { + + this._scale /= dollyScale; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + this.enableZoom = false; + + } + + } + + _dollyIn( dollyScale ) { + + if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) { + + this._scale *= dollyScale; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + this.enableZoom = false; + + } + + } + + _updateZoomParameters( x, y ) { + + if ( ! this.zoomToCursor ) { + + return; + + } + + this._performCursorZoom = true; + + const rect = this.domElement.getBoundingClientRect(); + const dx = x - rect.left; + const dy = y - rect.top; + const w = rect.width; + const h = rect.height; + + this._mouse.x = ( dx / w ) * 2 - 1; + this._mouse.y = - ( dy / h ) * 2 + 1; + + this._dollyDirection.set( this._mouse.x, this._mouse.y, 1 ).unproject( this.object ).sub( this.object.position ).normalize(); + + } + + _clampDistance( dist ) { + + return Math.max( this.minDistance, Math.min( this.maxDistance, dist ) ); + + } + + // + // event callbacks - update the object state + // + + _handleMouseDownRotate( event ) { + + this._rotateStart.set( event.clientX, event.clientY ); + + } + + _handleMouseDownDolly( event ) { + + this._updateZoomParameters( event.clientX, event.clientX ); + this._dollyStart.set( event.clientX, event.clientY ); + + } + + _handleMouseDownPan( event ) { + + this._panStart.set( event.clientX, event.clientY ); + + } + + _handleMouseMoveRotate( event ) { + + this._rotateEnd.set( event.clientX, event.clientY ); + + this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed ); + + const element = this.domElement; + + this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height + + this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight ); + + this._rotateStart.copy( this._rotateEnd ); + + this.update(); + + } + + _handleMouseMoveDolly( event ) { + + this._dollyEnd.set( event.clientX, event.clientY ); + + this._dollyDelta.subVectors( this._dollyEnd, this._dollyStart ); + + if ( this._dollyDelta.y > 0 ) { + + this._dollyOut( this._getZoomScale( this._dollyDelta.y ) ); + + } else if ( this._dollyDelta.y < 0 ) { + + this._dollyIn( this._getZoomScale( this._dollyDelta.y ) ); + + } + + this._dollyStart.copy( this._dollyEnd ); + + this.update(); + + } + + _handleMouseMovePan( event ) { + + this._panEnd.set( event.clientX, event.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( event ) { + + this._updateZoomParameters( event.clientX, event.clientY ); + + if ( event.deltaY < 0 ) { + + this._dollyIn( this._getZoomScale( event.deltaY ) ); + + } else if ( event.deltaY > 0 ) { + + this._dollyOut( this._getZoomScale( event.deltaY ) ); + + } + + this.update(); + + } + + _handleKeyDown( event ) { + + let needsUpdate = false; + + switch ( event.code ) { + + case this.keys.UP: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + this._rotateUp( _twoPI * this.rotateSpeed / this.domElement.clientHeight ); + + } else { + + this._pan( 0, this.keyPanSpeed ); + + } + + needsUpdate = true; + break; + + case this.keys.BOTTOM: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + this._rotateUp( - _twoPI * this.rotateSpeed / this.domElement.clientHeight ); + + } else { + + this._pan( 0, - this.keyPanSpeed ); + + } + + needsUpdate = true; + break; + + case this.keys.LEFT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + this._rotateLeft( _twoPI * this.rotateSpeed / this.domElement.clientHeight ); + + } else { + + this._pan( this.keyPanSpeed, 0 ); + + } + + needsUpdate = true; + break; + + case this.keys.RIGHT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + this._rotateLeft( - _twoPI * this.rotateSpeed / this.domElement.clientHeight ); + + } else { + + this._pan( - this.keyPanSpeed, 0 ); + + } + + needsUpdate = true; + break; + + } + + if ( needsUpdate ) { + + // prevent the browser from scrolling on cursor keys + event.preventDefault(); + + this.update(); + + } + + + } + + _handleTouchStartRotate( event ) { + + if ( this._pointers.length === 1 ) { + + this._rotateStart.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._rotateStart.set( x, y ); + + } + + } + + _handleTouchStartPan( event ) { + + if ( this._pointers.length === 1 ) { + + this._panStart.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._panStart.set( x, y ); + + } + + } + + _handleTouchStartDolly( event ) { + + const position = this._getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + this._dollyStart.set( 0, distance ); + + } + + _handleTouchStartDollyPan( event ) { + + if ( this.enableZoom ) this._handleTouchStartDolly( event ); + + if ( this.enablePan ) this._handleTouchStartPan( event ); + + } + + _handleTouchStartDollyRotate( event ) { + + if ( this.enableZoom ) this._handleTouchStartDolly( event ); + + if ( this.enableRotate ) this._handleTouchStartRotate( event ); + + } + + _handleTouchMoveRotate( event ) { + + if ( this._pointers.length == 1 ) { + + this._rotateEnd.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._rotateEnd.set( x, y ); + + } + + this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed ); + + const element = this.domElement; + + this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height + + this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight ); + + this._rotateStart.copy( this._rotateEnd ); + + } + + _handleTouchMovePan( event ) { + + if ( this._pointers.length === 1 ) { + + this._panEnd.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._panEnd.set( x, y ); + + } + + this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed ); + + this._pan( this._panDelta.x, this._panDelta.y ); + + this._panStart.copy( this._panEnd ); + + } + + _handleTouchMoveDolly( event ) { + + const position = this._getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + this._dollyEnd.set( 0, distance ); + + 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 centerX = ( event.pageX + position.x ) * 0.5; + const centerY = ( event.pageY + position.y ) * 0.5; + + this._updateZoomParameters( centerX, centerY ); + + } + + _handleTouchMoveDollyPan( event ) { + + if ( this.enableZoom ) this._handleTouchMoveDolly( event ); + + if ( this.enablePan ) this._handleTouchMovePan( event ); + + } + + _handleTouchMoveDollyRotate( event ) { + + if ( this.enableZoom ) this._handleTouchMoveDolly( event ); + + if ( this.enableRotate ) this._handleTouchMoveRotate( event ); + + } + + // pointers + + _addPointer( event ) { + + this._pointers.push( event.pointerId ); + + } + + _removePointer( event ) { + + delete this._pointerPositions[ event.pointerId ]; + + for ( let i = 0; i < this._pointers.length; i ++ ) { + + if ( this._pointers[ i ] == event.pointerId ) { + + this._pointers.splice( i, 1 ); + return; + + } + + } + + } + + _isTrackingPointer( event ) { + + for ( let i = 0; i < this._pointers.length; i ++ ) { + + if ( this._pointers[ i ] == event.pointerId ) return true; + + } + + return false; + + } + + _trackPointer( event ) { + + let position = this._pointerPositions[ event.pointerId ]; + + if ( position === undefined ) { + + position = new Vector2(); + this._pointerPositions[ event.pointerId ] = position; + + } + + position.set( event.pageX, event.pageY ); + + } + + _getSecondPointerPosition( event ) { + + const pointerId = ( event.pointerId === this._pointers[ 0 ] ) ? this._pointers[ 1 ] : this._pointers[ 0 ]; + + return this._pointerPositions[ pointerId ]; + + } + + // + + _customWheelEvent( event ) { + + const mode = event.deltaMode; + + // minimal wheel event altered to meet delta-zoom demand + const newEvent = { + clientX: event.clientX, + clientY: event.clientY, + deltaY: event.deltaY, + }; + + switch ( mode ) { + + case 1: // LINE_MODE + newEvent.deltaY *= 16; + break; + + case 2: // PAGE_MODE + newEvent.deltaY *= 100; + break; + + } + + // detect if event was triggered by pinching + if ( event.ctrlKey && ! this._controlActive ) { + + newEvent.deltaY *= 10; + + } + + return newEvent; + + } + +} + +function onPointerDown( event ) { + + if ( this.enabled === false ) return; + + if ( this._pointers.length === 0 ) { + + this.domElement.setPointerCapture( event.pointerId ); + + this.domElement.addEventListener( 'pointermove', this._onPointerMove ); + this.domElement.addEventListener( 'pointerup', this._onPointerUp ); + + } + + // + + if ( this._isTrackingPointer( event ) ) return; + + // + + this._addPointer( event ); + + if ( event.pointerType === 'touch' ) { + + this._onTouchStart( event ); + + } else { + + this._onMouseDown( event ); + + } + +} + +function onPointerMove( event ) { + + if ( this.enabled === false ) return; + + if ( event.pointerType === 'touch' ) { + + this._onTouchMove( event ); + + } else { + + this._onMouseMove( event ); + + } + +} + +function onPointerUp( event ) { + + this._removePointer( event ); + + switch ( this._pointers.length ) { + + case 0: + + this.domElement.releasePointerCapture( event.pointerId ); + + this.domElement.removeEventListener( 'pointermove', this._onPointerMove ); + this.domElement.removeEventListener( 'pointerup', this._onPointerUp ); + + this.dispatchEvent( _endEvent ); + + this.state = _STATE.NONE; + + break; + + case 1: + + const pointerId = this._pointers[ 0 ]; + const position = this._pointerPositions[ pointerId ]; + + // minimal placeholder event - allows state correction on pointer-up + this._onTouchStart( { pointerId: pointerId, pageX: position.x, pageY: position.y } ); + + break; + + } + +} + +function onMouseDown( event ) { + + let mouseAction; + + switch ( event.button ) { + + case 0: + + mouseAction = this.mouseButtons.LEFT; + break; + + case 1: + + mouseAction = this.mouseButtons.MIDDLE; + break; + + case 2: + + mouseAction = this.mouseButtons.RIGHT; + break; + + default: + + mouseAction = - 1; + + } + + switch ( mouseAction ) { + + case MOUSE.DOLLY: + + if ( this.enableZoom === false ) return; + + this._handleMouseDownDolly( event ); + + this.state = _STATE.DOLLY; + + break; + + case MOUSE.ROTATE: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enablePan === false ) return; + + this._handleMouseDownPan( event ); + + this.state = _STATE.PAN; + + } else { + + if ( this.enableRotate === false ) return; + + this._handleMouseDownRotate( event ); + + this.state = _STATE.ROTATE; + + } + + break; + + case MOUSE.PAN: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate === false ) return; + + this._handleMouseDownRotate( event ); + + this.state = _STATE.ROTATE; + + } else { + + if ( this.enablePan === false ) return; + + this._handleMouseDownPan( event ); + + this.state = _STATE.PAN; + + } + + break; + + default: + + this.state = _STATE.NONE; + + } + + if ( this.state !== _STATE.NONE ) { + + this.dispatchEvent( _startEvent ); + + } + +} + +function onMouseMove( event ) { + + switch ( this.state ) { + + case _STATE.ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleMouseMoveRotate( event ); + + break; + + case _STATE.DOLLY: + + if ( this.enableZoom === false ) return; + + this._handleMouseMoveDolly( event ); + + break; + + case _STATE.PAN: + + if ( this.enablePan === false ) return; + + this._handleMouseMovePan( event ); + + break; + + } + +} + +function onMouseWheel( event ) { + + if ( this.enabled === false || this.enableZoom === false || this.state !== _STATE.NONE ) return; + + event.preventDefault(); + + this.dispatchEvent( _startEvent ); + + this._handleMouseWheel( this._customWheelEvent( event ) ); + + this.dispatchEvent( _endEvent ); + +} + +function onKeyDown( event ) { + + if ( this.enabled === false || this.enablePan === false ) return; + + this._handleKeyDown( event ); + +} + +function onTouchStart( event ) { + + this._trackPointer( event ); + + switch ( this._pointers.length ) { + + case 1: + + switch ( this.touches.ONE ) { + + case TOUCH.ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleTouchStartRotate( event ); + + this.state = _STATE.TOUCH_ROTATE; + + break; + + case TOUCH.PAN: + + if ( this.enablePan === false ) return; + + this._handleTouchStartPan( event ); + + this.state = _STATE.TOUCH_PAN; + + break; + + default: + + this.state = _STATE.NONE; + + } + + break; + + case 2: + + switch ( this.touches.TWO ) { + + case TOUCH.DOLLY_PAN: + + if ( this.enableZoom === false && this.enablePan === false ) return; + + this._handleTouchStartDollyPan( event ); + + this.state = _STATE.TOUCH_DOLLY_PAN; + + break; + + case TOUCH.DOLLY_ROTATE: + + if ( this.enableZoom === false && this.enableRotate === false ) return; + + this._handleTouchStartDollyRotate( event ); + + this.state = _STATE.TOUCH_DOLLY_ROTATE; + + break; + + default: + + this.state = _STATE.NONE; + + } + + break; + + default: + + this.state = _STATE.NONE; + + } + + if ( this.state !== _STATE.NONE ) { + + this.dispatchEvent( _startEvent ); + + } + +} + +function onTouchMove( event ) { + + this._trackPointer( event ); + + switch ( this.state ) { + + case _STATE.TOUCH_ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleTouchMoveRotate( event ); + + this.update(); + + break; + + case _STATE.TOUCH_PAN: + + if ( this.enablePan === false ) return; + + this._handleTouchMovePan( event ); + + this.update(); + + break; + + case _STATE.TOUCH_DOLLY_PAN: + + if ( this.enableZoom === false && this.enablePan === false ) return; + + this._handleTouchMoveDollyPan( event ); + + this.update(); + + break; + + case _STATE.TOUCH_DOLLY_ROTATE: + + if ( this.enableZoom === false && this.enableRotate === false ) return; + + this._handleTouchMoveDollyRotate( event ); + + this.update(); + + break; + + default: + + this.state = _STATE.NONE; + + } + +} + +function onContextMenu( event ) { + + if ( this.enabled === false ) return; + + event.preventDefault(); + +} + +function interceptControlDown( event ) { + + if ( event.key === 'Control' ) { + + this._controlActive = true; + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + + document.addEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } ); + + } + +} + +function interceptControlUp( event ) { + + if ( event.key === 'Control' ) { + + this._controlActive = false; + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + + document.removeEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } ); + + } + +} + +export { OrbitControls }; diff --git a/public/vendor/three/three.module.js b/public/vendor/three/three.module.js new file mode 100644 index 0000000..282d108 --- /dev/null +++ b/public/vendor/three/three.module.js @@ -0,0 +1,6 @@ +/** + * @license + * Copyright 2010-2024 Three.js Authors + * SPDX-License-Identifier: MIT + */ +const t="170",e={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},n={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},i=0,r=1,s=2,a=3,o=0,l=1,c=2,h=3,u=0,d=1,p=2,m=0,f=1,g=2,v=3,_=4,x=5,y=100,M=101,S=102,b=103,T=104,w=200,E=201,A=202,R=203,C=204,I=205,P=206,L=207,U=208,D=209,N=210,O=211,F=212,B=213,z=214,k=0,V=1,H=2,G=3,W=4,X=5,j=6,q=7,Y=0,Z=1,J=2,K=0,$=1,Q=2,tt=3,et=4,nt=5,it=6,rt=7,st="attached",at="detached",ot=300,lt=301,ct=302,ht=303,ut=304,dt=306,pt=1e3,mt=1001,ft=1002,gt=1003,vt=1004,_t=1004,xt=1005,yt=1005,Mt=1006,St=1007,bt=1007,Tt=1008,wt=1008,Et=1009,At=1010,Rt=1011,Ct=1012,It=1013,Pt=1014,Lt=1015,Ut=1016,Dt=1017,Nt=1018,Ot=1020,Ft=35902,Bt=1021,zt=1022,kt=1023,Vt=1024,Ht=1025,Gt=1026,Wt=1027,Xt=1028,jt=1029,qt=1030,Yt=1031,Zt=1032,Jt=1033,Kt=33776,$t=33777,Qt=33778,te=33779,ee=35840,ne=35841,ie=35842,re=35843,se=36196,ae=37492,oe=37496,le=37808,ce=37809,he=37810,ue=37811,de=37812,pe=37813,me=37814,fe=37815,ge=37816,ve=37817,_e=37818,xe=37819,ye=37820,Me=37821,Se=36492,be=36494,Te=36495,we=36283,Ee=36284,Ae=36285,Re=36286,Ce=2200,Ie=2201,Pe=2202,Le=2300,Ue=2301,De=2302,Ne=2400,Oe=2401,Fe=2402,Be=2500,ze=2501,ke=0,Ve=1,He=2,Ge=3200,We=3201,Xe=3202,je=3203,qe=0,Ye=1,Ze="",Je="srgb",Ke="srgb-linear",$e="linear",Qe="srgb",tn=0,en=7680,nn=7681,rn=7682,sn=7683,an=34055,on=34056,ln=5386,cn=512,hn=513,un=514,dn=515,pn=516,mn=517,fn=518,gn=519,vn=512,_n=513,xn=514,yn=515,Mn=516,Sn=517,bn=518,Tn=519,wn=35044,En=35048,An=35040,Rn=35045,Cn=35049,In=35041,Pn=35046,Ln=35050,Un=35042,Dn="100",Nn="300 es",On=2e3,Fn=2001;class Bn{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e<i;e++)n[e].call(this,t);t.target=null}}}const zn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let kn=1234567;const Vn=Math.PI/180,Hn=180/Math.PI;function Gn(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(zn[255&t]+zn[t>>8&255]+zn[t>>16&255]+zn[t>>24&255]+"-"+zn[255&e]+zn[e>>8&255]+"-"+zn[e>>16&15|64]+zn[e>>24&255]+"-"+zn[63&n|128]+zn[n>>8&255]+"-"+zn[n>>16&255]+zn[n>>24&255]+zn[255&i]+zn[i>>8&255]+zn[i>>16&255]+zn[i>>24&255]).toLowerCase()}function Wn(t,e,n){return Math.max(e,Math.min(n,t))}function Xn(t,e){return(t%e+e)%e}function jn(t,e,n){return(1-n)*t+n*e}function qn(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Yn(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const Zn={DEG2RAD:Vn,RAD2DEG:Hn,generateUUID:Gn,clamp:Wn,euclideanModulo:Xn,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:jn,damp:function(t,e,n,i){return jn(t,e,1-Math.exp(-n*i))},pingpong:function(t,e=1){return e-Math.abs(Xn(t,2*e)-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*(3-2*t)},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){void 0!==t&&(kn=t);let e=kn+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296},degToRad:function(t){return t*Vn},radToDeg:function(t){return t*Hn},isPowerOfTwo:function(t){return!(t&t-1)&&0!==t},ceilPowerOfTwo:function(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},floorPowerOfTwo:function(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))},setQuaternionFromProperEuler:function(t,e,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":t.set(o*h,l*u,l*d,o*c);break;case"YZY":t.set(l*d,o*h,l*u,o*c);break;case"ZXZ":t.set(l*u,l*d,o*h,o*c);break;case"XZX":t.set(o*h,l*m,l*p,o*c);break;case"YXY":t.set(l*p,o*h,l*m,o*c);break;case"ZYZ":t.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Yn,denormalize:qn};class Jn{constructor(t=0,e=0){Jn.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,n=this.y,i=t.elements;return this.x=i[0]*e+i[3]*n+i[6],this.y=i[1]*e+i[4]*n+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}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(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.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(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(Wn(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const n=Math.cos(e),i=Math.sin(e),r=this.x-t.x,s=this.y-t.y;return this.x=r*n-s*i+t.x,this.y=r*i+s*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Kn{constructor(t,e,n,i,r,s,a,o,l){Kn.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,n,i,r,s,a,o,l)}set(t,e,n,i,r,s,a,o,l){const c=this.elements;return c[0]=t,c[1]=i,c[2]=a,c[3]=e,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],h=n[7],u=n[2],d=n[5],p=n[8],m=i[0],f=i[3],g=i[6],v=i[1],_=i[4],x=i[7],y=i[2],M=i[5],S=i[8];return r[0]=s*m+a*v+o*y,r[3]=s*f+a*_+o*M,r[6]=s*g+a*x+o*S,r[1]=l*m+c*v+h*y,r[4]=l*f+c*_+h*M,r[7]=l*g+c*x+h*S,r[2]=u*m+d*v+p*y,r[5]=u*f+d*_+p*M,r[8]=u*g+d*x+p*S,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8];return e*s*c-e*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=c*s-a*l,u=a*o-c*r,d=l*r-s*o,p=e*h+n*u+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=h*m,t[1]=(i*l-c*n)*m,t[2]=(a*n-i*s)*m,t[3]=u*m,t[4]=(c*e-i*o)*m,t[5]=(i*r-a*e)*m,t[6]=d*m,t[7]=(n*o-l*e)*m,t[8]=(s*e-n*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,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+t,-i*l,i*o,-i*(-l*s+o*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply($n.makeScale(t,e)),this}rotate(t){return this.premultiply($n.makeRotation(-t)),this}translate(t,e){return this.premultiply($n.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<9;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}const $n=new Kn;function Qn(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}const ti={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function ei(t,e){return new ti[t](e)}function ni(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function ii(){const t=ni("canvas");return t.style.display="block",t}const ri={};function si(t){t in ri||(ri[t]=!0,console.warn(t))}const ai={enabled:!0,workingColorSpace:Ke,spaces:{},convert:function(t,e,n){return!1!==this.enabled&&e!==n&&e&&n?(this.spaces[e].transfer===Qe&&(t.r=oi(t.r),t.g=oi(t.g),t.b=oi(t.b)),this.spaces[e].primaries!==this.spaces[n].primaries&&(t.applyMatrix3(this.spaces[e].toXYZ),t.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===Qe&&(t.r=li(t.r),t.g=li(t.g),t.b=li(t.b)),t):t},fromWorkingColorSpace:function(t,e){return this.convert(t,this.workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this.workingColorSpace)},getPrimaries:function(t){return this.spaces[t].primaries},getTransfer:function(t){return t===Ze?$e:this.spaces[t].transfer},getLuminanceCoefficients:function(t,e=this.workingColorSpace){return t.fromArray(this.spaces[e].luminanceCoefficients)},define:function(t){Object.assign(this.spaces,t)},_getMatrix:function(t,e,n){return t.copy(this.spaces[e].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(t){return this.spaces[t].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(t=this.workingColorSpace){return this.spaces[t].workingColorSpaceConfig.unpackColorSpace}};function oi(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function li(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}const ci=[.64,.33,.3,.6,.15,.06],hi=[.2126,.7152,.0722],ui=[.3127,.329],di=(new Kn).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),pi=(new Kn).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);let mi;ai.define({[Ke]:{primaries:ci,whitePoint:ui,transfer:$e,toXYZ:di,fromXYZ:pi,luminanceCoefficients:hi,workingColorSpaceConfig:{unpackColorSpace:Je},outputColorSpaceConfig:{drawingBufferColorSpace:Je}},[Je]:{primaries:ci,whitePoint:ui,transfer:Qe,toXYZ:di,fromXYZ:pi,luminanceCoefficients:hi,outputColorSpaceConfig:{drawingBufferColorSpace:Je}}});class fi{static getDataURL(t){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{void 0===mi&&(mi=ni("canvas")),mi.width=t.width,mi.height=t.height;const n=mi.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),e=mi}return e.width>2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=ni("canvas");e.width=t.width,e.height=t.height;const n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);const i=n.getImageData(0,0,t.width,t.height),r=i.data;for(let t=0;t<r.length;t++)r[t]=255*oi(r[t]/255);return n.putImageData(i,0,0),e}if(t.data){const e=t.data.slice(0);for(let t=0;t<e.length;t++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[t]=Math.floor(255*oi(e[t]/255)):e[t]=oi(e[t]);return{data:e,width:t.width,height:t.height}}return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),t}}let gi=0;class vi{constructor(t=null){this.isSource=!0,Object.defineProperty(this,"id",{value:gi++}),this.uuid=Gn(),this.data=t,this.dataReady=!0,this.version=0}set needsUpdate(t){!0===t&&this.version++}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.images[this.uuid])return t.images[this.uuid];const n={uuid:this.uuid,url:""},i=this.data;if(null!==i){let t;if(Array.isArray(i)){t=[];for(let e=0,n=i.length;e<n;e++)i[e].isDataTexture?t.push(_i(i[e].image)):t.push(_i(i[e]))}else t=_i(i);n.url=t}return e||(t.images[this.uuid]=n),n}}function _i(t){return"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap?fi.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let xi=0;class yi extends Bn{constructor(t=yi.DEFAULT_IMAGE,e=yi.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,a=1023,o=1009,l=yi.DEFAULT_ANISOTROPY,c=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:xi++}),this.uuid=Gn(),this.name="",this.source=new vi(t),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=s,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new Jn(0,0),this.repeat=new Jn(1,1),this.center=new Jn(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Kn,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=c,this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.pmremVersion=0}get image(){return this.source.data}set image(t=null){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return(new this.constructor).copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.textures[this.uuid])return t.textures[this.uuid];const n={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==ot)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case pt:t.x=t.x-Math.floor(t.x);break;case mt:t.x=t.x<0?0:1;break;case ft:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case pt:t.y=t.y-Math.floor(t.y);break;case mt:t.y=t.y<0?0:1;break;case ft:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){!0===t&&this.pmremVersion++}}yi.DEFAULT_IMAGE=null,yi.DEFAULT_MAPPING=ot,yi.DEFAULT_ANISOTROPY=1;class Mi{constructor(t=0,e=0,n=0,i=1){Mi.prototype.isVector4=!0,this.x=t,this.y=e,this.z=n,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,i){return this.x=t,this.y=e,this.z=n,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){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: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=this.w,s=t.elements;return this.x=s[0]*e+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*e+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*e+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*e+s[7]*n+s[11]*i+s[15]*r,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,i,r;const s=.01,a=.1,o=t.elements,l=o[0],c=o[4],h=o[8],u=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-u)<s&&Math.abs(h-m)<s&&Math.abs(p-f)<s){if(Math.abs(c+u)<a&&Math.abs(h+m)<a&&Math.abs(p+f)<a&&Math.abs(l+d+g-3)<a)return this.set(1,0,0,0),this;e=Math.PI;const t=(l+1)/2,o=(d+1)/2,v=(g+1)/2,_=(c+u)/4,x=(h+m)/4,y=(p+f)/4;return t>o&&t>v?t<s?(n=0,i=.707106781,r=.707106781):(n=Math.sqrt(t),i=_/n,r=x/n):o>v?o<s?(n=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),n=_/i,r=y/i):v<s?(n=.707106781,i=.707106781,r=0):(r=Math.sqrt(v),n=x/r,i=y/r),this.set(n,i,r,e),this}let v=Math.sqrt((f-p)*(f-p)+(h-m)*(h-m)+(u-c)*(u-c));return Math.abs(v)<.001&&(v=1),this.x=(f-p)/v,this.y=(h-m)/v,this.z=(u-c)/v,this.w=Math.acos((l+d+g-1)/2),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this.w=t.w+(e.w-t.w)*n,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Si extends Bn{constructor(t=1,e=1,n={}){super(),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=1,this.scissor=new Mi(0,0,t,e),this.scissorTest=!1,this.viewport=new Mi(0,0,t,e);const i={width:t,height:e,depth:1};n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Mt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},n);const r=new yi(i,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace);r.flipY=!1,r.generateMipmaps=n.generateMipmaps,r.internalFormat=n.internalFormat,this.textures=[];const s=n.count;for(let t=0;t<s;t++)this.textures[t]=r.clone(),this.textures[t].isRenderTargetTexture=!0;this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.depthTexture=n.depthTexture,this.samples=n.samples}get texture(){return this.textures[0]}set texture(t){this.textures[0]=t}setSize(t,e,n=1){if(this.width!==t||this.height!==e||this.depth!==n){this.width=t,this.height=e,this.depth=n;for(let i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=t,this.textures[i].image.height=e,this.textures[i].image.depth=n;this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return(new this.constructor).copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,n=t.textures.length;e<n;e++)this.textures[e]=t.textures[e].clone(),this.textures[e].isRenderTargetTexture=!0;const e=Object.assign({},t.texture.image);return this.texture.source=new vi(e),this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.resolveDepthBuffer=t.resolveDepthBuffer,this.resolveStencilBuffer=t.resolveStencilBuffer,null!==t.depthTexture&&(this.depthTexture=t.depthTexture.clone()),this.samples=t.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class bi extends Si{constructor(t=1,e=1,n={}){super(t,e,n),this.isWebGLRenderTarget=!0}}class Ti extends yi{constructor(t=null,e=1,n=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:t,width:e,height:n,depth:i},this.magFilter=gt,this.minFilter=gt,this.wrapR=mt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class wi extends bi{constructor(t=1,e=1,n=1,i={}){super(t,e,i),this.isWebGLArrayRenderTarget=!0,this.depth=n,this.texture=new Ti(null,t,e,n),this.texture.isRenderTargetTexture=!0}}class Ei extends yi{constructor(t=null,e=1,n=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:t,width:e,height:n,depth:i},this.magFilter=gt,this.minFilter=gt,this.wrapR=mt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Ai extends bi{constructor(t=1,e=1,n=1,i={}){super(t,e,i),this.isWebGL3DRenderTarget=!0,this.depth=n,this.texture=new Ei(null,t,e,n),this.texture.isRenderTargetTexture=!0}}class Ri{constructor(t=0,e=0,n=0,i=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=n,this._w=i}static slerpFlat(t,e,n,i,r,s,a){let o=n[i+0],l=n[i+1],c=n[i+2],h=n[i+3];const u=r[s+0],d=r[s+1],p=r[s+2],m=r[s+3];if(0===a)return t[e+0]=o,t[e+1]=l,t[e+2]=c,void(t[e+3]=h);if(1===a)return t[e+0]=u,t[e+1]=d,t[e+2]=p,void(t[e+3]=m);if(h!==m||o!==u||l!==d||c!==p){let t=1-a;const e=o*u+l*d+c*p+h*m,n=e>=0?1:-1,i=1-e*e;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,e*n);t=Math.sin(t*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*t+u*r,l=l*t+d*r,c=c*t+p*r,h=h*t+m*r,t===1-a){const t=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=t,l*=t,c*=t,h*=t}}t[e]=o,t[e+1]=l,t[e+2]=c,t[e+3]=h}static multiplyQuaternionsFlat(t,e,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],h=r[s],u=r[s+1],d=r[s+2],p=r[s+3];return t[e]=a*p+c*h+o*d-l*u,t[e+1]=o*p+c*u+l*h-a*d,t[e+2]=l*p+c*d+a*u-o*h,t[e+3]=c*p-a*h-o*u-l*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,i){return this._x=t,this._y=e,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const n=t._x,i=t._y,r=t._z,s=t._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),h=a(r/2),u=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const n=e/2,i=Math.sin(n);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,n=e[0],i=e[4],r=e[8],s=e[1],a=e[5],o=e[9],l=e[2],c=e[6],h=e[10],u=n+a+h;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(c-o)*t,this._y=(r-l)*t,this._z=(s-i)*t}else if(n>a&&n>h){const t=2*Math.sqrt(1+n-a-h);this._w=(c-o)/t,this._x=.25*t,this._y=(i+s)/t,this._z=(r+l)/t}else if(a>h){const t=2*Math.sqrt(1+a-n-h);this._w=(r-l)/t,this._x=(i+s)/t,this._y=.25*t,this._z=(o+c)/t}else{const t=2*Math.sqrt(1+h-n-a);this._w=(s-i)/t,this._x=(r+l)/t,this._y=(o+c)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return n<Number.EPSILON?(n=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(Wn(this.dot(t),-1,1)))}rotateTowards(t,e){const n=this.angleTo(t);if(0===n)return this;const i=Math.min(1,e/n);return this.slerp(t,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(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._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 t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const n=t._x,i=t._y,r=t._z,s=t._w,a=e._x,o=e._y,l=e._z,c=e._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*t._w+n*t._x+i*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),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 t=1-e;return this._w=t*s+e*this._w,this._x=t*n+e*this._x,this._y=t*i+e*this._y,this._z=t*r+e*this._z,this.normalize(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-e)*c)/l,u=Math.sin(e*c)/l;return this._w=s*h+this._w*u,this._x=n*h+this._x*u,this._y=i*h+this._y*u,this._z=r*h+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(t),i*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ci{constructor(t=0,e=0,n=0){Ci.prototype.isVector3=!0,this.x=t,this.y=e,this.z=n}set(t,e,n){return void 0===n&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Pi.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Pi.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*i,this.y=r[1]*e+r[4]*n+r[7]*i,this.z=r[2]*e+r[5]*n+r[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=t.elements,s=1/(r[3]*e+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*e+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*e+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(t){const e=this.x,n=this.y,i=this.z,r=t.x,s=t.y,a=t.z,o=t.w,l=2*(s*i-a*n),c=2*(a*e-r*i),h=2*(r*n-s*e);return this.x=e+o*l+s*h-a*c,this.y=n+o*c+a*l-r*h,this.z=i+o*h+r*c-s*l,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i,this.y=r[1]*e+r[5]*n+r[9]*i,this.z=r[2]*e+r[6]*n+r[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}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(t){return this.x*t.x+this.y*t.y+this.z*t.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(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const n=t.x,i=t.y,r=t.z,s=e.x,a=e.y,o=e.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Ii.copy(this).projectOnVector(t),this.sub(Ii)}reflect(t){return this.sub(Ii.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(Wn(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return e*e+n*n+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){const i=Math.sin(e)*t;return this.x=i*Math.sin(n),this.y=Math.cos(e)*t,this.z=i*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=2*Math.random()-1,n=Math.sqrt(1-e*e);return this.x=n*Math.cos(t),this.y=e,this.z=n*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ii=new Ci,Pi=new Ri;class Li{constructor(t=new Ci(1/0,1/0,1/0),e=new Ci(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,n=t.length;e<n;e+=3)this.expandByPoint(Di.fromArray(t,e));return this}setFromBufferAttribute(t){this.makeEmpty();for(let e=0,n=t.count;e<n;e++)this.expandByPoint(Di.fromBufferAttribute(t,e));return this}setFromPoints(t){this.makeEmpty();for(let e=0,n=t.length;e<n;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const n=Di.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(n),this.max.copy(t).add(n),this}setFromObject(t,e=!1){return this.makeEmpty(),this.expandByObject(t,e)}clone(){return(new this.constructor).copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t,e=!1){t.updateWorldMatrix(!1,!1);const n=t.geometry;if(void 0!==n){const i=n.getAttribute("position");if(!0===e&&void 0!==i&&!0!==t.isInstancedMesh)for(let e=0,n=i.count;e<n;e++)!0===t.isMesh?t.getVertexPosition(e,Di):Di.fromBufferAttribute(i,e),Di.applyMatrix4(t.matrixWorld),this.expandByPoint(Di);else void 0!==t.boundingBox?(null===t.boundingBox&&t.computeBoundingBox(),Ni.copy(t.boundingBox)):(null===n.boundingBox&&n.computeBoundingBox(),Ni.copy(n.boundingBox)),Ni.applyMatrix4(t.matrixWorld),this.union(Ni)}const i=t.children;for(let t=0,n=i.length;t<n;t++)this.expandByObject(i[t],e);return this}containsPoint(t){return t.x>=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,Di),Di.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Hi),Gi.subVectors(this.max,Hi),Oi.subVectors(t.a,Hi),Fi.subVectors(t.b,Hi),Bi.subVectors(t.c,Hi),zi.subVectors(Fi,Oi),ki.subVectors(Bi,Fi),Vi.subVectors(Oi,Bi);let e=[0,-zi.z,zi.y,0,-ki.z,ki.y,0,-Vi.z,Vi.y,zi.z,0,-zi.x,ki.z,0,-ki.x,Vi.z,0,-Vi.x,-zi.y,zi.x,0,-ki.y,ki.x,0,-Vi.y,Vi.x,0];return!!ji(e,Oi,Fi,Bi,Gi)&&(e=[1,0,0,0,1,0,0,0,1],!!ji(e,Oi,Fi,Bi,Gi)&&(Wi.crossVectors(zi,ki),e=[Wi.x,Wi.y,Wi.z],ji(e,Oi,Fi,Bi,Gi)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Di).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(Di).length()),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(Ui[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Ui[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Ui[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Ui[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Ui[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Ui[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Ui[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Ui[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Ui)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const Ui=[new Ci,new Ci,new Ci,new Ci,new Ci,new Ci,new Ci,new Ci],Di=new Ci,Ni=new Li,Oi=new Ci,Fi=new Ci,Bi=new Ci,zi=new Ci,ki=new Ci,Vi=new Ci,Hi=new Ci,Gi=new Ci,Wi=new Ci,Xi=new Ci;function ji(t,e,n,i,r){for(let s=0,a=t.length-3;s<=a;s+=3){Xi.fromArray(t,s);const a=r.x*Math.abs(Xi.x)+r.y*Math.abs(Xi.y)+r.z*Math.abs(Xi.z),o=e.dot(Xi),l=n.dot(Xi),c=i.dot(Xi);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const qi=new Li,Yi=new Ci,Zi=new Ci;class Ji{constructor(t=new Ci,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const n=this.center;void 0!==e?n.copy(e):qi.setFromPoints(t).getCenter(n);let i=0;for(let e=0,r=t.length;e<r;e++)i=Math.max(i,n.distanceToSquared(t[e]));return this.radius=Math.sqrt(i),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){const e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){const n=this.center.distanceToSquared(t);return e.copy(t),n>this.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Yi.subVectors(t,this.center);const e=Yi.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),n=.5*(t-this.radius);this.center.addScaledVector(Yi,n/t),this.radius+=n}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(!0===this.center.equals(t.center)?this.radius=Math.max(this.radius,t.radius):(Zi.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Yi.copy(t.center).add(Zi)),this.expandByPoint(Yi.copy(t.center).sub(Zi))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Ki=new Ci,$i=new Ci,Qi=new Ci,tr=new Ci,er=new Ci,nr=new Ci,ir=new Ci;class rr{constructor(t=new Ci,e=new Ci(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,Ki)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=Ki.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Ki.copy(this.origin).addScaledVector(this.direction,e),Ki.distanceToSquared(t))}distanceSqToSegment(t,e,n,i){$i.copy(t).add(e).multiplyScalar(.5),Qi.copy(e).sub(t).normalize(),tr.copy(this.origin).sub($i);const r=.5*t.distanceTo(e),s=-this.direction.dot(Qi),a=tr.dot(this.direction),o=-tr.dot(Qi),l=tr.lengthSq(),c=Math.abs(1-s*s);let h,u,d,p;if(c>0)if(h=s*o-a,u=s*a-o,p=r*c,h>=0)if(u>=-p)if(u<=p){const t=1/c;h*=t,u*=t,d=h*(h+s*u+2*a)+u*(s*h+u+2*o)+l}else u=r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u=-r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-s*r+a)),u=h>0?-r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+l):(h=Math.max(0,-(s*r+a)),u=h>0?r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l);else u=s>0?-r:r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy($i).addScaledVector(Qi,u),d}intersectSphere(t,e){Ki.subVectors(t.center,this.origin);const n=Ki.dot(this.direction),i=Ki.dot(Ki)-n*n,r=t.radius*t.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,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){const n=this.distanceToPlane(t);return null===n?null:this.at(n,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(n=(t.min.x-u.x)*l,i=(t.max.x-u.x)*l):(n=(t.max.x-u.x)*l,i=(t.min.x-u.x)*l),c>=0?(r=(t.min.y-u.y)*c,s=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,s=(t.min.y-u.y)*c),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s<i||isNaN(i))&&(i=s),h>=0?(a=(t.min.z-u.z)*h,o=(t.max.z-u.z)*h):(a=(t.max.z-u.z)*h,o=(t.min.z-u.z)*h),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o<i||i!=i)&&(i=o),i<0?null:this.at(n>=0?n:i,e)))}intersectsBox(t){return null!==this.intersectBox(t,Ki)}intersectTriangle(t,e,n,i,r){er.subVectors(e,t),nr.subVectors(n,t),ir.crossVectors(er,nr);let s,a=this.direction.dot(ir);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}tr.subVectors(this.origin,t);const o=s*this.direction.dot(nr.crossVectors(tr,nr));if(o<0)return null;const l=s*this.direction.dot(er.cross(tr));if(l<0)return null;if(o+l>a)return null;const c=-s*tr.dot(ir);return c<0?null:this.at(c/a,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class sr{constructor(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){sr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f)}set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=t,g[4]=e,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,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 sr).fromArray(this.elements)}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){const e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,n=t.elements,i=1/ar.setFromMatrixColumn(t,0).length(),r=1/ar.setFromMatrixColumn(t,1).length(),s=1/ar.setFromMatrixColumn(t,2).length();return e[0]=n[0]*i,e[1]=n[1]*i,e[2]=n[2]*i,e[3]=0,e[4]=n[4]*r,e[5]=n[5]*r,e[6]=n[6]*r,e[7]=0,e[8]=n[8]*s,e[9]=n[9]*s,e[10]=n[10]*s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,n=t.x,i=t.y,r=t.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),h=Math.sin(r);if("XYZ"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=-o*h,e[8]=l,e[1]=n+i*l,e[5]=t-r*l,e[9]=-a*o,e[2]=r-t*l,e[6]=i+n*l,e[10]=s*o}else if("YXZ"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t+r*a,e[4]=i*a-n,e[8]=s*l,e[1]=s*h,e[5]=s*c,e[9]=-a,e[2]=n*a-i,e[6]=r+t*a,e[10]=s*o}else if("ZXY"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t-r*a,e[4]=-s*h,e[8]=i+n*a,e[1]=n+i*a,e[5]=s*c,e[9]=r-t*a,e[2]=-s*l,e[6]=a,e[10]=s*o}else if("ZYX"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=i*l-n,e[8]=t*l+r,e[1]=o*h,e[5]=r*l+t,e[9]=n*l-i,e[2]=-l,e[6]=a*o,e[10]=s*o}else if("YZX"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=r-t*h,e[8]=i*h+n,e[1]=h,e[5]=s*c,e[9]=-a*c,e[2]=-l*c,e[6]=n*h+i,e[10]=t-r*h}else if("XZY"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=-h,e[8]=l*c,e[1]=t*h+r,e[5]=s*c,e[9]=n*h-i,e[2]=i*h-n,e[6]=a*c,e[10]=r*h+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(lr,t,cr)}lookAt(t,e,n){const i=this.elements;return dr.subVectors(t,e),0===dr.lengthSq()&&(dr.z=1),dr.normalize(),hr.crossVectors(n,dr),0===hr.lengthSq()&&(1===Math.abs(n.z)?dr.x+=1e-4:dr.z+=1e-4,dr.normalize(),hr.crossVectors(n,dr)),hr.normalize(),ur.crossVectors(dr,hr),i[0]=hr.x,i[4]=ur.x,i[8]=dr.x,i[1]=hr.y,i[5]=ur.y,i[9]=dr.y,i[2]=hr.z,i[6]=ur.z,i[10]=dr.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],h=n[5],u=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],v=n[3],_=n[7],x=n[11],y=n[15],M=i[0],S=i[4],b=i[8],T=i[12],w=i[1],E=i[5],A=i[9],R=i[13],C=i[2],I=i[6],P=i[10],L=i[14],U=i[3],D=i[7],N=i[11],O=i[15];return r[0]=s*M+a*w+o*C+l*U,r[4]=s*S+a*E+o*I+l*D,r[8]=s*b+a*A+o*P+l*N,r[12]=s*T+a*R+o*L+l*O,r[1]=c*M+h*w+u*C+d*U,r[5]=c*S+h*E+u*I+d*D,r[9]=c*b+h*A+u*P+d*N,r[13]=c*T+h*R+u*L+d*O,r[2]=p*M+m*w+f*C+g*U,r[6]=p*S+m*E+f*I+g*D,r[10]=p*b+m*A+f*P+g*N,r[14]=p*T+m*R+f*L+g*O,r[3]=v*M+_*w+x*C+y*U,r[7]=v*S+_*E+x*I+y*D,r[11]=v*b+_*A+x*P+y*N,r[15]=v*T+_*R+x*L+y*O,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[4],i=t[8],r=t[12],s=t[1],a=t[5],o=t[9],l=t[13],c=t[2],h=t[6],u=t[10],d=t[14];return t[3]*(+r*o*h-i*l*h-r*a*u+n*l*u+i*a*d-n*o*d)+t[7]*(+e*o*d-e*l*u+r*s*u-i*s*d+i*l*c-r*o*c)+t[11]*(+e*l*h-e*a*d-r*s*h+n*s*d+r*a*c-n*l*c)+t[15]*(-i*a*c-e*o*h+e*a*u+i*s*h-n*s*u+n*o*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){const i=this.elements;return t.isVector3?(i[12]=t.x,i[13]=t.y,i[14]=t.z):(i[12]=t,i[13]=e,i[14]=n),this}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=t[9],u=t[10],d=t[11],p=t[12],m=t[13],f=t[14],g=t[15],v=h*f*l-m*u*l+m*o*d-a*f*d-h*o*g+a*u*g,_=p*u*l-c*f*l-p*o*d+s*f*d+c*o*g-s*u*g,x=c*m*l-p*h*l+p*a*d-s*m*d-c*a*g+s*h*g,y=p*h*o-c*m*o-p*a*u+s*m*u+c*a*f-s*h*f,M=e*v+n*_+i*x+r*y;if(0===M)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/M;return t[0]=v*S,t[1]=(m*u*r-h*f*r-m*i*d+n*f*d+h*i*g-n*u*g)*S,t[2]=(a*f*r-m*o*r+m*i*l-n*f*l-a*i*g+n*o*g)*S,t[3]=(h*o*r-a*u*r-h*i*l+n*u*l+a*i*d-n*o*d)*S,t[4]=_*S,t[5]=(c*f*r-p*u*r+p*i*d-e*f*d-c*i*g+e*u*g)*S,t[6]=(p*o*r-s*f*r-p*i*l+e*f*l+s*i*g-e*o*g)*S,t[7]=(s*u*r-c*o*r+c*i*l-e*u*l-s*i*d+e*o*d)*S,t[8]=x*S,t[9]=(p*h*r-c*m*r-p*n*d+e*m*d+c*n*g-e*h*g)*S,t[10]=(s*m*r-p*a*r+p*n*l-e*m*l-s*n*g+e*a*g)*S,t[11]=(c*a*r-s*h*r-c*n*l+e*h*l+s*n*d-e*a*d)*S,t[12]=y*S,t[13]=(c*m*i-p*h*i+p*n*u-e*m*u-c*n*f+e*h*f)*S,t[14]=(p*a*i-s*m*i-p*n*o+e*m*o+s*n*f-e*a*f)*S,t[15]=(s*h*i-c*a*i+c*n*o-e*h*o-s*n*u+e*a*u)*S,this}scale(t){const e=this.elements,n=t.x,i=t.y,r=t.z;return e[0]*=n,e[4]*=i,e[8]*=r,e[1]*=n,e[5]*=i,e[9]*=r,e[2]*=n,e[6]*=i,e[10]*=r,e[3]*=n,e[7]*=i,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,i))}makeTranslation(t,e,n){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const n=Math.cos(e),i=Math.sin(e),r=1-n,s=t.x,a=t.y,o=t.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n,i,r,s){return this.set(1,n,r,0,t,1,s,0,e,i,1,0,0,0,0,1),this}compose(t,e,n){const i=this.elements,r=e._x,s=e._y,a=e._z,o=e._w,l=r+r,c=s+s,h=a+a,u=r*l,d=r*c,p=r*h,m=s*c,f=s*h,g=a*h,v=o*l,_=o*c,x=o*h,y=n.x,M=n.y,S=n.z;return i[0]=(1-(m+g))*y,i[1]=(d+x)*y,i[2]=(p-_)*y,i[3]=0,i[4]=(d-x)*M,i[5]=(1-(u+g))*M,i[6]=(f+v)*M,i[7]=0,i[8]=(p+_)*S,i[9]=(f-v)*S,i[10]=(1-(u+m))*S,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,n){const i=this.elements;let r=ar.set(i[0],i[1],i[2]).length();const s=ar.set(i[4],i[5],i[6]).length(),a=ar.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),t.x=i[12],t.y=i[13],t.z=i[14],or.copy(this);const o=1/r,l=1/s,c=1/a;return or.elements[0]*=o,or.elements[1]*=o,or.elements[2]*=o,or.elements[4]*=l,or.elements[5]*=l,or.elements[6]*=l,or.elements[8]*=c,or.elements[9]*=c,or.elements[10]*=c,e.setFromRotationMatrix(or),n.x=r,n.y=s,n.z=a,this}makePerspective(t,e,n,i,r,s,a=2e3){const o=this.elements,l=2*r/(e-t),c=2*r/(n-i),h=(e+t)/(e-t),u=(n+i)/(n-i);let d,p;if(a===On)d=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==Fn)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]=h,o[12]=0,o[1]=0,o[5]=c,o[9]=u,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(t,e,n,i,r,s,a=2e3){const o=this.elements,l=1/(e-t),c=1/(n-i),h=1/(s-r),u=(e+t)*l,d=(n+i)*c;let p,m;if(a===On)p=(s+r)*h,m=-2*h;else{if(a!==Fn)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*h,m=-1*h}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-u,o[1]=0,o[5]=2*c,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=m,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<16;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}}const ar=new Ci,or=new sr,lr=new Ci(0,0,0),cr=new Ci(1,1,1),hr=new Ci,ur=new Ci,dr=new Ci,pr=new sr,mr=new Ri;class fr{constructor(t=0,e=0,n=0,i=fr.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=n,this._order=i}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,i=this._order){return this._x=t,this._y=e,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,n=!0){const i=t.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],d=i[10];switch(e){case"XYZ":this._y=Math.asin(Wn(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Wn(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin(Wn(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Wn(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(Wn(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Wn(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===n&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return pr.makeRotationFromQuaternion(t),this.setFromRotationMatrix(pr,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return mr.setFromEuler(this),this.setFromQuaternion(mr,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}fr.DEFAULT_ORDER="XYZ";class gr{constructor(){this.mask=1}set(t){this.mask=1<<t>>>0}enable(t){this.mask|=1<<t}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t}disable(t){this.mask&=~(1<<t)}disableAll(){this.mask=0}test(t){return!!(this.mask&t.mask)}isEnabled(t){return!!(this.mask&1<<t)}}let vr=0;const _r=new Ci,xr=new Ri,yr=new sr,Mr=new Ci,Sr=new Ci,br=new Ci,Tr=new Ri,wr=new Ci(1,0,0),Er=new Ci(0,1,0),Ar=new Ci(0,0,1),Rr={type:"added"},Cr={type:"removed"},Ir={type:"childadded",child:null},Pr={type:"childremoved",child:null};class Lr extends Bn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:vr++}),this.uuid=Gn(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Lr.DEFAULT_UP.clone();const t=new Ci,e=new fr,n=new Ri,i=new Ci(1,1,1);e._onChange((function(){n.setFromEuler(e,!1)})),n._onChange((function(){e.setFromQuaternion(n,void 0,!1)})),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new sr},normalMatrix:{value:new Kn}}),this.matrix=new sr,this.matrixWorld=new sr,this.matrixAutoUpdate=Lr.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Lr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new gr,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return xr.setFromAxisAngle(t,e),this.quaternion.multiply(xr),this}rotateOnWorldAxis(t,e){return xr.setFromAxisAngle(t,e),this.quaternion.premultiply(xr),this}rotateX(t){return this.rotateOnAxis(wr,t)}rotateY(t){return this.rotateOnAxis(Er,t)}rotateZ(t){return this.rotateOnAxis(Ar,t)}translateOnAxis(t,e){return _r.copy(t).applyQuaternion(this.quaternion),this.position.add(_r.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(wr,t)}translateY(t){return this.translateOnAxis(Er,t)}translateZ(t){return this.translateOnAxis(Ar,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(yr.copy(this.matrixWorld).invert())}lookAt(t,e,n){t.isVector3?Mr.copy(t):Mr.set(t,e,n);const i=this.parent;this.updateWorldMatrix(!0,!1),Sr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?yr.lookAt(Sr,Mr,this.up):yr.lookAt(Mr,Sr,this.up),this.quaternion.setFromRotationMatrix(yr),i&&(yr.extractRotation(i.matrixWorld),xr.setFromRotationMatrix(yr),this.quaternion.premultiply(xr.invert()))}add(t){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return t===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",t),this):(t&&t.isObject3D?(t.removeFromParent(),t.parent=this,this.children.push(t),t.dispatchEvent(Rr),Ir.child=t,this.dispatchEvent(Ir),Ir.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",t),this)}remove(t){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.remove(arguments[t]);return this}const e=this.children.indexOf(t);return-1!==e&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(Cr),Pr.child=t,this.dispatchEvent(Pr),Pr.child=null),this}removeFromParent(){const t=this.parent;return null!==t&&t.remove(this),this}clear(){return this.remove(...this.children)}attach(t){return this.updateWorldMatrix(!0,!1),yr.copy(this.matrixWorld).invert(),null!==t.parent&&(t.parent.updateWorldMatrix(!0,!1),yr.multiply(t.parent.matrixWorld)),t.applyMatrix4(yr),t.removeFromParent(),t.parent=this,this.children.push(t),t.updateWorldMatrix(!1,!0),t.dispatchEvent(Rr),Ir.child=t,this.dispatchEvent(Ir),Ir.child=null,this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let n=0,i=this.children.length;n<i;n++){const i=this.children[n].getObjectByProperty(t,e);if(void 0!==i)return i}}getObjectsByProperty(t,e,n=[]){this[t]===e&&n.push(this);const i=this.children;for(let r=0,s=i.length;r<s;r++)i[r].getObjectsByProperty(t,e,n);return n}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Sr,t,br),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Sr,Tr,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(t){t(this);const e=this.children;for(let n=0,i=e.length;n<i;n++)e[n].traverse(t)}traverseVisible(t){if(!1===this.visible)return;t(this);const e=this.children;for(let n=0,i=e.length;n<i;n++)e[n].traverseVisible(t)}traverseAncestors(t){const e=this.parent;null!==e&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,t=!0);const e=this.children;for(let n=0,i=e.length;n<i;n++){e[n].updateMatrixWorld(t)}}updateWorldMatrix(t,e){const n=this.parent;if(!0===t&&null!==n&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),!0===e){const t=this.children;for(let e=0,n=t.length;e<n;e++){t[e].updateWorldMatrix(!1,!0)}}}toJSON(t){const e=void 0===t||"string"==typeof t,n={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const i={};function r(e,n){return void 0===e[n.uuid]&&(e[n.uuid]=n.toJSON(t)),n.uuid}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),!0===this.castShadow&&(i.castShadow=!0),!0===this.receiveShadow&&(i.receiveShadow=!0),!1===this.visible&&(i.visible=!1),!1===this.frustumCulled&&(i.frustumCulled=!1),0!==this.renderOrder&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(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((t=>({boxInitialized:t.boxInitialized,boxMin:t.box.min.toArray(),boxMax:t.box.max.toArray(),sphereInitialized:t.sphereInitialized,sphereRadius:t.sphere.radius,sphereCenter:t.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(t),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(t)),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(t).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const n=e.shapes;if(Array.isArray(n))for(let e=0,i=n.length;e<i;e++){const i=n[e];r(t.shapes,i)}else r(t.shapes,n)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(t.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const e=[];for(let n=0,i=this.material.length;n<i;n++)e.push(r(t.materials,this.material[n]));i.material=e}else i.material=r(t.materials,this.material);if(this.children.length>0){i.children=[];for(let e=0;e<this.children.length;e++)i.children.push(this.children[e].toJSON(t).object)}if(this.animations.length>0){i.animations=[];for(let e=0;e<this.animations.length;e++){const n=this.animations[e];i.animations.push(r(t.animations,n))}}if(e){const e=s(t.geometries),i=s(t.materials),r=s(t.textures),a=s(t.images),o=s(t.shapes),l=s(t.skeletons),c=s(t.animations),h=s(t.nodes);e.length>0&&(n.geometries=e),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),c.length>0&&(n.animations=c),h.length>0&&(n.nodes=h)}return n.object=i,n;function s(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e<t.children.length;e++){const n=t.children[e];this.add(n.clone())}return this}}Lr.DEFAULT_UP=new Ci(0,1,0),Lr.DEFAULT_MATRIX_AUTO_UPDATE=!0,Lr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Ur=new Ci,Dr=new Ci,Nr=new Ci,Or=new Ci,Fr=new Ci,Br=new Ci,zr=new Ci,kr=new Ci,Vr=new Ci,Hr=new Ci,Gr=new Mi,Wr=new Mi,Xr=new Mi;class jr{constructor(t=new Ci,e=new Ci,n=new Ci){this.a=t,this.b=e,this.c=n}static getNormal(t,e,n,i){i.subVectors(n,e),Ur.subVectors(t,e),i.cross(Ur);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(t,e,n,i,r){Ur.subVectors(i,e),Dr.subVectors(n,e),Nr.subVectors(t,e);const s=Ur.dot(Ur),a=Ur.dot(Dr),o=Ur.dot(Nr),l=Dr.dot(Dr),c=Dr.dot(Nr),h=s*l-a*a;if(0===h)return r.set(0,0,0),null;const u=1/h,d=(l*o-a*c)*u,p=(s*c-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,n,i){return null!==this.getBarycoord(t,e,n,i,Or)&&(Or.x>=0&&Or.y>=0&&Or.x+Or.y<=1)}static getInterpolation(t,e,n,i,r,s,a,o){return null===this.getBarycoord(t,e,n,i,Or)?(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,Or.x),o.addScaledVector(s,Or.y),o.addScaledVector(a,Or.z),o)}static getInterpolatedAttribute(t,e,n,i,r,s){return Gr.setScalar(0),Wr.setScalar(0),Xr.setScalar(0),Gr.fromBufferAttribute(t,e),Wr.fromBufferAttribute(t,n),Xr.fromBufferAttribute(t,i),s.setScalar(0),s.addScaledVector(Gr,r.x),s.addScaledVector(Wr,r.y),s.addScaledVector(Xr,r.z),s}static isFrontFacing(t,e,n,i){return Ur.subVectors(n,e),Dr.subVectors(t,e),Ur.cross(Dr).dot(i)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,i){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[i]),this}setFromAttributeAndIndices(t,e,n,i){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,i),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Ur.subVectors(this.c,this.b),Dr.subVectors(this.a,this.b),.5*Ur.cross(Dr).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return jr.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return jr.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,n,i,r){return jr.getInterpolation(t,this.a,this.b,this.c,e,n,i,r)}containsPoint(t){return jr.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return jr.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const n=this.a,i=this.b,r=this.c;let s,a;Fr.subVectors(i,n),Br.subVectors(r,n),kr.subVectors(t,n);const o=Fr.dot(kr),l=Br.dot(kr);if(o<=0&&l<=0)return e.copy(n);Vr.subVectors(t,i);const c=Fr.dot(Vr),h=Br.dot(Vr);if(c>=0&&h<=c)return e.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return s=o/(o-c),e.copy(n).addScaledVector(Fr,s);Hr.subVectors(t,r);const d=Fr.dot(Hr),p=Br.dot(Hr);if(p>=0&&d<=p)return e.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(n).addScaledVector(Br,a);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return zr.subVectors(r,i),a=(h-c)/(h-c+(d-p)),e.copy(i).addScaledVector(zr,a);const g=1/(f+m+u);return s=m*g,a=u*g,e.copy(n).addScaledVector(Fr,s).addScaledVector(Br,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}const qr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Yr={h:0,s:0,l:0},Zr={h:0,s:0,l:0};function Jr(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+6*(e-t)*(2/3-n):t}class Kr{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(void 0===e&&void 0===n){const e=t;e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=Je){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,ai.toWorkingColorSpace(this,e),this}setRGB(t,e,n,i=ai.workingColorSpace){return this.r=t,this.g=e,this.b=n,ai.toWorkingColorSpace(this,i),this}setHSL(t,e,n,i=ai.workingColorSpace){if(t=Xn(t,1),e=Wn(e,0,1),n=Wn(n,0,1),0===e)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+e):n+e-n*e,r=2*n-i;this.r=Jr(r,i,t+1/3),this.g=Jr(r,i,t),this.b=Jr(r,i,t-1/3)}return ai.toWorkingColorSpace(this,i),this}setStyle(t,e=Je){function n(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(t)){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,e);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,e);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,e);break;default:console.warn("THREE.Color: Unknown color model "+t)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(t)){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,e);if(6===r)return this.setHex(parseInt(n,16),e);console.warn("THREE.Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Je){const n=qr[t.toLowerCase()];return void 0!==n?this.setHex(n,e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=oi(t.r),this.g=oi(t.g),this.b=oi(t.b),this}copyLinearToSRGB(t){return this.r=li(t.r),this.g=li(t.g),this.b=li(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Je){return ai.fromWorkingColorSpace($r.copy(this),t),65536*Math.round(Wn(255*$r.r,0,255))+256*Math.round(Wn(255*$r.g,0,255))+Math.round(Wn(255*$r.b,0,255))}getHexString(t=Je){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=ai.workingColorSpace){ai.fromWorkingColorSpace($r.copy(this),e);const n=$r.r,i=$r.g,r=$r.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const t=s-a;switch(l=c<=.5?t/(s+a):t/(2-s-a),s){case n:o=(i-r)/t+(i<r?6:0);break;case i:o=(r-n)/t+2;break;case r:o=(n-i)/t+4}o/=6}return t.h=o,t.s=l,t.l=c,t}getRGB(t,e=ai.workingColorSpace){return ai.fromWorkingColorSpace($r.copy(this),e),t.r=$r.r,t.g=$r.g,t.b=$r.b,t}getStyle(t=Je){ai.fromWorkingColorSpace($r.copy(this),t);const e=$r.r,n=$r.g,i=$r.b;return t!==Je?`color(${t} ${e.toFixed(3)} ${n.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(255*e)},${Math.round(255*n)},${Math.round(255*i)})`}offsetHSL(t,e,n){return this.getHSL(Yr),this.setHSL(Yr.h+t,Yr.s+e,Yr.l+n)}add(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this}addColors(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this}addScalar(t){return this.r+=t,this.g+=t,this.b+=t,this}sub(t){return this.r=Math.max(0,this.r-t.r),this.g=Math.max(0,this.g-t.g),this.b=Math.max(0,this.b-t.b),this}multiply(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this}multiplyScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}lerp(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this}lerpColors(t,e,n){return this.r=t.r+(e.r-t.r)*n,this.g=t.g+(e.g-t.g)*n,this.b=t.b+(e.b-t.b)*n,this}lerpHSL(t,e){this.getHSL(Yr),t.getHSL(Zr);const n=jn(Yr.h,Zr.h,e),i=jn(Yr.s,Zr.s,e),r=jn(Yr.l,Zr.l,e);return this.setHSL(n,i,r),this}setFromVector3(t){return this.r=t.x,this.g=t.y,this.b=t.z,this}applyMatrix3(t){const e=this.r,n=this.g,i=this.b,r=t.elements;return this.r=r[0]*e+r[3]*n+r[6]*i,this.g=r[1]*e+r[4]*n+r[7]*i,this.b=r[2]*e+r[5]*n+r[8]*i,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}fromArray(t,e=0){return this.r=t[e],this.g=t[e+1],this.b=t[e+2],this}toArray(t=[],e=0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t}fromBufferAttribute(t,e){return this.r=t.getX(e),this.g=t.getY(e),this.b=t.getZ(e),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const $r=new Kr;Kr.NAMES=qr;let Qr=0;class ts extends Bn{static get type(){return"Material"}get type(){return this.constructor.type}set type(t){}constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Qr++}),this.uuid=Gn(),this.name="",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=C,this.blendDst=I,this.blendEquation=y,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Kr(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=en,this.stencilZFail=en,this.stencilZPass=en,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const n=t[e];if(void 0===n){console.warn(`THREE.Material: parameter '${e}' has value of undefined.`);continue}const i=this[e];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[e]=n:console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`)}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}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(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).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(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).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(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).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(t).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).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!==C&&(n.blendSrc=this.blendSrc),this.blendDst!==I&&(n.blendDst=this.blendDst),this.blendEquation!==y&&(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!==en&&(n.stencilFail=this.stencilFail),this.stencilZFail!==en&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==en&&(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),e){const e=i(t.textures),r=i(t.images);e.length>0&&(n.textures=e),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let n=null;if(null!==e){const t=e.length;n=new Array(t);for(let i=0;i!==t;++i)n[i]=e[i].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){!0===t&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class es extends ts{static get type(){return"MeshBasicMaterial"}constructor(t){super(),this.isMeshBasicMaterial=!0,this.color=new Kr(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 fr,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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const ns=is();function is(){const t=new ArrayBuffer(4),e=new Float32Array(t),n=new Uint32Array(t),i=new Uint32Array(512),r=new Uint32Array(512);for(let t=0;t<256;++t){const e=t-127;e<-27?(i[t]=0,i[256|t]=32768,r[t]=24,r[256|t]=24):e<-14?(i[t]=1024>>-e-14,i[256|t]=1024>>-e-14|32768,r[t]=-e-1,r[256|t]=-e-1):e<=15?(i[t]=e+15<<10,i[256|t]=e+15<<10|32768,r[t]=13,r[256|t]=13):e<128?(i[t]=31744,i[256|t]=64512,r[t]=24,r[256|t]=24):(i[t]=31744,i[256|t]=64512,r[t]=13,r[256|t]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let t=1;t<1024;++t){let e=t<<13,n=0;for(;!(8388608&e);)e<<=1,n-=8388608;e&=-8388609,n+=947912704,s[t]=e|n}for(let t=1024;t<2048;++t)s[t]=939524096+(t-1024<<13);for(let t=1;t<31;++t)a[t]=t<<23;a[31]=1199570944,a[32]=2147483648;for(let t=33;t<63;++t)a[t]=2147483648+(t-32<<23);a[63]=3347054592;for(let t=1;t<64;++t)32!==t&&(o[t]=1024);return{floatView:e,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function rs(t){Math.abs(t)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),t=Wn(t,-65504,65504),ns.floatView[0]=t;const e=ns.uint32View[0],n=e>>23&511;return ns.baseTable[n]+((8388607&e)>>ns.shiftTable[n])}function ss(t){const e=t>>10;return ns.uint32View[0]=ns.mantissaTable[ns.offsetTable[e]+(1023&t)]+ns.exponentTable[e],ns.floatView[0]}const as={toHalfFloat:rs,fromHalfFloat:ss},os=new Ci,ls=new Jn;class cs{constructor(t,e,n=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=n,this.usage=wn,this.updateRanges=[],this.gpuType=Lt,this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[t+i]=e.array[n+i];return this}copyArray(t){return this.array.set(t),this}applyMatrix3(t){if(2===this.itemSize)for(let e=0,n=this.count;e<n;e++)ls.fromBufferAttribute(this,e),ls.applyMatrix3(t),this.setXY(e,ls.x,ls.y);else if(3===this.itemSize)for(let e=0,n=this.count;e<n;e++)os.fromBufferAttribute(this,e),os.applyMatrix3(t),this.setXYZ(e,os.x,os.y,os.z);return this}applyMatrix4(t){for(let e=0,n=this.count;e<n;e++)os.fromBufferAttribute(this,e),os.applyMatrix4(t),this.setXYZ(e,os.x,os.y,os.z);return this}applyNormalMatrix(t){for(let e=0,n=this.count;e<n;e++)os.fromBufferAttribute(this,e),os.applyNormalMatrix(t),this.setXYZ(e,os.x,os.y,os.z);return this}transformDirection(t){for(let e=0,n=this.count;e<n;e++)os.fromBufferAttribute(this,e),os.transformDirection(t),this.setXYZ(e,os.x,os.y,os.z);return this}set(t,e=0){return this.array.set(t,e),this}getComponent(t,e){let n=this.array[t*this.itemSize+e];return this.normalized&&(n=qn(n,this.array)),n}setComponent(t,e,n){return this.normalized&&(n=Yn(n,this.array)),this.array[t*this.itemSize+e]=n,this}getX(t){let e=this.array[t*this.itemSize];return this.normalized&&(e=qn(e,this.array)),e}setX(t,e){return this.normalized&&(e=Yn(e,this.array)),this.array[t*this.itemSize]=e,this}getY(t){let e=this.array[t*this.itemSize+1];return this.normalized&&(e=qn(e,this.array)),e}setY(t,e){return this.normalized&&(e=Yn(e,this.array)),this.array[t*this.itemSize+1]=e,this}getZ(t){let e=this.array[t*this.itemSize+2];return this.normalized&&(e=qn(e,this.array)),e}setZ(t,e){return this.normalized&&(e=Yn(e,this.array)),this.array[t*this.itemSize+2]=e,this}getW(t){let e=this.array[t*this.itemSize+3];return this.normalized&&(e=qn(e,this.array)),e}setW(t,e){return this.normalized&&(e=Yn(e,this.array)),this.array[t*this.itemSize+3]=e,this}setXY(t,e,n){return t*=this.itemSize,this.normalized&&(e=Yn(e,this.array),n=Yn(n,this.array)),this.array[t+0]=e,this.array[t+1]=n,this}setXYZ(t,e,n,i){return t*=this.itemSize,this.normalized&&(e=Yn(e,this.array),n=Yn(n,this.array),i=Yn(i,this.array)),this.array[t+0]=e,this.array[t+1]=n,this.array[t+2]=i,this}setXYZW(t,e,n,i,r){return t*=this.itemSize,this.normalized&&(e=Yn(e,this.array),n=Yn(n,this.array),i=Yn(i,this.array),r=Yn(r,this.array)),this.array[t+0]=e,this.array[t+1]=n,this.array[t+2]=i,this.array[t+3]=r,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return""!==this.name&&(t.name=this.name),this.usage!==wn&&(t.usage=this.usage),t}}class hs extends cs{constructor(t,e,n){super(new Int8Array(t),e,n)}}class us extends cs{constructor(t,e,n){super(new Uint8Array(t),e,n)}}class ds extends cs{constructor(t,e,n){super(new Uint8ClampedArray(t),e,n)}}class ps extends cs{constructor(t,e,n){super(new Int16Array(t),e,n)}}class ms extends cs{constructor(t,e,n){super(new Uint16Array(t),e,n)}}class fs extends cs{constructor(t,e,n){super(new Int32Array(t),e,n)}}class gs extends cs{constructor(t,e,n){super(new Uint32Array(t),e,n)}}class vs extends cs{constructor(t,e,n){super(new Uint16Array(t),e,n),this.isFloat16BufferAttribute=!0}getX(t){let e=ss(this.array[t*this.itemSize]);return this.normalized&&(e=qn(e,this.array)),e}setX(t,e){return this.normalized&&(e=Yn(e,this.array)),this.array[t*this.itemSize]=rs(e),this}getY(t){let e=ss(this.array[t*this.itemSize+1]);return this.normalized&&(e=qn(e,this.array)),e}setY(t,e){return this.normalized&&(e=Yn(e,this.array)),this.array[t*this.itemSize+1]=rs(e),this}getZ(t){let e=ss(this.array[t*this.itemSize+2]);return this.normalized&&(e=qn(e,this.array)),e}setZ(t,e){return this.normalized&&(e=Yn(e,this.array)),this.array[t*this.itemSize+2]=rs(e),this}getW(t){let e=ss(this.array[t*this.itemSize+3]);return this.normalized&&(e=qn(e,this.array)),e}setW(t,e){return this.normalized&&(e=Yn(e,this.array)),this.array[t*this.itemSize+3]=rs(e),this}setXY(t,e,n){return t*=this.itemSize,this.normalized&&(e=Yn(e,this.array),n=Yn(n,this.array)),this.array[t+0]=rs(e),this.array[t+1]=rs(n),this}setXYZ(t,e,n,i){return t*=this.itemSize,this.normalized&&(e=Yn(e,this.array),n=Yn(n,this.array),i=Yn(i,this.array)),this.array[t+0]=rs(e),this.array[t+1]=rs(n),this.array[t+2]=rs(i),this}setXYZW(t,e,n,i,r){return t*=this.itemSize,this.normalized&&(e=Yn(e,this.array),n=Yn(n,this.array),i=Yn(i,this.array),r=Yn(r,this.array)),this.array[t+0]=rs(e),this.array[t+1]=rs(n),this.array[t+2]=rs(i),this.array[t+3]=rs(r),this}}class _s extends cs{constructor(t,e,n){super(new Float32Array(t),e,n)}}let xs=0;const ys=new sr,Ms=new Lr,Ss=new Ci,bs=new Li,Ts=new Li,ws=new Ci;class Es extends Bn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:xs++}),this.uuid=Gn(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(Qn(t)?gs:ms)(t,1):this.index=t,this}setIndirect(t){return this.indirect=t,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return void 0!==this.attributes[t]}addGroup(t,e,n=0){this.groups.push({start:t,count:e,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;void 0!==e&&(e.applyMatrix4(t),e.needsUpdate=!0);const n=this.attributes.normal;if(void 0!==n){const e=(new Kn).getNormalMatrix(t);n.applyNormalMatrix(e),n.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(t),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(t){return ys.makeRotationFromQuaternion(t),this.applyMatrix4(ys),this}rotateX(t){return ys.makeRotationX(t),this.applyMatrix4(ys),this}rotateY(t){return ys.makeRotationY(t),this.applyMatrix4(ys),this}rotateZ(t){return ys.makeRotationZ(t),this.applyMatrix4(ys),this}translate(t,e,n){return ys.makeTranslation(t,e,n),this.applyMatrix4(ys),this}scale(t,e,n){return ys.makeScale(t,e,n),this.applyMatrix4(ys),this}lookAt(t){return Ms.lookAt(t),Ms.updateMatrix(),this.applyMatrix4(Ms.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Ss).negate(),this.translate(Ss.x,Ss.y,Ss.z),this}setFromPoints(t){const e=this.getAttribute("position");if(void 0===e){const e=[];for(let n=0,i=t.length;n<i;n++){const i=t[n];e.push(i.x,i.y,i.z||0)}this.setAttribute("position",new _s(e,3))}else{for(let n=0,i=e.count;n<i;n++){const i=t[n];e.setXYZ(n,i.x,i.y,i.z||0)}t.length>e.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Li);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Ci(-1/0,-1/0,-1/0),new Ci(1/0,1/0,1/0));if(void 0!==t){if(this.boundingBox.setFromBufferAttribute(t),e)for(let t=0,n=e.length;t<n;t++){const n=e[t];bs.setFromBufferAttribute(n),this.morphTargetsRelative?(ws.addVectors(this.boundingBox.min,bs.min),this.boundingBox.expandByPoint(ws),ws.addVectors(this.boundingBox.max,bs.max),this.boundingBox.expandByPoint(ws)):(this.boundingBox.expandByPoint(bs.min),this.boundingBox.expandByPoint(bs.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new Ji);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new Ci,1/0);if(t){const n=this.boundingSphere.center;if(bs.setFromBufferAttribute(t),e)for(let t=0,n=e.length;t<n;t++){const n=e[t];Ts.setFromBufferAttribute(n),this.morphTargetsRelative?(ws.addVectors(bs.min,Ts.min),bs.expandByPoint(ws),ws.addVectors(bs.max,Ts.max),bs.expandByPoint(ws)):(bs.expandByPoint(Ts.min),bs.expandByPoint(Ts.max))}bs.getCenter(n);let i=0;for(let e=0,r=t.count;e<r;e++)ws.fromBufferAttribute(t,e),i=Math.max(i,n.distanceToSquared(ws));if(e)for(let r=0,s=e.length;r<s;r++){const s=e[r],a=this.morphTargetsRelative;for(let e=0,r=s.count;e<r;e++)ws.fromBufferAttribute(s,e),a&&(Ss.fromBufferAttribute(t,e),ws.add(Ss)),i=Math.max(i,n.distanceToSquared(ws))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const t=this.index,e=this.attributes;if(null===t||void 0===e.position||void 0===e.normal||void 0===e.uv)return void console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const n=e.position,i=e.normal,r=e.uv;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new cs(new Float32Array(4*n.count),4));const s=this.getAttribute("tangent"),a=[],o=[];for(let t=0;t<n.count;t++)a[t]=new Ci,o[t]=new Ci;const l=new Ci,c=new Ci,h=new Ci,u=new Jn,d=new Jn,p=new Jn,m=new Ci,f=new Ci;function g(t,e,i){l.fromBufferAttribute(n,t),c.fromBufferAttribute(n,e),h.fromBufferAttribute(n,i),u.fromBufferAttribute(r,t),d.fromBufferAttribute(r,e),p.fromBufferAttribute(r,i),c.sub(l),h.sub(l),d.sub(u),p.sub(u);const s=1/(d.x*p.y-p.x*d.y);isFinite(s)&&(m.copy(c).multiplyScalar(p.y).addScaledVector(h,-d.y).multiplyScalar(s),f.copy(h).multiplyScalar(d.x).addScaledVector(c,-p.x).multiplyScalar(s),a[t].add(m),a[e].add(m),a[i].add(m),o[t].add(f),o[e].add(f),o[i].add(f))}let v=this.groups;0===v.length&&(v=[{start:0,count:t.count}]);for(let e=0,n=v.length;e<n;++e){const n=v[e],i=n.start;for(let e=i,r=i+n.count;e<r;e+=3)g(t.getX(e+0),t.getX(e+1),t.getX(e+2))}const _=new Ci,x=new Ci,y=new Ci,M=new Ci;function S(t){y.fromBufferAttribute(i,t),M.copy(y);const e=a[t];_.copy(e),_.sub(y.multiplyScalar(y.dot(e))).normalize(),x.crossVectors(M,e);const n=x.dot(o[t])<0?-1:1;s.setXYZW(t,_.x,_.y,_.z,n)}for(let e=0,n=v.length;e<n;++e){const n=v[e],i=n.start;for(let e=i,r=i+n.count;e<r;e+=3)S(t.getX(e+0)),S(t.getX(e+1)),S(t.getX(e+2))}}computeVertexNormals(){const t=this.index,e=this.getAttribute("position");if(void 0!==e){let n=this.getAttribute("normal");if(void 0===n)n=new cs(new Float32Array(3*e.count),3),this.setAttribute("normal",n);else for(let t=0,e=n.count;t<e;t++)n.setXYZ(t,0,0,0);const i=new Ci,r=new Ci,s=new Ci,a=new Ci,o=new Ci,l=new Ci,c=new Ci,h=new Ci;if(t)for(let u=0,d=t.count;u<d;u+=3){const d=t.getX(u+0),p=t.getX(u+1),m=t.getX(u+2);i.fromBufferAttribute(e,d),r.fromBufferAttribute(e,p),s.fromBufferAttribute(e,m),c.subVectors(s,r),h.subVectors(i,r),c.cross(h),a.fromBufferAttribute(n,d),o.fromBufferAttribute(n,p),l.fromBufferAttribute(n,m),a.add(c),o.add(c),l.add(c),n.setXYZ(d,a.x,a.y,a.z),n.setXYZ(p,o.x,o.y,o.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let t=0,a=e.count;t<a;t+=3)i.fromBufferAttribute(e,t+0),r.fromBufferAttribute(e,t+1),s.fromBufferAttribute(e,t+2),c.subVectors(s,r),h.subVectors(i,r),c.cross(h),n.setXYZ(t+0,c.x,c.y,c.z),n.setXYZ(t+1,c.x,c.y,c.z),n.setXYZ(t+2,c.x,c.y,c.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const t=this.attributes.normal;for(let e=0,n=t.count;e<n;e++)ws.fromBufferAttribute(t,e),ws.normalize(),t.setXYZ(e,ws.x,ws.y,ws.z)}toNonIndexed(){function t(t,e){const n=t.array,i=t.itemSize,r=t.normalized,s=new n.constructor(e.length*i);let a=0,o=0;for(let r=0,l=e.length;r<l;r++){a=t.isInterleavedBufferAttribute?e[r]*t.data.stride+t.offset:e[r]*i;for(let t=0;t<i;t++)s[o++]=n[a++]}return new cs(s,i,r)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const e=new Es,n=this.index.array,i=this.attributes;for(const r in i){const s=t(i[r],n);e.setAttribute(r,s)}const r=this.morphAttributes;for(const i in r){const s=[],a=r[i];for(let e=0,i=a.length;e<i;e++){const i=t(a[e],n);s.push(i)}e.morphAttributes[i]=s}e.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let t=0,n=s.length;t<n;t++){const n=s[t];e.addGroup(n.start,n.count,n.materialIndex)}return e}toJSON(){const t={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.type,""!==this.name&&(t.name=this.name),Object.keys(this.userData).length>0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const n in e)void 0!==e[n]&&(t[n]=e[n]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const n=this.attributes;for(const e in n){const i=n[e];t.data.attributes[e]=i.toJSON(t.data)}const i={};let r=!1;for(const e in this.morphAttributes){const n=this.morphAttributes[e],s=[];for(let e=0,i=n.length;e<i;e++){const i=n[e];s.push(i.toJSON(t.data))}s.length>0&&(i[e]=s,r=!0)}r&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return(new this.constructor).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const n=t.index;null!==n&&this.setIndex(n.clone(e));const i=t.attributes;for(const t in i){const n=i[t];this.setAttribute(t,n.clone(e))}const r=t.morphAttributes;for(const t in r){const n=[],i=r[t];for(let t=0,r=i.length;t<r;t++)n.push(i[t].clone(e));this.morphAttributes[t]=n}this.morphTargetsRelative=t.morphTargetsRelative;const s=t.groups;for(let t=0,e=s.length;t<e;t++){const e=s[t];this.addGroup(e.start,e.count,e.materialIndex)}const a=t.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=t.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const As=new sr,Rs=new rr,Cs=new Ji,Is=new Ci,Ps=new Ci,Ls=new Ci,Us=new Ci,Ds=new Ci,Ns=new Ci,Os=new Ci,Fs=new Ci;class Bs extends Lr{constructor(t=new Es,e=new es){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),void 0!==t.morphTargetInfluences&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),void 0!==t.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,e=Object.keys(t);if(e.length>0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;t<e;t++){const e=n[t].name||String(t);this.morphTargetInfluences.push(0),this.morphTargetDictionary[e]=t}}}}getVertexPosition(t,e){const n=this.geometry,i=n.attributes.position,r=n.morphAttributes.position,s=n.morphTargetsRelative;e.fromBufferAttribute(i,t);const a=this.morphTargetInfluences;if(r&&a){Ns.set(0,0,0);for(let n=0,i=r.length;n<i;n++){const i=a[n],o=r[n];0!==i&&(Ds.fromBufferAttribute(o,t),s?Ns.addScaledVector(Ds,i):Ns.addScaledVector(Ds.sub(e),i))}e.add(Ns)}return e}raycast(t,e){const n=this.geometry,i=this.material,r=this.matrixWorld;if(void 0!==i){if(null===n.boundingSphere&&n.computeBoundingSphere(),Cs.copy(n.boundingSphere),Cs.applyMatrix4(r),Rs.copy(t.ray).recast(t.near),!1===Cs.containsPoint(Rs.origin)){if(null===Rs.intersectSphere(Cs,Is))return;if(Rs.origin.distanceToSquared(Is)>(t.far-t.near)**2)return}As.copy(r).invert(),Rs.copy(t.ray).applyMatrix4(As),null!==n.boundingBox&&!1===Rs.intersectsBox(n.boundingBox)||this._computeIntersections(t,e,Rs)}}_computeIntersections(t,e,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,c=r.attributes.uv1,h=r.attributes.normal,u=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=u.length;r<o;r++){const o=u[r],p=s[o.materialIndex];for(let r=Math.max(o.start,d.start),s=Math.min(a.count,Math.min(o.start+o.count,d.start+d.count));r<s;r+=3){i=zs(this,p,t,n,l,c,h,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=o.materialIndex,e.push(i))}}else{for(let r=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);r<o;r+=3){i=zs(this,s,t,n,l,c,h,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),e.push(i))}}else if(void 0!==o)if(Array.isArray(s))for(let r=0,a=u.length;r<a;r++){const a=u[r],p=s[a.materialIndex];for(let r=Math.max(a.start,d.start),s=Math.min(o.count,Math.min(a.start+a.count,d.start+d.count));r<s;r+=3){i=zs(this,p,t,n,l,c,h,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=a.materialIndex,e.push(i))}}else{for(let r=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);r<a;r+=3){i=zs(this,s,t,n,l,c,h,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),e.push(i))}}}}function zs(t,e,n,i,r,s,a,o,l,c){t.getVertexPosition(o,Ps),t.getVertexPosition(l,Ls),t.getVertexPosition(c,Us);const h=function(t,e,n,i,r,s,a,o){let l;if(l=1===e.side?i.intersectTriangle(a,s,r,!0,o):i.intersectTriangle(r,s,a,0===e.side,o),null===l)return null;Fs.copy(o),Fs.applyMatrix4(t.matrixWorld);const c=n.ray.origin.distanceTo(Fs);return c<n.near||c>n.far?null:{distance:c,point:Fs.clone(),object:t}}(t,e,n,i,Ps,Ls,Us,Os);if(h){const t=new Ci;jr.getBarycoord(Os,Ps,Ls,Us,t),r&&(h.uv=jr.getInterpolatedAttribute(r,o,l,c,t,new Jn)),s&&(h.uv1=jr.getInterpolatedAttribute(s,o,l,c,t,new Jn)),a&&(h.normal=jr.getInterpolatedAttribute(a,o,l,c,t,new Ci),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const e={a:o,b:l,c:c,normal:new Ci,materialIndex:0};jr.getNormal(Ps,Ls,Us,e.normal),h.face=e,h.barycoord=t}return h}class ks extends Es{constructor(t=1,e=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,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=[],c=[],h=[];let u=0,d=0;function p(t,e,n,i,r,s,p,m,f,g,v){const _=s/f,x=p/g,y=s/2,M=p/2,S=m/2,b=f+1,T=g+1;let w=0,E=0;const A=new Ci;for(let s=0;s<T;s++){const a=s*x-M;for(let o=0;o<b;o++){const u=o*_-y;A[t]=u*i,A[e]=a*r,A[n]=S,l.push(A.x,A.y,A.z),A[t]=0,A[e]=0,A[n]=m>0?1:-1,c.push(A.x,A.y,A.z),h.push(o/f),h.push(1-s/g),w+=1}}for(let t=0;t<g;t++)for(let e=0;e<f;e++){const n=u+e+b*t,i=u+e+b*(t+1),r=u+(e+1)+b*(t+1),s=u+(e+1)+b*t;o.push(n,i,s),o.push(i,r,s),E+=6}a.addGroup(d,E,v),d+=E,u+=w}p("z","y","x",-1,-1,n,e,t,s,r,0),p("z","y","x",1,-1,n,e,-t,s,r,1),p("x","z","y",1,1,t,n,e,i,s,2),p("x","z","y",1,-1,t,n,-e,i,s,3),p("x","y","z",1,-1,t,e,n,i,r,4),p("x","y","z",-1,-1,t,e,-n,i,r,5),this.setIndex(o),this.setAttribute("position",new _s(l,3)),this.setAttribute("normal",new _s(c,3)),this.setAttribute("uv",new _s(h,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new ks(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}}function Vs(t){const e={};for(const n in t){e[n]={};for(const i in t[n]){const r=t[n][i];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?r.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[n][i]=null):e[n][i]=r.clone():Array.isArray(r)?e[n][i]=r.slice():e[n][i]=r}}return e}function Hs(t){const e={};for(let n=0;n<t.length;n++){const i=Vs(t[n]);for(const t in i)e[t]=i[t]}return e}function Gs(t){const e=t.getRenderTarget();return null===e?t.outputColorSpace:!0===e.isXRRenderTarget?e.texture.colorSpace:ai.workingColorSpace}const Ws={clone:Vs,merge:Hs};class Xs extends ts{static get type(){return"ShaderMaterial"}constructor(t){super(),this.isShaderMaterial=!0,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==t&&this.setValues(t)}copy(t){return super.copy(t),this.fragmentShader=t.fragmentShader,this.vertexShader=t.vertexShader,this.uniforms=Vs(t.uniforms),this.uniformsGroups=function(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].clone());return e}(t.uniformsGroups),this.defines=Object.assign({},t.defines),this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.fog=t.fog,this.lights=t.lights,this.clipping=t.clipping,this.extensions=Object.assign({},t.extensions),this.glslVersion=t.glslVersion,this}toJSON(t){const e=super.toJSON(t);e.glslVersion=this.glslVersion,e.uniforms={};for(const n in this.uniforms){const i=this.uniforms[n].value;i&&i.isTexture?e.uniforms[n]={type:"t",value:i.toJSON(t).uuid}:i&&i.isColor?e.uniforms[n]={type:"c",value:i.getHex()}:i&&i.isVector2?e.uniforms[n]={type:"v2",value:i.toArray()}:i&&i.isVector3?e.uniforms[n]={type:"v3",value:i.toArray()}:i&&i.isVector4?e.uniforms[n]={type:"v4",value:i.toArray()}:i&&i.isMatrix3?e.uniforms[n]={type:"m3",value:i.toArray()}:i&&i.isMatrix4?e.uniforms[n]={type:"m4",value:i.toArray()}:e.uniforms[n]={value:i}}Object.keys(this.defines).length>0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const n={};for(const t in this.extensions)!0===this.extensions[t]&&(n[t]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}}class js extends Lr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new sr,this.projectionMatrix=new sr,this.projectionMatrixInverse=new sr,this.coordinateSystem=On}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const qs=new Ci,Ys=new Jn,Zs=new Jn;class Js extends js{constructor(t=50,e=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*Hn*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*Vn*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*Hn*Math.atan(Math.tan(.5*Vn*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,n){qs.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(qs.x,qs.y).multiplyScalar(-t/qs.z),qs.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(qs.x,qs.y).multiplyScalar(-t/qs.z)}getViewSize(t,e){return this.getViewBounds(t,Ys,Zs),e.subVectors(Zs,Ys)}setViewOffset(t,e,n,i,r,s){this.aspect=t/e,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=t,this.view.fullHeight=e,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 t=this.near;let e=t*Math.tan(.5*Vn*this.fov)/this.zoom,n=2*e,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const t=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/t,e-=s.offsetY*n/a,i*=s.width/t,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,e,e-n,t,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const Ks=-90;class $s extends Lr{constructor(t,e,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Js(Ks,1,t,e);i.layers=this.layers,this.add(i);const r=new Js(Ks,1,t,e);r.layers=this.layers,this.add(r);const s=new Js(Ks,1,t,e);s.layers=this.layers,this.add(s);const a=new Js(Ks,1,t,e);a.layers=this.layers,this.add(a);const o=new Js(Ks,1,t,e);o.layers=this.layers,this.add(o);const l=new Js(Ks,1,t,e);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[n,i,r,s,a,o]=e;for(const t of e)this.remove(t);if(t===On)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(t!==Fn)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);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 t of e)this.add(t),t.updateMatrixWorld()}update(t,e){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,c]=this.children,h=t.getRenderTarget(),u=t.getActiveCubeFace(),d=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0,i),t.render(e,r),t.setRenderTarget(n,1,i),t.render(e,s),t.setRenderTarget(n,2,i),t.render(e,a),t.setRenderTarget(n,3,i),t.render(e,o),t.setRenderTarget(n,4,i),t.render(e,l),n.texture.generateMipmaps=m,t.setRenderTarget(n,5,i),t.render(e,c),t.setRenderTarget(h,u,d),t.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Qs extends yi{constructor(t,e,n,i,r,s,a,o,l,c){super(t=void 0!==t?t:[],e=void 0!==e?e:lt,n,i,r,s,a,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class ta extends bi{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const n={width:t,height:t,depth:1},i=[n,n,n,n,n,n];this.texture=new Qs(i,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:Mt}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.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 <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\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 <common>\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 ks(5,5,5),r=new Xs({name:"CubemapFromEquirect",uniforms:Vs(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=e;const s=new Bs(i,r),a=e.minFilter;e.minFilter===Tt&&(e.minFilter=Mt);return new $s(1,10,this).update(t,s),e.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(t,e,n,i){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,n,i);t.setRenderTarget(r)}}const ea=new Ci,na=new Ci,ia=new Kn;class ra{constructor(t=new Ci(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,n,i){return this.normal.set(t,e,n),this.constant=i,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,n){const i=ea.subVectors(n,e).cross(na.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e){const n=t.delta(ea),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(t.start)?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const n=e||ia.getNormalMatrix(t),i=this.coplanarPoint(ea).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const sa=new Ji,aa=new Ci;class oa{constructor(t=new ra,e=new ra,n=new ra,i=new ra,r=new ra,s=new ra){this.planes=[t,e,n,i,r,s]}set(t,e,n,i,r,s){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(t){const e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t,e=2e3){const n=this.planes,i=t.elements,r=i[0],s=i[1],a=i[2],o=i[3],l=i[4],c=i[5],h=i[6],u=i[7],d=i[8],p=i[9],m=i[10],f=i[11],g=i[12],v=i[13],_=i[14],x=i[15];if(n[0].setComponents(o-r,u-l,f-d,x-g).normalize(),n[1].setComponents(o+r,u+l,f+d,x+g).normalize(),n[2].setComponents(o+s,u+c,f+p,x+v).normalize(),n[3].setComponents(o-s,u-c,f-p,x-v).normalize(),n[4].setComponents(o-a,u-h,f-m,x-_).normalize(),e===On)n[5].setComponents(o+a,u+h,f+m,x+_).normalize();else{if(e!==Fn)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);n[5].setComponents(a,h,m,_).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),sa.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),sa.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(sa)}intersectsSprite(t){return sa.center.set(0,0,0),sa.radius=.7071067811865476,sa.applyMatrix4(t.matrixWorld),this.intersectsSphere(sa)}intersectsSphere(t){const e=this.planes,n=t.center,i=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(n)<i)return!1}return!0}intersectsBox(t){const e=this.planes;for(let n=0;n<6;n++){const i=e[n];if(aa.x=i.normal.x>0?t.max.x:t.min.x,aa.y=i.normal.y>0?t.max.y:t.min.y,aa.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(aa)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function la(){let t=null,e=!1,n=null,i=null;function r(e,s){n(e,s),i=t.requestAnimationFrame(r)}return{start:function(){!0!==e&&null!==n&&(i=t.requestAnimationFrame(r),e=!0)},stop:function(){t.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(t){n=t},setContext:function(e){t=e}}}function ca(t){const e=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),e.get(t)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const i=e.get(n);i&&(t.deleteBuffer(i.buffer),e.delete(n))},update:function(n,i){if(n.isInterleavedBufferAttribute&&(n=n.data),n.isGLBufferAttribute){const t=e.get(n);return void((!t||t.version<n.version)&&e.set(n,{buffer:n.buffer,type:n.type,bytesPerElement:n.elementSize,version:n.version}))}const r=e.get(n);if(void 0===r)e.set(n,function(e,n){const i=e.array,r=e.usage,s=i.byteLength,a=t.createBuffer();let o;if(t.bindBuffer(n,a),t.bufferData(n,i,r),e.onUploadCallback(),i instanceof Float32Array)o=t.FLOAT;else if(i instanceof Uint16Array)o=e.isFloat16BufferAttribute?t.HALF_FLOAT:t.UNSIGNED_SHORT;else if(i instanceof Int16Array)o=t.SHORT;else if(i instanceof Uint32Array)o=t.UNSIGNED_INT;else if(i instanceof Int32Array)o=t.INT;else if(i instanceof Int8Array)o=t.BYTE;else if(i instanceof Uint8Array)o=t.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+i);o=t.UNSIGNED_BYTE}return{buffer:a,type:o,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,size:s}}(n,i));else if(r.version<n.version){if(r.size!==n.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");!function(e,n,i){const r=n.array,s=n.updateRanges;if(t.bindBuffer(i,e),0===s.length)t.bufferSubData(i,0,r);else{s.sort(((t,e)=>t.start-e.start));let e=0;for(let t=1;t<s.length;t++){const n=s[e],i=s[t];i.start<=n.start+n.count+1?n.count=Math.max(n.count,i.start+i.count-n.start):(++e,s[e]=i)}s.length=e+1;for(let e=0,n=s.length;e<n;e++){const n=s[e];t.bufferSubData(i,n.start*r.BYTES_PER_ELEMENT,r,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}(r.buffer,n,i),r.version=n.version}}}}class ha extends Es{constructor(t=1,e=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:n,heightSegments:i};const r=t/2,s=e/2,a=Math.floor(n),o=Math.floor(i),l=a+1,c=o+1,h=t/a,u=e/o,d=[],p=[],m=[],f=[];for(let t=0;t<c;t++){const e=t*u-s;for(let n=0;n<l;n++){const i=n*h-r;p.push(i,-e,0),m.push(0,0,1),f.push(n/a),f.push(1-t/o)}}for(let t=0;t<o;t++)for(let e=0;e<a;e++){const n=e+l*t,i=e+l*(t+1),r=e+1+l*(t+1),s=e+1+l*t;d.push(n,i,s),d.push(i,r,s)}this.setIndex(d),this.setAttribute("position",new _s(p,3)),this.setAttribute("normal",new _s(m,3)),this.setAttribute("uv",new _s(f,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new ha(t.width,t.height,t.widthSegments,t.heightSegments)}}const ua={alphahash_fragment:"#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif",alphahash_pars_fragment:"#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif",alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif",alphatest_pars_fragment:"#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",batching_pars_vertex:"#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 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( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec3 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n\t}\n#endif",batching_vertex:"#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif",begin_vertex:"vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated",iridescence_fragment:"#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 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\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\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\n\t\t#else\n\t\t\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\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 <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\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 <cube_uv_reflection_fragment>\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 <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",cube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\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 <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",depth_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\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 <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\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 <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",meshbasic_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\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 <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\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 <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\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 <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\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 <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\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 <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\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 <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",shadow_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\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 <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}"},da={common:{diffuse:{value:new Kr(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Kn},alphaMap:{value:null},alphaMapTransform:{value:new Kn},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Kn}},envmap:{envMap:{value:null},envMapRotation:{value:new Kn},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Kn}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Kn}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Kn},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Kn},normalScale:{value:new Jn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Kn},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Kn}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Kn}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Kn}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Kr(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 Kr(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Kn},alphaTest:{value:0},uvTransform:{value:new Kn}},sprite:{diffuse:{value:new Kr(16777215)},opacity:{value:1},center:{value:new Jn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Kn},alphaMap:{value:null},alphaMapTransform:{value:new Kn},alphaTest:{value:0}}},pa={basic:{uniforms:Hs([da.common,da.specularmap,da.envmap,da.aomap,da.lightmap,da.fog]),vertexShader:ua.meshbasic_vert,fragmentShader:ua.meshbasic_frag},lambert:{uniforms:Hs([da.common,da.specularmap,da.envmap,da.aomap,da.lightmap,da.emissivemap,da.bumpmap,da.normalmap,da.displacementmap,da.fog,da.lights,{emissive:{value:new Kr(0)}}]),vertexShader:ua.meshlambert_vert,fragmentShader:ua.meshlambert_frag},phong:{uniforms:Hs([da.common,da.specularmap,da.envmap,da.aomap,da.lightmap,da.emissivemap,da.bumpmap,da.normalmap,da.displacementmap,da.fog,da.lights,{emissive:{value:new Kr(0)},specular:{value:new Kr(1118481)},shininess:{value:30}}]),vertexShader:ua.meshphong_vert,fragmentShader:ua.meshphong_frag},standard:{uniforms:Hs([da.common,da.envmap,da.aomap,da.lightmap,da.emissivemap,da.bumpmap,da.normalmap,da.displacementmap,da.roughnessmap,da.metalnessmap,da.fog,da.lights,{emissive:{value:new Kr(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ua.meshphysical_vert,fragmentShader:ua.meshphysical_frag},toon:{uniforms:Hs([da.common,da.aomap,da.lightmap,da.emissivemap,da.bumpmap,da.normalmap,da.displacementmap,da.gradientmap,da.fog,da.lights,{emissive:{value:new Kr(0)}}]),vertexShader:ua.meshtoon_vert,fragmentShader:ua.meshtoon_frag},matcap:{uniforms:Hs([da.common,da.bumpmap,da.normalmap,da.displacementmap,da.fog,{matcap:{value:null}}]),vertexShader:ua.meshmatcap_vert,fragmentShader:ua.meshmatcap_frag},points:{uniforms:Hs([da.points,da.fog]),vertexShader:ua.points_vert,fragmentShader:ua.points_frag},dashed:{uniforms:Hs([da.common,da.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ua.linedashed_vert,fragmentShader:ua.linedashed_frag},depth:{uniforms:Hs([da.common,da.displacementmap]),vertexShader:ua.depth_vert,fragmentShader:ua.depth_frag},normal:{uniforms:Hs([da.common,da.bumpmap,da.normalmap,da.displacementmap,{opacity:{value:1}}]),vertexShader:ua.meshnormal_vert,fragmentShader:ua.meshnormal_frag},sprite:{uniforms:Hs([da.sprite,da.fog]),vertexShader:ua.sprite_vert,fragmentShader:ua.sprite_frag},background:{uniforms:{uvTransform:{value:new Kn},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ua.background_vert,fragmentShader:ua.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Kn}},vertexShader:ua.backgroundCube_vert,fragmentShader:ua.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ua.cube_vert,fragmentShader:ua.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ua.equirect_vert,fragmentShader:ua.equirect_frag},distanceRGBA:{uniforms:Hs([da.common,da.displacementmap,{referencePosition:{value:new Ci},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ua.distanceRGBA_vert,fragmentShader:ua.distanceRGBA_frag},shadow:{uniforms:Hs([da.lights,da.fog,{color:{value:new Kr(0)},opacity:{value:1}}]),vertexShader:ua.shadow_vert,fragmentShader:ua.shadow_frag}};pa.physical={uniforms:Hs([pa.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Kn},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Kn},clearcoatNormalScale:{value:new Jn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Kn},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Kn},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Kn},sheen:{value:0},sheenColor:{value:new Kr(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Kn},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Kn},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Kn},transmissionSamplerSize:{value:new Jn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Kn},attenuationDistance:{value:0},attenuationColor:{value:new Kr(0)},specularColor:{value:new Kr(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Kn},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Kn},anisotropyVector:{value:new Jn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Kn}}]),vertexShader:ua.meshphysical_vert,fragmentShader:ua.meshphysical_frag};const ma={r:0,b:0,g:0},fa=new fr,ga=new sr;function va(t,e,n,i,r,s,a){const o=new Kr(0);let l,c,h=!0===s?0:1,u=null,d=0,p=null;function m(t){let i=!0===t.isScene?t.background:null;if(i&&i.isTexture){i=(t.backgroundBlurriness>0?n:e).get(i)}return i}function f(e,n){e.getRGB(ma,Gs(t)),i.buffers.color.setClear(ma.r,ma.g,ma.b,n,a)}return{getClearColor:function(){return o},setClearColor:function(t,e=1){o.set(t),h=e,f(o,h)},getClearAlpha:function(){return h},setClearAlpha:function(t){h=t,f(o,h)},render:function(e){let n=!1;const r=m(e);null===r?f(o,h):r&&r.isColor&&(f(r,1),n=!0);const s=t.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),(t.autoClear||n)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))},addToRenderList:function(e,n){const i=m(n);i&&(i.isCubeTexture||i.mapping===dt)?(void 0===c&&(c=new Bs(new ks(1,1,1),new Xs({name:"BackgroundCubeMaterial",uniforms:Vs(pa.backgroundCube.uniforms),vertexShader:pa.backgroundCube.vertexShader,fragmentShader:pa.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(t,e,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(c)),fa.copy(n.backgroundRotation),fa.x*=-1,fa.y*=-1,fa.z*=-1,i.isCubeTexture&&!1===i.isRenderTargetTexture&&(fa.y*=-1,fa.z*=-1),c.material.uniforms.envMap.value=i,c.material.uniforms.flipEnvMap.value=i.isCubeTexture&&!1===i.isRenderTargetTexture?-1:1,c.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(ga.makeRotationFromEuler(fa)),c.material.toneMapped=ai.getTransfer(i.colorSpace)!==Qe,u===i&&d===i.version&&p===t.toneMapping||(c.material.needsUpdate=!0,u=i,d=i.version,p=t.toneMapping),c.layers.enableAll(),e.unshift(c,c.geometry,c.material,0,0,null)):i&&i.isTexture&&(void 0===l&&(l=new Bs(new ha(2,2),new Xs({name:"BackgroundMaterial",uniforms:Vs(pa.background.uniforms),vertexShader:pa.background.vertexShader,fragmentShader:pa.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=ai.getTransfer(i.colorSpace)!==Qe,!0===i.matrixAutoUpdate&&i.updateMatrix(),l.material.uniforms.uvTransform.value.copy(i.matrix),u===i&&d===i.version&&p===t.toneMapping||(l.material.needsUpdate=!0,u=i,d=i.version,p=t.toneMapping),l.layers.enableAll(),e.unshift(l,l.geometry,l.material,0,0,null))}}}function _a(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),i={},r=c(null);let s=r,a=!1;function o(e){return t.bindVertexArray(e)}function l(e){return t.deleteVertexArray(e)}function c(t){const e=[],i=[],r=[];for(let t=0;t<n;t++)e[t]=0,i[t]=0,r[t]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:e,enabledAttributes:i,attributeDivisors:r,object:t,attributes:{},index:null}}function h(){const t=s.newAttributes;for(let e=0,n=t.length;e<n;e++)t[e]=0}function u(t){d(t,0)}function d(e,n){const i=s.newAttributes,r=s.enabledAttributes,a=s.attributeDivisors;i[e]=1,0===r[e]&&(t.enableVertexAttribArray(e),r[e]=1),a[e]!==n&&(t.vertexAttribDivisor(e,n),a[e]=n)}function p(){const e=s.newAttributes,n=s.enabledAttributes;for(let i=0,r=n.length;i<r;i++)n[i]!==e[i]&&(t.disableVertexAttribArray(i),n[i]=0)}function m(e,n,i,r,s,a,o){!0===o?t.vertexAttribIPointer(e,n,i,s,a):t.vertexAttribPointer(e,n,i,r,s,a)}function f(){g(),a=!0,s!==r&&(s=r,o(s.object))}function g(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:function(n,r,l,f,g){let v=!1;const _=function(e,n,r){const s=!0===r.wireframe;let a=i[e.id];void 0===a&&(a={},i[e.id]=a);let o=a[n.id];void 0===o&&(o={},a[n.id]=o);let l=o[s];void 0===l&&(l=c(t.createVertexArray()),o[s]=l);return l}(f,l,r);s!==_&&(s=_,o(s.object)),v=function(t,e,n,i){const r=s.attributes,a=e.attributes;let o=0;const l=n.getAttributes();for(const e in l){if(l[e].location>=0){const n=r[e];let i=a[e];if(void 0===i&&("instanceMatrix"===e&&t.instanceMatrix&&(i=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(i=t.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,f,l,g),v&&function(t,e,n,i){const r={},a=e.attributes;let o=0;const l=n.getAttributes();for(const e in l){if(l[e].location>=0){let n=a[e];void 0===n&&("instanceMatrix"===e&&t.instanceMatrix&&(n=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(n=t.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[e]=i,o++}}s.attributes=r,s.attributesNum=o,s.index=i}(n,f,l,g),null!==g&&e.update(g,t.ELEMENT_ARRAY_BUFFER),(v||a)&&(a=!1,function(n,i,r,s){h();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=e.get(o);if(void 0===l)continue;const c=l.buffer,h=l.type,p=l.bytesPerElement,f=h===t.INT||h===t.UNSIGNED_INT||o.gpuType===It;if(o.isInterleavedBufferAttribute){const e=o.data,l=e.stride,g=o.offset;if(e.isInstancedInterleavedBuffer){for(let t=0;t<r.locationSize;t++)d(r.location+t,e.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=e.meshPerAttribute*e.count)}else for(let t=0;t<r.locationSize;t++)u(r.location+t);t.bindBuffer(t.ARRAY_BUFFER,c);for(let t=0;t<r.locationSize;t++)m(r.location+t,a/r.locationSize,h,i,l*p,(g+a/r.locationSize*t)*p,f)}else{if(o.isInstancedBufferAttribute){for(let t=0;t<r.locationSize;t++)d(r.location+t,o.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=o.meshPerAttribute*o.count)}else for(let t=0;t<r.locationSize;t++)u(r.location+t);t.bindBuffer(t.ARRAY_BUFFER,c);for(let t=0;t<r.locationSize;t++)m(r.location+t,a/r.locationSize,h,i,a*p,a/r.locationSize*t*p,f)}}else if(void 0!==l){const e=l[i];if(void 0!==e)switch(e.length){case 2:t.vertexAttrib2fv(r.location,e);break;case 3:t.vertexAttrib3fv(r.location,e);break;case 4:t.vertexAttrib4fv(r.location,e);break;default:t.vertexAttrib1fv(r.location,e)}}}}p()}(n,r,l,f),null!==g&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.get(g).buffer))},reset:f,resetDefaultState:g,dispose:function(){f();for(const t in i){const e=i[t];for(const t in e){const n=e[t];for(const t in n)l(n[t].object),delete n[t];delete e[t]}delete i[t]}},releaseStatesOfGeometry:function(t){if(void 0===i[t.id])return;const e=i[t.id];for(const t in e){const n=e[t];for(const t in n)l(n[t].object),delete n[t];delete e[t]}delete i[t.id]},releaseStatesOfProgram:function(t){for(const e in i){const n=i[e];if(void 0===n[t.id])continue;const r=n[t.id];for(const t in r)l(r[t].object),delete r[t];delete n[t.id]}},initAttributes:h,enableAttribute:u,disableUnusedAttributes:p}}function xa(t,e,n){let i;function r(e,r,s){0!==s&&(t.drawArraysInstanced(i,e,r,s),n.update(r,i,s))}this.setMode=function(t){i=t},this.render=function(e,r){t.drawArrays(i,e,r),n.update(r,i,1)},this.renderInstances=r,this.renderMultiDraw=function(t,r,s){if(0===s)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,t,0,r,0,s);let a=0;for(let t=0;t<s;t++)a+=r[t];n.update(a,i,1)},this.renderMultiDrawInstances=function(t,s,a,o){if(0===a)return;const l=e.get("WEBGL_multi_draw");if(null===l)for(let e=0;e<t.length;e++)r(t[e],s[e],o[e]);else{l.multiDrawArraysInstancedWEBGL(i,t,0,s,0,o,0,a);let e=0;for(let t=0;t<a;t++)e+=s[t]*o[t];n.update(e,i,1)}}}function ya(t,e,n,i){let r;function s(e){if("highp"===e){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.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,c=!0===n.reverseDepthBuffer&&e.has("EXT_clip_control"),h=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),u=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===e.has("EXT_texture_filter_anisotropic")){const n=e.get("EXT_texture_filter_anisotropic");r=t.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(e){return e===kt||i.convert(e)===t.getParameter(t.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const r=n===Ut&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(n!==Et&&i.convert(n)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==Lt&&!r)},precision:a,logarithmicDepthBuffer:l,reverseDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:t.getParameter(t.MAX_TEXTURE_SIZE),maxCubemapSize:t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:t.getParameter(t.MAX_VERTEX_ATTRIBS),maxVertexUniforms:t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:t.getParameter(t.MAX_VARYING_VECTORS),maxFragmentUniforms:t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:u>0,maxSamples:t.getParameter(t.MAX_SAMPLES)}}function Ma(t){const e=this;let n=null,i=0,r=!1,s=!1;const a=new ra,o=new Kn,l={value:null,needsUpdate:!1};function c(t,n,i,r){const s=null!==t?t.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const e=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length<e)&&(c=new Float32Array(e));for(let e=0,n=i;e!==s;++e,n+=4)a.copy(t[e]).applyMatrix4(r,o),a.normal.toArray(c,n),c[n+3]=a.constant}l.value=c,l.needsUpdate=!0}return e.numPlanes=s,e.numIntersection=0,c}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(t,e){const n=0!==t.length||e||0!==i||r;return r=e,i=t.length,n},this.beginShadows=function(){s=!0,c(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(t,e){n=c(t,e,0)},this.setState=function(a,o,h){const u=a.clippingPlanes,d=a.clipIntersection,p=a.clipShadows,m=t.get(a);if(!r||null===u||0===u.length||s&&!p)s?c(null):function(){l.value!==n&&(l.value=n,l.needsUpdate=i>0);e.numPlanes=i,e.numIntersection=0}();else{const t=s?0:i,e=4*t;let r=m.clippingState||null;l.value=r,r=c(u,o,e,h);for(let t=0;t!==e;++t)r[t]=n[t];m.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=t}}}function Sa(t){let e=new WeakMap;function n(t,e){return e===ht?t.mapping=lt:e===ut&&(t.mapping=ct),t}function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping;if(s===ht||s===ut){if(e.has(r)){return n(e.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=new ta(s.height);return a.fromEquirectangularTexture(t,r),e.set(r,a),r.addEventListener("dispose",i),n(a.texture,r.mapping)}return null}}}return r},dispose:function(){e=new WeakMap}}}class ba extends js{constructor(t=-1,e=1,n=1,i=-1,r=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=n,this.bottom=i,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=null===t.view?null:Object.assign({},t.view),this}setViewOffset(t,e,n,i,r,s){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=t,this.view.fullHeight=e,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 t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-t,s=n+t,a=i+e,o=i-e;if(null!==this.view&&this.view.enabled){const t=(this.right-this.left)/this.view.fullWidth/this.zoom,e=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=t*this.view.offsetX,s=r+t*this.view.width,a-=e*this.view.offsetY,o=a-e*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,null!==this.view&&(e.object.view=Object.assign({},this.view)),e}}const Ta=[.125,.215,.35,.446,.526,.582],wa=20,Ea=new ba,Aa=new Kr;let Ra=null,Ca=0,Ia=0,Pa=!1;const La=(1+Math.sqrt(5))/2,Ua=1/La,Da=[new Ci(-La,Ua,0),new Ci(La,Ua,0),new Ci(-Ua,0,La),new Ci(Ua,0,La),new Ci(0,La,-Ua),new Ci(0,La,Ua),new Ci(-1,1,-1),new Ci(1,1,-1),new Ci(-1,1,1),new Ci(1,1,1)];class Na{constructor(t){this._renderer=t,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(t,e=0,n=.1,i=100){Ra=this._renderer.getRenderTarget(),Ca=this._renderer.getActiveCubeFace(),Ia=this._renderer.getActiveMipmapLevel(),Pa=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(t,n,i,r),e>0&&this._blur(r,0,0,e),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=za(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Ba(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let t=0;t<this._lodPlanes.length;t++)this._lodPlanes[t].dispose()}_cleanup(t){this._renderer.setRenderTarget(Ra,Ca,Ia),this._renderer.xr.enabled=Pa,t.scissorTest=!1,Fa(t,0,0,t.width,t.height)}_fromTexture(t,e){t.mapping===lt||t.mapping===ct?this._setSize(0===t.image.length?16:t.image[0].width||t.image[0].image.width):this._setSize(t.image.width/4),Ra=this._renderer.getRenderTarget(),Ca=this._renderer.getActiveCubeFace(),Ia=this._renderer.getActiveMipmapLevel(),Pa=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=e||this._allocateTargets();return this._textureToCubeUV(t,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const t=3*Math.max(this._cubeSize,112),e=4*this._cubeSize,n={magFilter:Mt,minFilter:Mt,generateMipmaps:!1,type:Ut,format:kt,colorSpace:Ke,depthBuffer:!1},i=Oa(t,e,n);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==t||this._pingPongRenderTarget.height!==e){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=Oa(t,e,n);const{_lodMax:i}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=function(t){const e=[],n=[],i=[];let r=t;const s=t-4+1+Ta.length;for(let a=0;a<s;a++){const s=Math.pow(2,r);n.push(s);let o=1/s;a>t-4?o=Ta[a-t+4-1]:0===a&&(o=0),i.push(o);const l=1/(s-2),c=-l,h=1+l,u=[c,c,h,c,h,h,c,c,h,h,c,h],d=6,p=6,m=3,f=2,g=1,v=new Float32Array(m*p*d),_=new Float32Array(f*p*d),x=new Float32Array(g*p*d);for(let t=0;t<d;t++){const e=t%3*2/3-1,n=t>2?0:-1,i=[e,n,0,e+2/3,n,0,e+2/3,n+1,0,e,n,0,e+2/3,n+1,0,e,n+1,0];v.set(i,m*p*t),_.set(u,f*p*t);const r=[t,t,t,t,t,t];x.set(r,g*p*t)}const y=new Es;y.setAttribute("position",new cs(v,m)),y.setAttribute("uv",new cs(_,f)),y.setAttribute("faceIndex",new cs(x,g)),e.push(y),r>4&&r--}return{lodPlanes:e,sizeLods:n,sigmas:i}}(i)),this._blurMaterial=function(t,e,n){const i=new Float32Array(wa),r=new Ci(0,1,0),s=new Xs({name:"SphericalGaussianBlur",defines:{n:wa,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:ka(),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 <cube_uv_reflection_fragment>\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,t,e)}return i}_compileMaterial(t){const e=new Bs(this._lodPlanes[0],t);this._renderer.compile(e,Ea)}_sceneToCubeUV(t,e,n,i){const r=new Js(90,1,e,n),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(Aa),o.toneMapping=0,o.autoClear=!1;const h=new es({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),u=new Bs(new ks,h);let d=!1;const p=t.background;p?p.isColor&&(h.color.copy(p),t.background=null,d=!0):(h.color.copy(Aa),d=!0);for(let e=0;e<6;e++){const n=e%3;0===n?(r.up.set(0,s[e],0),r.lookAt(a[e],0,0)):1===n?(r.up.set(0,0,s[e]),r.lookAt(0,a[e],0)):(r.up.set(0,s[e],0),r.lookAt(0,0,a[e]));const l=this._cubeSize;Fa(i,n*l,e>2?l:0,l,l),o.setRenderTarget(i),d&&o.render(u,r),o.render(t,r)}u.geometry.dispose(),u.material.dispose(),o.toneMapping=c,o.autoClear=l,t.background=p}_textureToCubeUV(t,e){const n=this._renderer,i=t.mapping===lt||t.mapping===ct;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=za()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===t.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Ba());const r=i?this._cubemapMaterial:this._equirectMaterial,s=new Bs(this._lodPlanes[0],r);r.uniforms.envMap.value=t;const a=this._cubeSize;Fa(e,0,0,3*a,2*a),n.setRenderTarget(e),n.render(s,Ea)}_applyPMREM(t){const e=this._renderer,n=e.autoClear;e.autoClear=!1;const i=this._lodPlanes.length;for(let e=1;e<i;e++){const n=Math.sqrt(this._sigmas[e]*this._sigmas[e]-this._sigmas[e-1]*this._sigmas[e-1]),r=Da[(i-e-1)%Da.length];this._blur(t,e-1,e,n,r)}e.autoClear=n}_blur(t,e,n,i,r){const s=this._pingPongRenderTarget;this._halfBlur(t,s,e,n,i,"latitudinal",r),this._halfBlur(s,t,n,n,i,"longitudinal",r)}_halfBlur(t,e,n,i,r,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&console.error("blur direction must be either latitudinal or longitudinal!");const c=new Bs(this._lodPlanes[i],l),h=l.uniforms,u=this._sizeLods[n]-1,d=isFinite(r)?Math.PI/(2*u):2*Math.PI/39,p=r/d,m=isFinite(r)?1+Math.floor(3*p):wa;m>wa&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let t=0;t<wa;++t){const e=t/p,n=Math.exp(-e*e/2);f.push(n),0===t?g+=n:t<m&&(g+=2*n)}for(let t=0;t<f.length;t++)f[t]=f[t]/g;h.envMap.value=t.texture,h.samples.value=m,h.weights.value=f,h.latitudinal.value="latitudinal"===s,a&&(h.poleAxis.value=a);const{_lodMax:v}=this;h.dTheta.value=d,h.mipInt.value=v-n;const _=this._sizeLods[i];Fa(e,3*_*(i>v-4?i-v+4:0),4*(this._cubeSize-_),3*_,2*_),o.setRenderTarget(e),o.render(c,Ea)}}function Oa(t,e,n){const i=new bi(t,e,n);return i.texture.mapping=dt,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Fa(t,e,n,i,r){t.viewport.set(e,n,i,r),t.scissor.set(e,n,i,r)}function Ba(){return new Xs({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:ka(),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 <common>\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 za(){return new Xs({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:ka(),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 ka(){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 Va(t){let e=new WeakMap,n=null;function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping,a=s===ht||s===ut,o=s===lt||s===ct;if(a||o){let s=e.get(r);const l=void 0!==s?s.texture.pmremVersion:0;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return null===n&&(n=new Na(t)),s=a?n.fromEquirectangular(r,s):n.fromCubemap(r,s),s.texture.pmremVersion=r.pmremVersion,e.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(t){let e=0;const n=6;for(let i=0;i<n;i++)void 0!==t[i]&&e++;return e===n}(l)?(null===n&&(n=new Na(t)),s=a?n.fromEquirectangular(r):n.fromCubemap(r),s.texture.pmremVersion=r.pmremVersion,e.set(r,s),r.addEventListener("dispose",i),s.texture):null}}}return r},dispose:function(){e=new WeakMap,null!==n&&(n.dispose(),n=null)}}}function Ha(t){const e={};function n(n){if(void 0!==e[n])return e[n];let i;switch(n){case"WEBGL_depth_texture":i=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=t.getExtension(n)}return e[n]=i,i}return{has:function(t){return null!==n(t)},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(t){const e=n(t);return null===e&&si("THREE.WebGLRenderer: "+t+" extension not supported."),e}}}function Ga(t,e,n,i){const r={},s=new WeakMap;function a(t){const o=t.target;null!==o.index&&e.remove(o.index);for(const t in o.attributes)e.remove(o.attributes[t]);for(const t in o.morphAttributes){const n=o.morphAttributes[t];for(let t=0,i=n.length;t<i;t++)e.remove(n[t])}o.removeEventListener("dispose",a),delete r[o.id];const l=s.get(o);l&&(e.remove(l),s.delete(o)),i.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,n.memory.geometries--}function o(t){const n=[],i=t.index,r=t.attributes.position;let a=0;if(null!==i){const t=i.array;a=i.version;for(let e=0,i=t.length;e<i;e+=3){const i=t[e+0],r=t[e+1],s=t[e+2];n.push(i,r,r,s,s,i)}}else{if(void 0===r)return;{const t=r.array;a=r.version;for(let e=0,i=t.length/3-1;e<i;e+=3){const t=e+0,i=e+1,r=e+2;n.push(t,i,i,r,r,t)}}}const o=new(Qn(n)?gs:ms)(n,1);o.version=a;const l=s.get(t);l&&e.remove(l),s.set(t,o)}return{get:function(t,e){return!0===r[e.id]||(e.addEventListener("dispose",a),r[e.id]=!0,n.memory.geometries++),e},update:function(n){const i=n.attributes;for(const n in i)e.update(i[n],t.ARRAY_BUFFER);const r=n.morphAttributes;for(const n in r){const i=r[n];for(let n=0,r=i.length;n<r;n++)e.update(i[n],t.ARRAY_BUFFER)}},getWireframeAttribute:function(t){const e=s.get(t);if(e){const n=t.index;null!==n&&e.version<n.version&&o(t)}else o(t);return s.get(t)}}}function Wa(t,e,n){let i,r,s;function a(e,a,o){0!==o&&(t.drawElementsInstanced(i,a,r,e*s,o),n.update(a,i,o))}this.setMode=function(t){i=t},this.setIndex=function(t){r=t.type,s=t.bytesPerElement},this.render=function(e,a){t.drawElements(i,a,r,e*s),n.update(a,i,1)},this.renderInstances=a,this.renderMultiDraw=function(t,s,a){if(0===a)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,s,0,r,t,0,a);let o=0;for(let t=0;t<a;t++)o+=s[t];n.update(o,i,1)},this.renderMultiDrawInstances=function(t,o,l,c){if(0===l)return;const h=e.get("WEBGL_multi_draw");if(null===h)for(let e=0;e<t.length;e++)a(t[e]/s,o[e],c[e]);else{h.multiDrawElementsInstancedWEBGL(i,o,0,r,t,0,c,0,l);let e=0;for(let t=0;t<l;t++)e+=o[t]*c[t];n.update(e,i,1)}}}function Xa(t){const e={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:e,programs:null,autoReset:!0,reset:function(){e.calls=0,e.triangles=0,e.points=0,e.lines=0},update:function(n,i,r){switch(e.calls++,i){case t.TRIANGLES:e.triangles+=r*(n/3);break;case t.LINES:e.lines+=r*(n/2);break;case t.LINE_STRIP:e.lines+=r*(n-1);break;case t.LINE_LOOP:e.lines+=r*n;break;case t.POINTS:e.points+=r*n;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",i)}}}}function ja(t,e,n){const i=new WeakMap,r=new Mi;return{update:function(s,a,o){const l=s.morphTargetInfluences,c=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,h=void 0!==c?c.length:0;let u=i.get(a);if(void 0===u||u.count!==h){void 0!==u&&u.texture.dispose();const d=void 0!==a.morphAttributes.position,p=void 0!==a.morphAttributes.normal,m=void 0!==a.morphAttributes.color,f=a.morphAttributes.position||[],g=a.morphAttributes.normal||[],v=a.morphAttributes.color||[];let _=0;!0===d&&(_=1),!0===p&&(_=2),!0===m&&(_=3);let x=a.attributes.position.count*_,y=1;x>e.maxTextureSize&&(y=Math.ceil(x/e.maxTextureSize),x=e.maxTextureSize);const M=new Float32Array(x*y*4*h),S=new Ti(M,x,y,h);S.type=Lt,S.needsUpdate=!0;const b=4*_;for(let w=0;w<h;w++){const E=f[w],A=g[w],R=v[w],C=x*y*4*w;for(let I=0;I<E.count;I++){const P=I*b;!0===d&&(r.fromBufferAttribute(E,I),M[C+P+0]=r.x,M[C+P+1]=r.y,M[C+P+2]=r.z,M[C+P+3]=0),!0===p&&(r.fromBufferAttribute(A,I),M[C+P+4]=r.x,M[C+P+5]=r.y,M[C+P+6]=r.z,M[C+P+7]=0),!0===m&&(r.fromBufferAttribute(R,I),M[C+P+8]=r.x,M[C+P+9]=r.y,M[C+P+10]=r.z,M[C+P+11]=4===R.itemSize?r.w:1)}}function T(){S.dispose(),i.delete(a),a.removeEventListener("dispose",T)}u={count:h,texture:S,size:new Jn(x,y)},i.set(a,u),a.addEventListener("dispose",T)}if(!0===s.isInstancedMesh&&null!==s.morphTexture)o.getUniforms().setValue(t,"morphTexture",s.morphTexture,n);else{let L=0;for(let D=0;D<l.length;D++)L+=l[D];const U=a.morphTargetsRelative?1:1-L;o.getUniforms().setValue(t,"morphTargetBaseInfluence",U),o.getUniforms().setValue(t,"morphTargetInfluences",l)}o.getUniforms().setValue(t,"morphTargetsTexture",u.texture,n),o.getUniforms().setValue(t,"morphTargetsTextureSize",u.size)}}}function qa(t,e,n,i){let r=new WeakMap;function s(t){const e=t.target;e.removeEventListener("dispose",s),n.remove(e.instanceMatrix),null!==e.instanceColor&&n.remove(e.instanceColor)}return{update:function(a){const o=i.render.frame,l=a.geometry,c=e.get(a,l);if(r.get(c)!==o&&(e.update(c),r.set(c,o)),a.isInstancedMesh&&(!1===a.hasEventListener("dispose",s)&&a.addEventListener("dispose",s),r.get(a)!==o&&(n.update(a.instanceMatrix,t.ARRAY_BUFFER),null!==a.instanceColor&&n.update(a.instanceColor,t.ARRAY_BUFFER),r.set(a,o))),a.isSkinnedMesh){const t=a.skeleton;r.get(t)!==o&&(t.update(),r.set(t,o))}return c},dispose:function(){r=new WeakMap}}}class Ya extends yi{constructor(t,e,n,i,r,s,a,o,l,c=1026){if(c!==Gt&&c!==Wt)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===n&&c===Gt&&(n=Pt),void 0===n&&c===Wt&&(n=Ot),super(null,i,r,s,a,o,c,n,l),this.isDepthTexture=!0,this.image={width:t,height:e},this.magFilter=void 0!==a?a:gt,this.minFilter=void 0!==o?o:gt,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.compareFunction=t.compareFunction,this}toJSON(t){const e=super.toJSON(t);return null!==this.compareFunction&&(e.compareFunction=this.compareFunction),e}}const Za=new yi,Ja=new Ya(1,1),Ka=new Ti,$a=new Ei,Qa=new Qs,to=[],eo=[],no=new Float32Array(16),io=new Float32Array(9),ro=new Float32Array(4);function so(t,e,n){const i=t[0];if(i<=0||i>0)return t;const r=e*n;let s=to[r];if(void 0===s&&(s=new Float32Array(r),to[r]=s),0!==e){i.toArray(s,0);for(let i=1,r=0;i!==e;++i)r+=n,t[i].toArray(s,r)}return s}function ao(t,e){if(t.length!==e.length)return!1;for(let n=0,i=t.length;n<i;n++)if(t[n]!==e[n])return!1;return!0}function oo(t,e){for(let n=0,i=e.length;n<i;n++)t[n]=e[n]}function lo(t,e){let n=eo[e];void 0===n&&(n=new Int32Array(e),eo[e]=n);for(let i=0;i!==e;++i)n[i]=t.allocateTextureUnit();return n}function co(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function ho(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y||(t.uniform2f(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(ao(n,e))return;t.uniform2fv(this.addr,e),oo(n,e)}}function uo(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y&&n[2]===e.z||(t.uniform3f(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else if(void 0!==e.r)n[0]===e.r&&n[1]===e.g&&n[2]===e.b||(t.uniform3f(this.addr,e.r,e.g,e.b),n[0]=e.r,n[1]=e.g,n[2]=e.b);else{if(ao(n,e))return;t.uniform3fv(this.addr,e),oo(n,e)}}function po(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y&&n[2]===e.z&&n[3]===e.w||(t.uniform4f(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(ao(n,e))return;t.uniform4fv(this.addr,e),oo(n,e)}}function mo(t,e){const n=this.cache,i=e.elements;if(void 0===i){if(ao(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),oo(n,e)}else{if(ao(n,i))return;ro.set(i),t.uniformMatrix2fv(this.addr,!1,ro),oo(n,i)}}function fo(t,e){const n=this.cache,i=e.elements;if(void 0===i){if(ao(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),oo(n,e)}else{if(ao(n,i))return;io.set(i),t.uniformMatrix3fv(this.addr,!1,io),oo(n,i)}}function go(t,e){const n=this.cache,i=e.elements;if(void 0===i){if(ao(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),oo(n,e)}else{if(ao(n,i))return;no.set(i),t.uniformMatrix4fv(this.addr,!1,no),oo(n,i)}}function vo(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function _o(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y||(t.uniform2i(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(ao(n,e))return;t.uniform2iv(this.addr,e),oo(n,e)}}function xo(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y&&n[2]===e.z||(t.uniform3i(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else{if(ao(n,e))return;t.uniform3iv(this.addr,e),oo(n,e)}}function yo(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y&&n[2]===e.z&&n[3]===e.w||(t.uniform4i(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(ao(n,e))return;t.uniform4iv(this.addr,e),oo(n,e)}}function Mo(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function So(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y||(t.uniform2ui(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(ao(n,e))return;t.uniform2uiv(this.addr,e),oo(n,e)}}function bo(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y&&n[2]===e.z||(t.uniform3ui(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else{if(ao(n,e))return;t.uniform3uiv(this.addr,e),oo(n,e)}}function To(t,e){const n=this.cache;if(void 0!==e.x)n[0]===e.x&&n[1]===e.y&&n[2]===e.z&&n[3]===e.w||(t.uniform4ui(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(ao(n,e))return;t.uniform4uiv(this.addr,e),oo(n,e)}}function wo(t,e,n){const i=this.cache,r=n.allocateTextureUnit();let s;i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),this.type===t.SAMPLER_2D_SHADOW?(Ja.compareFunction=515,s=Ja):s=Za,n.setTexture2D(e||s,r)}function Eo(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.setTexture3D(e||$a,r)}function Ao(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.setTextureCube(e||Qa,r)}function Ro(t,e,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(t.uniform1i(this.addr,r),i[0]=r),n.setTexture2DArray(e||Ka,r)}function Co(t,e){t.uniform1fv(this.addr,e)}function Io(t,e){const n=so(e,this.size,2);t.uniform2fv(this.addr,n)}function Po(t,e){const n=so(e,this.size,3);t.uniform3fv(this.addr,n)}function Lo(t,e){const n=so(e,this.size,4);t.uniform4fv(this.addr,n)}function Uo(t,e){const n=so(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function Do(t,e){const n=so(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function No(t,e){const n=so(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function Oo(t,e){t.uniform1iv(this.addr,e)}function Fo(t,e){t.uniform2iv(this.addr,e)}function Bo(t,e){t.uniform3iv(this.addr,e)}function zo(t,e){t.uniform4iv(this.addr,e)}function ko(t,e){t.uniform1uiv(this.addr,e)}function Vo(t,e){t.uniform2uiv(this.addr,e)}function Ho(t,e){t.uniform3uiv(this.addr,e)}function Go(t,e){t.uniform4uiv(this.addr,e)}function Wo(t,e,n){const i=this.cache,r=e.length,s=lo(n,r);ao(i,s)||(t.uniform1iv(this.addr,s),oo(i,s));for(let t=0;t!==r;++t)n.setTexture2D(e[t]||Za,s[t])}function Xo(t,e,n){const i=this.cache,r=e.length,s=lo(n,r);ao(i,s)||(t.uniform1iv(this.addr,s),oo(i,s));for(let t=0;t!==r;++t)n.setTexture3D(e[t]||$a,s[t])}function jo(t,e,n){const i=this.cache,r=e.length,s=lo(n,r);ao(i,s)||(t.uniform1iv(this.addr,s),oo(i,s));for(let t=0;t!==r;++t)n.setTextureCube(e[t]||Qa,s[t])}function qo(t,e,n){const i=this.cache,r=e.length,s=lo(n,r);ao(i,s)||(t.uniform1iv(this.addr,s),oo(i,s));for(let t=0;t!==r;++t)n.setTexture2DArray(e[t]||Ka,s[t])}class Yo{constructor(t,e,n){this.id=t,this.addr=n,this.cache=[],this.type=e.type,this.setValue=function(t){switch(t){case 5126:return co;case 35664:return ho;case 35665:return uo;case 35666:return po;case 35674:return mo;case 35675:return fo;case 35676:return go;case 5124:case 35670:return vo;case 35667:case 35671:return _o;case 35668:case 35672:return xo;case 35669:case 35673:return yo;case 5125:return Mo;case 36294:return So;case 36295:return bo;case 36296:return To;case 35678:case 36198:case 36298:case 36306:case 35682:return wo;case 35679:case 36299:case 36307:return Eo;case 35680:case 36300:case 36308:case 36293:return Ao;case 36289:case 36303:case 36311:case 36292:return Ro}}(e.type)}}class Zo{constructor(t,e,n){this.id=t,this.addr=n,this.cache=[],this.type=e.type,this.size=e.size,this.setValue=function(t){switch(t){case 5126:return Co;case 35664:return Io;case 35665:return Po;case 35666:return Lo;case 35674:return Uo;case 35675:return Do;case 35676:return No;case 5124:case 35670:return Oo;case 35667:case 35671:return Fo;case 35668:case 35672:return Bo;case 35669:case 35673:return zo;case 5125:return ko;case 36294:return Vo;case 36295:return Ho;case 36296:return Go;case 35678:case 36198:case 36298:case 36306:case 35682:return Wo;case 35679:case 36299:case 36307:return Xo;case 35680:case 36300:case 36308:case 36293:return jo;case 36289:case 36303:case 36311:case 36292:return qo}}(e.type)}}class Jo{constructor(t){this.id=t,this.seq=[],this.map={}}setValue(t,e,n){const i=this.seq;for(let r=0,s=i.length;r!==s;++r){const s=i[r];s.setValue(t,e[s.id],n)}}}const Ko=/(\w+)(\])?(\[|\.)?/g;function $o(t,e){t.seq.push(e),t.map[e.id]=e}function Qo(t,e,n){const i=t.name,r=i.length;for(Ko.lastIndex=0;;){const s=Ko.exec(i),a=Ko.lastIndex;let o=s[1];const l="]"===s[2],c=s[3];if(l&&(o|=0),void 0===c||"["===c&&a+2===r){$o(n,void 0===c?new Yo(o,t,e):new Zo(o,t,e));break}{let t=n.map[o];void 0===t&&(t=new Jo(o),$o(n,t)),n=t}}}class tl{constructor(t,e){this.seq=[],this.map={};const n=t.getProgramParameter(e,t.ACTIVE_UNIFORMS);for(let i=0;i<n;++i){const n=t.getActiveUniform(e,i);Qo(n,t.getUniformLocation(e,n.name),this)}}setValue(t,e,n,i){const r=this.map[e];void 0!==r&&r.setValue(t,n,i)}setOptional(t,e,n){const i=e[n];void 0!==i&&this.setValue(t,n,i)}static upload(t,e,n,i){for(let r=0,s=e.length;r!==s;++r){const s=e[r],a=n[s.id];!1!==a.needsUpdate&&s.setValue(t,a.value,i)}}static seqWithValue(t,e){const n=[];for(let i=0,r=t.length;i!==r;++i){const r=t[i];r.id in e&&n.push(r)}return n}}function el(t,e,n){const i=t.createShader(e);return t.shaderSource(i,n),t.compileShader(i),i}let nl=0;const il=new Kn;function rl(t,e,n){const i=t.getShaderParameter(e,t.COMPILE_STATUS),r=t.getShaderInfoLog(e).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"+function(t,e){const n=t.split("\n"),i=[],r=Math.max(e-6,0),s=Math.min(e+6,n.length);for(let t=r;t<s;t++){const r=t+1;i.push(`${r===e?">":" "} ${r}: ${n[t]}`)}return i.join("\n")}(t.getShaderSource(e),i)}return r}function sl(t,e){const n=function(t){ai._getMatrix(il,ai.workingColorSpace,t);const e=`mat3( ${il.elements.map((t=>t.toFixed(4)))} )`;switch(ai.getTransfer(t)){case $e:return[e,"LinearTransferOETF"];case Qe:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",t),[e,"LinearTransferOETF"]}}(e);return[`vec4 ${t}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join("\n")}function al(t,e){let n;switch(e){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:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const ol=new Ci;function ll(){ai.getLuminanceCoefficients(ol);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${ol.x.toFixed(4)}, ${ol.y.toFixed(4)}, ${ol.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function cl(t){return""!==t}function hl(t,e){const n=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function ul(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const dl=/^[ \t]*#include +<([\w\d./]+)>/gm;function pl(t){return t.replace(dl,fl)}const ml=new Map;function fl(t,e){let n=ua[e];if(void 0===n){const t=ml.get(e);if(void 0===t)throw new Error("Can not resolve #include <"+e+">");n=ua[t],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,t)}return pl(n)}const gl=/#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 vl(t){return t.replace(gl,_l)}function _l(t,e,n,i){let r="";for(let t=parseInt(e);t<parseInt(n);t++)r+=i.replace(/\[\s*i\s*\]/g,"[ "+t+" ]").replace(/UNROLLED_LOOP_INDEX/g,t);return r}function xl(t){let e=`precision ${t.precision} float;\n\tprecision ${t.precision} int;\n\tprecision ${t.precision} sampler2D;\n\tprecision ${t.precision} samplerCube;\n\tprecision ${t.precision} sampler3D;\n\tprecision ${t.precision} sampler2DArray;\n\tprecision ${t.precision} sampler2DShadow;\n\tprecision ${t.precision} samplerCubeShadow;\n\tprecision ${t.precision} sampler2DArrayShadow;\n\tprecision ${t.precision} isampler2D;\n\tprecision ${t.precision} isampler3D;\n\tprecision ${t.precision} isamplerCube;\n\tprecision ${t.precision} isampler2DArray;\n\tprecision ${t.precision} usampler2D;\n\tprecision ${t.precision} usampler3D;\n\tprecision ${t.precision} usamplerCube;\n\tprecision ${t.precision} usampler2DArray;\n\t`;return"highp"===t.precision?e+="\n#define HIGH_PRECISION":"mediump"===t.precision?e+="\n#define MEDIUM_PRECISION":"lowp"===t.precision&&(e+="\n#define LOW_PRECISION"),e}function yl(t,e,n,i){const r=t.getContext(),s=n.defines;let a=n.vertexShader,o=n.fragmentShader;const l=function(t){let e="SHADOWMAP_TYPE_BASIC";return 1===t.shadowMapType?e="SHADOWMAP_TYPE_PCF":2===t.shadowMapType?e="SHADOWMAP_TYPE_PCF_SOFT":3===t.shadowMapType&&(e="SHADOWMAP_TYPE_VSM"),e}(n),c=function(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case lt:case ct:e="ENVMAP_TYPE_CUBE";break;case dt:e="ENVMAP_TYPE_CUBE_UV"}return e}(n),h=function(t){let e="ENVMAP_MODE_REFLECTION";t.envMap&&t.envMapMode===ct&&(e="ENVMAP_MODE_REFRACTION");return e}(n),u=function(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case 0:e="ENVMAP_BLENDING_MULTIPLY";break;case 1:e="ENVMAP_BLENDING_MIX";break;case 2:e="ENVMAP_BLENDING_ADD"}return e}(n),d=function(t){const e=t.envMapCubeUVHeight;if(null===e)return null;const n=Math.log2(e)-2,i=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:i,maxMip:n}}(n),p=function(t){return[t.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",t.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(cl).join("\n")}(n),m=function(t){const e=[];for(const n in t){const i=t[n];!1!==i&&e.push("#define "+n+" "+i)}return e.join("\n")}(s),f=r.createProgram();let g,v,_=n.glslVersion?"#version "+n.glslVersion+"\n":"";n.isRawShaderMaterial?(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,m].filter(cl).join("\n"),g.length>0&&(g+="\n"),v=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,m].filter(cl).join("\n"),v.length>0&&(v+="\n")):(g=[xl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,m,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+h:"",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(cl).join("\n"),v=[xl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,m,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+c:"",n.envMap?"#define "+h:"",n.envMap?"#define "+u:"",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?ua.tonemapping_pars_fragment:"",0!==n.toneMapping?al("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",ua.colorspace_pars_fragment,sl("linearToOutputTexel",n.outputColorSpace),ll(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(cl).join("\n")),a=pl(a),a=hl(a,n),a=ul(a,n),o=pl(o),o=hl(o,n),o=ul(o,n),a=vl(a),o=vl(o),!0!==n.isRawShaderMaterial&&(_="#version 300 es\n",g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,v=["#define varying in",n.glslVersion===Nn?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Nn?"":"#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"+v);const x=_+g+a,y=_+v+o,M=el(r,r.VERTEX_SHADER,x),S=el(r,r.FRAGMENT_SHADER,y);function b(e){if(t.debug.checkShaderErrors){const n=r.getProgramInfoLog(f).trim(),i=r.getShaderInfoLog(M).trim(),s=r.getShaderInfoLog(S).trim();let a=!0,o=!0;if(!1===r.getProgramParameter(f,r.LINK_STATUS))if(a=!1,"function"==typeof t.debug.onShaderError)t.debug.onShaderError(r,f,M,S);else{const t=rl(r,M,"vertex"),i=rl(r,S,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(f,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+e.name+"\nMaterial Type: "+e.type+"\n\nProgram Info Log: "+n+"\n"+t+"\n"+i)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==i&&""!==s||(o=!1);o&&(e.diagnostics={runnable:a,programLog:n,vertexShader:{log:i,prefix:g},fragmentShader:{log:s,prefix:v}})}r.deleteShader(M),r.deleteShader(S),T=new tl(r,f),w=function(t,e){const n={},i=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let r=0;r<i;r++){const i=t.getActiveAttrib(e,r),s=i.name;let a=1;i.type===t.FLOAT_MAT2&&(a=2),i.type===t.FLOAT_MAT3&&(a=3),i.type===t.FLOAT_MAT4&&(a=4),n[s]={type:i.type,location:t.getAttribLocation(e,s),locationSize:a}}return n}(r,f)}let T,w;r.attachShader(f,M),r.attachShader(f,S),void 0!==n.index0AttributeName?r.bindAttribLocation(f,0,n.index0AttributeName):!0===n.morphTargets&&r.bindAttribLocation(f,0,"position"),r.linkProgram(f),this.getUniforms=function(){return void 0===T&&b(this),T},this.getAttributes=function(){return void 0===w&&b(this),w};let E=!1===n.rendererExtensionParallelShaderCompile;return this.isReady=function(){return!1===E&&(E=r.getProgramParameter(f,37297)),E},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(f),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=nl++,this.cacheKey=e,this.usedTimes=1,this.program=f,this.vertexShader=M,this.fragmentShader=S,this}let Ml=0;class Sl{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){const e=t.vertexShader,n=t.fragmentShader,i=this._getShaderStage(e),r=this._getShaderStage(n),s=this._getShaderCacheForMaterial(t);return!1===s.has(i)&&(s.add(i),i.usedTimes++),!1===s.has(r)&&(s.add(r),r.usedTimes++),this}remove(t){const e=this.materialCache.get(t);for(const t of e)t.usedTimes--,0===t.usedTimes&&this.shaderCache.delete(t.code);return this.materialCache.delete(t),this}getVertexShaderID(t){return this._getShaderStage(t.vertexShader).id}getFragmentShaderID(t){return this._getShaderStage(t.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){const e=this.materialCache;let n=e.get(t);return void 0===n&&(n=new Set,e.set(t,n)),n}_getShaderStage(t){const e=this.shaderCache;let n=e.get(t);return void 0===n&&(n=new bl(t),e.set(t,n)),n}}class bl{constructor(t){this.id=Ml++,this.code=t,this.usedTimes=0}}function Tl(t,e,n,i,r,s,a){const o=new gr,l=new Sl,c=new Set,h=[],u=r.logarithmicDepthBuffer,d=r.vertexTextures;let p=r.precision;const m={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function f(t){return c.add(t),0===t?"uv":`uv${t}`}return{getParameters:function(s,o,h,g,v){const _=g.fog,x=v.geometry,y=s.isMeshStandardMaterial?g.environment:null,M=(s.isMeshStandardMaterial?n:e).get(s.envMap||y),S=M&&M.mapping===dt?M.image.height:null,b=m[s.type];null!==s.precision&&(p=r.getMaxPrecision(s.precision),p!==s.precision&&console.warn("THREE.WebGLProgram.getParameters:",s.precision,"not supported, using",p,"instead."));const T=x.morphAttributes.position||x.morphAttributes.normal||x.morphAttributes.color,w=void 0!==T?T.length:0;let E,A,R,C,I=0;if(void 0!==x.morphAttributes.position&&(I=1),void 0!==x.morphAttributes.normal&&(I=2),void 0!==x.morphAttributes.color&&(I=3),b){const t=pa[b];E=t.vertexShader,A=t.fragmentShader}else E=s.vertexShader,A=s.fragmentShader,l.update(s),R=l.getVertexShaderID(s),C=l.getFragmentShaderID(s);const P=t.getRenderTarget(),L=t.state.buffers.depth.getReversed(),U=!0===v.isInstancedMesh,D=!0===v.isBatchedMesh,N=!!s.map,O=!!s.matcap,F=!!M,B=!!s.aoMap,z=!!s.lightMap,k=!!s.bumpMap,V=!!s.normalMap,H=!!s.displacementMap,G=!!s.emissiveMap,W=!!s.metalnessMap,X=!!s.roughnessMap,j=s.anisotropy>0,q=s.clearcoat>0,Y=s.dispersion>0,Z=s.iridescence>0,J=s.sheen>0,K=s.transmission>0,$=j&&!!s.anisotropyMap,Q=q&&!!s.clearcoatMap,tt=q&&!!s.clearcoatNormalMap,et=q&&!!s.clearcoatRoughnessMap,nt=Z&&!!s.iridescenceMap,it=Z&&!!s.iridescenceThicknessMap,rt=J&&!!s.sheenColorMap,st=J&&!!s.sheenRoughnessMap,at=!!s.specularMap,ot=!!s.specularColorMap,lt=!!s.specularIntensityMap,ct=K&&!!s.transmissionMap,ht=K&&!!s.thicknessMap,ut=!!s.gradientMap,pt=!!s.alphaMap,mt=s.alphaTest>0,ft=!!s.alphaHash,gt=!!s.extensions;let vt=0;s.toneMapped&&(null!==P&&!0!==P.isXRRenderTarget||(vt=t.toneMapping));const _t={shaderID:b,shaderType:s.type,shaderName:s.name,vertexShader:E,fragmentShader:A,defines:s.defines,customVertexShaderID:R,customFragmentShaderID:C,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:p,batching:D,batchingColor:D&&null!==v._colorsTexture,instancing:U,instancingColor:U&&null!==v.instanceColor,instancingMorph:U&&null!==v.morphTexture,supportsVertexTextures:d,outputColorSpace:null===P?t.outputColorSpace:!0===P.isXRRenderTarget?P.texture.colorSpace:Ke,alphaToCoverage:!!s.alphaToCoverage,map:N,matcap:O,envMap:F,envMapMode:F&&M.mapping,envMapCubeUVHeight:S,aoMap:B,lightMap:z,bumpMap:k,normalMap:V,displacementMap:d&&H,emissiveMap:G,normalMapObjectSpace:V&&1===s.normalMapType,normalMapTangentSpace:V&&0===s.normalMapType,metalnessMap:W,roughnessMap:X,anisotropy:j,anisotropyMap:$,clearcoat:q,clearcoatMap:Q,clearcoatNormalMap:tt,clearcoatRoughnessMap:et,dispersion:Y,iridescence:Z,iridescenceMap:nt,iridescenceThicknessMap:it,sheen:J,sheenColorMap:rt,sheenRoughnessMap:st,specularMap:at,specularColorMap:ot,specularIntensityMap:lt,transmission:K,transmissionMap:ct,thicknessMap:ht,gradientMap:ut,opaque:!1===s.transparent&&1===s.blending&&!1===s.alphaToCoverage,alphaMap:pt,alphaTest:mt,alphaHash:ft,combine:s.combine,mapUv:N&&f(s.map.channel),aoMapUv:B&&f(s.aoMap.channel),lightMapUv:z&&f(s.lightMap.channel),bumpMapUv:k&&f(s.bumpMap.channel),normalMapUv:V&&f(s.normalMap.channel),displacementMapUv:H&&f(s.displacementMap.channel),emissiveMapUv:G&&f(s.emissiveMap.channel),metalnessMapUv:W&&f(s.metalnessMap.channel),roughnessMapUv:X&&f(s.roughnessMap.channel),anisotropyMapUv:$&&f(s.anisotropyMap.channel),clearcoatMapUv:Q&&f(s.clearcoatMap.channel),clearcoatNormalMapUv:tt&&f(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:et&&f(s.clearcoatRoughnessMap.channel),iridescenceMapUv:nt&&f(s.iridescenceMap.channel),iridescenceThicknessMapUv:it&&f(s.iridescenceThicknessMap.channel),sheenColorMapUv:rt&&f(s.sheenColorMap.channel),sheenRoughnessMapUv:st&&f(s.sheenRoughnessMap.channel),specularMapUv:at&&f(s.specularMap.channel),specularColorMapUv:ot&&f(s.specularColorMap.channel),specularIntensityMapUv:lt&&f(s.specularIntensityMap.channel),transmissionMapUv:ct&&f(s.transmissionMap.channel),thicknessMapUv:ht&&f(s.thicknessMap.channel),alphaMapUv:pt&&f(s.alphaMap.channel),vertexTangents:!!x.attributes.tangent&&(V||j),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!x.attributes.color&&4===x.attributes.color.itemSize,pointsUvs:!0===v.isPoints&&!!x.attributes.uv&&(N||pt),fog:!!_,useFog:!0===s.fog,fogExp2:!!_&&_.isFogExp2,flatShading:!0===s.flatShading,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:u,reverseDepthBuffer:L,skinning:!0===v.isSkinnedMesh,morphTargets:void 0!==x.morphAttributes.position,morphNormals:void 0!==x.morphAttributes.normal,morphColors:void 0!==x.morphAttributes.color,morphTargetsCount:w,morphTextureStride:I,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:t.shadowMap.enabled&&h.length>0,shadowMapType:t.shadowMap.type,toneMapping:vt,decodeVideoTexture:N&&!0===s.map.isVideoTexture&&ai.getTransfer(s.map.colorSpace)===Qe,decodeVideoTextureEmissive:G&&!0===s.emissiveMap.isVideoTexture&&ai.getTransfer(s.emissiveMap.colorSpace)===Qe,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:gt&&!0===s.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(gt&&!0===s.extensions.multiDraw||D)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return _t.vertexUv1s=c.has(1),_t.vertexUv2s=c.has(2),_t.vertexUv3s=c.has(3),c.clear(),_t},getProgramCacheKey:function(e){const n=[];if(e.shaderID?n.push(e.shaderID):(n.push(e.customVertexShaderID),n.push(e.customFragmentShaderID)),void 0!==e.defines)for(const t in e.defines)n.push(t),n.push(e.defines[t]);return!1===e.isRawShaderMaterial&&(!function(t,e){t.push(e.precision),t.push(e.outputColorSpace),t.push(e.envMapMode),t.push(e.envMapCubeUVHeight),t.push(e.mapUv),t.push(e.alphaMapUv),t.push(e.lightMapUv),t.push(e.aoMapUv),t.push(e.bumpMapUv),t.push(e.normalMapUv),t.push(e.displacementMapUv),t.push(e.emissiveMapUv),t.push(e.metalnessMapUv),t.push(e.roughnessMapUv),t.push(e.anisotropyMapUv),t.push(e.clearcoatMapUv),t.push(e.clearcoatNormalMapUv),t.push(e.clearcoatRoughnessMapUv),t.push(e.iridescenceMapUv),t.push(e.iridescenceThicknessMapUv),t.push(e.sheenColorMapUv),t.push(e.sheenRoughnessMapUv),t.push(e.specularMapUv),t.push(e.specularColorMapUv),t.push(e.specularIntensityMapUv),t.push(e.transmissionMapUv),t.push(e.thicknessMapUv),t.push(e.combine),t.push(e.fogExp2),t.push(e.sizeAttenuation),t.push(e.morphTargetsCount),t.push(e.morphAttributeCount),t.push(e.numDirLights),t.push(e.numPointLights),t.push(e.numSpotLights),t.push(e.numSpotLightMaps),t.push(e.numHemiLights),t.push(e.numRectAreaLights),t.push(e.numDirLightShadows),t.push(e.numPointLightShadows),t.push(e.numSpotLightShadows),t.push(e.numSpotLightShadowsWithMaps),t.push(e.numLightProbes),t.push(e.shadowMapType),t.push(e.toneMapping),t.push(e.numClippingPlanes),t.push(e.numClipIntersection),t.push(e.depthPacking)}(n,e),function(t,e){o.disableAll(),e.supportsVertexTextures&&o.enable(0);e.instancing&&o.enable(1);e.instancingColor&&o.enable(2);e.instancingMorph&&o.enable(3);e.matcap&&o.enable(4);e.envMap&&o.enable(5);e.normalMapObjectSpace&&o.enable(6);e.normalMapTangentSpace&&o.enable(7);e.clearcoat&&o.enable(8);e.iridescence&&o.enable(9);e.alphaTest&&o.enable(10);e.vertexColors&&o.enable(11);e.vertexAlphas&&o.enable(12);e.vertexUv1s&&o.enable(13);e.vertexUv2s&&o.enable(14);e.vertexUv3s&&o.enable(15);e.vertexTangents&&o.enable(16);e.anisotropy&&o.enable(17);e.alphaHash&&o.enable(18);e.batching&&o.enable(19);e.dispersion&&o.enable(20);e.batchingColor&&o.enable(21);t.push(o.mask),o.disableAll(),e.fog&&o.enable(0);e.useFog&&o.enable(1);e.flatShading&&o.enable(2);e.logarithmicDepthBuffer&&o.enable(3);e.reverseDepthBuffer&&o.enable(4);e.skinning&&o.enable(5);e.morphTargets&&o.enable(6);e.morphNormals&&o.enable(7);e.morphColors&&o.enable(8);e.premultipliedAlpha&&o.enable(9);e.shadowMapEnabled&&o.enable(10);e.doubleSided&&o.enable(11);e.flipSided&&o.enable(12);e.useDepthPacking&&o.enable(13);e.dithering&&o.enable(14);e.transmission&&o.enable(15);e.sheen&&o.enable(16);e.opaque&&o.enable(17);e.pointsUvs&&o.enable(18);e.decodeVideoTexture&&o.enable(19);e.decodeVideoTextureEmissive&&o.enable(20);e.alphaToCoverage&&o.enable(21);t.push(o.mask)}(n,e),n.push(t.outputColorSpace)),n.push(e.customProgramCacheKey),n.join()},getUniforms:function(t){const e=m[t.type];let n;if(e){const t=pa[e];n=Ws.clone(t.uniforms)}else n=t.uniforms;return n},acquireProgram:function(e,n){let i;for(let t=0,e=h.length;t<e;t++){const e=h[t];if(e.cacheKey===n){i=e,++i.usedTimes;break}}return void 0===i&&(i=new yl(t,n,e,s),h.push(i)),i},releaseProgram:function(t){if(0==--t.usedTimes){const e=h.indexOf(t);h[e]=h[h.length-1],h.pop(),t.destroy()}},releaseShaderCache:function(t){l.remove(t)},programs:h,dispose:function(){l.dispose()}}}function wl(){let t=new WeakMap;return{has:function(e){return t.has(e)},get:function(e){let n=t.get(e);return void 0===n&&(n={},t.set(e,n)),n},remove:function(e){t.delete(e)},update:function(e,n,i){t.get(e)[n]=i},dispose:function(){t=new WeakMap}}}function El(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function Al(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function Rl(){const t=[];let e=0;const n=[],i=[],r=[];function s(n,i,r,s,a,o){let l=t[e];return void 0===l?(l={id:n.id,object:n,geometry:i,material:r,groupOrder:s,renderOrder:n.renderOrder,z:a,group:o},t[e]=l):(l.id=n.id,l.object=n,l.geometry=i,l.material=r,l.groupOrder=s,l.renderOrder=n.renderOrder,l.z=a,l.group=o),e++,l}return{opaque:n,transmissive:i,transparent:r,init:function(){e=0,n.length=0,i.length=0,r.length=0},push:function(t,e,a,o,l,c){const h=s(t,e,a,o,l,c);a.transmission>0?i.push(h):!0===a.transparent?r.push(h):n.push(h)},unshift:function(t,e,a,o,l,c){const h=s(t,e,a,o,l,c);a.transmission>0?i.unshift(h):!0===a.transparent?r.unshift(h):n.unshift(h)},finish:function(){for(let n=e,i=t.length;n<i;n++){const e=t[n];if(null===e.id)break;e.id=null,e.object=null,e.geometry=null,e.material=null,e.group=null}},sort:function(t,e){n.length>1&&n.sort(t||El),i.length>1&&i.sort(e||Al),r.length>1&&r.sort(e||Al)}}}function Cl(){let t=new WeakMap;return{get:function(e,n){const i=t.get(e);let r;return void 0===i?(r=new Rl,t.set(e,[r])):n>=i.length?(r=new Rl,i.push(r)):r=i[n],r},dispose:function(){t=new WeakMap}}}function Il(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new Ci,color:new Kr};break;case"SpotLight":n={position:new Ci,direction:new Ci,color:new Kr,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Ci,color:new Kr,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Ci,skyColor:new Kr,groundColor:new Kr};break;case"RectAreaLight":n={color:new Kr,position:new Ci,halfWidth:new Ci,halfHeight:new Ci}}return t[e.id]=n,n}}}let Pl=0;function Ll(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function Ul(t){const e=new Il,n=function(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Jn};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Jn,shadowCameraNear:1,shadowCameraFar:1e3}}return t[e.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 t=0;t<9;t++)i.probe.push(new Ci);const r=new Ci,s=new sr,a=new sr;return{setup:function(r){let s=0,a=0,o=0;for(let t=0;t<9;t++)i.probe[t].set(0,0,0);let l=0,c=0,h=0,u=0,d=0,p=0,m=0,f=0,g=0,v=0,_=0;r.sort(Ll);for(let t=0,x=r.length;t<x;t++){const x=r[t],y=x.color,M=x.intensity,S=x.distance,b=x.shadow&&x.shadow.map?x.shadow.map.texture:null;if(x.isAmbientLight)s+=y.r*M,a+=y.g*M,o+=y.b*M;else if(x.isLightProbe){for(let t=0;t<9;t++)i.probe[t].addScaledVector(x.sh.coefficients[t],M);_++}else if(x.isDirectionalLight){const t=e.get(x);if(t.color.copy(x.color).multiplyScalar(x.intensity),x.castShadow){const t=x.shadow,e=n.get(x);e.shadowIntensity=t.intensity,e.shadowBias=t.bias,e.shadowNormalBias=t.normalBias,e.shadowRadius=t.radius,e.shadowMapSize=t.mapSize,i.directionalShadow[l]=e,i.directionalShadowMap[l]=b,i.directionalShadowMatrix[l]=x.shadow.matrix,p++}i.directional[l]=t,l++}else if(x.isSpotLight){const t=e.get(x);t.position.setFromMatrixPosition(x.matrixWorld),t.color.copy(y).multiplyScalar(M),t.distance=S,t.coneCos=Math.cos(x.angle),t.penumbraCos=Math.cos(x.angle*(1-x.penumbra)),t.decay=x.decay,i.spot[h]=t;const r=x.shadow;if(x.map&&(i.spotLightMap[g]=x.map,g++,r.updateMatrices(x),x.castShadow&&v++),i.spotLightMatrix[h]=r.matrix,x.castShadow){const t=n.get(x);t.shadowIntensity=r.intensity,t.shadowBias=r.bias,t.shadowNormalBias=r.normalBias,t.shadowRadius=r.radius,t.shadowMapSize=r.mapSize,i.spotShadow[h]=t,i.spotShadowMap[h]=b,f++}h++}else if(x.isRectAreaLight){const t=e.get(x);t.color.copy(y).multiplyScalar(M),t.halfWidth.set(.5*x.width,0,0),t.halfHeight.set(0,.5*x.height,0),i.rectArea[u]=t,u++}else if(x.isPointLight){const t=e.get(x);if(t.color.copy(x.color).multiplyScalar(x.intensity),t.distance=x.distance,t.decay=x.decay,x.castShadow){const t=x.shadow,e=n.get(x);e.shadowIntensity=t.intensity,e.shadowBias=t.bias,e.shadowNormalBias=t.normalBias,e.shadowRadius=t.radius,e.shadowMapSize=t.mapSize,e.shadowCameraNear=t.camera.near,e.shadowCameraFar=t.camera.far,i.pointShadow[c]=e,i.pointShadowMap[c]=b,i.pointShadowMatrix[c]=x.shadow.matrix,m++}i.point[c]=t,c++}else if(x.isHemisphereLight){const t=e.get(x);t.skyColor.copy(x.color).multiplyScalar(M),t.groundColor.copy(x.groundColor).multiplyScalar(M),i.hemi[d]=t,d++}}u>0&&(!0===t.has("OES_texture_float_linear")?(i.rectAreaLTC1=da.LTC_FLOAT_1,i.rectAreaLTC2=da.LTC_FLOAT_2):(i.rectAreaLTC1=da.LTC_HALF_1,i.rectAreaLTC2=da.LTC_HALF_2)),i.ambient[0]=s,i.ambient[1]=a,i.ambient[2]=o;const x=i.hash;x.directionalLength===l&&x.pointLength===c&&x.spotLength===h&&x.rectAreaLength===u&&x.hemiLength===d&&x.numDirectionalShadows===p&&x.numPointShadows===m&&x.numSpotShadows===f&&x.numSpotMaps===g&&x.numLightProbes===_||(i.directional.length=l,i.spot.length=h,i.rectArea.length=u,i.point.length=c,i.hemi.length=d,i.directionalShadow.length=p,i.directionalShadowMap.length=p,i.pointShadow.length=m,i.pointShadowMap.length=m,i.spotShadow.length=f,i.spotShadowMap.length=f,i.directionalShadowMatrix.length=p,i.pointShadowMatrix.length=m,i.spotLightMatrix.length=f+g-v,i.spotLightMap.length=g,i.numSpotLightShadowsWithMaps=v,i.numLightProbes=_,x.directionalLength=l,x.pointLength=c,x.spotLength=h,x.rectAreaLength=u,x.hemiLength=d,x.numDirectionalShadows=p,x.numPointShadows=m,x.numSpotShadows=f,x.numSpotMaps=g,x.numLightProbes=_,i.version=Pl++)},setupView:function(t,e){let n=0,o=0,l=0,c=0,h=0;const u=e.matrixWorldInverse;for(let e=0,d=t.length;e<d;e++){const d=t[e];if(d.isDirectionalLight){const t=i.directional[n];t.direction.setFromMatrixPosition(d.matrixWorld),r.setFromMatrixPosition(d.target.matrixWorld),t.direction.sub(r),t.direction.transformDirection(u),n++}else if(d.isSpotLight){const t=i.spot[l];t.position.setFromMatrixPosition(d.matrixWorld),t.position.applyMatrix4(u),t.direction.setFromMatrixPosition(d.matrixWorld),r.setFromMatrixPosition(d.target.matrixWorld),t.direction.sub(r),t.direction.transformDirection(u),l++}else if(d.isRectAreaLight){const t=i.rectArea[c];t.position.setFromMatrixPosition(d.matrixWorld),t.position.applyMatrix4(u),a.identity(),s.copy(d.matrixWorld),s.premultiply(u),a.extractRotation(s),t.halfWidth.set(.5*d.width,0,0),t.halfHeight.set(0,.5*d.height,0),t.halfWidth.applyMatrix4(a),t.halfHeight.applyMatrix4(a),c++}else if(d.isPointLight){const t=i.point[o];t.position.setFromMatrixPosition(d.matrixWorld),t.position.applyMatrix4(u),o++}else if(d.isHemisphereLight){const t=i.hemi[h];t.direction.setFromMatrixPosition(d.matrixWorld),t.direction.transformDirection(u),h++}}},state:i}}function Dl(t){const e=new Ul(t),n=[],i=[];const r={lightsArray:n,shadowsArray:i,camera:null,lights:e,transmissionRenderTarget:{}};return{init:function(t){r.camera=t,n.length=0,i.length=0},state:r,setupLights:function(){e.setup(n)},setupLightsView:function(t){e.setupView(n,t)},pushLight:function(t){n.push(t)},pushShadow:function(t){i.push(t)}}}function Nl(t){let e=new WeakMap;return{get:function(n,i=0){const r=e.get(n);let s;return void 0===r?(s=new Dl(t),e.set(n,[s])):i>=r.length?(s=new Dl(t),r.push(s)):s=r[i],s},dispose:function(){e=new WeakMap}}}class Ol extends ts{static get type(){return"MeshDepthMaterial"}constructor(t){super(),this.isMeshDepthMaterial=!0,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(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class Fl extends ts{static get type(){return"MeshDistanceMaterial"}constructor(t){super(),this.isMeshDistanceMaterial=!0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}function Bl(t,e,n){let i=new oa;const r=new Jn,s=new Jn,a=new Mi,o=new Ol({depthPacking:3201}),l=new Fl,c={},h=n.maxTextureSize,m={[u]:1,[d]:0,[p]:2},f=new Xs({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Jn},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 <packing>\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=f.clone();g.defines.HORIZONTAL_PASS=1;const v=new Es;v.setAttribute("position",new cs(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const _=new Bs(v,f),x=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let y=this.type;function M(n,i){const s=e.update(_);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,g.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,g.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new bi(r.x,r.y)),f.uniforms.shadow_pass.value=n.map.texture,f.uniforms.resolution.value=n.mapSize,f.uniforms.radius.value=n.radius,t.setRenderTarget(n.mapPass),t.clear(),t.renderBufferDirect(i,null,s,f,_,null),g.uniforms.shadow_pass.value=n.mapPass.texture,g.uniforms.resolution.value=n.mapSize,g.uniforms.radius.value=n.radius,t.setRenderTarget(n.map),t.clear(),t.renderBufferDirect(i,null,s,g,_,null)}function S(e,n,i,r){let s=null;const a=!0===i.isPointLight?e.customDistanceMaterial:e.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?l:o,t.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 t=s.uuid,e=n.uuid;let i=c[t];void 0===i&&(i={},c[t]=i);let r=i[e];void 0===r&&(r=s.clone(),i[e]=r,n.addEventListener("dispose",T)),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:m[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){t.properties.get(s).light=i}return s}function b(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=e.update(n),l=n.material;if(Array.isArray(l)){const e=i.groups;for(let c=0,h=e.length;c<h;c++){const h=e[c],u=l[h.materialIndex];if(u&&u.visible){const e=S(n,u,a,o);n.onBeforeShadow(t,n,r,s,i,e,h),t.renderBufferDirect(s,null,i,e,n,h),n.onAfterShadow(t,n,r,s,i,e,h)}}}else if(l.visible){const e=S(n,l,a,o);n.onBeforeShadow(t,n,r,s,i,e,null),t.renderBufferDirect(s,null,i,e,n,null),n.onAfterShadow(t,n,r,s,i,e,null)}}const l=n.children;for(let t=0,e=l.length;t<e;t++)b(l[t],r,s,a,o)}function T(t){t.target.removeEventListener("dispose",T);for(const e in c){const n=c[e],i=t.target.uuid;if(i in n){n[i].dispose(),delete n[i]}}}this.render=function(e,n,o){if(!1===x.enabled)return;if(!1===x.autoUpdate&&!1===x.needsUpdate)return;if(0===e.length)return;const l=t.getRenderTarget(),c=t.getActiveCubeFace(),u=t.getActiveMipmapLevel(),d=t.state;d.setBlending(0),d.buffers.color.setClear(1,1,1,1),d.buffers.depth.setTest(!0),d.setScissorTest(!1);const p=3!==y&&3===this.type,m=3===y&&3!==this.type;for(let l=0,c=e.length;l<c;l++){const c=e[l],u=c.shadow;if(void 0===u){console.warn("THREE.WebGLShadowMap:",c,"has no shadow.");continue}if(!1===u.autoUpdate&&!1===u.needsUpdate)continue;r.copy(u.mapSize);const f=u.getFrameExtents();if(r.multiply(f),s.copy(u.mapSize),(r.x>h||r.y>h)&&(r.x>h&&(s.x=Math.floor(h/f.x),r.x=s.x*f.x,u.mapSize.x=s.x),r.y>h&&(s.y=Math.floor(h/f.y),r.y=s.y*f.y,u.mapSize.y=s.y)),null===u.map||!0===p||!0===m){const t=3!==this.type?{minFilter:gt,magFilter:gt}:{};null!==u.map&&u.map.dispose(),u.map=new bi(r.x,r.y,t),u.map.texture.name=c.name+".shadowMap",u.camera.updateProjectionMatrix()}t.setRenderTarget(u.map),t.clear();const g=u.getViewportCount();for(let t=0;t<g;t++){const e=u.getViewport(t);a.set(s.x*e.x,s.y*e.y,s.x*e.z,s.y*e.w),d.viewport(a),u.updateMatrices(c,t),i=u.getFrustum(),b(n,o,u.camera,c,this.type)}!0!==u.isPointLightShadow&&3===this.type&&M(u,o),u.needsUpdate=!1}y=this.type,x.needsUpdate=!1,t.setRenderTarget(l,c,u)}}const zl={[k]:1,[H]:6,[W]:7,[G]:5,[V]:0,[j]:2,[q]:4,[X]:3};function kl(t,e){const n=new function(){let e=!1;const n=new Mi;let i=null;const r=new Mi(0,0,0,0);return{setMask:function(n){i===n||e||(t.colorMask(n,n,n,n),i=n)},setLocked:function(t){e=t},setClear:function(e,i,s,a,o){!0===o&&(e*=a,i*=a,s*=a),n.set(e,i,s,a),!1===r.equals(n)&&(t.clearColor(e,i,s,a),r.copy(n))},reset:function(){e=!1,i=null,r.set(-1,0,0,0)}}},i=new function(){let n=!1,i=!1,r=null,s=null,a=null;return{setReversed:function(t){if(i!==t){const t=e.get("EXT_clip_control");i?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT);const n=a;a=null,this.setClear(n)}i=t},getReversed:function(){return i},setTest:function(e){e?rt(t.DEPTH_TEST):st(t.DEPTH_TEST)},setMask:function(e){r===e||n||(t.depthMask(e),r=e)},setFunc:function(e){if(i&&(e=zl[e]),s!==e){switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}s=e}},setLocked:function(t){n=t},setClear:function(e){a!==e&&(i&&(e=1-e),t.clearDepth(e),a=e)},reset:function(){n=!1,r=null,s=null,a=null,i=!1}}},r=new function(){let e=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null;return{setTest:function(n){e||(n?rt(t.STENCIL_TEST):st(t.STENCIL_TEST))},setMask:function(i){n===i||e||(t.stencilMask(i),n=i)},setFunc:function(e,n,a){i===e&&r===n&&s===a||(t.stencilFunc(e,n,a),i=e,r=n,s=a)},setOp:function(e,n,i){a===e&&o===n&&l===i||(t.stencilOp(e,n,i),a=e,o=n,l=i)},setLocked:function(t){e=t},setClear:function(e){c!==e&&(t.clearStencil(e),c=e)},reset:function(){e=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null}}},s=new WeakMap,a=new WeakMap;let o={},l={},c=new WeakMap,h=[],u=null,d=!1,p=null,m=null,f=null,g=null,v=null,_=null,x=null,b=new Kr(0,0,0),T=0,k=!1,V=null,H=null,G=null,W=null,X=null;const j=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let q=!1,Y=0;const Z=t.getParameter(t.VERSION);-1!==Z.indexOf("WebGL")?(Y=parseFloat(/^WebGL (\d)/.exec(Z)[1]),q=Y>=1):-1!==Z.indexOf("OpenGL ES")&&(Y=parseFloat(/^OpenGL ES (\d)/.exec(Z)[1]),q=Y>=2);let J=null,K={};const $=t.getParameter(t.SCISSOR_BOX),Q=t.getParameter(t.VIEWPORT),tt=(new Mi).fromArray($),et=(new Mi).fromArray(Q);function nt(e,n,i,r){const s=new Uint8Array(4),a=t.createTexture();t.bindTexture(e,a),t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let a=0;a<i;a++)e===t.TEXTURE_3D||e===t.TEXTURE_2D_ARRAY?t.texImage3D(n,0,t.RGBA,1,1,r,0,t.RGBA,t.UNSIGNED_BYTE,s):t.texImage2D(n+a,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,s);return a}const it={};function rt(e){!0!==o[e]&&(t.enable(e),o[e]=!0)}function st(e){!1!==o[e]&&(t.disable(e),o[e]=!1)}it[t.TEXTURE_2D]=nt(t.TEXTURE_2D,t.TEXTURE_2D,1),it[t.TEXTURE_CUBE_MAP]=nt(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),it[t.TEXTURE_2D_ARRAY]=nt(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),it[t.TEXTURE_3D]=nt(t.TEXTURE_3D,t.TEXTURE_3D,1,1),n.setClear(0,0,0,1),i.setClear(1),r.setClear(0),rt(t.DEPTH_TEST),i.setFunc(3),ct(!1),ht(1),rt(t.CULL_FACE),lt(0);const at={[y]:t.FUNC_ADD,[M]:t.FUNC_SUBTRACT,[S]:t.FUNC_REVERSE_SUBTRACT};at[103]=t.MIN,at[104]=t.MAX;const ot={[w]:t.ZERO,[E]:t.ONE,[A]:t.SRC_COLOR,[C]:t.SRC_ALPHA,[N]:t.SRC_ALPHA_SATURATE,[U]:t.DST_COLOR,[P]:t.DST_ALPHA,[R]:t.ONE_MINUS_SRC_COLOR,[I]:t.ONE_MINUS_SRC_ALPHA,[D]:t.ONE_MINUS_DST_COLOR,[L]:t.ONE_MINUS_DST_ALPHA,[O]:t.CONSTANT_COLOR,[F]:t.ONE_MINUS_CONSTANT_COLOR,[B]:t.CONSTANT_ALPHA,[z]:t.ONE_MINUS_CONSTANT_ALPHA};function lt(e,n,i,r,s,a,o,l,c,h){if(0!==e){if(!1===d&&(rt(t.BLEND),d=!0),5===e)s=s||n,a=a||i,o=o||r,n===m&&s===v||(t.blendEquationSeparate(at[n],at[s]),m=n,v=s),i===f&&r===g&&a===_&&o===x||(t.blendFuncSeparate(ot[i],ot[r],ot[a],ot[o]),f=i,g=r,_=a,x=o),!1!==l.equals(b)&&c===T||(t.blendColor(l.r,l.g,l.b,c),b.copy(l),T=c),p=e,k=!1;else if(e!==p||h!==k){if(m===y&&v===y||(t.blendEquation(t.FUNC_ADD),m=y,v=y),h)switch(e){case 1:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case 2:t.blendFunc(t.ONE,t.ONE);break;case 3:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case 4:t.blendFuncSeparate(t.ZERO,t.SRC_COLOR,t.ZERO,t.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}else switch(e){case 1:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case 2:t.blendFunc(t.SRC_ALPHA,t.ONE);break;case 3:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case 4:t.blendFunc(t.ZERO,t.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}f=null,g=null,_=null,x=null,b.set(0,0,0),T=0,p=e,k=h}}else!0===d&&(st(t.BLEND),d=!1)}function ct(e){V!==e&&(e?t.frontFace(t.CW):t.frontFace(t.CCW),V=e)}function ht(e){0!==e?(rt(t.CULL_FACE),e!==H&&(1===e?t.cullFace(t.BACK):2===e?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):st(t.CULL_FACE),H=e}function ut(e,n,i){e?(rt(t.POLYGON_OFFSET_FILL),W===n&&X===i||(t.polygonOffset(n,i),W=n,X=i)):st(t.POLYGON_OFFSET_FILL)}return{buffers:{color:n,depth:i,stencil:r},enable:rt,disable:st,bindFramebuffer:function(e,n){return l[e]!==n&&(t.bindFramebuffer(e,n),l[e]=n,e===t.DRAW_FRAMEBUFFER&&(l[t.FRAMEBUFFER]=n),e===t.FRAMEBUFFER&&(l[t.DRAW_FRAMEBUFFER]=n),!0)},drawBuffers:function(e,n){let i=h,r=!1;if(e){i=c.get(n),void 0===i&&(i=[],c.set(n,i));const s=e.textures;if(i.length!==s.length||i[0]!==t.COLOR_ATTACHMENT0){for(let e=0,n=s.length;e<n;e++)i[e]=t.COLOR_ATTACHMENT0+e;i.length=s.length,r=!0}}else i[0]!==t.BACK&&(i[0]=t.BACK,r=!0);r&&t.drawBuffers(i)},useProgram:function(e){return u!==e&&(t.useProgram(e),u=e,!0)},setBlending:lt,setMaterial:function(e,s){2===e.side?st(t.CULL_FACE):rt(t.CULL_FACE);let a=1===e.side;s&&(a=!a),ct(a),1===e.blending&&!1===e.transparent?lt(0):lt(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.blendColor,e.blendAlpha,e.premultipliedAlpha),i.setFunc(e.depthFunc),i.setTest(e.depthTest),i.setMask(e.depthWrite),n.setMask(e.colorWrite);const o=e.stencilWrite;r.setTest(o),o&&(r.setMask(e.stencilWriteMask),r.setFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),r.setOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),ut(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage?rt(t.SAMPLE_ALPHA_TO_COVERAGE):st(t.SAMPLE_ALPHA_TO_COVERAGE)},setFlipSided:ct,setCullFace:ht,setLineWidth:function(e){e!==G&&(q&&t.lineWidth(e),G=e)},setPolygonOffset:ut,setScissorTest:function(e){e?rt(t.SCISSOR_TEST):st(t.SCISSOR_TEST)},activeTexture:function(e){void 0===e&&(e=t.TEXTURE0+j-1),J!==e&&(t.activeTexture(e),J=e)},bindTexture:function(e,n,i){void 0===i&&(i=null===J?t.TEXTURE0+j-1:J);let r=K[i];void 0===r&&(r={type:void 0,texture:void 0},K[i]=r),r.type===e&&r.texture===n||(J!==i&&(t.activeTexture(i),J=i),t.bindTexture(e,n||it[e]),r.type=e,r.texture=n)},unbindTexture:function(){const e=K[J];void 0!==e&&void 0!==e.type&&(t.bindTexture(e.type,null),e.type=void 0,e.texture=void 0)},compressedTexImage2D:function(){try{t.compressedTexImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},compressedTexImage3D:function(){try{t.compressedTexImage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texImage2D:function(){try{t.texImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texImage3D:function(){try{t.texImage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},updateUBOMapping:function(e,n){let i=a.get(n);void 0===i&&(i=new WeakMap,a.set(n,i));let r=i.get(e);void 0===r&&(r=t.getUniformBlockIndex(n,e.name),i.set(e,r))},uniformBlockBinding:function(e,n){const i=a.get(n).get(e);s.get(n)!==i&&(t.uniformBlockBinding(n,i,e.__bindingPointIndex),s.set(n,i))},texStorage2D:function(){try{t.texStorage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texStorage3D:function(){try{t.texStorage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texSubImage2D:function(){try{t.texSubImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texSubImage3D:function(){try{t.texSubImage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},compressedTexSubImage2D:function(){try{t.compressedTexSubImage2D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},compressedTexSubImage3D:function(){try{t.compressedTexSubImage3D.apply(t,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},scissor:function(e){!1===tt.equals(e)&&(t.scissor(e.x,e.y,e.z,e.w),tt.copy(e))},viewport:function(e){!1===et.equals(e)&&(t.viewport(e.x,e.y,e.z,e.w),et.copy(e))},reset:function(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.blendColor(0,0,0,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),i.setReversed(!1),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),o={},J=null,K={},l={},c=new WeakMap,h=[],u=null,d=!1,p=null,m=null,f=null,g=null,v=null,_=null,x=null,b=new Kr(0,0,0),T=0,k=!1,V=null,H=null,G=null,W=null,X=null,tt.set(0,0,t.canvas.width,t.canvas.height),et.set(0,0,t.canvas.width,t.canvas.height),n.reset(),i.reset(),r.reset()}}}function Vl(t,e,n,i){const r=function(t){switch(t){case Et:case At:return{byteLength:1,components:1};case Ct:case Rt:case Ut:return{byteLength:2,components:1};case Dt:case Nt:return{byteLength:2,components:4};case Pt:case It:case Lt:return{byteLength:4,components:1};case Ft:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${t}.`)}(i);switch(n){case Bt:case Vt:return t*e;case Ht:return t*e*2;case Xt:case jt:return t*e/r.components*r.byteLength;case qt:case Yt:return t*e*2/r.components*r.byteLength;case zt:return t*e*3/r.components*r.byteLength;case kt:case Jt:return t*e*4/r.components*r.byteLength;case Kt:case $t:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*8;case Qt:case te:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case ne:case re:return Math.max(t,16)*Math.max(e,8)/4;case ee:case ie:return Math.max(t,8)*Math.max(e,8)/2;case se:case ae:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*8;case oe:case le:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case ce:return Math.floor((t+4)/5)*Math.floor((e+3)/4)*16;case he:return Math.floor((t+4)/5)*Math.floor((e+4)/5)*16;case ue:return Math.floor((t+5)/6)*Math.floor((e+4)/5)*16;case de:return Math.floor((t+5)/6)*Math.floor((e+5)/6)*16;case pe:return Math.floor((t+7)/8)*Math.floor((e+4)/5)*16;case me:return Math.floor((t+7)/8)*Math.floor((e+5)/6)*16;case fe:return Math.floor((t+7)/8)*Math.floor((e+7)/8)*16;case ge:return Math.floor((t+9)/10)*Math.floor((e+4)/5)*16;case ve:return Math.floor((t+9)/10)*Math.floor((e+5)/6)*16;case _e:return Math.floor((t+9)/10)*Math.floor((e+7)/8)*16;case xe:return Math.floor((t+9)/10)*Math.floor((e+9)/10)*16;case ye:return Math.floor((t+11)/12)*Math.floor((e+9)/10)*16;case Me:return Math.floor((t+11)/12)*Math.floor((e+11)/12)*16;case Se:case be:case Te:return Math.ceil(t/4)*Math.ceil(e/4)*16;case we:case Ee:return Math.ceil(t/4)*Math.ceil(e/4)*8;case Ae:case Re:return Math.ceil(t/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${n} format.`)}const Hl={contain:function(t,e){const n=t.image&&t.image.width?t.image.width/t.image.height:1;return n>e?(t.repeat.x=1,t.repeat.y=n/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2):(t.repeat.x=e/n,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0),t},cover:function(t,e){const n=t.image&&t.image.width?t.image.width/t.image.height:1;return n>e?(t.repeat.x=e/n,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0):(t.repeat.x=1,t.repeat.y=n/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2),t},fill:function(t){return t.repeat.x=1,t.repeat.y=1,t.offset.x=0,t.offset.y=0,t},getByteLength:Vl};function Gl(t,e,n,i,r,s,a){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),c=new Jn,h=new WeakMap;let u;const d=new WeakMap;let p=!1;try{p="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(t){}function m(t,e){return p?new OffscreenCanvas(t,e):ni("canvas")}function f(t,e,n){let i=1;const r=V(t);if((r.width>n||r.height>n)&&(i=n/Math.max(r.width,r.height)),i<1){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&t instanceof VideoFrame){const n=Math.floor(i*r.width),s=Math.floor(i*r.height);void 0===u&&(u=m(n,s));const a=e?m(n,s):u;a.width=n,a.height=s;return a.getContext("2d").drawImage(t,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 t&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),t}return t}function g(t){return t.generateMipmaps}function v(e){t.generateMipmap(e)}function _(e){return e.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:e.isWebGL3DRenderTarget?t.TEXTURE_3D:e.isWebGLArrayRenderTarget||e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function x(n,i,r,s,a=!1){if(null!==n){if(void 0!==t[n])return t[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=i;if(i===t.RED&&(r===t.FLOAT&&(o=t.R32F),r===t.HALF_FLOAT&&(o=t.R16F),r===t.UNSIGNED_BYTE&&(o=t.R8)),i===t.RED_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.R8UI),r===t.UNSIGNED_SHORT&&(o=t.R16UI),r===t.UNSIGNED_INT&&(o=t.R32UI),r===t.BYTE&&(o=t.R8I),r===t.SHORT&&(o=t.R16I),r===t.INT&&(o=t.R32I)),i===t.RG&&(r===t.FLOAT&&(o=t.RG32F),r===t.HALF_FLOAT&&(o=t.RG16F),r===t.UNSIGNED_BYTE&&(o=t.RG8)),i===t.RG_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RG8UI),r===t.UNSIGNED_SHORT&&(o=t.RG16UI),r===t.UNSIGNED_INT&&(o=t.RG32UI),r===t.BYTE&&(o=t.RG8I),r===t.SHORT&&(o=t.RG16I),r===t.INT&&(o=t.RG32I)),i===t.RGB_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RGB8UI),r===t.UNSIGNED_SHORT&&(o=t.RGB16UI),r===t.UNSIGNED_INT&&(o=t.RGB32UI),r===t.BYTE&&(o=t.RGB8I),r===t.SHORT&&(o=t.RGB16I),r===t.INT&&(o=t.RGB32I)),i===t.RGBA_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RGBA8UI),r===t.UNSIGNED_SHORT&&(o=t.RGBA16UI),r===t.UNSIGNED_INT&&(o=t.RGBA32UI),r===t.BYTE&&(o=t.RGBA8I),r===t.SHORT&&(o=t.RGBA16I),r===t.INT&&(o=t.RGBA32I)),i===t.RGB&&r===t.UNSIGNED_INT_5_9_9_9_REV&&(o=t.RGB9_E5),i===t.RGBA){const e=a?$e:ai.getTransfer(s);r===t.FLOAT&&(o=t.RGBA32F),r===t.HALF_FLOAT&&(o=t.RGBA16F),r===t.UNSIGNED_BYTE&&(o=e===Qe?t.SRGB8_ALPHA8:t.RGBA8),r===t.UNSIGNED_SHORT_4_4_4_4&&(o=t.RGBA4),r===t.UNSIGNED_SHORT_5_5_5_1&&(o=t.RGB5_A1)}return o!==t.R16F&&o!==t.R32F&&o!==t.RG16F&&o!==t.RG32F&&o!==t.RGBA16F&&o!==t.RGBA32F||e.get("EXT_color_buffer_float"),o}function y(e,n){let i;return e?null===n||n===Pt||n===Ot?i=t.DEPTH24_STENCIL8:n===Lt?i=t.DEPTH32F_STENCIL8:n===Ct&&(i=t.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===Pt||n===Ot?i=t.DEPTH_COMPONENT24:n===Lt?i=t.DEPTH_COMPONENT32F:n===Ct&&(i=t.DEPTH_COMPONENT16),i}function M(t,e){return!0===g(t)||t.isFramebufferTexture&&t.minFilter!==gt&&t.minFilter!==Mt?Math.log2(Math.max(e.width,e.height))+1:void 0!==t.mipmaps&&t.mipmaps.length>0?t.mipmaps.length:t.isCompressedTexture&&Array.isArray(t.image)?e.mipmaps.length:1}function S(t){const e=t.target;e.removeEventListener("dispose",S),function(t){const e=i.get(t);if(void 0===e.__webglInit)return;const n=t.source,r=d.get(n);if(r){const i=r[e.__cacheKey];i.usedTimes--,0===i.usedTimes&&T(t),0===Object.keys(r).length&&d.delete(n)}i.remove(t)}(e),e.isVideoTexture&&h.delete(e)}function b(e){const n=e.target;n.removeEventListener("dispose",b),function(e){const n=i.get(e);e.depthTexture&&(e.depthTexture.dispose(),i.remove(e.depthTexture));if(e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++){if(Array.isArray(n.__webglFramebuffer[e]))for(let i=0;i<n.__webglFramebuffer[e].length;i++)t.deleteFramebuffer(n.__webglFramebuffer[e][i]);else t.deleteFramebuffer(n.__webglFramebuffer[e]);n.__webglDepthbuffer&&t.deleteRenderbuffer(n.__webglDepthbuffer[e])}else{if(Array.isArray(n.__webglFramebuffer))for(let e=0;e<n.__webglFramebuffer.length;e++)t.deleteFramebuffer(n.__webglFramebuffer[e]);else t.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&t.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&t.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let e=0;e<n.__webglColorRenderbuffer.length;e++)n.__webglColorRenderbuffer[e]&&t.deleteRenderbuffer(n.__webglColorRenderbuffer[e]);n.__webglDepthRenderbuffer&&t.deleteRenderbuffer(n.__webglDepthRenderbuffer)}const r=e.textures;for(let e=0,n=r.length;e<n;e++){const n=i.get(r[e]);n.__webglTexture&&(t.deleteTexture(n.__webglTexture),a.memory.textures--),i.remove(r[e])}i.remove(e)}(n)}function T(e){const n=i.get(e);t.deleteTexture(n.__webglTexture);const r=e.source;delete d.get(r)[n.__cacheKey],a.memory.textures--}let w=0;function E(e,r){const s=i.get(e);if(e.isVideoTexture&&function(t){const e=a.render.frame;h.get(t)!==e&&(h.set(t,e),t.update())}(e),!1===e.isRenderTargetTexture&&e.version>0&&s.__version!==e.version){const t=e.image;if(null===t)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==t.complete)return void L(s,e,r);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.bindTexture(t.TEXTURE_2D,s.__webglTexture,t.TEXTURE0+r)}const A={[pt]:t.REPEAT,[mt]:t.CLAMP_TO_EDGE,[ft]:t.MIRRORED_REPEAT},R={[gt]:t.NEAREST,[vt]:t.NEAREST_MIPMAP_NEAREST,[xt]:t.NEAREST_MIPMAP_LINEAR,[Mt]:t.LINEAR,[St]:t.LINEAR_MIPMAP_NEAREST,[Tt]:t.LINEAR_MIPMAP_LINEAR},C={[vn]:t.NEVER,[Tn]:t.ALWAYS,[_n]:t.LESS,[yn]:t.LEQUAL,[xn]:t.EQUAL,[bn]:t.GEQUAL,[Mn]:t.GREATER,[Sn]:t.NOTEQUAL};function I(n,s){if(s.type!==Lt||!1!==e.has("OES_texture_float_linear")||s.magFilter!==Mt&&s.magFilter!==St&&s.magFilter!==xt&&s.magFilter!==Tt&&s.minFilter!==Mt&&s.minFilter!==St&&s.minFilter!==xt&&s.minFilter!==Tt||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(n,t.TEXTURE_WRAP_S,A[s.wrapS]),t.texParameteri(n,t.TEXTURE_WRAP_T,A[s.wrapT]),n!==t.TEXTURE_3D&&n!==t.TEXTURE_2D_ARRAY||t.texParameteri(n,t.TEXTURE_WRAP_R,A[s.wrapR]),t.texParameteri(n,t.TEXTURE_MAG_FILTER,R[s.magFilter]),t.texParameteri(n,t.TEXTURE_MIN_FILTER,R[s.minFilter]),s.compareFunction&&(t.texParameteri(n,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(n,t.TEXTURE_COMPARE_FUNC,C[s.compareFunction])),!0===e.has("EXT_texture_filter_anisotropic")){if(s.magFilter===gt)return;if(s.minFilter!==xt&&s.minFilter!==Tt)return;if(s.type===Lt&&!1===e.has("OES_texture_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=e.get("EXT_texture_filter_anisotropic");t.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function P(e,n){let i=!1;void 0===e.__webglInit&&(e.__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(t){const e=[];return e.push(t.wrapS),e.push(t.wrapT),e.push(t.wrapR||0),e.push(t.magFilter),e.push(t.minFilter),e.push(t.anisotropy),e.push(t.internalFormat),e.push(t.format),e.push(t.type),e.push(t.generateMipmaps),e.push(t.premultiplyAlpha),e.push(t.flipY),e.push(t.unpackAlignment),e.push(t.colorSpace),e.join()}(n);if(o!==e.__cacheKey){void 0===s[o]&&(s[o]={texture:t.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[e.__cacheKey];void 0!==r&&(s[e.__cacheKey].usedTimes--,0===r.usedTimes&&T(n)),e.__cacheKey=o,e.__webglTexture=s[o].texture}return i}function L(e,a,o){let l=t.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=t.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=t.TEXTURE_3D);const c=P(e,a),h=a.source;n.bindTexture(l,e.__webglTexture,t.TEXTURE0+o);const u=i.get(h);if(h.version!==u.__version||!0===c){n.activeTexture(t.TEXTURE0+o);const e=ai.getPrimaries(ai.workingColorSpace),i=a.colorSpace===Ze?null:ai.getPrimaries(a.colorSpace),d=a.colorSpace===Ze||e===i?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,a.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,a.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let p=f(a.image,!1,r.maxTextureSize);p=k(a,p);const m=s.convert(a.format,a.colorSpace),_=s.convert(a.type);let S,b=x(a.internalFormat,m,_,a.colorSpace,a.isVideoTexture);I(l,a);const T=a.mipmaps,w=!0!==a.isVideoTexture,E=void 0===u.__version||!0===c,A=h.dataReady,R=M(a,p);if(a.isDepthTexture)b=y(a.format===Wt,a.type),E&&(w?n.texStorage2D(t.TEXTURE_2D,1,b,p.width,p.height):n.texImage2D(t.TEXTURE_2D,0,b,p.width,p.height,0,m,_,null));else if(a.isDataTexture)if(T.length>0){w&&E&&n.texStorage2D(t.TEXTURE_2D,R,b,T[0].width,T[0].height);for(let e=0,i=T.length;e<i;e++)S=T[e],w?A&&n.texSubImage2D(t.TEXTURE_2D,e,0,0,S.width,S.height,m,_,S.data):n.texImage2D(t.TEXTURE_2D,e,b,S.width,S.height,0,m,_,S.data);a.generateMipmaps=!1}else w?(E&&n.texStorage2D(t.TEXTURE_2D,R,b,p.width,p.height),A&&n.texSubImage2D(t.TEXTURE_2D,0,0,0,p.width,p.height,m,_,p.data)):n.texImage2D(t.TEXTURE_2D,0,b,p.width,p.height,0,m,_,p.data);else if(a.isCompressedTexture)if(a.isCompressedArrayTexture){w&&E&&n.texStorage3D(t.TEXTURE_2D_ARRAY,R,b,T[0].width,T[0].height,p.depth);for(let e=0,i=T.length;e<i;e++)if(S=T[e],a.format!==kt)if(null!==m)if(w){if(A)if(a.layerUpdates.size>0){const i=Vl(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(t.TEXTURE_2D_ARRAY,e,0,0,r,S.width,S.height,1,m,s)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,S.width,S.height,p.depth,m,S.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,e,b,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 w?A&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,S.width,S.height,p.depth,m,_,S.data):n.texImage3D(t.TEXTURE_2D_ARRAY,e,b,S.width,S.height,p.depth,0,m,_,S.data)}else{w&&E&&n.texStorage2D(t.TEXTURE_2D,R,b,T[0].width,T[0].height);for(let e=0,i=T.length;e<i;e++)S=T[e],a.format!==kt?null!==m?w?A&&n.compressedTexSubImage2D(t.TEXTURE_2D,e,0,0,S.width,S.height,m,S.data):n.compressedTexImage2D(t.TEXTURE_2D,e,b,S.width,S.height,0,S.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):w?A&&n.texSubImage2D(t.TEXTURE_2D,e,0,0,S.width,S.height,m,_,S.data):n.texImage2D(t.TEXTURE_2D,e,b,S.width,S.height,0,m,_,S.data)}else if(a.isDataArrayTexture)if(w){if(E&&n.texStorage3D(t.TEXTURE_2D_ARRAY,R,b,p.width,p.height,p.depth),A)if(a.layerUpdates.size>0){const e=Vl(p.width,p.height,a.format,a.type);for(const i of a.layerUpdates){const r=p.data.subarray(i*e/p.data.BYTES_PER_ELEMENT,(i+1)*e/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,i,p.width,p.height,1,m,_,r)}a.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,m,_,p.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,b,p.width,p.height,p.depth,0,m,_,p.data);else if(a.isData3DTexture)w?(E&&n.texStorage3D(t.TEXTURE_3D,R,b,p.width,p.height,p.depth),A&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,m,_,p.data)):n.texImage3D(t.TEXTURE_3D,0,b,p.width,p.height,p.depth,0,m,_,p.data);else if(a.isFramebufferTexture){if(E)if(w)n.texStorage2D(t.TEXTURE_2D,R,b,p.width,p.height);else{let e=p.width,i=p.height;for(let r=0;r<R;r++)n.texImage2D(t.TEXTURE_2D,r,b,e,i,0,m,_,null),e>>=1,i>>=1}}else if(T.length>0){if(w&&E){const e=V(T[0]);n.texStorage2D(t.TEXTURE_2D,R,b,e.width,e.height)}for(let e=0,i=T.length;e<i;e++)S=T[e],w?A&&n.texSubImage2D(t.TEXTURE_2D,e,0,0,m,_,S):n.texImage2D(t.TEXTURE_2D,e,b,m,_,S);a.generateMipmaps=!1}else if(w){if(E){const e=V(p);n.texStorage2D(t.TEXTURE_2D,R,b,e.width,e.height)}A&&n.texSubImage2D(t.TEXTURE_2D,0,0,0,m,_,p)}else n.texImage2D(t.TEXTURE_2D,0,b,m,_,p);g(a)&&v(l),u.__version=h.version,a.onUpdate&&a.onUpdate(a)}e.__version=a.version}function U(e,r,a,l,c,h){const u=s.convert(a.format,a.colorSpace),d=s.convert(a.type),p=x(a.internalFormat,u,d,a.colorSpace),m=i.get(r),f=i.get(a);if(f.__renderTarget=r,!m.__hasExternalTextures){const e=Math.max(1,r.width>>h),i=Math.max(1,r.height>>h);c===t.TEXTURE_3D||c===t.TEXTURE_2D_ARRAY?n.texImage3D(c,h,p,e,i,r.depth,0,u,d,null):n.texImage2D(c,h,p,e,i,0,u,d,null)}n.bindFramebuffer(t.FRAMEBUFFER,e),z(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,l,c,f.__webglTexture,0,B(r)):(c===t.TEXTURE_2D||c>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,l,c,f.__webglTexture,h),n.bindFramebuffer(t.FRAMEBUFFER,null)}function D(e,n,i){if(t.bindRenderbuffer(t.RENDERBUFFER,e),n.depthBuffer){const r=n.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=y(n.stencilBuffer,s),l=n.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,c=B(n);z(n)?o.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,c,a,n.width,n.height):i?t.renderbufferStorageMultisample(t.RENDERBUFFER,c,a,n.width,n.height):t.renderbufferStorage(t.RENDERBUFFER,a,n.width,n.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,l,t.RENDERBUFFER,e)}else{const e=n.textures;for(let r=0;r<e.length;r++){const a=e[r],l=s.convert(a.format,a.colorSpace),c=s.convert(a.type),h=x(a.internalFormat,l,c,a.colorSpace),u=B(n);i&&!1===z(n)?t.renderbufferStorageMultisample(t.RENDERBUFFER,u,h,n.width,n.height):z(n)?o.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,u,h,n.width,n.height):t.renderbufferStorage(t.RENDERBUFFER,h,n.width,n.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function N(e){const r=i.get(e),s=!0===e.isWebGLCubeRenderTarget;if(r.__boundDepthTexture!==e.depthTexture){const t=e.depthTexture;if(r.__depthDisposeCallback&&r.__depthDisposeCallback(),t){const e=()=>{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,t.removeEventListener("dispose",e)};t.addEventListener("dispose",e),r.__depthDisposeCallback=e}r.__boundDepthTexture=t}if(e.depthTexture&&!r.__autoAllocateDepthBuffer){if(s)throw new Error("target.depthTexture not supported in Cube render targets");!function(e,r){if(r&&r.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,e),!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),E(r.depthTexture,0);const a=s.__webglTexture,l=B(r);if(r.depthTexture.format===Gt)z(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,a,0,l):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,a,0);else{if(r.depthTexture.format!==Wt)throw new Error("Unknown depthTexture format");z(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,a,0,l):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,a,0)}}(r.__webglFramebuffer,e)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(t.FRAMEBUFFER,r.__webglFramebuffer[i]),void 0===r.__webglDepthbuffer[i])r.__webglDepthbuffer[i]=t.createRenderbuffer(),D(r.__webglDepthbuffer[i],e,!1);else{const n=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[i];t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,s)}}else if(n.bindFramebuffer(t.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=t.createRenderbuffer(),D(r.__webglDepthbuffer,e,!1);else{const n=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,i=r.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,i),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,i)}n.bindFramebuffer(t.FRAMEBUFFER,null)}const O=[],F=[];function B(t){return Math.min(r.maxSamples,t.samples)}function z(t){const n=i.get(t);return t.samples>0&&!0===e.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function k(t,e){const n=t.colorSpace,i=t.format,r=t.type;return!0===t.isCompressedTexture||!0===t.isVideoTexture||n!==Ke&&n!==Ze&&(ai.getTransfer(n)===Qe?i===kt&&r===Et||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",n)),e}function V(t){return"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement?(c.width=t.naturalWidth||t.width,c.height=t.naturalHeight||t.height):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?(c.width=t.displayWidth,c.height=t.displayHeight):(c.width=t.width,c.height=t.height),c}this.allocateTextureUnit=function(){const t=w;return t>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+t+" texture units while this GPU supports only "+r.maxTextures),w+=1,t},this.resetTextureUnits=function(){w=0},this.setTexture2D=E,this.setTexture2DArray=function(e,r){const s=i.get(e);e.version>0&&s.__version!==e.version?L(s,e,r):n.bindTexture(t.TEXTURE_2D_ARRAY,s.__webglTexture,t.TEXTURE0+r)},this.setTexture3D=function(e,r){const s=i.get(e);e.version>0&&s.__version!==e.version?L(s,e,r):n.bindTexture(t.TEXTURE_3D,s.__webglTexture,t.TEXTURE0+r)},this.setTextureCube=function(e,a){const o=i.get(e);e.version>0&&o.__version!==e.version?function(e,a,o){if(6!==a.image.length)return;const l=P(e,a),c=a.source;n.bindTexture(t.TEXTURE_CUBE_MAP,e.__webglTexture,t.TEXTURE0+o);const h=i.get(c);if(c.version!==h.__version||!0===l){n.activeTexture(t.TEXTURE0+o);const e=ai.getPrimaries(ai.workingColorSpace),i=a.colorSpace===Ze?null:ai.getPrimaries(a.colorSpace),u=a.colorSpace===Ze||e===i?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,a.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,a.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,u);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,m=[];for(let t=0;t<6;t++)m[t]=d||p?p?a.image[t].image:a.image[t]:f(a.image[t],!0,r.maxCubemapSize),m[t]=k(a,m[t]);const _=m[0],y=s.convert(a.format,a.colorSpace),S=s.convert(a.type),b=x(a.internalFormat,y,S,a.colorSpace),T=!0!==a.isVideoTexture,w=void 0===h.__version||!0===l,E=c.dataReady;let A,R=M(a,_);if(I(t.TEXTURE_CUBE_MAP,a),d){T&&w&&n.texStorage2D(t.TEXTURE_CUBE_MAP,R,b,_.width,_.height);for(let e=0;e<6;e++){A=m[e].mipmaps;for(let i=0;i<A.length;i++){const r=A[i];a.format!==kt?null!==y?T?E&&n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,i,0,0,r.width,r.height,y,r.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,i,b,r.width,r.height,0,r.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):T?E&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,i,0,0,r.width,r.height,y,S,r.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,i,b,r.width,r.height,0,y,S,r.data)}}}else{if(A=a.mipmaps,T&&w){A.length>0&&R++;const e=V(m[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,R,b,e.width,e.height)}for(let e=0;e<6;e++)if(p){T?E&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,m[e].width,m[e].height,y,S,m[e].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,b,m[e].width,m[e].height,0,y,S,m[e].data);for(let i=0;i<A.length;i++){const r=A[i].image[e].image;T?E&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,i+1,0,0,r.width,r.height,y,S,r.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,i+1,b,r.width,r.height,0,y,S,r.data)}}else{T?E&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,y,S,m[e]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,b,y,S,m[e]);for(let i=0;i<A.length;i++){const r=A[i];T?E&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,i+1,0,0,y,S,r.image[e]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,i+1,b,y,S,r.image[e])}}}g(a)&&v(t.TEXTURE_CUBE_MAP),h.__version=c.version,a.onUpdate&&a.onUpdate(a)}e.__version=a.version}(o,e,a):n.bindTexture(t.TEXTURE_CUBE_MAP,o.__webglTexture,t.TEXTURE0+a)},this.rebindTextures=function(e,n,r){const s=i.get(e);void 0!==n&&U(s.__webglFramebuffer,e,e.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),void 0!==r&&N(e)},this.setupRenderTarget=function(e){const r=e.texture,o=i.get(e),l=i.get(r);e.addEventListener("dispose",b);const c=e.textures,h=!0===e.isWebGLCubeRenderTarget,u=c.length>1;if(u||(void 0===l.__webglTexture&&(l.__webglTexture=t.createTexture()),l.__version=r.version,a.memory.textures++),h){o.__webglFramebuffer=[];for(let e=0;e<6;e++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[e]=[];for(let n=0;n<r.mipmaps.length;n++)o.__webglFramebuffer[e][n]=t.createFramebuffer()}else o.__webglFramebuffer[e]=t.createFramebuffer()}else{if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer=[];for(let e=0;e<r.mipmaps.length;e++)o.__webglFramebuffer[e]=t.createFramebuffer()}else o.__webglFramebuffer=t.createFramebuffer();if(u)for(let e=0,n=c.length;e<n;e++){const n=i.get(c[e]);void 0===n.__webglTexture&&(n.__webglTexture=t.createTexture(),a.memory.textures++)}if(e.samples>0&&!1===z(e)){o.__webglMultisampledFramebuffer=t.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n<c.length;n++){const i=c[n];o.__webglColorRenderbuffer[n]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,o.__webglColorRenderbuffer[n]);const r=s.convert(i.format,i.colorSpace),a=s.convert(i.type),l=x(i.internalFormat,r,a,i.colorSpace,!0===e.isXRRenderTarget),h=B(e);t.renderbufferStorageMultisample(t.RENDERBUFFER,h,l,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+n,t.RENDERBUFFER,o.__webglColorRenderbuffer[n])}t.bindRenderbuffer(t.RENDERBUFFER,null),e.depthBuffer&&(o.__webglDepthRenderbuffer=t.createRenderbuffer(),D(o.__webglDepthRenderbuffer,e,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(h){n.bindTexture(t.TEXTURE_CUBE_MAP,l.__webglTexture),I(t.TEXTURE_CUBE_MAP,r);for(let n=0;n<6;n++)if(r.mipmaps&&r.mipmaps.length>0)for(let i=0;i<r.mipmaps.length;i++)U(o.__webglFramebuffer[n][i],e,r,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,i);else U(o.__webglFramebuffer[n],e,r,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);g(r)&&v(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(u){for(let r=0,s=c.length;r<s;r++){const s=c[r],a=i.get(s);n.bindTexture(t.TEXTURE_2D,a.__webglTexture),I(t.TEXTURE_2D,s),U(o.__webglFramebuffer,e,s,t.COLOR_ATTACHMENT0+r,t.TEXTURE_2D,0),g(s)&&v(t.TEXTURE_2D)}n.unbindTexture()}else{let i=t.TEXTURE_2D;if((e.isWebGL3DRenderTarget||e.isWebGLArrayRenderTarget)&&(i=e.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(i,l.__webglTexture),I(i,r),r.mipmaps&&r.mipmaps.length>0)for(let n=0;n<r.mipmaps.length;n++)U(o.__webglFramebuffer[n],e,r,t.COLOR_ATTACHMENT0,i,n);else U(o.__webglFramebuffer,e,r,t.COLOR_ATTACHMENT0,i,0);g(r)&&v(i),n.unbindTexture()}e.depthBuffer&&N(e)},this.updateRenderTargetMipmap=function(t){const e=t.textures;for(let r=0,s=e.length;r<s;r++){const s=e[r];if(g(s)){const e=_(t),r=i.get(s).__webglTexture;n.bindTexture(e,r),v(e),n.unbindTexture()}}},this.updateMultisampleRenderTarget=function(e){if(e.samples>0)if(!1===z(e)){const r=e.textures,s=e.width,a=e.height;let o=t.COLOR_BUFFER_BIT;const c=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,h=i.get(e),u=r.length>1;if(u)for(let e=0;e<r.length;e++)n.bindFramebuffer(t.FRAMEBUFFER,h.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,h.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,h.__webglMultisampledFramebuffer),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,h.__webglFramebuffer);for(let n=0;n<r.length;n++){if(e.resolveDepthBuffer&&(e.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),e.stencilBuffer&&e.resolveStencilBuffer&&(o|=t.STENCIL_BUFFER_BIT)),u){t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,h.__webglColorRenderbuffer[n]);const e=i.get(r[n]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}t.blitFramebuffer(0,0,s,a,0,0,s,a,o,t.NEAREST),!0===l&&(O.length=0,F.length=0,O.push(t.COLOR_ATTACHMENT0+n),e.depthBuffer&&!1===e.resolveDepthBuffer&&(O.push(c),F.push(c),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,F)),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,O))}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),u)for(let e=0;e<r.length;e++){n.bindFramebuffer(t.FRAMEBUFFER,h.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,h.__webglColorRenderbuffer[e]);const s=i.get(r[e]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,h.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,s,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,h.__webglMultisampledFramebuffer)}else if(e.depthBuffer&&!1===e.resolveDepthBuffer&&l){const n=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[n])}},this.setupDepthRenderbuffer=N,this.setupFrameBufferTexture=U,this.useMultisampledRTT=z}function Wl(t,e){return{convert:function(n,i=""){let r;const s=ai.getTransfer(i);if(n===Et)return t.UNSIGNED_BYTE;if(n===Dt)return t.UNSIGNED_SHORT_4_4_4_4;if(n===Nt)return t.UNSIGNED_SHORT_5_5_5_1;if(n===Ft)return t.UNSIGNED_INT_5_9_9_9_REV;if(n===At)return t.BYTE;if(n===Rt)return t.SHORT;if(n===Ct)return t.UNSIGNED_SHORT;if(n===It)return t.INT;if(n===Pt)return t.UNSIGNED_INT;if(n===Lt)return t.FLOAT;if(n===Ut)return t.HALF_FLOAT;if(n===Bt)return t.ALPHA;if(n===zt)return t.RGB;if(n===kt)return t.RGBA;if(n===Vt)return t.LUMINANCE;if(n===Ht)return t.LUMINANCE_ALPHA;if(n===Gt)return t.DEPTH_COMPONENT;if(n===Wt)return t.DEPTH_STENCIL;if(n===Xt)return t.RED;if(n===jt)return t.RED_INTEGER;if(n===qt)return t.RG;if(n===Yt)return t.RG_INTEGER;if(n===Jt)return t.RGBA_INTEGER;if(n===Kt||n===$t||n===Qt||n===te)if(s===Qe){if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(n===Kt)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===$t)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Qt)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===te)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=e.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(n===Kt)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===$t)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Qt)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===te)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(n===ee||n===ne||n===ie||n===re){if(r=e.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(n===ee)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===ne)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===ie)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===re)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(n===se||n===ae||n===oe){if(r=e.get("WEBGL_compressed_texture_etc"),null===r)return null;if(n===se||n===ae)return s===Qe?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===oe)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}if(n===le||n===ce||n===he||n===ue||n===de||n===pe||n===me||n===fe||n===ge||n===ve||n===_e||n===xe||n===ye||n===Me){if(r=e.get("WEBGL_compressed_texture_astc"),null===r)return null;if(n===le)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===ce)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===he)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===ue)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===de)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===pe)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===me)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===fe)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===ge)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===ve)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===_e)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===xe)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===ye)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Me)return s===Qe?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(n===Se||n===be||n===Te){if(r=e.get("EXT_texture_compression_bptc"),null===r)return null;if(n===Se)return s===Qe?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===be)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Te)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(n===we||n===Ee||n===Ae||n===Re){if(r=e.get("EXT_texture_compression_rgtc"),null===r)return null;if(n===Se)return r.COMPRESSED_RED_RGTC1_EXT;if(n===Ee)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Ae)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Re)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return n===Ot?t.UNSIGNED_INT_24_8:void 0!==t[n]?t[n]:null}}}class Xl extends Js{constructor(t=[]){super(),this.isArrayCamera=!0,this.cameras=t}}class jl extends Lr{constructor(){super(),this.isGroup=!0,this.type="Group"}}const ql={type:"move"};class Yl{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new jl,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 jl,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Ci,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Ci),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new jl,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Ci,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Ci),this._grip}dispatchEvent(t){return null!==this._targetRay&&this._targetRay.dispatchEvent(t),null!==this._grip&&this._grip.dispatchEvent(t),null!==this._hand&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){const e=this._hand;if(e)for(const n of t.hand.values())this._getHandJoint(e,n)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(t,e,n){let i=null,r=null,s=null;const a=this._targetRay,o=this._grip,l=this._hand;if(t&&"visible-blurred"!==e.session.visibilityState){if(l&&t.hand){s=!0;for(const i of t.hand.values()){const t=e.getJointPose(i,n),r=this._getHandJoint(l,i);null!==t&&(r.matrix.fromArray(t.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=t.radius),r.visible=null!==t}const i=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,c=.005;l.inputState.pinching&&a>o+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(r=e.getPose(t.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=e.getPose(t.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(ql)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(t,e){if(void 0===t.joints[e.jointName]){const n=new jl;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}}class Zl{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e,n){if(null===this.texture){const i=new yi;t.properties.get(i).__webglTexture=e.texture,e.depthNear==n.depthNear&&e.depthFar==n.depthFar||(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(t){if(null!==this.texture&&null===this.mesh){const e=t.cameras[0].viewport,n=new Xs({vertexShader:"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}",fragmentShader:"\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n\tvec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n\tif ( coord.x >= 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:e.z},depthHeight:{value:e.w}}});this.mesh=new Bs(new ha(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Jl extends Bn{constructor(t,e){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,c=null,h=null,u=null,d=null,p=null;const m=new Zl,f=e.getContextAttributes();let g=null,v=null;const _=[],x=[],y=new Jn;let M=null;const S=new Js;S.viewport=new Mi;const b=new Js;b.viewport=new Mi;const T=[S,b],w=new Xl;let E=null,A=null;function R(t){const e=x.indexOf(t.inputSource);if(-1===e)return;const n=_[e];void 0!==n&&(n.update(t.inputSource,t.frame,l||s),n.dispatchEvent({type:t.type,data:t.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",I);for(let t=0;t<_.length;t++){const e=x[t];null!==e&&(x[t]=null,_[t].disconnect(e))}E=null,A=null,m.reset(),t.setRenderTarget(g),d=null,u=null,h=null,i=null,v=null,N.stop(),n.isPresenting=!1,t.setPixelRatio(M),t.setSize(y.width,y.height,!1),n.dispatchEvent({type:"sessionend"})}function I(t){for(let e=0;e<t.removed.length;e++){const n=t.removed[e],i=x.indexOf(n);i>=0&&(x[i]=null,_[i].disconnect(n))}for(let e=0;e<t.added.length;e++){const n=t.added[e];let i=x.indexOf(n);if(-1===i){for(let t=0;t<_.length;t++){if(t>=x.length){x.push(n),i=t;break}if(null===x[t]){x[t]=n,i=t;break}}if(-1===i)break}const r=_[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(t){let e=_[t];return void 0===e&&(e=new Yl,_[t]=e),e.getTargetRaySpace()},this.getControllerGrip=function(t){let e=_[t];return void 0===e&&(e=new Yl,_[t]=e),e.getGripSpace()},this.getHand=function(t){let e=_[t];return void 0===e&&(e=new Yl,_[t]=e),e.getHandSpace()},this.setFramebufferScaleFactor=function(t){r=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(t){a=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(t){l=t},this.getBaseLayer=function(){return null!==u?u:d},this.getBinding=function(){return h},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(c){if(i=c,null!==i){if(g=t.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",I),!0!==f.xrCompatible&&await e.makeXRCompatible(),M=t.getPixelRatio(),t.getSize(y),void 0===i.renderState.layers){const n={antialias:f.antialias,alpha:!0,depth:f.depth,stencil:f.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,e,n),i.updateRenderState({baseLayer:d}),t.setPixelRatio(1),t.setSize(d.framebufferWidth,d.framebufferHeight,!1),v=new bi(d.framebufferWidth,d.framebufferHeight,{format:kt,type:Et,colorSpace:t.outputColorSpace,stencilBuffer:f.stencil})}else{let n=null,s=null,a=null;f.depth&&(a=f.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,n=f.stencil?Wt:Gt,s=f.stencil?Ot:Pt);const o={colorFormat:e.RGBA8,depthFormat:a,scaleFactor:r};h=new XRWebGLBinding(i,e),u=h.createProjectionLayer(o),i.updateRenderState({layers:[u]}),t.setPixelRatio(1),t.setSize(u.textureWidth,u.textureHeight,!1),v=new bi(u.textureWidth,u.textureHeight,{format:kt,type:Et,depthTexture:new Ya(u.textureWidth,u.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:f.stencil,colorSpace:t.outputColorSpace,samples:f.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues})}v.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),N.setContext(i),N.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};const P=new Ci,L=new Ci;function U(t,e){null===e?t.matrixWorld.copy(t.matrix):t.matrixWorld.multiplyMatrices(e.matrixWorld,t.matrix),t.matrixWorldInverse.copy(t.matrixWorld).invert()}this.updateCamera=function(t){if(null===i)return;let e=t.near,n=t.far;null!==m.texture&&(m.depthNear>0&&(e=m.depthNear),m.depthFar>0&&(n=m.depthFar)),w.near=b.near=S.near=e,w.far=b.far=S.far=n,E===w.near&&A===w.far||(i.updateRenderState({depthNear:w.near,depthFar:w.far}),E=w.near,A=w.far),S.layers.mask=2|t.layers.mask,b.layers.mask=4|t.layers.mask,w.layers.mask=S.layers.mask|b.layers.mask;const r=t.parent,s=w.cameras;U(w,r);for(let t=0;t<s.length;t++)U(s[t],r);2===s.length?function(t,e,n){P.setFromMatrixPosition(e.matrixWorld),L.setFromMatrixPosition(n.matrixWorld);const i=P.distanceTo(L),r=e.projectionMatrix.elements,s=n.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),l=(r[9]+1)/r[5],c=(r[9]-1)/r[5],h=(r[8]-1)/r[0],u=(s[8]+1)/s[0],d=a*h,p=a*u,m=i/(-h+u),f=m*-h;if(e.matrixWorld.decompose(t.position,t.quaternion,t.scale),t.translateX(f),t.translateZ(m),t.matrixWorld.compose(t.position,t.quaternion,t.scale),t.matrixWorldInverse.copy(t.matrixWorld).invert(),-1===r[10])t.projectionMatrix.copy(e.projectionMatrix),t.projectionMatrixInverse.copy(e.projectionMatrixInverse);else{const e=a+m,n=o+m,r=d-f,s=p+(i-f),h=l*o/n*e,u=c*o/n*e;t.projectionMatrix.makePerspective(r,s,h,u,e,n),t.projectionMatrixInverse.copy(t.projectionMatrix).invert()}}(w,S,b):w.projectionMatrix.copy(S.projectionMatrix),function(t,e,n){null===n?t.matrix.copy(e.matrixWorld):(t.matrix.copy(n.matrixWorld),t.matrix.invert(),t.matrix.multiply(e.matrixWorld));t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(!0),t.projectionMatrix.copy(e.projectionMatrix),t.projectionMatrixInverse.copy(e.projectionMatrixInverse),t.isPerspectiveCamera&&(t.fov=2*Hn*Math.atan(1/t.projectionMatrix.elements[5]),t.zoom=1)}(t,w,r)},this.getCamera=function(){return w},this.getFoveation=function(){if(null!==u||null!==d)return o},this.setFoveation=function(t){o=t,null!==u&&(u.fixedFoveation=t),null!==d&&void 0!==d.fixedFoveation&&(d.fixedFoveation=t)},this.hasDepthSensing=function(){return null!==m.texture},this.getDepthSensingMesh=function(){return m.getMesh(w)};let D=null;const N=new la;N.setAnimationLoop((function(e,r){if(c=r.getViewerPose(l||s),p=r,null!==c){const e=c.views;null!==d&&(t.setRenderTargetFramebuffer(v,d.framebuffer),t.setRenderTarget(v));let n=!1;e.length!==w.cameras.length&&(w.cameras.length=0,n=!0);for(let i=0;i<e.length;i++){const r=e[i];let s=null;if(null!==d)s=d.getViewport(r);else{const e=h.getViewSubImage(u,r);s=e.viewport,0===i&&(t.setRenderTargetTextures(v,e.colorTexture,u.ignoreDepthValues?void 0:e.depthStencilTexture),t.setRenderTarget(v))}let a=T[i];void 0===a&&(a=new Js,a.layers.enable(i),a.viewport=new Mi,T[i]=a),a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(r.projectionMatrix),a.projectionMatrixInverse.copy(a.projectionMatrix).invert(),a.viewport.set(s.x,s.y,s.width,s.height),0===i&&(w.matrix.copy(a.matrix),w.matrix.decompose(w.position,w.quaternion,w.scale)),!0===n&&w.cameras.push(a)}const r=i.enabledFeatures;if(r&&r.includes("depth-sensing")){const n=h.getDepthInformation(e[0]);n&&n.isValid&&n.texture&&m.init(t,n,i.renderState)}}for(let t=0;t<_.length;t++){const e=x[t],n=_[t];null!==e&&void 0!==n&&n.update(e,r,l||s)}D&&D(e,r),r.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:r}),p=null})),this.setAnimationLoop=function(t){D=t},this.dispose=function(){}}}const Kl=new fr,$l=new sr;function Ql(t,e){function n(t,e){!0===t.matrixAutoUpdate&&t.updateMatrix(),e.value.copy(t.matrix)}function i(t,i){t.opacity.value=i.opacity,i.color&&t.diffuse.value.copy(i.color),i.emissive&&t.emissive.value.copy(i.emissive).multiplyScalar(i.emissiveIntensity),i.map&&(t.map.value=i.map,n(i.map,t.mapTransform)),i.alphaMap&&(t.alphaMap.value=i.alphaMap,n(i.alphaMap,t.alphaMapTransform)),i.bumpMap&&(t.bumpMap.value=i.bumpMap,n(i.bumpMap,t.bumpMapTransform),t.bumpScale.value=i.bumpScale,1===i.side&&(t.bumpScale.value*=-1)),i.normalMap&&(t.normalMap.value=i.normalMap,n(i.normalMap,t.normalMapTransform),t.normalScale.value.copy(i.normalScale),1===i.side&&t.normalScale.value.negate()),i.displacementMap&&(t.displacementMap.value=i.displacementMap,n(i.displacementMap,t.displacementMapTransform),t.displacementScale.value=i.displacementScale,t.displacementBias.value=i.displacementBias),i.emissiveMap&&(t.emissiveMap.value=i.emissiveMap,n(i.emissiveMap,t.emissiveMapTransform)),i.specularMap&&(t.specularMap.value=i.specularMap,n(i.specularMap,t.specularMapTransform)),i.alphaTest>0&&(t.alphaTest.value=i.alphaTest);const r=e.get(i),s=r.envMap,a=r.envMapRotation;s&&(t.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),t.envMapRotation.value.setFromMatrix4($l.makeRotationFromEuler(Kl)),t.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,t.reflectivity.value=i.reflectivity,t.ior.value=i.ior,t.refractionRatio.value=i.refractionRatio),i.lightMap&&(t.lightMap.value=i.lightMap,t.lightMapIntensity.value=i.lightMapIntensity,n(i.lightMap,t.lightMapTransform)),i.aoMap&&(t.aoMap.value=i.aoMap,t.aoMapIntensity.value=i.aoMapIntensity,n(i.aoMap,t.aoMapTransform))}return{refreshFogUniforms:function(e,n){n.color.getRGB(e.fogColor.value,Gs(t)),n.isFog?(e.fogNear.value=n.near,e.fogFar.value=n.far):n.isFogExp2&&(e.fogDensity.value=n.density)},refreshMaterialUniforms:function(t,r,s,a,o){r.isMeshBasicMaterial||r.isMeshLambertMaterial?i(t,r):r.isMeshToonMaterial?(i(t,r),function(t,e){e.gradientMap&&(t.gradientMap.value=e.gradientMap)}(t,r)):r.isMeshPhongMaterial?(i(t,r),function(t,e){t.specular.value.copy(e.specular),t.shininess.value=Math.max(e.shininess,1e-4)}(t,r)):r.isMeshStandardMaterial?(i(t,r),function(t,e){t.metalness.value=e.metalness,e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap,n(e.metalnessMap,t.metalnessMapTransform));t.roughness.value=e.roughness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap,n(e.roughnessMap,t.roughnessMapTransform));e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}(t,r),r.isMeshPhysicalMaterial&&function(t,e,i){t.ior.value=e.ior,e.sheen>0&&(t.sheenColor.value.copy(e.sheenColor).multiplyScalar(e.sheen),t.sheenRoughness.value=e.sheenRoughness,e.sheenColorMap&&(t.sheenColorMap.value=e.sheenColorMap,n(e.sheenColorMap,t.sheenColorMapTransform)),e.sheenRoughnessMap&&(t.sheenRoughnessMap.value=e.sheenRoughnessMap,n(e.sheenRoughnessMap,t.sheenRoughnessMapTransform)));e.clearcoat>0&&(t.clearcoat.value=e.clearcoat,t.clearcoatRoughness.value=e.clearcoatRoughness,e.clearcoatMap&&(t.clearcoatMap.value=e.clearcoatMap,n(e.clearcoatMap,t.clearcoatMapTransform)),e.clearcoatRoughnessMap&&(t.clearcoatRoughnessMap.value=e.clearcoatRoughnessMap,n(e.clearcoatRoughnessMap,t.clearcoatRoughnessMapTransform)),e.clearcoatNormalMap&&(t.clearcoatNormalMap.value=e.clearcoatNormalMap,n(e.clearcoatNormalMap,t.clearcoatNormalMapTransform),t.clearcoatNormalScale.value.copy(e.clearcoatNormalScale),1===e.side&&t.clearcoatNormalScale.value.negate()));e.dispersion>0&&(t.dispersion.value=e.dispersion);e.iridescence>0&&(t.iridescence.value=e.iridescence,t.iridescenceIOR.value=e.iridescenceIOR,t.iridescenceThicknessMinimum.value=e.iridescenceThicknessRange[0],t.iridescenceThicknessMaximum.value=e.iridescenceThicknessRange[1],e.iridescenceMap&&(t.iridescenceMap.value=e.iridescenceMap,n(e.iridescenceMap,t.iridescenceMapTransform)),e.iridescenceThicknessMap&&(t.iridescenceThicknessMap.value=e.iridescenceThicknessMap,n(e.iridescenceThicknessMap,t.iridescenceThicknessMapTransform)));e.transmission>0&&(t.transmission.value=e.transmission,t.transmissionSamplerMap.value=i.texture,t.transmissionSamplerSize.value.set(i.width,i.height),e.transmissionMap&&(t.transmissionMap.value=e.transmissionMap,n(e.transmissionMap,t.transmissionMapTransform)),t.thickness.value=e.thickness,e.thicknessMap&&(t.thicknessMap.value=e.thicknessMap,n(e.thicknessMap,t.thicknessMapTransform)),t.attenuationDistance.value=e.attenuationDistance,t.attenuationColor.value.copy(e.attenuationColor));e.anisotropy>0&&(t.anisotropyVector.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation)),e.anisotropyMap&&(t.anisotropyMap.value=e.anisotropyMap,n(e.anisotropyMap,t.anisotropyMapTransform)));t.specularIntensity.value=e.specularIntensity,t.specularColor.value.copy(e.specularColor),e.specularColorMap&&(t.specularColorMap.value=e.specularColorMap,n(e.specularColorMap,t.specularColorMapTransform));e.specularIntensityMap&&(t.specularIntensityMap.value=e.specularIntensityMap,n(e.specularIntensityMap,t.specularIntensityMapTransform))}(t,r,o)):r.isMeshMatcapMaterial?(i(t,r),function(t,e){e.matcap&&(t.matcap.value=e.matcap)}(t,r)):r.isMeshDepthMaterial?i(t,r):r.isMeshDistanceMaterial?(i(t,r),function(t,n){const i=e.get(n).light;t.referencePosition.value.setFromMatrixPosition(i.matrixWorld),t.nearDistance.value=i.shadow.camera.near,t.farDistance.value=i.shadow.camera.far}(t,r)):r.isMeshNormalMaterial?i(t,r):r.isLineBasicMaterial?(function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,e.map&&(t.map.value=e.map,n(e.map,t.mapTransform))}(t,r),r.isLineDashedMaterial&&function(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}(t,r)):r.isPointsMaterial?function(t,e,i,r){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.size.value=e.size*i,t.scale.value=.5*r,e.map&&(t.map.value=e.map,n(e.map,t.uvTransform));e.alphaMap&&(t.alphaMap.value=e.alphaMap,n(e.alphaMap,t.alphaMapTransform));e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,r,s,a):r.isSpriteMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.rotation.value=e.rotation,e.map&&(t.map.value=e.map,n(e.map,t.mapTransform));e.alphaMap&&(t.alphaMap.value=e.alphaMap,n(e.alphaMap,t.alphaMapTransform));e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,r):r.isShadowMaterial?(t.color.value.copy(r.color),t.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function tc(t,e,n,i){let r={},s={},a=[];const o=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function l(t,e,n,i){const r=t.value,s=e+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const t=i[s];if("number"==typeof r||"boolean"==typeof r){if(t!==r)return i[s]=r,!0}else if(!1===t.equals(r))return t.copy(r),!0}return!1}function c(t){const e={boundary:0,storage:0};return"number"==typeof t||"boolean"==typeof t?(e.boundary=4,e.storage=4):t.isVector2?(e.boundary=8,e.storage=8):t.isVector3||t.isColor?(e.boundary=16,e.storage=12):t.isVector4?(e.boundary=16,e.storage=16):t.isMatrix3?(e.boundary=48,e.storage=48):t.isMatrix4?(e.boundary=64,e.storage=64):t.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",t),e}function h(e){const n=e.target;n.removeEventListener("dispose",h);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),t.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(t,e){const n=e.program;i.uniformBlockBinding(t,n)},update:function(n,u){let d=r[n.id];void 0===d&&(!function(t){const e=t.uniforms;let n=0;const i=16;for(let t=0,r=e.length;t<r;t++){const r=Array.isArray(e[t])?e[t]:[e[t]];for(let t=0,e=r.length;t<e;t++){const e=r[t],s=Array.isArray(e.value)?e.value:[e.value];for(let t=0,r=s.length;t<r;t++){const r=c(s[t]),a=n%i,o=a%r.boundary,l=a+o;n+=o,0!==l&&i-l<r.storage&&(n+=i-l),e.__data=new Float32Array(r.storage/Float32Array.BYTES_PER_ELEMENT),e.__offset=n,n+=r.storage}}}const r=n%i;r>0&&(n+=i-r);t.__size=n,t.__cache={}}(n),d=function(e){const n=function(){for(let t=0;t<o;t++)if(-1===a.indexOf(t))return a.push(t),t;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}();e.__bindingPointIndex=n;const i=t.createBuffer(),r=e.__size,s=e.usage;return t.bindBuffer(t.UNIFORM_BUFFER,i),t.bufferData(t.UNIFORM_BUFFER,r,s),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,n,i),i}(n),r[n.id]=d,n.addEventListener("dispose",h));const p=u.program;i.updateUBOMapping(n,p);const m=e.render.frame;s[n.id]!==m&&(!function(e){const n=r[e.id],i=e.uniforms,s=e.__cache;t.bindBuffer(t.UNIFORM_BUFFER,n);for(let e=0,n=i.length;e<n;e++){const n=Array.isArray(i[e])?i[e]:[i[e]];for(let i=0,r=n.length;i<r;i++){const r=n[i];if(!0===l(r,e,i,s)){const e=r.__offset,n=Array.isArray(r.value)?r.value:[r.value];let i=0;for(let s=0;s<n.length;s++){const a=n[s],o=c(a);"number"==typeof a||"boolean"==typeof a?(r.__data[0]=a,t.bufferSubData(t.UNIFORM_BUFFER,e+i,r.__data)):a.isMatrix3?(r.__data[0]=a.elements[0],r.__data[1]=a.elements[1],r.__data[2]=a.elements[2],r.__data[3]=0,r.__data[4]=a.elements[3],r.__data[5]=a.elements[4],r.__data[6]=a.elements[5],r.__data[7]=0,r.__data[8]=a.elements[6],r.__data[9]=a.elements[7],r.__data[10]=a.elements[8],r.__data[11]=0):(a.toArray(r.__data,i),i+=o.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,e,r.__data)}}}t.bindBuffer(t.UNIFORM_BUFFER,null)}(n),s[n.id]=m)},dispose:function(){for(const e in r)t.deleteBuffer(r[e]);a=[],r={},s={}}}}class ec{constructor(e={}){const{canvas:n=ii(),context:i=null,depth:r=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reverseDepthBuffer:d=!1}=e;let p;if(this.isWebGLRenderer=!0,null!==i){if("undefined"!=typeof WebGLRenderingContext&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=i.getContextAttributes().alpha}else p=a;const m=new Uint32Array(4),f=new Int32Array(4);let g=null,v=null;const _=[],x=[];this.domElement=n,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=Je,this.toneMapping=0,this.toneMappingExposure=1;const y=this;let M=!1,S=0,b=0,T=null,w=-1,E=null;const A=new Mi,R=new Mi;let C=null;const I=new Kr(0);let P=0,L=n.width,U=n.height,D=1,N=null,O=null;const F=new Mi(0,0,L,U),B=new Mi(0,0,L,U);let z=!1;const k=new oa;let V=!1,H=!1;const G=new sr,W=new sr,X=new Ci,j=new Mi,q={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Y=!1;function Z(){return null===T?D:1}let J,K,$,Q,tt,et,nt,it,rt,st,at,ot,lt,ct,ht,ut,dt,pt,mt,ft,gt,vt,_t,xt,yt=i;function Mt(t,e){return n.getContext(t,e)}try{const e={alpha:!0,depth:r,stencil:s,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${t}`),n.addEventListener("webglcontextlost",wt,!1),n.addEventListener("webglcontextrestored",At,!1),n.addEventListener("webglcontextcreationerror",Rt,!1),null===yt){const t="webgl2";if(yt=Mt(t,e),null===yt)throw Mt(t)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(t){throw console.error("THREE.WebGLRenderer: "+t.message),t}function St(){J=new Ha(yt),J.init(),vt=new Wl(yt,J),K=new ya(yt,J,e,vt),$=new kl(yt,J),K.reverseDepthBuffer&&d&&$.buffers.depth.setReversed(!0),Q=new Xa(yt),tt=new wl,et=new Gl(yt,J,$,tt,K,vt,Q),nt=new Sa(y),it=new Va(y),rt=new ca(yt),_t=new _a(yt,rt),st=new Ga(yt,rt,Q,_t),at=new qa(yt,st,rt,Q),mt=new ja(yt,K,et),ut=new Ma(tt),ot=new Tl(y,nt,it,J,K,_t,ut),lt=new Ql(y,tt),ct=new Cl,ht=new Nl(J),pt=new va(y,nt,it,$,at,p,l),dt=new Bl(y,at,K),xt=new tc(yt,Q,K,$),ft=new xa(yt,J,Q),gt=new Wa(yt,J,Q),Q.programs=ot.programs,y.capabilities=K,y.extensions=J,y.properties=tt,y.renderLists=ct,y.shadowMap=dt,y.state=$,y.info=Q}St();const bt=new Jl(y,yt);function wt(t){t.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),M=!0}function At(){console.log("THREE.WebGLRenderer: Context Restored."),M=!1;const t=Q.autoReset,e=dt.enabled,n=dt.autoUpdate,i=dt.needsUpdate,r=dt.type;St(),Q.autoReset=t,dt.enabled=e,dt.autoUpdate=n,dt.needsUpdate=i,dt.type=r}function Rt(t){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",t.statusMessage)}function It(t){const e=t.target;e.removeEventListener("dispose",It),function(t){(function(t){const e=tt.get(t).programs;void 0!==e&&(e.forEach((function(t){ot.releaseProgram(t)})),t.isShaderMaterial&&ot.releaseShaderCache(t))})(t),tt.remove(t)}(e)}function Lt(t,e,n){!0===t.transparent&&2===t.side&&!1===t.forceSinglePass?(t.side=1,t.needsUpdate=!0,qt(t,e,n),t.side=0,t.needsUpdate=!0,qt(t,e,n),t.side=2):qt(t,e,n)}this.xr=bt,this.getContext=function(){return yt},this.getContextAttributes=function(){return yt.getContextAttributes()},this.forceContextLoss=function(){const t=J.get("WEBGL_lose_context");t&&t.loseContext()},this.forceContextRestore=function(){const t=J.get("WEBGL_lose_context");t&&t.restoreContext()},this.getPixelRatio=function(){return D},this.setPixelRatio=function(t){void 0!==t&&(D=t,this.setSize(L,U,!1))},this.getSize=function(t){return t.set(L,U)},this.setSize=function(t,e,i=!0){bt.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(L=t,U=e,n.width=Math.floor(t*D),n.height=Math.floor(e*D),!0===i&&(n.style.width=t+"px",n.style.height=e+"px"),this.setViewport(0,0,t,e))},this.getDrawingBufferSize=function(t){return t.set(L*D,U*D).floor()},this.setDrawingBufferSize=function(t,e,i){L=t,U=e,D=i,n.width=Math.floor(t*i),n.height=Math.floor(e*i),this.setViewport(0,0,t,e)},this.getCurrentViewport=function(t){return t.copy(A)},this.getViewport=function(t){return t.copy(F)},this.setViewport=function(t,e,n,i){t.isVector4?F.set(t.x,t.y,t.z,t.w):F.set(t,e,n,i),$.viewport(A.copy(F).multiplyScalar(D).round())},this.getScissor=function(t){return t.copy(B)},this.setScissor=function(t,e,n,i){t.isVector4?B.set(t.x,t.y,t.z,t.w):B.set(t,e,n,i),$.scissor(R.copy(B).multiplyScalar(D).round())},this.getScissorTest=function(){return z},this.setScissorTest=function(t){$.setScissorTest(z=t)},this.setOpaqueSort=function(t){N=t},this.setTransparentSort=function(t){O=t},this.getClearColor=function(t){return t.copy(pt.getClearColor())},this.setClearColor=function(){pt.setClearColor.apply(pt,arguments)},this.getClearAlpha=function(){return pt.getClearAlpha()},this.setClearAlpha=function(){pt.setClearAlpha.apply(pt,arguments)},this.clear=function(t=!0,e=!0,n=!0){let i=0;if(t){let t=!1;if(null!==T){const e=T.texture.format;t=e===Jt||e===Yt||e===jt}if(t){const t=T.texture.type,e=t===Et||t===Pt||t===Ct||t===Ot||t===Dt||t===Nt,n=pt.getClearColor(),i=pt.getClearAlpha(),r=n.r,s=n.g,a=n.b;e?(m[0]=r,m[1]=s,m[2]=a,m[3]=i,yt.clearBufferuiv(yt.COLOR,0,m)):(f[0]=r,f[1]=s,f[2]=a,f[3]=i,yt.clearBufferiv(yt.COLOR,0,f))}else i|=yt.COLOR_BUFFER_BIT}e&&(i|=yt.DEPTH_BUFFER_BIT),n&&(i|=yt.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),yt.clear(i)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){n.removeEventListener("webglcontextlost",wt,!1),n.removeEventListener("webglcontextrestored",At,!1),n.removeEventListener("webglcontextcreationerror",Rt,!1),ct.dispose(),ht.dispose(),tt.dispose(),nt.dispose(),it.dispose(),at.dispose(),_t.dispose(),xt.dispose(),ot.dispose(),bt.dispose(),bt.removeEventListener("sessionstart",Bt),bt.removeEventListener("sessionend",zt),kt.stop()},this.renderBufferDirect=function(t,e,n,i,r,s){null===e&&(e=q);const a=r.isMesh&&r.matrixWorld.determinant()<0,o=function(t,e,n,i,r){!0!==e.isScene&&(e=q);et.resetTextureUnits();const s=e.fog,a=i.isMeshStandardMaterial?e.environment:null,o=null===T?y.outputColorSpace:!0===T.isXRRenderTarget?T.texture.colorSpace:Ke,l=(i.isMeshStandardMaterial?it:nt).get(i.envMap||a),c=!0===i.vertexColors&&!!n.attributes.color&&4===n.attributes.color.itemSize,h=!!n.attributes.tangent&&(!!i.normalMap||i.anisotropy>0),u=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let m=0;i.toneMapped&&(null!==T&&!0!==T.isXRRenderTarget||(m=y.toneMapping));const f=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=void 0!==f?f.length:0,_=tt.get(i),x=v.state.lights;if(!0===V&&(!0===H||t!==E)){const e=t===E&&i.id===w;ut.setState(i,t,e)}let M=!1;i.version===_.__version?_.needsLights&&_.lightsStateVersion!==x.state.version||_.outputColorSpace!==o||r.isBatchedMesh&&!1===_.batching?M=!0:r.isBatchedMesh||!0!==_.batching?r.isBatchedMesh&&!0===_.batchingColor&&null===r.colorTexture||r.isBatchedMesh&&!1===_.batchingColor&&null!==r.colorTexture||r.isInstancedMesh&&!1===_.instancing?M=!0:r.isInstancedMesh||!0!==_.instancing?r.isSkinnedMesh&&!1===_.skinning?M=!0:r.isSkinnedMesh||!0!==_.skinning?r.isInstancedMesh&&!0===_.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===_.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===_.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===_.instancingMorph&&null!==r.morphTexture||_.envMap!==l||!0===i.fog&&_.fog!==s?M=!0:void 0===_.numClippingPlanes||_.numClippingPlanes===ut.numPlanes&&_.numIntersection===ut.numIntersection?(_.vertexAlphas!==c||_.vertexTangents!==h||_.morphTargets!==u||_.morphNormals!==d||_.morphColors!==p||_.toneMapping!==m||_.morphTargetsCount!==g)&&(M=!0):M=!0:M=!0:M=!0:M=!0:(M=!0,_.__version=i.version);let S=_.currentProgram;!0===M&&(S=qt(i,e,r));let b=!1,A=!1,R=!1;const C=S.getUniforms(),I=_.uniforms;$.useProgram(S.program)&&(b=!0,A=!0,R=!0);i.id!==w&&(w=i.id,A=!0);if(b||E!==t){$.buffers.depth.getReversed()?(G.copy(t.projectionMatrix),function(t){const e=t.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}(G),function(t){const e=t.elements;-1===e[11]?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=1-e[14])}(G),C.setValue(yt,"projectionMatrix",G)):C.setValue(yt,"projectionMatrix",t.projectionMatrix),C.setValue(yt,"viewMatrix",t.matrixWorldInverse);const e=C.map.cameraPosition;void 0!==e&&e.setValue(yt,X.setFromMatrixPosition(t.matrixWorld)),K.logarithmicDepthBuffer&&C.setValue(yt,"logDepthBufFC",2/(Math.log(t.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&C.setValue(yt,"isOrthographic",!0===t.isOrthographicCamera),E!==t&&(E=t,A=!0,R=!0)}if(r.isSkinnedMesh){C.setOptional(yt,r,"bindMatrix"),C.setOptional(yt,r,"bindMatrixInverse");const t=r.skeleton;t&&(null===t.boneTexture&&t.computeBoneTexture(),C.setValue(yt,"boneTexture",t.boneTexture,et))}r.isBatchedMesh&&(C.setOptional(yt,r,"batchingTexture"),C.setValue(yt,"batchingTexture",r._matricesTexture,et),C.setOptional(yt,r,"batchingIdTexture"),C.setValue(yt,"batchingIdTexture",r._indirectTexture,et),C.setOptional(yt,r,"batchingColorTexture"),null!==r._colorsTexture&&C.setValue(yt,"batchingColorTexture",r._colorsTexture,et));const P=n.morphAttributes;void 0===P.position&&void 0===P.normal&&void 0===P.color||mt.update(r,n,S);(A||_.receiveShadow!==r.receiveShadow)&&(_.receiveShadow=r.receiveShadow,C.setValue(yt,"receiveShadow",r.receiveShadow));i.isMeshGouraudMaterial&&null!==i.envMap&&(I.envMap.value=l,I.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);i.isMeshStandardMaterial&&null===i.envMap&&null!==e.environment&&(I.envMapIntensity.value=e.environmentIntensity);A&&(C.setValue(yt,"toneMappingExposure",y.toneMappingExposure),_.needsLights&&(N=R,(L=I).ambientLightColor.needsUpdate=N,L.lightProbe.needsUpdate=N,L.directionalLights.needsUpdate=N,L.directionalLightShadows.needsUpdate=N,L.pointLights.needsUpdate=N,L.pointLightShadows.needsUpdate=N,L.spotLights.needsUpdate=N,L.spotLightShadows.needsUpdate=N,L.rectAreaLights.needsUpdate=N,L.hemisphereLights.needsUpdate=N),s&&!0===i.fog&<.refreshFogUniforms(I,s),lt.refreshMaterialUniforms(I,i,D,U,v.state.transmissionRenderTarget[t.id]),tl.upload(yt,Zt(_),I,et));var L,N;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(tl.upload(yt,Zt(_),I,et),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&C.setValue(yt,"center",r.center);if(C.setValue(yt,"modelViewMatrix",r.modelViewMatrix),C.setValue(yt,"normalMatrix",r.normalMatrix),C.setValue(yt,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const t=i.uniformsGroups;for(let e=0,n=t.length;e<n;e++){const n=t[e];xt.update(n,S),xt.bind(n,S)}}return S}(t,e,n,i,r);$.setMaterial(i,a);let l=n.index,c=1;if(!0===i.wireframe){if(l=st.getWireframeAttribute(n),void 0===l)return;c=2}const h=n.drawRange,u=n.attributes.position;let d=h.start*c,p=(h.start+h.count)*c;null!==s&&(d=Math.max(d,s.start*c),p=Math.min(p,(s.start+s.count)*c)),null!==l?(d=Math.max(d,0),p=Math.min(p,l.count)):null!=u&&(d=Math.max(d,0),p=Math.min(p,u.count));const m=p-d;if(m<0||m===1/0)return;let f;_t.setup(r,i,o,n,l);let g=ft;if(null!==l&&(f=rt.get(l),g=gt,g.setIndex(f)),r.isMesh)!0===i.wireframe?($.setLineWidth(i.wireframeLinewidth*Z()),g.setMode(yt.LINES)):g.setMode(yt.TRIANGLES);else if(r.isLine){let t=i.linewidth;void 0===t&&(t=1),$.setLineWidth(t*Z()),r.isLineSegments?g.setMode(yt.LINES):r.isLineLoop?g.setMode(yt.LINE_LOOP):g.setMode(yt.LINE_STRIP)}else r.isPoints?g.setMode(yt.POINTS):r.isSprite&&g.setMode(yt.TRIANGLES);if(r.isBatchedMesh)if(null!==r._multiDrawInstances)g.renderMultiDrawInstances(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount,r._multiDrawInstances);else if(J.get("WEBGL_multi_draw"))g.renderMultiDraw(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount);else{const t=r._multiDrawStarts,e=r._multiDrawCounts,n=r._multiDrawCount,s=l?rt.get(l).bytesPerElement:1,a=tt.get(i).currentProgram.getUniforms();for(let i=0;i<n;i++)a.setValue(yt,"_gl_DrawID",i),g.render(t[i]/s,e[i])}else if(r.isInstancedMesh)g.renderInstances(d,m,r.count);else if(n.isInstancedBufferGeometry){const t=void 0!==n._maxInstanceCount?n._maxInstanceCount:1/0,e=Math.min(n.instanceCount,t);g.renderInstances(d,m,e)}else g.render(d,m)},this.compile=function(t,e,n=null){null===n&&(n=t),v=ht.get(n),v.init(e),x.push(v),n.traverseVisible((function(t){t.isLight&&t.layers.test(e.layers)&&(v.pushLight(t),t.castShadow&&v.pushShadow(t))})),t!==n&&t.traverseVisible((function(t){t.isLight&&t.layers.test(e.layers)&&(v.pushLight(t),t.castShadow&&v.pushShadow(t))})),v.setupLights();const i=new Set;return t.traverse((function(t){if(!(t.isMesh||t.isPoints||t.isLine||t.isSprite))return;const e=t.material;if(e)if(Array.isArray(e))for(let r=0;r<e.length;r++){const s=e[r];Lt(s,n,t),i.add(s)}else Lt(e,n,t),i.add(e)})),x.pop(),v=null,i},this.compileAsync=function(t,e,n=null){const i=this.compile(t,e,n);return new Promise((e=>{function n(){i.forEach((function(t){tt.get(t).currentProgram.isReady()&&i.delete(t)})),0!==i.size?setTimeout(n,10):e(t)}null!==J.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)}))};let Ft=null;function Bt(){kt.stop()}function zt(){kt.start()}const kt=new la;function Vt(t,e,n,i){if(!1===t.visible)return;if(t.layers.test(e.layers))if(t.isGroup)n=t.renderOrder;else if(t.isLOD)!0===t.autoUpdate&&t.update(e);else if(t.isLight)v.pushLight(t),t.castShadow&&v.pushShadow(t);else if(t.isSprite){if(!t.frustumCulled||k.intersectsSprite(t)){i&&j.setFromMatrixPosition(t.matrixWorld).applyMatrix4(W);const e=at.update(t),r=t.material;r.visible&&g.push(t,e,r,n,j.z,null)}}else if((t.isMesh||t.isLine||t.isPoints)&&(!t.frustumCulled||k.intersectsObject(t))){const e=at.update(t),r=t.material;if(i&&(void 0!==t.boundingSphere?(null===t.boundingSphere&&t.computeBoundingSphere(),j.copy(t.boundingSphere.center)):(null===e.boundingSphere&&e.computeBoundingSphere(),j.copy(e.boundingSphere.center)),j.applyMatrix4(t.matrixWorld).applyMatrix4(W)),Array.isArray(r)){const i=e.groups;for(let s=0,a=i.length;s<a;s++){const a=i[s],o=r[a.materialIndex];o&&o.visible&&g.push(t,e,o,n,j.z,a)}}else r.visible&&g.push(t,e,r,n,j.z,null)}const r=t.children;for(let t=0,s=r.length;t<s;t++)Vt(r[t],e,n,i)}function Ht(t,e,n,i){const r=t.opaque,s=t.transmissive,a=t.transparent;v.setupLightsView(n),!0===V&&ut.setGlobalState(y.clippingPlanes,n),i&&$.viewport(A.copy(i)),r.length>0&&Wt(r,e,n),s.length>0&&Wt(s,e,n),a.length>0&&Wt(a,e,n),$.buffers.depth.setTest(!0),$.buffers.depth.setMask(!0),$.buffers.color.setMask(!0),$.setPolygonOffset(!1)}function Gt(t,e,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===v.state.transmissionRenderTarget[i.id]&&(v.state.transmissionRenderTarget[i.id]=new bi(1,1,{generateMipmaps:!0,type:J.has("EXT_color_buffer_half_float")||J.has("EXT_color_buffer_float")?Ut:Et,minFilter:Tt,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:ai.workingColorSpace}));const r=v.state.transmissionRenderTarget[i.id],a=i.viewport||A;r.setSize(a.z,a.w);const o=y.getRenderTarget();y.setRenderTarget(r),y.getClearColor(I),P=y.getClearAlpha(),P<1&&y.setClearColor(16777215,.5),y.clear(),Y&&pt.render(n);const l=y.toneMapping;y.toneMapping=0;const c=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),v.setupLightsView(i),!0===V&&ut.setGlobalState(y.clippingPlanes,i),Wt(t,n,i),et.updateMultisampleRenderTarget(r),et.updateRenderTargetMipmap(r),!1===J.has("WEBGL_multisampled_render_to_texture")){let t=!1;for(let r=0,s=e.length;r<s;r++){const s=e[r],a=s.object,o=s.geometry,l=s.material,c=s.group;if(2===l.side&&a.layers.test(i.layers)){const e=l.side;l.side=1,l.needsUpdate=!0,Xt(a,n,i,o,l,c),l.side=e,l.needsUpdate=!0,t=!0}}!0===t&&(et.updateMultisampleRenderTarget(r),et.updateRenderTargetMipmap(r))}y.setRenderTarget(o),y.setClearColor(I,P),void 0!==c&&(i.viewport=c),y.toneMapping=l}function Wt(t,e,n){const i=!0===e.isScene?e.overrideMaterial:null;for(let r=0,s=t.length;r<s;r++){const s=t[r],a=s.object,o=s.geometry,l=null===i?s.material:i,c=s.group;a.layers.test(n.layers)&&Xt(a,e,n,o,l,c)}}function Xt(t,e,n,i,r,s){t.onBeforeRender(y,e,n,i,r,s),t.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix),r.onBeforeRender(y,e,n,i,t,s),!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,r.needsUpdate=!0,y.renderBufferDirect(n,e,i,r,t,s),r.side=0,r.needsUpdate=!0,y.renderBufferDirect(n,e,i,r,t,s),r.side=2):y.renderBufferDirect(n,e,i,r,t,s),t.onAfterRender(y,e,n,i,r,s)}function qt(t,e,n){!0!==e.isScene&&(e=q);const i=tt.get(t),r=v.state.lights,s=v.state.shadowsArray,a=r.state.version,o=ot.getParameters(t,r.state,s,e,n),l=ot.getProgramCacheKey(o);let c=i.programs;i.environment=t.isMeshStandardMaterial?e.environment:null,i.fog=e.fog,i.envMap=(t.isMeshStandardMaterial?it:nt).get(t.envMap||i.environment),i.envMapRotation=null!==i.environment&&null===t.envMap?e.environmentRotation:t.envMapRotation,void 0===c&&(t.addEventListener("dispose",It),c=new Map,i.programs=c);let h=c.get(l);if(void 0!==h){if(i.currentProgram===h&&i.lightsStateVersion===a)return Kt(t,o),h}else o.uniforms=ot.getUniforms(t),t.onBeforeCompile(o,y),h=ot.acquireProgram(o,l),c.set(l,h),i.uniforms=o.uniforms;const u=i.uniforms;return(t.isShaderMaterial||t.isRawShaderMaterial)&&!0!==t.clipping||(u.clippingPlanes=ut.uniform),Kt(t,o),i.needsLights=function(t){return t.isMeshLambertMaterial||t.isMeshToonMaterial||t.isMeshPhongMaterial||t.isMeshStandardMaterial||t.isShadowMaterial||t.isShaderMaterial&&!0===t.lights}(t),i.lightsStateVersion=a,i.needsLights&&(u.ambientLightColor.value=r.state.ambient,u.lightProbe.value=r.state.probe,u.directionalLights.value=r.state.directional,u.directionalLightShadows.value=r.state.directionalShadow,u.spotLights.value=r.state.spot,u.spotLightShadows.value=r.state.spotShadow,u.rectAreaLights.value=r.state.rectArea,u.ltc_1.value=r.state.rectAreaLTC1,u.ltc_2.value=r.state.rectAreaLTC2,u.pointLights.value=r.state.point,u.pointLightShadows.value=r.state.pointShadow,u.hemisphereLights.value=r.state.hemi,u.directionalShadowMap.value=r.state.directionalShadowMap,u.directionalShadowMatrix.value=r.state.directionalShadowMatrix,u.spotShadowMap.value=r.state.spotShadowMap,u.spotLightMatrix.value=r.state.spotLightMatrix,u.spotLightMap.value=r.state.spotLightMap,u.pointShadowMap.value=r.state.pointShadowMap,u.pointShadowMatrix.value=r.state.pointShadowMatrix),i.currentProgram=h,i.uniformsList=null,h}function Zt(t){if(null===t.uniformsList){const e=t.currentProgram.getUniforms();t.uniformsList=tl.seqWithValue(e.seq,t.uniforms)}return t.uniformsList}function Kt(t,e){const n=tt.get(t);n.outputColorSpace=e.outputColorSpace,n.batching=e.batching,n.batchingColor=e.batchingColor,n.instancing=e.instancing,n.instancingColor=e.instancingColor,n.instancingMorph=e.instancingMorph,n.skinning=e.skinning,n.morphTargets=e.morphTargets,n.morphNormals=e.morphNormals,n.morphColors=e.morphColors,n.morphTargetsCount=e.morphTargetsCount,n.numClippingPlanes=e.numClippingPlanes,n.numIntersection=e.numClipIntersection,n.vertexAlphas=e.vertexAlphas,n.vertexTangents=e.vertexTangents,n.toneMapping=e.toneMapping}kt.setAnimationLoop((function(t){Ft&&Ft(t)})),"undefined"!=typeof self&&kt.setContext(self),this.setAnimationLoop=function(t){Ft=t,bt.setAnimationLoop(t),null===t?kt.stop():kt.start()},bt.addEventListener("sessionstart",Bt),bt.addEventListener("sessionend",zt),this.render=function(t,e){if(void 0!==e&&!0!==e.isCamera)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!0===M)return;if(!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),null===e.parent&&!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),!0===bt.enabled&&!0===bt.isPresenting&&(!0===bt.cameraAutoUpdate&&bt.updateCamera(e),e=bt.getCamera()),!0===t.isScene&&t.onBeforeRender(y,t,e,T),v=ht.get(t,x.length),v.init(e),x.push(v),W.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),k.setFromProjectionMatrix(W),H=this.localClippingEnabled,V=ut.init(this.clippingPlanes,H),g=ct.get(t,_.length),g.init(),_.push(g),!0===bt.enabled&&!0===bt.isPresenting){const t=y.xr.getDepthSensingMesh();null!==t&&Vt(t,e,-1/0,y.sortObjects)}Vt(t,e,0,y.sortObjects),g.finish(),!0===y.sortObjects&&g.sort(N,O),Y=!1===bt.enabled||!1===bt.isPresenting||!1===bt.hasDepthSensing(),Y&&pt.addToRenderList(g,t),this.info.render.frame++,!0===V&&ut.beginShadows();const n=v.state.shadowsArray;dt.render(n,t,e),!0===V&&ut.endShadows(),!0===this.info.autoReset&&this.info.reset();const i=g.opaque,r=g.transmissive;if(v.setupLights(),e.isArrayCamera){const n=e.cameras;if(r.length>0)for(let e=0,s=n.length;e<s;e++){Gt(i,r,t,n[e])}Y&&pt.render(t);for(let e=0,i=n.length;e<i;e++){const i=n[e];Ht(g,t,i,i.viewport)}}else r.length>0&&Gt(i,r,t,e),Y&&pt.render(t),Ht(g,t,e);null!==T&&(et.updateMultisampleRenderTarget(T),et.updateRenderTargetMipmap(T)),!0===t.isScene&&t.onAfterRender(y,t,e),_t.resetDefaultState(),w=-1,E=null,x.pop(),x.length>0?(v=x[x.length-1],!0===V&&ut.setGlobalState(y.clippingPlanes,v.state.camera)):v=null,_.pop(),g=_.length>0?_[_.length-1]:null},this.getActiveCubeFace=function(){return S},this.getActiveMipmapLevel=function(){return b},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(t,e,n){tt.get(t.texture).__webglTexture=e,tt.get(t.depthTexture).__webglTexture=n;const i=tt.get(t);i.__hasExternalTextures=!0,i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||!0===J.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(t,e){const n=tt.get(t);n.__webglFramebuffer=e,n.__useDefaultFramebuffer=void 0===e},this.setRenderTarget=function(t,e=0,n=0){T=t,S=e,b=n;let i=!0,r=null,s=!1,a=!1;if(t){const o=tt.get(t);if(void 0!==o.__useDefaultFramebuffer)$.bindFramebuffer(yt.FRAMEBUFFER,null),i=!1;else if(void 0===o.__webglFramebuffer)et.setupRenderTarget(t);else if(o.__hasExternalTextures)et.rebindTextures(t,tt.get(t.texture).__webglTexture,tt.get(t.depthTexture).__webglTexture);else if(t.depthBuffer){const e=t.depthTexture;if(o.__boundDepthTexture!==e){if(null!==e&&tt.has(e)&&(t.width!==e.image.width||t.height!==e.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");et.setupDepthRenderbuffer(t)}}const l=t.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const c=tt.get(t).__webglFramebuffer;t.isWebGLCubeRenderTarget?(r=Array.isArray(c[e])?c[e][n]:c[e],s=!0):r=t.samples>0&&!1===et.useMultisampledRTT(t)?tt.get(t).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,A.copy(t.viewport),R.copy(t.scissor),C=t.scissorTest}else A.copy(F).multiplyScalar(D).floor(),R.copy(B).multiplyScalar(D).floor(),C=z;if($.bindFramebuffer(yt.FRAMEBUFFER,r)&&i&&$.drawBuffers(t,r),$.viewport(A),$.scissor(R),$.setScissorTest(C),s){const i=tt.get(t.texture);yt.framebufferTexture2D(yt.FRAMEBUFFER,yt.COLOR_ATTACHMENT0,yt.TEXTURE_CUBE_MAP_POSITIVE_X+e,i.__webglTexture,n)}else if(a){const i=tt.get(t.texture),r=e||0;yt.framebufferTextureLayer(yt.FRAMEBUFFER,yt.COLOR_ATTACHMENT0,i.__webglTexture,n||0,r)}w=-1},this.readRenderTargetPixels=function(t,e,n,i,r,s,a){if(!t||!t.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=tt.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){$.bindFramebuffer(yt.FRAMEBUFFER,o);try{const a=t.texture,o=a.format,l=a.type;if(!K.textureFormatReadable(o))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!K.textureTypeReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r&&yt.readPixels(e,n,i,r,vt.convert(o),vt.convert(l),s)}finally{const t=null!==T?tt.get(T).__webglFramebuffer:null;$.bindFramebuffer(yt.FRAMEBUFFER,t)}}},this.readRenderTargetPixelsAsync=async function(t,e,n,i,r,s,a){if(!t||!t.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=tt.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){const a=t.texture,l=a.format,c=a.type;if(!K.textureFormatReadable(l))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!K.textureTypeReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r){$.bindFramebuffer(yt.FRAMEBUFFER,o);const t=yt.createBuffer();yt.bindBuffer(yt.PIXEL_PACK_BUFFER,t),yt.bufferData(yt.PIXEL_PACK_BUFFER,s.byteLength,yt.STREAM_READ),yt.readPixels(e,n,i,r,vt.convert(l),vt.convert(c),0);const a=null!==T?tt.get(T).__webglFramebuffer:null;$.bindFramebuffer(yt.FRAMEBUFFER,a);const h=yt.fenceSync(yt.SYNC_GPU_COMMANDS_COMPLETE,0);return yt.flush(),await function(t,e,n){return new Promise((function(i,r){setTimeout((function s(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:r();break;case t.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:i()}}),n)}))}(yt,h,4),yt.bindBuffer(yt.PIXEL_PACK_BUFFER,t),yt.getBufferSubData(yt.PIXEL_PACK_BUFFER,0,s),yt.deleteBuffer(t),yt.deleteSync(h),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(t,e=null,n=0){!0!==t.isTexture&&(si("WebGLRenderer: copyFramebufferToTexture function signature has changed."),e=arguments[0]||null,t=arguments[1]);const i=Math.pow(2,-n),r=Math.floor(t.image.width*i),s=Math.floor(t.image.height*i),a=null!==e?e.x:0,o=null!==e?e.y:0;et.setTexture2D(t,0),yt.copyTexSubImage2D(yt.TEXTURE_2D,n,0,0,a,o,r,s),$.unbindTexture()},this.copyTextureToTexture=function(t,e,n=null,i=null,r=0){let s,a,o,l,c,h,u,d,p;!0!==t.isTexture&&(si("WebGLRenderer: copyTextureToTexture function signature has changed."),i=arguments[0]||null,t=arguments[1],e=arguments[2],r=arguments[3]||0,n=null);const m=t.isCompressedTexture?t.mipmaps[r]:t.image;null!==n?(s=n.max.x-n.min.x,a=n.max.y-n.min.y,o=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,c=n.min.y,h=n.isBox3?n.min.z:0):(s=m.width,a=m.height,o=m.depth||1,l=0,c=0,h=0),null!==i?(u=i.x,d=i.y,p=i.z):(u=0,d=0,p=0);const f=vt.convert(e.format),g=vt.convert(e.type);let v;e.isData3DTexture?(et.setTexture3D(e,0),v=yt.TEXTURE_3D):e.isDataArrayTexture||e.isCompressedArrayTexture?(et.setTexture2DArray(e,0),v=yt.TEXTURE_2D_ARRAY):(et.setTexture2D(e,0),v=yt.TEXTURE_2D),yt.pixelStorei(yt.UNPACK_FLIP_Y_WEBGL,e.flipY),yt.pixelStorei(yt.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),yt.pixelStorei(yt.UNPACK_ALIGNMENT,e.unpackAlignment);const _=yt.getParameter(yt.UNPACK_ROW_LENGTH),x=yt.getParameter(yt.UNPACK_IMAGE_HEIGHT),y=yt.getParameter(yt.UNPACK_SKIP_PIXELS),M=yt.getParameter(yt.UNPACK_SKIP_ROWS),S=yt.getParameter(yt.UNPACK_SKIP_IMAGES);yt.pixelStorei(yt.UNPACK_ROW_LENGTH,m.width),yt.pixelStorei(yt.UNPACK_IMAGE_HEIGHT,m.height),yt.pixelStorei(yt.UNPACK_SKIP_PIXELS,l),yt.pixelStorei(yt.UNPACK_SKIP_ROWS,c),yt.pixelStorei(yt.UNPACK_SKIP_IMAGES,h);const b=t.isDataArrayTexture||t.isData3DTexture,T=e.isDataArrayTexture||e.isData3DTexture;if(t.isRenderTargetTexture||t.isDepthTexture){const n=tt.get(t),i=tt.get(e),m=tt.get(n.__renderTarget),f=tt.get(i.__renderTarget);$.bindFramebuffer(yt.READ_FRAMEBUFFER,m.__webglFramebuffer),$.bindFramebuffer(yt.DRAW_FRAMEBUFFER,f.__webglFramebuffer);for(let n=0;n<o;n++)b&&yt.framebufferTextureLayer(yt.READ_FRAMEBUFFER,yt.COLOR_ATTACHMENT0,tt.get(t).__webglTexture,r,h+n),t.isDepthTexture?(T&&yt.framebufferTextureLayer(yt.DRAW_FRAMEBUFFER,yt.COLOR_ATTACHMENT0,tt.get(e).__webglTexture,r,p+n),yt.blitFramebuffer(l,c,s,a,u,d,s,a,yt.DEPTH_BUFFER_BIT,yt.NEAREST)):T?yt.copyTexSubImage3D(v,r,u,d,p+n,l,c,s,a):yt.copyTexSubImage2D(v,r,u,d,p+n,l,c,s,a);$.bindFramebuffer(yt.READ_FRAMEBUFFER,null),$.bindFramebuffer(yt.DRAW_FRAMEBUFFER,null)}else T?t.isDataTexture||t.isData3DTexture?yt.texSubImage3D(v,r,u,d,p,s,a,o,f,g,m.data):e.isCompressedArrayTexture?yt.compressedTexSubImage3D(v,r,u,d,p,s,a,o,f,m.data):yt.texSubImage3D(v,r,u,d,p,s,a,o,f,g,m):t.isDataTexture?yt.texSubImage2D(yt.TEXTURE_2D,r,u,d,s,a,f,g,m.data):t.isCompressedTexture?yt.compressedTexSubImage2D(yt.TEXTURE_2D,r,u,d,m.width,m.height,f,m.data):yt.texSubImage2D(yt.TEXTURE_2D,r,u,d,s,a,f,g,m);yt.pixelStorei(yt.UNPACK_ROW_LENGTH,_),yt.pixelStorei(yt.UNPACK_IMAGE_HEIGHT,x),yt.pixelStorei(yt.UNPACK_SKIP_PIXELS,y),yt.pixelStorei(yt.UNPACK_SKIP_ROWS,M),yt.pixelStorei(yt.UNPACK_SKIP_IMAGES,S),0===r&&e.generateMipmaps&&yt.generateMipmap(v),$.unbindTexture()},this.copyTextureToTexture3D=function(t,e,n=null,i=null,r=0){return!0!==t.isTexture&&(si("WebGLRenderer: copyTextureToTexture3D function signature has changed."),n=arguments[0]||null,i=arguments[1]||null,t=arguments[2],e=arguments[3],r=arguments[4]||0),si('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(t,e,n,i,r)},this.initRenderTarget=function(t){void 0===tt.get(t).__webglFramebuffer&&et.setupRenderTarget(t)},this.initTexture=function(t){t.isCubeTexture?et.setTextureCube(t,0):t.isData3DTexture?et.setTexture3D(t,0):t.isDataArrayTexture||t.isCompressedArrayTexture?et.setTexture2DArray(t,0):et.setTexture2D(t,0),$.unbindTexture()},this.resetState=function(){S=0,b=0,T=null,$.reset(),_t.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return On}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorspace=ai._getDrawingBufferColorSpace(t),e.unpackColorSpace=ai._getUnpackColorSpace()}}class nc{constructor(t,e=25e-5){this.isFogExp2=!0,this.name="",this.color=new Kr(t),this.density=e}clone(){return new nc(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class ic{constructor(t,e=1,n=1e3){this.isFog=!0,this.name="",this.color=new Kr(t),this.near=e,this.far=n}clone(){return new ic(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class rc extends Lr{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 fr,this.environmentIntensity=1,this.environmentRotation=new fr,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),null!==t.background&&(this.background=t.background.clone()),null!==t.environment&&(this.environment=t.environment.clone()),null!==t.fog&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,this.backgroundRotation.copy(t.backgroundRotation),this.environmentIntensity=t.environmentIntensity,this.environmentRotation.copy(t.environmentRotation),null!==t.overrideMaterial&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return null!==this.fog&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}class sc{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=void 0!==t?t.length/e:0,this.usage=wn,this.updateRanges=[],this.version=0,this.uuid=Gn()}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,n){t*=this.stride,n*=e.stride;for(let i=0,r=this.stride;i<r;i++)this.array[t+i]=e.array[n+i];return this}set(t,e=0){return this.array.set(t,e),this}clone(t){void 0===t.arrayBuffers&&(t.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=Gn()),void 0===t.arrayBuffers[this.array.buffer._uuid]&&(t.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const e=new this.array.constructor(t.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(e,this.stride);return n.setUsage(this.usage),n}onUpload(t){return this.onUploadCallback=t,this}toJSON(t){return void 0===t.arrayBuffers&&(t.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=Gn()),void 0===t.arrayBuffers[this.array.buffer._uuid]&&(t.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const ac=new Ci;class oc{constructor(t,e,n,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=t,this.itemSize=e,this.offset=n,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(t){this.data.needsUpdate=t}applyMatrix4(t){for(let e=0,n=this.data.count;e<n;e++)ac.fromBufferAttribute(this,e),ac.applyMatrix4(t),this.setXYZ(e,ac.x,ac.y,ac.z);return this}applyNormalMatrix(t){for(let e=0,n=this.count;e<n;e++)ac.fromBufferAttribute(this,e),ac.applyNormalMatrix(t),this.setXYZ(e,ac.x,ac.y,ac.z);return this}transformDirection(t){for(let e=0,n=this.count;e<n;e++)ac.fromBufferAttribute(this,e),ac.transformDirection(t),this.setXYZ(e,ac.x,ac.y,ac.z);return this}getComponent(t,e){let n=this.array[t*this.data.stride+this.offset+e];return this.normalized&&(n=qn(n,this.array)),n}setComponent(t,e,n){return this.normalized&&(n=Yn(n,this.array)),this.data.array[t*this.data.stride+this.offset+e]=n,this}setX(t,e){return this.normalized&&(e=Yn(e,this.array)),this.data.array[t*this.data.stride+this.offset]=e,this}setY(t,e){return this.normalized&&(e=Yn(e,this.array)),this.data.array[t*this.data.stride+this.offset+1]=e,this}setZ(t,e){return this.normalized&&(e=Yn(e,this.array)),this.data.array[t*this.data.stride+this.offset+2]=e,this}setW(t,e){return this.normalized&&(e=Yn(e,this.array)),this.data.array[t*this.data.stride+this.offset+3]=e,this}getX(t){let e=this.data.array[t*this.data.stride+this.offset];return this.normalized&&(e=qn(e,this.array)),e}getY(t){let e=this.data.array[t*this.data.stride+this.offset+1];return this.normalized&&(e=qn(e,this.array)),e}getZ(t){let e=this.data.array[t*this.data.stride+this.offset+2];return this.normalized&&(e=qn(e,this.array)),e}getW(t){let e=this.data.array[t*this.data.stride+this.offset+3];return this.normalized&&(e=qn(e,this.array)),e}setXY(t,e,n){return t=t*this.data.stride+this.offset,this.normalized&&(e=Yn(e,this.array),n=Yn(n,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=n,this}setXYZ(t,e,n,i){return t=t*this.data.stride+this.offset,this.normalized&&(e=Yn(e,this.array),n=Yn(n,this.array),i=Yn(i,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=n,this.data.array[t+2]=i,this}setXYZW(t,e,n,i,r){return t=t*this.data.stride+this.offset,this.normalized&&(e=Yn(e,this.array),n=Yn(n,this.array),i=Yn(i,this.array),r=Yn(r,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=n,this.data.array[t+2]=i,this.data.array[t+3]=r,this}clone(t){if(void 0===t){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let e=0;e<this.count;e++){const n=e*this.data.stride+this.offset;for(let e=0;e<this.itemSize;e++)t.push(this.data.array[n+e])}return new cs(new this.array.constructor(t),this.itemSize,this.normalized)}return void 0===t.interleavedBuffers&&(t.interleavedBuffers={}),void 0===t.interleavedBuffers[this.data.uuid]&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new oc(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(t){if(void 0===t){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let e=0;e<this.count;e++){const n=e*this.data.stride+this.offset;for(let e=0;e<this.itemSize;e++)t.push(this.data.array[n+e])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}return void 0===t.interleavedBuffers&&(t.interleavedBuffers={}),void 0===t.interleavedBuffers[this.data.uuid]&&(t.interleavedBuffers[this.data.uuid]=this.data.toJSON(t)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}class lc extends ts{static get type(){return"SpriteMaterial"}constructor(t){super(),this.isSpriteMaterial=!0,this.color=new Kr(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.rotation=t.rotation,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}let cc;const hc=new Ci,uc=new Ci,dc=new Ci,pc=new Jn,mc=new Jn,fc=new sr,gc=new Ci,vc=new Ci,_c=new Ci,xc=new Jn,yc=new Jn,Mc=new Jn;class Sc extends Lr{constructor(t=new lc){if(super(),this.isSprite=!0,this.type="Sprite",void 0===cc){cc=new Es;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),e=new sc(t,5);cc.setIndex([0,1,2,0,2,3]),cc.setAttribute("position",new oc(e,3,0,!1)),cc.setAttribute("uv",new oc(e,2,3,!1))}this.geometry=cc,this.material=t,this.center=new Jn(.5,.5)}raycast(t,e){null===t.camera&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),uc.setFromMatrixScale(this.matrixWorld),fc.copy(t.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse,this.matrixWorld),dc.setFromMatrixPosition(this.modelViewMatrix),t.camera.isPerspectiveCamera&&!1===this.material.sizeAttenuation&&uc.multiplyScalar(-dc.z);const n=this.material.rotation;let i,r;0!==n&&(r=Math.cos(n),i=Math.sin(n));const s=this.center;bc(gc.set(-.5,-.5,0),dc,s,uc,i,r),bc(vc.set(.5,-.5,0),dc,s,uc,i,r),bc(_c.set(.5,.5,0),dc,s,uc,i,r),xc.set(0,0),yc.set(1,0),Mc.set(1,1);let a=t.ray.intersectTriangle(gc,vc,_c,!1,hc);if(null===a&&(bc(vc.set(-.5,.5,0),dc,s,uc,i,r),yc.set(0,1),a=t.ray.intersectTriangle(gc,_c,vc,!1,hc),null===a))return;const o=t.ray.origin.distanceTo(hc);o<t.near||o>t.far||e.push({distance:o,point:hc.clone(),uv:jr.getInterpolation(hc,gc,vc,_c,xc,yc,Mc,new Jn),face:null,object:this})}copy(t,e){return super.copy(t,e),void 0!==t.center&&this.center.copy(t.center),this.material=t.material,this}}function bc(t,e,n,i,r,s){pc.subVectors(t,n).addScalar(.5).multiply(i),void 0!==r?(mc.x=s*pc.x-r*pc.y,mc.y=r*pc.x+s*pc.y):mc.copy(pc),t.copy(e),t.x+=mc.x,t.y+=mc.y,t.applyMatrix4(fc)}const Tc=new Ci,wc=new Ci;class Ec extends Lr{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(t){super.copy(t,!1);const e=t.levels;for(let t=0,n=e.length;t<n;t++){const n=e[t];this.addLevel(n.object.clone(),n.distance,n.hysteresis)}return this.autoUpdate=t.autoUpdate,this}addLevel(t,e=0,n=0){e=Math.abs(e);const i=this.levels;let r;for(r=0;r<i.length&&!(e<i[r].distance);r++);return i.splice(r,0,{distance:e,hysteresis:n,object:t}),this.add(t),this}removeLevel(t){const e=this.levels;for(let n=0;n<e.length;n++)if(e[n].distance===t){const t=e.splice(n,1);return this.remove(t[0].object),!0}return!1}getCurrentLevel(){return this._currentLevel}getObjectForDistance(t){const e=this.levels;if(e.length>0){let n,i;for(n=1,i=e.length;n<i;n++){let i=e[n].distance;if(e[n].object.visible&&(i-=i*e[n].hysteresis),t<i)break}return e[n-1].object}return null}raycast(t,e){if(this.levels.length>0){Tc.setFromMatrixPosition(this.matrixWorld);const n=t.ray.origin.distanceTo(Tc);this.getObjectForDistance(n).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){Tc.setFromMatrixPosition(t.matrixWorld),wc.setFromMatrixPosition(this.matrixWorld);const n=Tc.distanceTo(wc)/t.zoom;let i,r;for(e[0].object.visible=!0,i=1,r=e.length;i<r;i++){let t=e[i].distance;if(e[i].object.visible&&(t-=t*e[i].hysteresis),!(n>=t))break;e[i-1].object.visible=!1,e[i].object.visible=!0}for(this._currentLevel=i-1;i<r;i++)e[i].object.visible=!1}}toJSON(t){const e=super.toJSON(t);!1===this.autoUpdate&&(e.object.autoUpdate=!1),e.object.levels=[];const n=this.levels;for(let t=0,i=n.length;t<i;t++){const i=n[t];e.object.levels.push({object:i.object.uuid,distance:i.distance,hysteresis:i.hysteresis})}return e}}const Ac=new Ci,Rc=new Mi,Cc=new Mi,Ic=new Ci,Pc=new sr,Lc=new Ci,Uc=new Ji,Dc=new sr,Nc=new rr;class Oc extends Bs{constructor(t,e){super(t,e),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=st,this.bindMatrix=new sr,this.bindMatrixInverse=new sr,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const t=this.geometry;null===this.boundingBox&&(this.boundingBox=new Li),this.boundingBox.makeEmpty();const e=t.getAttribute("position");for(let t=0;t<e.count;t++)this.getVertexPosition(t,Lc),this.boundingBox.expandByPoint(Lc)}computeBoundingSphere(){const t=this.geometry;null===this.boundingSphere&&(this.boundingSphere=new Ji),this.boundingSphere.makeEmpty();const e=t.getAttribute("position");for(let t=0;t<e.count;t++)this.getVertexPosition(t,Lc),this.boundingSphere.expandByPoint(Lc)}copy(t,e){return super.copy(t,e),this.bindMode=t.bindMode,this.bindMatrix.copy(t.bindMatrix),this.bindMatrixInverse.copy(t.bindMatrixInverse),this.skeleton=t.skeleton,null!==t.boundingBox&&(this.boundingBox=t.boundingBox.clone()),null!==t.boundingSphere&&(this.boundingSphere=t.boundingSphere.clone()),this}raycast(t,e){const n=this.material,i=this.matrixWorld;void 0!==n&&(null===this.boundingSphere&&this.computeBoundingSphere(),Uc.copy(this.boundingSphere),Uc.applyMatrix4(i),!1!==t.ray.intersectsSphere(Uc)&&(Dc.copy(i).invert(),Nc.copy(t.ray).applyMatrix4(Dc),null!==this.boundingBox&&!1===Nc.intersectsBox(this.boundingBox)||this._computeIntersections(t,e,Nc)))}getVertexPosition(t,e){return super.getVertexPosition(t,e),this.applyBoneTransform(t,e),e}bind(t,e){this.skeleton=t,void 0===e&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),e=this.matrixWorld),this.bindMatrix.copy(e),this.bindMatrixInverse.copy(e).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const t=new Mi,e=this.geometry.attributes.skinWeight;for(let n=0,i=e.count;n<i;n++){t.fromBufferAttribute(e,n);const i=1/t.manhattanLength();i!==1/0?t.multiplyScalar(i):t.set(1,0,0,0),e.setXYZW(n,t.x,t.y,t.z,t.w)}}updateMatrixWorld(t){super.updateMatrixWorld(t),this.bindMode===st?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===at?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(t,e){const n=this.skeleton,i=this.geometry;Rc.fromBufferAttribute(i.attributes.skinIndex,t),Cc.fromBufferAttribute(i.attributes.skinWeight,t),Ac.copy(e).applyMatrix4(this.bindMatrix),e.set(0,0,0);for(let t=0;t<4;t++){const i=Cc.getComponent(t);if(0!==i){const r=Rc.getComponent(t);Pc.multiplyMatrices(n.bones[r].matrixWorld,n.boneInverses[r]),e.addScaledVector(Ic.copy(Ac).applyMatrix4(Pc),i)}}return e.applyMatrix4(this.bindMatrixInverse)}}class Fc extends Lr{constructor(){super(),this.isBone=!0,this.type="Bone"}}class Bc extends yi{constructor(t=null,e=1,n=1,i,r,s,a,o,l=1003,c=1003,h,u){super(null,s,a,o,l,c,i,r,h,u),this.isDataTexture=!0,this.image={data:t,width:e,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const zc=new sr,kc=new sr;class Vc{constructor(t=[],e=[]){this.uuid=Gn(),this.bones=t.slice(0),this.boneInverses=e,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){const t=this.bones,e=this.boneInverses;if(this.boneMatrices=new Float32Array(16*t.length),0===e.length)this.calculateInverses();else if(t.length!==e.length){console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let t=0,e=this.bones.length;t<e;t++)this.boneInverses.push(new sr)}}calculateInverses(){this.boneInverses.length=0;for(let t=0,e=this.bones.length;t<e;t++){const e=new sr;this.bones[t]&&e.copy(this.bones[t].matrixWorld).invert(),this.boneInverses.push(e)}}pose(){for(let t=0,e=this.bones.length;t<e;t++){const e=this.bones[t];e&&e.matrixWorld.copy(this.boneInverses[t]).invert()}for(let t=0,e=this.bones.length;t<e;t++){const e=this.bones[t];e&&(e.parent&&e.parent.isBone?(e.matrix.copy(e.parent.matrixWorld).invert(),e.matrix.multiply(e.matrixWorld)):e.matrix.copy(e.matrixWorld),e.matrix.decompose(e.position,e.quaternion,e.scale))}}update(){const t=this.bones,e=this.boneInverses,n=this.boneMatrices,i=this.boneTexture;for(let i=0,r=t.length;i<r;i++){const r=t[i]?t[i].matrixWorld:kc;zc.multiplyMatrices(r,e[i]),zc.toArray(n,16*i)}null!==i&&(i.needsUpdate=!0)}clone(){return new Vc(this.bones,this.boneInverses)}computeBoneTexture(){let t=Math.sqrt(4*this.bones.length);t=4*Math.ceil(t/4),t=Math.max(t,4);const e=new Float32Array(t*t*4);e.set(this.boneMatrices);const n=new Bc(e,t,t,kt,Lt);return n.needsUpdate=!0,this.boneMatrices=e,this.boneTexture=n,this}getBoneByName(t){for(let e=0,n=this.bones.length;e<n;e++){const n=this.bones[e];if(n.name===t)return n}}dispose(){null!==this.boneTexture&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(t,e){this.uuid=t.uuid;for(let n=0,i=t.bones.length;n<i;n++){const i=t.bones[n];let r=e[i];void 0===r&&(console.warn("THREE.Skeleton: No bone found with UUID:",i),r=new Fc),this.bones.push(r),this.boneInverses.push((new sr).fromArray(t.boneInverses[n]))}return this.init(),this}toJSON(){const t={metadata:{version:4.6,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};t.uuid=this.uuid;const e=this.bones,n=this.boneInverses;for(let i=0,r=e.length;i<r;i++){const r=e[i];t.bones.push(r.uuid);const s=n[i];t.boneInverses.push(s.toArray())}return t}}class Hc extends cs{constructor(t,e,n,i=1){super(t,e,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}toJSON(){const t=super.toJSON();return t.meshPerAttribute=this.meshPerAttribute,t.isInstancedBufferAttribute=!0,t}}const Gc=new sr,Wc=new sr,Xc=[],jc=new Li,qc=new sr,Yc=new Bs,Zc=new Ji;class Jc extends Bs{constructor(t,e,n){super(t,e),this.isInstancedMesh=!0,this.instanceMatrix=new Hc(new Float32Array(16*n),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let t=0;t<n;t++)this.setMatrixAt(t,qc)}computeBoundingBox(){const t=this.geometry,e=this.count;null===this.boundingBox&&(this.boundingBox=new Li),null===t.boundingBox&&t.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<e;n++)this.getMatrixAt(n,Gc),jc.copy(t.boundingBox).applyMatrix4(Gc),this.boundingBox.union(jc)}computeBoundingSphere(){const t=this.geometry,e=this.count;null===this.boundingSphere&&(this.boundingSphere=new Ji),null===t.boundingSphere&&t.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<e;n++)this.getMatrixAt(n,Gc),Zc.copy(t.boundingSphere).applyMatrix4(Gc),this.boundingSphere.union(Zc)}copy(t,e){return super.copy(t,e),this.instanceMatrix.copy(t.instanceMatrix),null!==t.morphTexture&&(this.morphTexture=t.morphTexture.clone()),null!==t.instanceColor&&(this.instanceColor=t.instanceColor.clone()),this.count=t.count,null!==t.boundingBox&&(this.boundingBox=t.boundingBox.clone()),null!==t.boundingSphere&&(this.boundingSphere=t.boundingSphere.clone()),this}getColorAt(t,e){e.fromArray(this.instanceColor.array,3*t)}getMatrixAt(t,e){e.fromArray(this.instanceMatrix.array,16*t)}getMorphAt(t,e){const n=e.morphTargetInfluences,i=this.morphTexture.source.data.data,r=t*(n.length+1)+1;for(let t=0;t<n.length;t++)n[t]=i[r+t]}raycast(t,e){const n=this.matrixWorld,i=this.count;if(Yc.geometry=this.geometry,Yc.material=this.material,void 0!==Yc.material&&(null===this.boundingSphere&&this.computeBoundingSphere(),Zc.copy(this.boundingSphere),Zc.applyMatrix4(n),!1!==t.ray.intersectsSphere(Zc)))for(let r=0;r<i;r++){this.getMatrixAt(r,Gc),Wc.multiplyMatrices(n,Gc),Yc.matrixWorld=Wc,Yc.raycast(t,Xc);for(let t=0,n=Xc.length;t<n;t++){const n=Xc[t];n.instanceId=r,n.object=this,e.push(n)}Xc.length=0}}setColorAt(t,e){null===this.instanceColor&&(this.instanceColor=new Hc(new Float32Array(3*this.instanceMatrix.count).fill(1),3)),e.toArray(this.instanceColor.array,3*t)}setMatrixAt(t,e){e.toArray(this.instanceMatrix.array,16*t)}setMorphAt(t,e){const n=e.morphTargetInfluences,i=n.length+1;null===this.morphTexture&&(this.morphTexture=new Bc(new Float32Array(i*this.count),i,this.count,Xt,Lt));const r=this.morphTexture.source.data.data;let s=0;for(let t=0;t<n.length;t++)s+=n[t];const a=this.geometry.morphTargetsRelative?1:1-s,o=i*t;r[o]=a,r.set(n,o+1)}updateMorphTargets(){}dispose(){return this.dispatchEvent({type:"dispose"}),null!==this.morphTexture&&(this.morphTexture.dispose(),this.morphTexture=null),this}}function Kc(t,e){return t-e}function $c(t,e){return t.z-e.z}function Qc(t,e){return e.z-t.z}class th{constructor(){this.index=0,this.pool=[],this.list=[]}push(t,e,n,i){const r=this.pool,s=this.list;this.index>=r.length&&r.push({start:-1,count:-1,z:-1,index:-1});const a=r[this.index];s.push(a),this.index++,a.start=t,a.count=e,a.z=n,a.index=i}reset(){this.list.length=0,this.index=0}}const eh=new sr,nh=new Kr(1,1,1),ih=new oa,rh=new Li,sh=new Ji,ah=new Ci,oh=new Ci,lh=new Ci,ch=new th,hh=new Bs,uh=[];function dh(t,e,n=0){const i=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const r=t.count;for(let s=0;s<r;s++)for(let r=0;r<i;r++)e.setComponent(s+n,r,t.getComponent(s,r))}else e.array.set(t.array,n*i);e.needsUpdate=!0}function ph(t,e){if(t.constructor!==e.constructor){const n=Math.min(t.length,e.length);for(let i=0;i<n;i++)e[i]=t[i]}else{const n=Math.min(t.length,e.length);e.set(new t.constructor(t.buffer,0,n))}}class mh extends Bs{get maxInstanceCount(){return this._maxInstanceCount}get instanceCount(){return this._instanceInfo.length-this._availableInstanceIds.length}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get unusedIndexCount(){return this._maxIndexCount-this._nextIndexStart}constructor(t,e,n=2*e,i){super(new Es,i),this.isBatchedMesh=!0,this.perObjectFrustumCulled=!0,this.sortObjects=!0,this.boundingBox=null,this.boundingSphere=null,this.customSort=null,this._instanceInfo=[],this._geometryInfo=[],this._availableInstanceIds=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._visibilityChanged=!0,this._geometryInitialized=!1,this._maxInstanceCount=t,this._maxVertexCount=e,this._maxIndexCount=n,this._multiDrawCounts=new Int32Array(t),this._multiDrawStarts=new Int32Array(t),this._multiDrawCount=0,this._multiDrawInstances=null,this._matricesTexture=null,this._indirectTexture=null,this._colorsTexture=null,this._initMatricesTexture(),this._initIndirectTexture()}_initMatricesTexture(){let t=Math.sqrt(4*this._maxInstanceCount);t=4*Math.ceil(t/4),t=Math.max(t,4);const e=new Float32Array(t*t*4),n=new Bc(e,t,t,kt,Lt);this._matricesTexture=n}_initIndirectTexture(){let t=Math.sqrt(this._maxInstanceCount);t=Math.ceil(t);const e=new Uint32Array(t*t),n=new Bc(e,t,t,jt,Pt);this._indirectTexture=n}_initColorsTexture(){let t=Math.sqrt(this._maxInstanceCount);t=Math.ceil(t);const e=new Float32Array(t*t*4).fill(1),n=new Bc(e,t,t,kt,Lt);n.colorSpace=ai.workingColorSpace,this._colorsTexture=n}_initializeGeometry(t){const e=this.geometry,n=this._maxVertexCount,i=this._maxIndexCount;if(!1===this._geometryInitialized){for(const i in t.attributes){const r=t.getAttribute(i),{array:s,itemSize:a,normalized:o}=r,l=new s.constructor(n*a),c=new cs(l,a,o);e.setAttribute(i,c)}if(null!==t.getIndex()){const t=n>65535?new Uint32Array(i):new Uint16Array(i);e.setIndex(new cs(t,1))}this._geometryInitialized=!0}}_validateGeometry(t){const e=this.geometry;if(Boolean(t.getIndex())!==Boolean(e.getIndex()))throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const n in e.attributes){if(!t.hasAttribute(n))throw new Error(`BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`);const i=t.getAttribute(n),r=e.getAttribute(n);if(i.itemSize!==r.itemSize||i.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(t){return this.customSort=t,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Li);const t=this.boundingBox,e=this._instanceInfo;t.makeEmpty();for(let n=0,i=e.length;n<i;n++){if(!1===e[n].active)continue;const i=e[n].geometryIndex;this.getMatrixAt(n,eh),this.getBoundingBoxAt(i,rh).applyMatrix4(eh),t.union(rh)}}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new Ji);const t=this.boundingSphere,e=this._instanceInfo;t.makeEmpty();for(let n=0,i=e.length;n<i;n++){if(!1===e[n].active)continue;const i=e[n].geometryIndex;this.getMatrixAt(n,eh),this.getBoundingSphereAt(i,sh).applyMatrix4(eh),t.union(sh)}}addInstance(t){if(this._instanceInfo.length>=this.maxInstanceCount&&0===this._availableInstanceIds.length)throw new Error("BatchedMesh: Maximum item count reached.");const e={visible:!0,active:!0,geometryIndex:t};let n=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(Kc),n=this._availableInstanceIds.shift(),this._instanceInfo[n]=e):(n=this._instanceInfo.length,this._instanceInfo.push(e));const i=this._matricesTexture;eh.identity().toArray(i.image.data,16*n),i.needsUpdate=!0;const r=this._colorsTexture;return r&&(nh.toArray(r.image.data,4*n),r.needsUpdate=!0),this._visibilityChanged=!0,n}addGeometry(t,e=-1,n=-1){this._initializeGeometry(t),this._validateGeometry(t);const i={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},r=this._geometryInfo;i.vertexStart=this._nextVertexStart,i.reservedVertexCount=-1===e?t.getAttribute("position").count:e;const s=t.getIndex();if(null!==s&&(i.indexStart=this._nextIndexStart,i.reservedIndexCount=-1===n?s.count:n),-1!==i.indexStart&&i.indexStart+i.reservedIndexCount>this._maxIndexCount||i.vertexStart+i.reservedVertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");let a;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Kc),a=this._availableGeometryIds.shift(),r[a]=i):(a=this._geometryCount,this._geometryCount++,r.push(i)),this.setGeometryAt(a,t),this._nextIndexStart=i.indexStart+i.reservedIndexCount,this._nextVertexStart=i.vertexStart+i.reservedVertexCount,a}setGeometryAt(t,e){if(t>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(e);const n=this.geometry,i=null!==n.getIndex(),r=n.getIndex(),s=e.getIndex(),a=this._geometryInfo[t];if(i&&s.count>a.reservedIndexCount||e.attributes.position.count>a.reservedVertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const o=a.vertexStart,l=a.reservedVertexCount;a.vertexCount=e.getAttribute("position").count;for(const t in n.attributes){const i=e.getAttribute(t),r=n.getAttribute(t);dh(i,r,o);const s=i.itemSize;for(let t=i.count,e=l;t<e;t++){const e=o+t;for(let t=0;t<s;t++)r.setComponent(e,t,0)}r.needsUpdate=!0,r.addUpdateRange(o*s,l*s)}if(i){const t=a.indexStart,n=a.reservedIndexCount;a.indexCount=e.getIndex().count;for(let e=0;e<s.count;e++)r.setX(t+e,o+s.getX(e));for(let e=s.count,i=n;e<i;e++)r.setX(t+e,o);r.needsUpdate=!0,r.addUpdateRange(t,a.reservedIndexCount)}return a.start=i?a.indexStart:a.vertexStart,a.count=i?a.indexCount:a.vertexCount,a.boundingBox=null,null!==e.boundingBox&&(a.boundingBox=e.boundingBox.clone()),a.boundingSphere=null,null!==e.boundingSphere&&(a.boundingSphere=e.boundingSphere.clone()),this._visibilityChanged=!0,t}deleteGeometry(t){const e=this._geometryInfo;if(t>=e.length||!1===e[t].active)return this;const n=this._instanceInfo;for(let e=0,i=n.length;e<i;e++)n[e].geometryIndex===t&&this.deleteInstance(e);return e[t].active=!1,this._availableGeometryIds.push(t),this._visibilityChanged=!0,this}deleteInstance(t){const e=this._instanceInfo;return t>=e.length||!1===e[t].active||(e[t].active=!1,this._availableInstanceIds.push(t),this._visibilityChanged=!0),this}optimize(){let t=0,e=0;const n=this._geometryInfo,i=n.map(((t,e)=>e)).sort(((t,e)=>n[t].vertexStart-n[e].vertexStart)),r=this.geometry;for(let s=0,a=n.length;s<a;s++){const a=i[s],o=n[a];if(!1!==o.active){if(null!==r.index){if(o.indexStart!==e){const{indexStart:n,vertexStart:i,reservedIndexCount:s}=o,a=r.index,l=a.array,c=t-i;for(let t=n;t<n+s;t++)l[t]=l[t]+c;a.array.copyWithin(e,n,n+s),a.addUpdateRange(e,s),o.indexStart=e}e+=o.reservedIndexCount}if(o.vertexStart!==t){const{vertexStart:e,reservedVertexCount:n}=o,i=r.attributes;for(const r in i){const s=i[r],{array:a,itemSize:o}=s;a.copyWithin(t*o,e*o,(e+n)*o),s.addUpdateRange(t*o,n*o)}o.vertexStart=t}t+=o.reservedVertexCount,o.start=r.index?o.indexStart:o.vertexStart,this._nextIndexStart=r.index?o.indexStart+o.reservedIndexCount:0,this._nextVertexStart=o.vertexStart+o.reservedVertexCount}}return this}getBoundingBoxAt(t,e){if(t>=this._geometryCount)return null;const n=this.geometry,i=this._geometryInfo[t];if(null===i.boundingBox){const t=new Li,e=n.index,r=n.attributes.position;for(let n=i.start,s=i.start+i.count;n<s;n++){let i=n;e&&(i=e.getX(i)),t.expandByPoint(ah.fromBufferAttribute(r,i))}i.boundingBox=t}return e.copy(i.boundingBox),e}getBoundingSphereAt(t,e){if(t>=this._geometryCount)return null;const n=this.geometry,i=this._geometryInfo[t];if(null===i.boundingSphere){const e=new Ji;this.getBoundingBoxAt(t,rh),rh.getCenter(e.center);const r=n.index,s=n.attributes.position;let a=0;for(let t=i.start,n=i.start+i.count;t<n;t++){let n=t;r&&(n=r.getX(n)),ah.fromBufferAttribute(s,n),a=Math.max(a,e.center.distanceToSquared(ah))}e.radius=Math.sqrt(a),i.boundingSphere=e}return e.copy(i.boundingSphere),e}setMatrixAt(t,e){const n=this._instanceInfo,i=this._matricesTexture,r=this._matricesTexture.image.data;return t>=n.length||!1===n[t].active||(e.toArray(r,16*t),i.needsUpdate=!0),this}getMatrixAt(t,e){const n=this._instanceInfo,i=this._matricesTexture.image.data;return t>=n.length||!1===n[t].active?null:e.fromArray(i,16*t)}setColorAt(t,e){null===this._colorsTexture&&this._initColorsTexture();const n=this._colorsTexture,i=this._colorsTexture.image.data,r=this._instanceInfo;return t>=r.length||!1===r[t].active||(e.toArray(i,4*t),n.needsUpdate=!0),this}getColorAt(t,e){const n=this._colorsTexture.image.data,i=this._instanceInfo;return t>=i.length||!1===i[t].active?null:e.fromArray(n,4*t)}setVisibleAt(t,e){const n=this._instanceInfo;return t>=n.length||!1===n[t].active||n[t].visible===e||(n[t].visible=e,this._visibilityChanged=!0),this}getVisibleAt(t){const e=this._instanceInfo;return!(t>=e.length||!1===e[t].active)&&e[t].visible}setGeometryIdAt(t,e){const n=this._instanceInfo,i=this._geometryInfo;return t>=n.length||!1===n[t].active||e>=i.length||!1===i[e].active?null:(n[t].geometryIndex=e,this)}getGeometryIdAt(t){const e=this._instanceInfo;return t>=e.length||!1===e[t].active?-1:e[t].geometryIndex}getGeometryRangeAt(t,e={}){if(t<0||t>=this._geometryCount)return null;const n=this._geometryInfo[t];return e.vertexStart=n.vertexStart,e.vertexCount=n.vertexCount,e.reservedVertexCount=n.reservedVertexCount,e.indexStart=n.indexStart,e.indexCount=n.indexCount,e.reservedIndexCount=n.reservedIndexCount,e.start=n.start,e.count=n.count,e}setInstanceCount(t){const e=this._availableInstanceIds,n=this._instanceInfo;for(e.sort(Kc);e[e.length-1]===n.length;)n.pop(),e.pop();if(t<n.length)throw new Error(`BatchedMesh: Instance ids outside the range ${t} are being used. Cannot shrink instance count.`);const i=new Int32Array(t),r=new Int32Array(t);ph(this._multiDrawCounts,i),ph(this._multiDrawStarts,r),this._multiDrawCounts=i,this._multiDrawStarts=r,this._maxInstanceCount=t;const s=this._indirectTexture,a=this._matricesTexture,o=this._colorsTexture;s.dispose(),this._initIndirectTexture(),ph(s.image.data,this._indirectTexture.image.data),a.dispose(),this._initMatricesTexture(),ph(a.image.data,this._matricesTexture.image.data),o&&(o.dispose(),this._initColorsTexture(),ph(o.image.data,this._colorsTexture.image.data))}setGeometrySize(t,e){const n=[...this._geometryInfo].filter((t=>t.active));if(Math.max(...n.map((t=>t.vertexStart+t.reservedVertexCount)))>t)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${e}. Cannot shrink further.`);if(this.geometry.index){if(Math.max(...n.map((t=>t.indexStart+t.reservedIndexCount)))>e)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${e}. Cannot shrink further.`)}const i=this.geometry;i.dispose(),this._maxVertexCount=t,this._maxIndexCount=e,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Es,this._initializeGeometry(i));const r=this.geometry;i.index&&ph(i.index.array,r.index.array);for(const t in i.attributes)ph(i.attributes[t].array,r.attributes[t].array)}raycast(t,e){const n=this._instanceInfo,i=this._geometryInfo,r=this.matrixWorld,s=this.geometry;hh.material=this.material,hh.geometry.index=s.index,hh.geometry.attributes=s.attributes,null===hh.geometry.boundingBox&&(hh.geometry.boundingBox=new Li),null===hh.geometry.boundingSphere&&(hh.geometry.boundingSphere=new Ji);for(let s=0,a=n.length;s<a;s++){if(!n[s].visible||!n[s].active)continue;const a=n[s].geometryIndex,o=i[a];hh.geometry.setDrawRange(o.start,o.count),this.getMatrixAt(s,hh.matrixWorld).premultiply(r),this.getBoundingBoxAt(a,hh.geometry.boundingBox),this.getBoundingSphereAt(a,hh.geometry.boundingSphere),hh.raycast(t,uh);for(let t=0,n=uh.length;t<n;t++){const n=uh[t];n.object=this,n.batchId=s,e.push(n)}uh.length=0}hh.material=null,hh.geometry.index=null,hh.geometry.attributes={},hh.geometry.setDrawRange(0,1/0)}copy(t){return super.copy(t),this.geometry=t.geometry.clone(),this.perObjectFrustumCulled=t.perObjectFrustumCulled,this.sortObjects=t.sortObjects,this.boundingBox=null!==t.boundingBox?t.boundingBox.clone():null,this.boundingSphere=null!==t.boundingSphere?t.boundingSphere.clone():null,this._geometryInfo=t._geometryInfo.map((t=>({...t,boundingBox:null!==t.boundingBox?t.boundingBox.clone():null,boundingSphere:null!==t.boundingSphere?t.boundingSphere.clone():null}))),this._instanceInfo=t._instanceInfo.map((t=>({...t}))),this._maxInstanceCount=t._maxInstanceCount,this._maxVertexCount=t._maxVertexCount,this._maxIndexCount=t._maxIndexCount,this._geometryInitialized=t._geometryInitialized,this._geometryCount=t._geometryCount,this._multiDrawCounts=t._multiDrawCounts.slice(),this._multiDrawStarts=t._multiDrawStarts.slice(),this._matricesTexture=t._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),null!==this._colorsTexture&&(this._colorsTexture=t._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(t,e,n,i,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const s=i.getIndex(),a=null===s?1:s.array.BYTES_PER_ELEMENT,o=this._instanceInfo,l=this._multiDrawStarts,c=this._multiDrawCounts,h=this._geometryInfo,u=this.perObjectFrustumCulled,d=this._indirectTexture,p=d.image.data;u&&(eh.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse).multiply(this.matrixWorld),ih.setFromProjectionMatrix(eh,t.coordinateSystem));let m=0;if(this.sortObjects){eh.copy(this.matrixWorld).invert(),ah.setFromMatrixPosition(n.matrixWorld).applyMatrix4(eh),oh.set(0,0,-1).transformDirection(n.matrixWorld).transformDirection(eh);for(let t=0,e=o.length;t<e;t++)if(o[t].visible&&o[t].active){const e=o[t].geometryIndex;this.getMatrixAt(t,eh),this.getBoundingSphereAt(e,sh).applyMatrix4(eh);let n=!1;if(u&&(n=!ih.intersectsSphere(sh)),!n){const n=h[e],i=lh.subVectors(sh.center,ah).dot(oh);ch.push(n.start,n.count,i,t)}}const t=ch.list,e=this.customSort;null===e?t.sort(r.transparent?Qc:$c):e.call(this,t,n);for(let e=0,n=t.length;e<n;e++){const n=t[e];l[m]=n.start*a,c[m]=n.count,p[m]=n.index,m++}ch.reset()}else for(let t=0,e=o.length;t<e;t++)if(o[t].visible&&o[t].active){const e=o[t].geometryIndex;let n=!1;if(u&&(this.getMatrixAt(t,eh),this.getBoundingSphereAt(e,sh).applyMatrix4(eh),n=!ih.intersectsSphere(sh)),!n){const n=h[e];l[m]=n.start*a,c[m]=n.count,p[m]=t,m++}}d.needsUpdate=!0,this._multiDrawCount=m,this._visibilityChanged=!1}onBeforeShadow(t,e,n,i,r,s){this.onBeforeRender(t,null,i,r,s)}}class fh extends ts{static get type(){return"LineBasicMaterial"}constructor(t){super(),this.isLineBasicMaterial=!0,this.color=new Kr(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.linewidth=t.linewidth,this.linecap=t.linecap,this.linejoin=t.linejoin,this.fog=t.fog,this}}const gh=new Ci,vh=new Ci,_h=new sr,xh=new rr,yh=new Ji,Mh=new Ci,Sh=new Ci;class bh extends Lr{constructor(t=new Es,e=new fh){super(),this.isLine=!0,this.type="Line",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}computeLineDistances(){const t=this.geometry;if(null===t.index){const e=t.attributes.position,n=[0];for(let t=1,i=e.count;t<i;t++)gh.fromBufferAttribute(e,t-1),vh.fromBufferAttribute(e,t),n[t]=n[t-1],n[t]+=gh.distanceTo(vh);t.setAttribute("lineDistance",new _s(n,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(t,e){const n=this.geometry,i=this.matrixWorld,r=t.params.Line.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),yh.copy(n.boundingSphere),yh.applyMatrix4(i),yh.radius+=r,!1===t.ray.intersectsSphere(yh))return;_h.copy(i).invert(),xh.copy(t.ray).applyMatrix4(_h);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=this.isLineSegments?2:1,c=n.index,h=n.attributes.position;if(null!==c){const n=Math.max(0,s.start),i=Math.min(c.count,s.start+s.count);for(let r=n,s=i-1;r<s;r+=l){const n=c.getX(r),i=c.getX(r+1),s=Th(this,t,xh,o,n,i);s&&e.push(s)}if(this.isLineLoop){const r=c.getX(i-1),s=c.getX(n),a=Th(this,t,xh,o,r,s);a&&e.push(a)}}else{const n=Math.max(0,s.start),i=Math.min(h.count,s.start+s.count);for(let r=n,s=i-1;r<s;r+=l){const n=Th(this,t,xh,o,r,r+1);n&&e.push(n)}if(this.isLineLoop){const r=Th(this,t,xh,o,i-1,n);r&&e.push(r)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,e=Object.keys(t);if(e.length>0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;t<e;t++){const e=n[t].name||String(t);this.morphTargetInfluences.push(0),this.morphTargetDictionary[e]=t}}}}}function Th(t,e,n,i,r,s){const a=t.geometry.attributes.position;gh.fromBufferAttribute(a,r),vh.fromBufferAttribute(a,s);if(n.distanceSqToSegment(gh,vh,Mh,Sh)>i)return;Mh.applyMatrix4(t.matrixWorld);const o=e.ray.origin.distanceTo(Mh);return o<e.near||o>e.far?void 0:{distance:o,point:Sh.clone().applyMatrix4(t.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:t}}const wh=new Ci,Eh=new Ci;class Ah extends bh{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(null===t.index){const e=t.attributes.position,n=[];for(let t=0,i=e.count;t<i;t+=2)wh.fromBufferAttribute(e,t),Eh.fromBufferAttribute(e,t+1),n[t]=0===t?0:n[t-1],n[t+1]=n[t]+wh.distanceTo(Eh);t.setAttribute("lineDistance",new _s(n,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class Rh extends bh{constructor(t,e){super(t,e),this.isLineLoop=!0,this.type="LineLoop"}}class Ch extends ts{static get type(){return"PointsMaterial"}constructor(t){super(),this.isPointsMaterial=!0,this.color=new Kr(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}const Ih=new sr,Ph=new rr,Lh=new Ji,Uh=new Ci;class Dh extends Lr{constructor(t=new Es,e=new Ch){super(),this.isPoints=!0,this.type="Points",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}raycast(t,e){const n=this.geometry,i=this.matrixWorld,r=t.params.Points.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),Lh.copy(n.boundingSphere),Lh.applyMatrix4(i),Lh.radius+=r,!1===t.ray.intersectsSphere(Lh))return;Ih.copy(i).invert(),Ph.copy(t.ray).applyMatrix4(Ih);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=n.index,c=n.attributes.position;if(null!==l){for(let n=Math.max(0,s.start),r=Math.min(l.count,s.start+s.count);n<r;n++){const r=l.getX(n);Uh.fromBufferAttribute(c,r),Nh(Uh,r,o,i,t,e,this)}}else{for(let n=Math.max(0,s.start),r=Math.min(c.count,s.start+s.count);n<r;n++)Uh.fromBufferAttribute(c,n),Nh(Uh,n,o,i,t,e,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,e=Object.keys(t);if(e.length>0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;t<e;t++){const e=n[t].name||String(t);this.morphTargetInfluences.push(0),this.morphTargetDictionary[e]=t}}}}}function Nh(t,e,n,i,r,s,a){const o=Ph.distanceSqToPoint(t);if(o<n){const n=new Ci;Ph.closestPointToPoint(t,n),n.applyMatrix4(i);const l=r.ray.origin.distanceTo(n);if(l<r.near||l>r.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:n,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class Oh extends yi{constructor(t,e,n,i,r,s,a,o,l){super(t,e,n,i,r,s,a,o,l),this.isVideoTexture=!0,this.minFilter=void 0!==s?s:Mt,this.magFilter=void 0!==r?r:Mt,this.generateMipmaps=!1;const c=this;"requestVideoFrameCallback"in t&&t.requestVideoFrameCallback((function e(){c.needsUpdate=!0,t.requestVideoFrameCallback(e)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const t=this.image;!1==="requestVideoFrameCallback"in t&&t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class Fh extends yi{constructor(t,e){super({width:t,height:e}),this.isFramebufferTexture=!0,this.magFilter=gt,this.minFilter=gt,this.generateMipmaps=!1,this.needsUpdate=!0}}class Bh extends yi{constructor(t,e,n,i,r,s,a,o,l,c,h,u){super(null,s,a,o,l,c,i,r,h,u),this.isCompressedTexture=!0,this.image={width:e,height:n},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}}class zh extends Bh{constructor(t,e,n,i,r,s){super(t,e,n,r,s),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=mt,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class kh extends Bh{constructor(t,e,n){super(void 0,t[0].width,t[0].height,e,n,lt),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}}class Vh extends yi{constructor(t,e,n,i,r,s,a,o,l){super(t,e,n,i,r,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Hh{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(t,e){const n=this.getUtoTmapping(t);return this.getPoint(n,e)}getPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPoint(n/t));return e}getSpacedPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPointAt(n/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let n,i=this.getPoint(0),r=0;e.push(0);for(let s=1;s<=t;s++)n=this.getPoint(s/t),r+=n.distanceTo(i),e.push(r),i=n;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e){const n=this.getLengths();let i=0;const r=n.length;let s;s=e||t*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 c=n[i];return(i+(s-c)/(n[i+1]-c))/(r-1)}getTangent(t,e){const n=1e-4;let i=t-n,r=t+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=e||(s.isVector2?new Jn:new Ci);return o.copy(a).sub(s).normalize(),o}getTangentAt(t,e){const n=this.getUtoTmapping(t);return this.getTangent(n,e)}computeFrenetFrames(t,e){const n=new Ci,i=[],r=[],s=[],a=new Ci,o=new sr;for(let e=0;e<=t;e++){const n=e/t;i[e]=this.getTangentAt(n,new Ci)}r[0]=new Ci,s[0]=new Ci;let l=Number.MAX_VALUE;const c=Math.abs(i[0].x),h=Math.abs(i[0].y),u=Math.abs(i[0].z);c<=l&&(l=c,n.set(1,0,0)),h<=l&&(l=h,n.set(0,1,0)),u<=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 e=1;e<=t;e++){if(r[e]=r[e-1].clone(),s[e]=s[e-1].clone(),a.crossVectors(i[e-1],i[e]),a.length()>Number.EPSILON){a.normalize();const t=Math.acos(Wn(i[e-1].dot(i[e]),-1,1));r[e].applyMatrix4(o.makeRotationAxis(a,t))}s[e].crossVectors(i[e],r[e])}if(!0===e){let e=Math.acos(Wn(r[0].dot(r[t]),-1,1));e/=t,i[0].dot(a.crossVectors(r[0],r[t]))>0&&(e=-e);for(let n=1;n<=t;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],e*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class Gh extends Hh{constructor(t=0,e=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(t,e=new Jn){const n=e,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)<Number.EPSILON;for(;r<0;)r+=i;for(;r>i;)r-=i;r<Number.EPSILON&&(r=s?0:i),!0!==this.aClockwise||s||(r===i?r=-i:r-=i);const a=this.aStartAngle+t*r;let o=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(0!==this.aRotation){const t=Math.cos(this.aRotation),e=Math.sin(this.aRotation),n=o-this.aX,i=l-this.aY;o=n*t-i*e+this.aX,l=n*e+i*t+this.aY}return n.set(o,l)}copy(t){return super.copy(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}toJSON(){const t=super.toJSON();return t.aX=this.aX,t.aY=this.aY,t.xRadius=this.xRadius,t.yRadius=this.yRadius,t.aStartAngle=this.aStartAngle,t.aEndAngle=this.aEndAngle,t.aClockwise=this.aClockwise,t.aRotation=this.aRotation,t}fromJSON(t){return super.fromJSON(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}}class Wh extends Gh{constructor(t,e,n,i,r,s){super(t,e,n,n,i,r,s),this.isArcCurve=!0,this.type="ArcCurve"}}function Xh(){let t=0,e=0,n=0,i=0;function r(r,s,a,o){t=r,e=a,n=-3*r+3*s-2*a-o,i=2*r-2*s+a+o}return{initCatmullRom:function(t,e,n,i,s){r(e,n,s*(n-t),s*(i-e))},initNonuniformCatmullRom:function(t,e,n,i,s,a,o){let l=(e-t)/s-(n-t)/(s+a)+(n-e)/a,c=(n-e)/a-(i-e)/(a+o)+(i-n)/o;l*=a,c*=a,r(e,n,l,c)},calc:function(r){const s=r*r;return t+e*r+n*s+i*(s*r)}}}const jh=new Ci,qh=new Xh,Yh=new Xh,Zh=new Xh;class Jh extends Hh{constructor(t=[],e=!1,n="centripetal",i=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=t,this.closed=e,this.curveType=n,this.tension=i}getPoint(t,e=new Ci){const n=e,i=this.points,r=i.length,s=(r-(this.closed?0:1))*t;let a,o,l=Math.floor(s),c=s-l;this.closed?l+=l>0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===c&&l===r-1&&(l=r-2,c=1),this.closed||l>0?a=i[(l-1)%r]:(jh.subVectors(i[0],i[1]).add(i[0]),a=jh);const h=i[l%r],u=i[(l+1)%r];if(this.closed||l+2<r?o=i[(l+2)%r]:(jh.subVectors(i[r-1],i[r-2]).add(i[r-1]),o=jh),"centripetal"===this.curveType||"chordal"===this.curveType){const t="chordal"===this.curveType?.5:.25;let e=Math.pow(a.distanceToSquared(h),t),n=Math.pow(h.distanceToSquared(u),t),i=Math.pow(u.distanceToSquared(o),t);n<1e-4&&(n=1),e<1e-4&&(e=n),i<1e-4&&(i=n),qh.initNonuniformCatmullRom(a.x,h.x,u.x,o.x,e,n,i),Yh.initNonuniformCatmullRom(a.y,h.y,u.y,o.y,e,n,i),Zh.initNonuniformCatmullRom(a.z,h.z,u.z,o.z,e,n,i)}else"catmullrom"===this.curveType&&(qh.initCatmullRom(a.x,h.x,u.x,o.x,this.tension),Yh.initCatmullRom(a.y,h.y,u.y,o.y,this.tension),Zh.initCatmullRom(a.z,h.z,u.z,o.z,this.tension));return n.set(qh.calc(c),Yh.calc(c),Zh.calc(c)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push(n.clone())}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,n=this.points.length;e<n;e++){const n=this.points[e];t.points.push(n.toArray())}return t.closed=this.closed,t.curveType=this.curveType,t.tension=this.tension,t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push((new Ci).fromArray(n))}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}}function Kh(t,e,n,i,r){const s=.5*(i-e),a=.5*(r-n),o=t*t;return(2*n-2*i+s+a)*(t*o)+(-3*n+3*i-2*s-a)*o+s*t+n}function $h(t,e,n,i){return function(t,e){const n=1-t;return n*n*e}(t,e)+function(t,e){return 2*(1-t)*t*e}(t,n)+function(t,e){return t*t*e}(t,i)}function Qh(t,e,n,i,r){return function(t,e){const n=1-t;return n*n*n*e}(t,e)+function(t,e){const n=1-t;return 3*n*n*t*e}(t,n)+function(t,e){return 3*(1-t)*t*t*e}(t,i)+function(t,e){return t*t*t*e}(t,r)}class tu extends Hh{constructor(t=new Jn,e=new Jn,n=new Jn,i=new Jn){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=t,this.v1=e,this.v2=n,this.v3=i}getPoint(t,e=new Jn){const n=e,i=this.v0,r=this.v1,s=this.v2,a=this.v3;return n.set(Qh(t,i.x,r.x,s.x,a.x),Qh(t,i.y,r.y,s.y,a.y)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}class eu extends Hh{constructor(t=new Ci,e=new Ci,n=new Ci,i=new Ci){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=t,this.v1=e,this.v2=n,this.v3=i}getPoint(t,e=new Ci){const n=e,i=this.v0,r=this.v1,s=this.v2,a=this.v3;return n.set(Qh(t,i.x,r.x,s.x,a.x),Qh(t,i.y,r.y,s.y,a.y),Qh(t,i.z,r.z,s.z,a.z)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}class nu extends Hh{constructor(t=new Jn,e=new Jn){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=t,this.v2=e}getPoint(t,e=new Jn){const n=e;return 1===t?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(t).add(this.v1)),n}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e=new Jn){return e.subVectors(this.v2,this.v1).normalize()}getTangentAt(t,e){return this.getTangent(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class iu extends Hh{constructor(t=new Ci,e=new Ci){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=t,this.v2=e}getPoint(t,e=new Ci){const n=e;return 1===t?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(t).add(this.v1)),n}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e=new Ci){return e.subVectors(this.v2,this.v1).normalize()}getTangentAt(t,e){return this.getTangent(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class ru extends Hh{constructor(t=new Jn,e=new Jn,n=new Jn){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=t,this.v1=e,this.v2=n}getPoint(t,e=new Jn){const n=e,i=this.v0,r=this.v1,s=this.v2;return n.set($h(t,i.x,r.x,s.x),$h(t,i.y,r.y,s.y)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class su extends Hh{constructor(t=new Ci,e=new Ci,n=new Ci){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=t,this.v1=e,this.v2=n}getPoint(t,e=new Ci){const n=e,i=this.v0,r=this.v1,s=this.v2;return n.set($h(t,i.x,r.x,s.x),$h(t,i.y,r.y,s.y),$h(t,i.z,r.z,s.z)),n}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class au extends Hh{constructor(t=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=t}getPoint(t,e=new Jn){const n=e,i=this.points,r=(i.length-1)*t,s=Math.floor(r),a=r-s,o=i[0===s?s:s-1],l=i[s],c=i[s>i.length-2?i.length-1:s+1],h=i[s>i.length-3?i.length-1:s+2];return n.set(Kh(a,o.x,l.x,c.x,h.x),Kh(a,o.y,l.y,c.y,h.y)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,n=this.points.length;e<n;e++){const n=this.points[e];t.points.push(n.toArray())}return t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,n=t.points.length;e<n;e++){const n=t.points[e];this.points.push((new Jn).fromArray(n))}return this}}var ou=Object.freeze({__proto__:null,ArcCurve:Wh,CatmullRomCurve3:Jh,CubicBezierCurve:tu,CubicBezierCurve3:eu,EllipseCurve:Gh,LineCurve:nu,LineCurve3:iu,QuadraticBezierCurve:ru,QuadraticBezierCurve3:su,SplineCurve:au});class lu extends Hh{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(t){this.curves.push(t)}closePath(){const t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);if(!t.equals(e)){const n=!0===t.isVector2?"LineCurve":"LineCurve3";this.curves.push(new ou[n](e,t))}return this}getPoint(t,e){const n=t*this.getLength(),i=this.getCurveLengths();let r=0;for(;r<i.length;){if(i[r]>=n){const t=i[r]-n,s=this.curves[r],a=s.getLength(),o=0===a?0:1-t/a;return s.getPointAt(o,e)}r++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let n=0,i=this.curves.length;n<i;n++)e+=this.curves[n].getLength(),t.push(e);return this.cacheLengths=t,t}getSpacedPoints(t=40){const e=[];for(let n=0;n<=t;n++)e.push(this.getPoint(n/t));return this.autoClose&&e.push(e[0]),e}getPoints(t=12){const e=[];let n;for(let i=0,r=this.curves;i<r.length;i++){const s=r[i],a=s.isEllipseCurve?2*t:s.isLineCurve||s.isLineCurve3?1:s.isSplineCurve?t*s.points.length:t,o=s.getPoints(a);for(let t=0;t<o.length;t++){const i=o[t];n&&n.equals(i)||(e.push(i),n=i)}}return this.autoClose&&e.length>1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,n=t.curves.length;e<n;e++){const n=t.curves[e];this.curves.push(n.clone())}return this.autoClose=t.autoClose,this}toJSON(){const t=super.toJSON();t.autoClose=this.autoClose,t.curves=[];for(let e=0,n=this.curves.length;e<n;e++){const n=this.curves[e];t.curves.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.autoClose=t.autoClose,this.curves=[];for(let e=0,n=t.curves.length;e<n;e++){const n=t.curves[e];this.curves.push((new ou[n.type]).fromJSON(n))}return this}}class cu extends lu{constructor(t){super(),this.type="Path",this.currentPoint=new Jn,t&&this.setFromPoints(t)}setFromPoints(t){this.moveTo(t[0].x,t[0].y);for(let e=1,n=t.length;e<n;e++)this.lineTo(t[e].x,t[e].y);return this}moveTo(t,e){return this.currentPoint.set(t,e),this}lineTo(t,e){const n=new nu(this.currentPoint.clone(),new Jn(t,e));return this.curves.push(n),this.currentPoint.set(t,e),this}quadraticCurveTo(t,e,n,i){const r=new ru(this.currentPoint.clone(),new Jn(t,e),new Jn(n,i));return this.curves.push(r),this.currentPoint.set(n,i),this}bezierCurveTo(t,e,n,i,r,s){const a=new tu(this.currentPoint.clone(),new Jn(t,e),new Jn(n,i),new Jn(r,s));return this.curves.push(a),this.currentPoint.set(r,s),this}splineThru(t){const e=[this.currentPoint.clone()].concat(t),n=new au(e);return this.curves.push(n),this.currentPoint.copy(t[t.length-1]),this}arc(t,e,n,i,r,s){const a=this.currentPoint.x,o=this.currentPoint.y;return this.absarc(t+a,e+o,n,i,r,s),this}absarc(t,e,n,i,r,s){return this.absellipse(t,e,n,n,i,r,s),this}ellipse(t,e,n,i,r,s,a,o){const l=this.currentPoint.x,c=this.currentPoint.y;return this.absellipse(t+l,e+c,n,i,r,s,a,o),this}absellipse(t,e,n,i,r,s,a,o){const l=new Gh(t,e,n,i,r,s,a,o);if(this.curves.length>0){const t=l.getPoint(0);t.equals(this.currentPoint)||this.lineTo(t.x,t.y)}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class hu extends Es{constructor(t=[new Jn(0,-.5),new Jn(.5,0),new Jn(0,.5)],e=12,n=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:n,phiLength:i},e=Math.floor(e),i=Wn(i,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/e,h=new Ci,u=new Jn,d=new Ci,p=new Ci,m=new Ci;let f=0,g=0;for(let e=0;e<=t.length-1;e++)switch(e){case 0:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,m.copy(d),d.normalize(),o.push(d.x,d.y,d.z);break;case t.length-1:o.push(m.x,m.y,m.z);break;default:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),o.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=e;r++){const d=n+r*c*i,p=Math.sin(d),m=Math.cos(d);for(let n=0;n<=t.length-1;n++){h.x=t[n].x*p,h.y=t[n].y,h.z=t[n].x*m,s.push(h.x,h.y,h.z),u.x=r/e,u.y=n/(t.length-1),a.push(u.x,u.y);const i=o[3*n+0]*p,c=o[3*n+1],d=o[3*n+0]*m;l.push(i,c,d)}}for(let n=0;n<e;n++)for(let e=0;e<t.length-1;e++){const i=e+n*t.length,s=i,a=i+t.length,o=i+t.length+1,l=i+1;r.push(s,a,l),r.push(o,l,a)}this.setIndex(r),this.setAttribute("position",new _s(s,3)),this.setAttribute("uv",new _s(a,2)),this.setAttribute("normal",new _s(l,3))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new hu(t.points,t.segments,t.phiStart,t.phiLength)}}class uu extends hu{constructor(t=1,e=1,n=4,i=8){const r=new cu;r.absarc(0,-e/2,t,1.5*Math.PI,0),r.absarc(0,e/2,t,0,.5*Math.PI),super(r.getPoints(n),i),this.type="CapsuleGeometry",this.parameters={radius:t,length:e,capSegments:n,radialSegments:i}}static fromJSON(t){return new uu(t.radius,t.length,t.capSegments,t.radialSegments)}}class du extends Es{constructor(t=1,e=32,n=0,i=2*Math.PI){super(),this.type="CircleGeometry",this.parameters={radius:t,segments:e,thetaStart:n,thetaLength:i},e=Math.max(3,e);const r=[],s=[],a=[],o=[],l=new Ci,c=new Jn;s.push(0,0,0),a.push(0,0,1),o.push(.5,.5);for(let r=0,h=3;r<=e;r++,h+=3){const u=n+r/e*i;l.x=t*Math.cos(u),l.y=t*Math.sin(u),s.push(l.x,l.y,l.z),a.push(0,0,1),c.x=(s[h]/t+1)/2,c.y=(s[h+1]/t+1)/2,o.push(c.x,c.y)}for(let t=1;t<=e;t++)r.push(t,t+1,0);this.setIndex(r),this.setAttribute("position",new _s(s,3)),this.setAttribute("normal",new _s(a,3)),this.setAttribute("uv",new _s(o,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new du(t.radius,t.segments,t.thetaStart,t.thetaLength)}}class pu extends Es{constructor(t=1,e=1,n=1,i=32,r=1,s=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:e,height:n,radialSegments:i,heightSegments:r,openEnded:s,thetaStart:a,thetaLength:o};const l=this;i=Math.floor(i),r=Math.floor(r);const c=[],h=[],u=[],d=[];let p=0;const m=[],f=n/2;let g=0;function v(n){const r=p,s=new Jn,m=new Ci;let v=0;const _=!0===n?t:e,x=!0===n?1:-1;for(let t=1;t<=i;t++)h.push(0,f*x,0),u.push(0,x,0),d.push(.5,.5),p++;const y=p;for(let t=0;t<=i;t++){const e=t/i*o+a,n=Math.cos(e),r=Math.sin(e);m.x=_*r,m.y=f*x,m.z=_*n,h.push(m.x,m.y,m.z),u.push(0,x,0),s.x=.5*n+.5,s.y=.5*r*x+.5,d.push(s.x,s.y),p++}for(let t=0;t<i;t++){const e=r+t,i=y+t;!0===n?c.push(i,i+1,e):c.push(i+1,i,e),v+=3}l.addGroup(g,v,!0===n?1:2),g+=v}!function(){const s=new Ci,v=new Ci;let _=0;const x=(e-t)/n;for(let l=0;l<=r;l++){const c=[],g=l/r,_=g*(e-t)+t;for(let t=0;t<=i;t++){const e=t/i,r=e*o+a,l=Math.sin(r),m=Math.cos(r);v.x=_*l,v.y=-g*n+f,v.z=_*m,h.push(v.x,v.y,v.z),s.set(l,x,m).normalize(),u.push(s.x,s.y,s.z),d.push(e,1-g),c.push(p++)}m.push(c)}for(let n=0;n<i;n++)for(let i=0;i<r;i++){const s=m[i][n],a=m[i+1][n],o=m[i+1][n+1],l=m[i][n+1];(t>0||0!==i)&&(c.push(s,a,l),_+=3),(e>0||i!==r-1)&&(c.push(a,o,l),_+=3)}l.addGroup(g,_,0),g+=_}(),!1===s&&(t>0&&v(!0),e>0&&v(!1)),this.setIndex(c),this.setAttribute("position",new _s(h,3)),this.setAttribute("normal",new _s(u,3)),this.setAttribute("uv",new _s(d,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new pu(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class mu extends pu{constructor(t=1,e=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,t,e,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(t){return new mu(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class fu extends Es{constructor(t=[],e=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:n,detail:i};const r=[],s=[];function a(t,e,n,i){const r=i+1,s=[];for(let i=0;i<=r;i++){s[i]=[];const a=t.clone().lerp(n,i/r),o=e.clone().lerp(n,i/r),l=r-i;for(let t=0;t<=l;t++)s[i][t]=0===t&&i===r?a:a.clone().lerp(o,t/l)}for(let t=0;t<r;t++)for(let e=0;e<2*(r-t)-1;e++){const n=Math.floor(e/2);e%2==0?(o(s[t][n+1]),o(s[t+1][n]),o(s[t][n])):(o(s[t][n+1]),o(s[t+1][n+1]),o(s[t+1][n]))}}function o(t){r.push(t.x,t.y,t.z)}function l(e,n){const i=3*e;n.x=t[i+0],n.y=t[i+1],n.z=t[i+2]}function c(t,e,n,i){i<0&&1===t.x&&(s[e]=t.x-1),0===n.x&&0===n.z&&(s[e]=i/2/Math.PI+.5)}function h(t){return Math.atan2(t.z,-t.x)}!function(t){const n=new Ci,i=new Ci,r=new Ci;for(let s=0;s<e.length;s+=3)l(e[s+0],n),l(e[s+1],i),l(e[s+2],r),a(n,i,r,t)}(i),function(t){const e=new Ci;for(let n=0;n<r.length;n+=3)e.x=r[n+0],e.y=r[n+1],e.z=r[n+2],e.normalize().multiplyScalar(t),r[n+0]=e.x,r[n+1]=e.y,r[n+2]=e.z}(n),function(){const t=new Ci;for(let n=0;n<r.length;n+=3){t.x=r[n+0],t.y=r[n+1],t.z=r[n+2];const i=h(t)/2/Math.PI+.5,a=(e=t,Math.atan2(-e.y,Math.sqrt(e.x*e.x+e.z*e.z))/Math.PI+.5);s.push(i,1-a)}var e;(function(){const t=new Ci,e=new Ci,n=new Ci,i=new Ci,a=new Jn,o=new Jn,l=new Jn;for(let u=0,d=0;u<r.length;u+=9,d+=6){t.set(r[u+0],r[u+1],r[u+2]),e.set(r[u+3],r[u+4],r[u+5]),n.set(r[u+6],r[u+7],r[u+8]),a.set(s[d+0],s[d+1]),o.set(s[d+2],s[d+3]),l.set(s[d+4],s[d+5]),i.copy(t).add(e).add(n).divideScalar(3);const p=h(i);c(a,d+0,t,p),c(o,d+2,e,p),c(l,d+4,n,p)}})(),function(){for(let t=0;t<s.length;t+=6){const e=s[t+0],n=s[t+2],i=s[t+4],r=Math.max(e,n,i),a=Math.min(e,n,i);r>.9&&a<.1&&(e<.2&&(s[t+0]+=1),n<.2&&(s[t+2]+=1),i<.2&&(s[t+4]+=1))}}()}(),this.setAttribute("position",new _s(r,3)),this.setAttribute("normal",new _s(r.slice(),3)),this.setAttribute("uv",new _s(s,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new fu(t.vertices,t.indices,t.radius,t.details)}}class gu extends fu{constructor(t=1,e=0){const n=(1+Math.sqrt(5))/2,i=1/n;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],t,e),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new gu(t.radius,t.detail)}}const vu=new Ci,_u=new Ci,xu=new Ci,yu=new jr;class Mu extends Es{constructor(t=null,e=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:t,thresholdAngle:e},null!==t){const n=4,i=Math.pow(10,n),r=Math.cos(Vn*e),s=t.getIndex(),a=t.getAttribute("position"),o=s?s.count:a.count,l=[0,0,0],c=["a","b","c"],h=new Array(3),u={},d=[];for(let t=0;t<o;t+=3){s?(l[0]=s.getX(t),l[1]=s.getX(t+1),l[2]=s.getX(t+2)):(l[0]=t,l[1]=t+1,l[2]=t+2);const{a:e,b:n,c:o}=yu;if(e.fromBufferAttribute(a,l[0]),n.fromBufferAttribute(a,l[1]),o.fromBufferAttribute(a,l[2]),yu.getNormal(xu),h[0]=`${Math.round(e.x*i)},${Math.round(e.y*i)},${Math.round(e.z*i)}`,h[1]=`${Math.round(n.x*i)},${Math.round(n.y*i)},${Math.round(n.z*i)}`,h[2]=`${Math.round(o.x*i)},${Math.round(o.y*i)},${Math.round(o.z*i)}`,h[0]!==h[1]&&h[1]!==h[2]&&h[2]!==h[0])for(let t=0;t<3;t++){const e=(t+1)%3,n=h[t],i=h[e],s=yu[c[t]],a=yu[c[e]],o=`${n}_${i}`,p=`${i}_${n}`;p in u&&u[p]?(xu.dot(u[p].normal)<=r&&(d.push(s.x,s.y,s.z),d.push(a.x,a.y,a.z)),u[p]=null):o in u||(u[o]={index0:l[t],index1:l[e],normal:xu.clone()})}}for(const t in u)if(u[t]){const{index0:e,index1:n}=u[t];vu.fromBufferAttribute(a,e),_u.fromBufferAttribute(a,n),d.push(vu.x,vu.y,vu.z),d.push(_u.x,_u.y,_u.z)}this.setAttribute("position",new _s(d,3))}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}}class Su extends cu{constructor(t){super(t),this.uuid=Gn(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let n=0,i=this.holes.length;n<i;n++)e[n]=this.holes[n].getPoints(t);return e}extractPoints(t){return{shape:this.getPoints(t),holes:this.getPointsHoles(t)}}copy(t){super.copy(t),this.holes=[];for(let e=0,n=t.holes.length;e<n;e++){const n=t.holes[e];this.holes.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.uuid=this.uuid,t.holes=[];for(let e=0,n=this.holes.length;e<n;e++){const n=this.holes[e];t.holes.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.uuid=t.uuid,this.holes=[];for(let e=0,n=t.holes.length;e<n;e++){const n=t.holes[e];this.holes.push((new cu).fromJSON(n))}return this}}const bu=function(t,e,n=2){const i=e&&e.length,r=i?e[0]*n:t.length;let s=Tu(t,0,r,n,!0);const a=[];if(!s||s.next===s.prev)return a;let o,l,c,h,u,d,p;if(i&&(s=function(t,e,n,i){const r=[];let s,a,o,l,c;for(s=0,a=e.length;s<a;s++)o=e[s]*i,l=s<a-1?e[s+1]*i:t.length,c=Tu(t,o,l,i,!1),c===c.next&&(c.steiner=!0),r.push(Nu(c));for(r.sort(Pu),s=0;s<r.length;s++)n=Lu(r[s],n);return n}(t,e,s,n)),t.length>80*n){o=c=t[0],l=h=t[1];for(let e=n;e<r;e+=n)u=t[e],d=t[e+1],u<o&&(o=u),d<l&&(l=d),u>c&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=0!==p?32767/p:0}return Eu(s,a,n,o,l,p,0),a};function Tu(t,e,n,i,r){let s,a;if(r===function(t,e,n,i){let r=0;for(let s=e,a=n-i;s<n;s+=i)r+=(t[a]-t[s])*(t[s+1]+t[a+1]),a=s;return r}(t,e,n,i)>0)for(s=e;s<n;s+=i)a=Xu(s,t[s],t[s+1],a);else for(s=n-i;s>=e;s-=i)a=Xu(s,t[s],t[s+1],a);return a&&zu(a,a.next)&&(ju(a),a=a.next),a}function wu(t,e){if(!t)return t;e||(e=t);let n,i=t;do{if(n=!1,i.steiner||!zu(i,i.next)&&0!==Bu(i.prev,i,i.next))i=i.next;else{if(ju(i),i=e=i.prev,i===i.next)break;n=!0}}while(n||i!==e);return e}function Eu(t,e,n,i,r,s,a){if(!t)return;!a&&s&&function(t,e,n,i){let r=t;do{0===r.z&&(r.z=Du(r.x,r.y,e,n,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){let e,n,i,r,s,a,o,l,c=1;do{for(n=t,t=null,s=null,a=0;n;){for(a++,i=n,o=0,e=0;e<c&&(o++,i=i.nextZ,i);e++);for(l=c;o>0||l>0&&i;)0!==o&&(0===l||!i||n.z<=i.z)?(r=n,n=n.nextZ,o--):(r=i,i=i.nextZ,l--),s?s.nextZ=r:t=r,r.prevZ=s,s=r;n=i}s.nextZ=null,c*=2}while(a>1)}(r)}(t,i,r,s);let o,l,c=t;for(;t.prev!==t.next;)if(o=t.prev,l=t.next,s?Ru(t,i,r,s):Au(t))e.push(o.i/n|0),e.push(t.i/n|0),e.push(l.i/n|0),ju(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?Eu(t=Cu(wu(t),e,n),e,n,i,r,s,2):2===a&&Iu(t,e,n,i,r,s):Eu(wu(t),e,n,i,r,s,1);break}}function Au(t){const e=t.prev,n=t,i=t.next;if(Bu(e,n,i)>=0)return!1;const r=e.x,s=n.x,a=i.x,o=e.y,l=n.y,c=i.y,h=r<s?r<a?r:a:s<a?s:a,u=o<l?o<c?o:c:l<c?l:c,d=r>s?r>a?r:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c;let m=i.next;for(;m!==e;){if(m.x>=h&&m.x<=d&&m.y>=u&&m.y<=p&&Ou(r,o,s,l,a,c,m.x,m.y)&&Bu(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Ru(t,e,n,i){const r=t.prev,s=t,a=t.next;if(Bu(r,s,a)>=0)return!1;const o=r.x,l=s.x,c=a.x,h=r.y,u=s.y,d=a.y,p=o<l?o<c?o:c:l<c?l:c,m=h<u?h<d?h:d:u<d?u:d,f=o>l?o>c?o:c:l>c?l:c,g=h>u?h>d?h:d:u>d?u:d,v=Du(p,m,e,n,i),_=Du(f,g,e,n,i);let x=t.prevZ,y=t.nextZ;for(;x&&x.z>=v&&y&&y.z<=_;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&Ou(o,h,l,u,c,d,x.x,x.y)&&Bu(x.prev,x,x.next)>=0)return!1;if(x=x.prevZ,y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&Ou(o,h,l,u,c,d,y.x,y.y)&&Bu(y.prev,y,y.next)>=0)return!1;y=y.nextZ}for(;x&&x.z>=v;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&Ou(o,h,l,u,c,d,x.x,x.y)&&Bu(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;y&&y.z<=_;){if(y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&Ou(o,h,l,u,c,d,y.x,y.y)&&Bu(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function Cu(t,e,n){let i=t;do{const r=i.prev,s=i.next.next;!zu(r,s)&&ku(r,i,i.next,s)&&Gu(r,s)&&Gu(s,r)&&(e.push(r.i/n|0),e.push(i.i/n|0),e.push(s.i/n|0),ju(i),ju(i.next),i=t=s),i=i.next}while(i!==t);return wu(i)}function Iu(t,e,n,i,r,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Fu(a,t)){let o=Wu(a,t);return a=wu(a,a.next),o=wu(o,o.next),Eu(a,e,n,i,r,s,0),void Eu(o,e,n,i,r,s,0)}t=t.next}a=a.next}while(a!==t)}function Pu(t,e){return t.x-e.x}function Lu(t,e){const n=function(t,e){let n,i=e,r=-1/0;const s=t.x,a=t.y;do{if(a<=i.y&&a>=i.next.y&&i.next.y!==i.y){const t=i.x+(a-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(t<=s&&t>r&&(r=t,n=i.x<i.next.x?i:i.next,t===s))return n}i=i.next}while(i!==e);if(!n)return null;const o=n,l=n.x,c=n.y;let h,u=1/0;i=n;do{s>=i.x&&i.x>=l&&s!==i.x&&Ou(a<c?s:r,a,l,c,a<c?r:s,a,i.x,i.y)&&(h=Math.abs(a-i.y)/(s-i.x),Gu(i,t)&&(h<u||h===u&&(i.x>n.x||i.x===n.x&&Uu(n,i)))&&(n=i,u=h)),i=i.next}while(i!==o);return n}(t,e);if(!n)return e;const i=Wu(n,t);return wu(i,i.next),wu(n,n.next)}function Uu(t,e){return Bu(t.prev,t,e.prev)<0&&Bu(e.next,t,t.next)<0}function Du(t,e,n,i,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Nu(t){let e=t,n=t;do{(e.x<n.x||e.x===n.x&&e.y<n.y)&&(n=e),e=e.next}while(e!==t);return n}function Ou(t,e,n,i,r,s,a,o){return(r-a)*(e-o)>=(t-a)*(s-o)&&(t-a)*(i-o)>=(n-a)*(e-o)&&(n-a)*(s-o)>=(r-a)*(i-o)}function Fu(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&ku(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(Gu(t,e)&&Gu(e,t)&&function(t,e){let n=t,i=!1;const r=(t.x+e.x)/2,s=(t.y+e.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&r<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==t);return i}(t,e)&&(Bu(t.prev,t,e.prev)||Bu(t,e.prev,e))||zu(t,e)&&Bu(t.prev,t,t.next)>0&&Bu(e.prev,e,e.next)>0)}function Bu(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function zu(t,e){return t.x===e.x&&t.y===e.y}function ku(t,e,n,i){const r=Hu(Bu(t,e,n)),s=Hu(Bu(t,e,i)),a=Hu(Bu(n,i,t)),o=Hu(Bu(n,i,e));return r!==s&&a!==o||(!(0!==r||!Vu(t,n,e))||(!(0!==s||!Vu(t,i,e))||(!(0!==a||!Vu(n,t,i))||!(0!==o||!Vu(n,e,i)))))}function Vu(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function Hu(t){return t>0?1:t<0?-1:0}function Gu(t,e){return Bu(t.prev,t,t.next)<0?Bu(t,e,t.next)>=0&&Bu(t,t.prev,e)>=0:Bu(t,e,t.prev)<0||Bu(t,t.next,e)<0}function Wu(t,e){const n=new qu(t.i,t.x,t.y),i=new qu(e.i,e.x,e.y),r=t.next,s=e.prev;return t.next=e,e.prev=t,n.next=r,r.prev=n,i.next=n,n.prev=i,s.next=i,i.prev=s,i}function Xu(t,e,n,i){const r=new qu(t,e,n);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function ju(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function qu(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class Yu{static area(t){const e=t.length;let n=0;for(let i=e-1,r=0;r<e;i=r++)n+=t[i].x*t[r].y-t[r].x*t[i].y;return.5*n}static isClockWise(t){return Yu.area(t)<0}static triangulateShape(t,e){const n=[],i=[],r=[];Zu(t),Ju(n,t);let s=t.length;e.forEach(Zu);for(let t=0;t<e.length;t++)i.push(s),s+=e[t].length,Ju(n,e[t]);const a=bu(n,i);for(let t=0;t<a.length;t+=3)r.push(a.slice(t,t+3));return r}}function Zu(t){const e=t.length;e>2&&t[e-1].equals(t[0])&&t.pop()}function Ju(t,e){for(let n=0;n<e.length;n++)t.push(e[n].x),t.push(e[n].y)}class Ku extends Es{constructor(t=new Su([new Jn(.5,.5),new Jn(-.5,.5),new Jn(-.5,-.5),new Jn(.5,-.5)]),e={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:t,options:e},t=Array.isArray(t)?t:[t];const n=this,i=[],r=[];for(let e=0,n=t.length;e<n;e++){s(t[e])}function s(t){const s=[],a=void 0!==e.curveSegments?e.curveSegments:12,o=void 0!==e.steps?e.steps:1,l=void 0!==e.depth?e.depth:1;let c=void 0===e.bevelEnabled||e.bevelEnabled,h=void 0!==e.bevelThickness?e.bevelThickness:.2,u=void 0!==e.bevelSize?e.bevelSize:h-.1,d=void 0!==e.bevelOffset?e.bevelOffset:0,p=void 0!==e.bevelSegments?e.bevelSegments:3;const m=e.extrudePath,f=void 0!==e.UVGenerator?e.UVGenerator:$u;let g,v,_,x,y,M=!1;m&&(g=m.getSpacedPoints(o),M=!0,c=!1,v=m.computeFrenetFrames(o,!1),_=new Ci,x=new Ci,y=new Ci),c||(p=0,h=0,u=0,d=0);const S=t.extractPoints(a);let b=S.shape;const T=S.holes;if(!Yu.isClockWise(b)){b=b.reverse();for(let t=0,e=T.length;t<e;t++){const e=T[t];Yu.isClockWise(e)&&(T[t]=e.reverse())}}const w=Yu.triangulateShape(b,T),E=b;for(let t=0,e=T.length;t<e;t++){const e=T[t];b=b.concat(e)}function A(t,e,n){return e||console.error("THREE.ExtrudeGeometry: vec does not exist"),t.clone().addScaledVector(e,n)}const R=b.length,C=w.length;function I(t,e,n){let i,r,s;const a=t.x-e.x,o=t.y-e.y,l=n.x-t.x,c=n.y-t.y,h=a*a+o*o,u=a*c-o*l;if(Math.abs(u)>Number.EPSILON){const u=Math.sqrt(h),d=Math.sqrt(l*l+c*c),p=e.x-o/u,m=e.y+a/u,f=((n.x-c/d-p)*c-(n.y+l/d-m)*l)/(a*c-o*l);i=p+a*f-t.x,r=m+o*f-t.y;const g=i*i+r*r;if(g<=2)return new Jn(i,r);s=Math.sqrt(g/2)}else{let t=!1;a>Number.EPSILON?l>Number.EPSILON&&(t=!0):a<-Number.EPSILON?l<-Number.EPSILON&&(t=!0):Math.sign(o)===Math.sign(c)&&(t=!0),t?(i=-o,r=a,s=Math.sqrt(h)):(i=a,r=o,s=Math.sqrt(h/2))}return new Jn(i/s,r/s)}const P=[];for(let t=0,e=E.length,n=e-1,i=t+1;t<e;t++,n++,i++)n===e&&(n=0),i===e&&(i=0),P[t]=I(E[t],E[n],E[i]);const L=[];let U,D=P.concat();for(let t=0,e=T.length;t<e;t++){const e=T[t];U=[];for(let t=0,n=e.length,i=n-1,r=t+1;t<n;t++,i++,r++)i===n&&(i=0),r===n&&(r=0),U[t]=I(e[t],e[i],e[r]);L.push(U),D=D.concat(U)}for(let t=0;t<p;t++){const e=t/p,n=h*Math.cos(e*Math.PI/2),i=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=E.length;t<e;t++){const e=A(E[t],P[t],i);F(e.x,e.y,-n)}for(let t=0,e=T.length;t<e;t++){const e=T[t];U=L[t];for(let t=0,r=e.length;t<r;t++){const r=A(e[t],U[t],i);F(r.x,r.y,-n)}}}const N=u+d;for(let t=0;t<R;t++){const e=c?A(b[t],D[t],N):b[t];M?(x.copy(v.normals[0]).multiplyScalar(e.x),_.copy(v.binormals[0]).multiplyScalar(e.y),y.copy(g[0]).add(x).add(_),F(y.x,y.y,y.z)):F(e.x,e.y,0)}for(let t=1;t<=o;t++)for(let e=0;e<R;e++){const n=c?A(b[e],D[e],N):b[e];M?(x.copy(v.normals[t]).multiplyScalar(n.x),_.copy(v.binormals[t]).multiplyScalar(n.y),y.copy(g[t]).add(x).add(_),F(y.x,y.y,y.z)):F(n.x,n.y,l/o*t)}for(let t=p-1;t>=0;t--){const e=t/p,n=h*Math.cos(e*Math.PI/2),i=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=E.length;t<e;t++){const e=A(E[t],P[t],i);F(e.x,e.y,l+n)}for(let t=0,e=T.length;t<e;t++){const e=T[t];U=L[t];for(let t=0,r=e.length;t<r;t++){const r=A(e[t],U[t],i);M?F(r.x,r.y+g[o-1].y,g[o-1].x+n):F(r.x,r.y,l+n)}}}function O(t,e){let n=t.length;for(;--n>=0;){const i=n;let r=n-1;r<0&&(r=t.length-1);for(let t=0,n=o+2*p;t<n;t++){const n=R*t,s=R*(t+1);z(e+i+n,e+r+n,e+r+s,e+i+s)}}}function F(t,e,n){s.push(t),s.push(e),s.push(n)}function B(t,e,r){k(t),k(e),k(r);const s=i.length/3,a=f.generateTopUV(n,i,s-3,s-2,s-1);V(a[0]),V(a[1]),V(a[2])}function z(t,e,r,s){k(t),k(e),k(s),k(e),k(r),k(s);const a=i.length/3,o=f.generateSideWallUV(n,i,a-6,a-3,a-2,a-1);V(o[0]),V(o[1]),V(o[3]),V(o[1]),V(o[2]),V(o[3])}function k(t){i.push(s[3*t+0]),i.push(s[3*t+1]),i.push(s[3*t+2])}function V(t){r.push(t.x),r.push(t.y)}!function(){const t=i.length/3;if(c){let t=0,e=R*t;for(let t=0;t<C;t++){const n=w[t];B(n[2]+e,n[1]+e,n[0]+e)}t=o+2*p,e=R*t;for(let t=0;t<C;t++){const n=w[t];B(n[0]+e,n[1]+e,n[2]+e)}}else{for(let t=0;t<C;t++){const e=w[t];B(e[2],e[1],e[0])}for(let t=0;t<C;t++){const e=w[t];B(e[0]+R*o,e[1]+R*o,e[2]+R*o)}}n.addGroup(t,i.length/3-t,0)}(),function(){const t=i.length/3;let e=0;O(E,e),e+=E.length;for(let t=0,n=T.length;t<n;t++){const n=T[t];O(n,e),e+=n.length}n.addGroup(t,i.length/3-t,1)}()}this.setAttribute("position",new _s(i,3)),this.setAttribute("uv",new _s(r,2)),this.computeVertexNormals()}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}toJSON(){const t=super.toJSON();return function(t,e,n){if(n.shapes=[],Array.isArray(t))for(let e=0,i=t.length;e<i;e++){const i=t[e];n.shapes.push(i.uuid)}else n.shapes.push(t.uuid);n.options=Object.assign({},e),void 0!==e.extrudePath&&(n.options.extrudePath=e.extrudePath.toJSON());return n}(this.parameters.shapes,this.parameters.options,t)}static fromJSON(t,e){const n=[];for(let i=0,r=t.shapes.length;i<r;i++){const r=e[t.shapes[i]];n.push(r)}const i=t.options.extrudePath;return void 0!==i&&(t.options.extrudePath=(new ou[i.type]).fromJSON(i)),new Ku(n,t.options)}}const $u={generateTopUV:function(t,e,n,i,r){const s=e[3*n],a=e[3*n+1],o=e[3*i],l=e[3*i+1],c=e[3*r],h=e[3*r+1];return[new Jn(s,a),new Jn(o,l),new Jn(c,h)]},generateSideWallUV:function(t,e,n,i,r,s){const a=e[3*n],o=e[3*n+1],l=e[3*n+2],c=e[3*i],h=e[3*i+1],u=e[3*i+2],d=e[3*r],p=e[3*r+1],m=e[3*r+2],f=e[3*s],g=e[3*s+1],v=e[3*s+2];return Math.abs(o-h)<Math.abs(a-c)?[new Jn(a,1-l),new Jn(c,1-u),new Jn(d,1-m),new Jn(f,1-v)]:[new Jn(o,1-l),new Jn(h,1-u),new Jn(p,1-m),new Jn(g,1-v)]}};class Qu extends fu{constructor(t=1,e=0){const n=(1+Math.sqrt(5))/2;super([-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],t,e),this.type="IcosahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new Qu(t.radius,t.detail)}}class td extends fu{constructor(t=1,e=0){super([1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],t,e),this.type="OctahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new td(t.radius,t.detail)}}class ed extends Es{constructor(t=.5,e=1,n=32,i=1,r=0,s=2*Math.PI){super(),this.type="RingGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:n,phiSegments:i,thetaStart:r,thetaLength:s},n=Math.max(3,n);const a=[],o=[],l=[],c=[];let h=t;const u=(e-t)/(i=Math.max(1,i)),d=new Ci,p=new Jn;for(let t=0;t<=i;t++){for(let t=0;t<=n;t++){const i=r+t/n*s;d.x=h*Math.cos(i),d.y=h*Math.sin(i),o.push(d.x,d.y,d.z),l.push(0,0,1),p.x=(d.x/e+1)/2,p.y=(d.y/e+1)/2,c.push(p.x,p.y)}h+=u}for(let t=0;t<i;t++){const e=t*(n+1);for(let t=0;t<n;t++){const i=t+e,r=i,s=i+n+1,o=i+n+2,l=i+1;a.push(r,s,l),a.push(s,o,l)}}this.setIndex(a),this.setAttribute("position",new _s(o,3)),this.setAttribute("normal",new _s(l,3)),this.setAttribute("uv",new _s(c,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new ed(t.innerRadius,t.outerRadius,t.thetaSegments,t.phiSegments,t.thetaStart,t.thetaLength)}}class nd extends Es{constructor(t=new Su([new Jn(0,.5),new Jn(-.5,-.5),new Jn(.5,-.5)]),e=12){super(),this.type="ShapeGeometry",this.parameters={shapes:t,curveSegments:e};const n=[],i=[],r=[],s=[];let a=0,o=0;if(!1===Array.isArray(t))l(t);else for(let e=0;e<t.length;e++)l(t[e]),this.addGroup(a,o,e),a+=o,o=0;function l(t){const a=i.length/3,l=t.extractPoints(e);let c=l.shape;const h=l.holes;!1===Yu.isClockWise(c)&&(c=c.reverse());for(let t=0,e=h.length;t<e;t++){const e=h[t];!0===Yu.isClockWise(e)&&(h[t]=e.reverse())}const u=Yu.triangulateShape(c,h);for(let t=0,e=h.length;t<e;t++){const e=h[t];c=c.concat(e)}for(let t=0,e=c.length;t<e;t++){const e=c[t];i.push(e.x,e.y,0),r.push(0,0,1),s.push(e.x,e.y)}for(let t=0,e=u.length;t<e;t++){const e=u[t],i=e[0]+a,r=e[1]+a,s=e[2]+a;n.push(i,r,s),o+=3}}this.setIndex(n),this.setAttribute("position",new _s(i,3)),this.setAttribute("normal",new _s(r,3)),this.setAttribute("uv",new _s(s,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}toJSON(){const t=super.toJSON();return function(t,e){if(e.shapes=[],Array.isArray(t))for(let n=0,i=t.length;n<i;n++){const i=t[n];e.shapes.push(i.uuid)}else e.shapes.push(t.uuid);return e}(this.parameters.shapes,t)}static fromJSON(t,e){const n=[];for(let i=0,r=t.shapes.length;i<r;i++){const r=e[t.shapes[i]];n.push(r)}return new nd(n,t.curveSegments)}}class id extends Es{constructor(t=1,e=32,n=16,i=0,r=2*Math.PI,s=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:n,phiStart:i,phiLength:r,thetaStart:s,thetaLength:a},e=Math.max(3,Math.floor(e)),n=Math.max(2,Math.floor(n));const o=Math.min(s+a,Math.PI);let l=0;const c=[],h=new Ci,u=new Ci,d=[],p=[],m=[],f=[];for(let d=0;d<=n;d++){const g=[],v=d/n;let _=0;0===d&&0===s?_=.5/e:d===n&&o===Math.PI&&(_=-.5/e);for(let n=0;n<=e;n++){const o=n/e;h.x=-t*Math.cos(i+o*r)*Math.sin(s+v*a),h.y=t*Math.cos(s+v*a),h.z=t*Math.sin(i+o*r)*Math.sin(s+v*a),p.push(h.x,h.y,h.z),u.copy(h).normalize(),m.push(u.x,u.y,u.z),f.push(o+_,1-v),g.push(l++)}c.push(g)}for(let t=0;t<n;t++)for(let i=0;i<e;i++){const e=c[t][i+1],r=c[t][i],a=c[t+1][i],l=c[t+1][i+1];(0!==t||s>0)&&d.push(e,r,l),(t!==n-1||o<Math.PI)&&d.push(r,a,l)}this.setIndex(d),this.setAttribute("position",new _s(p,3)),this.setAttribute("normal",new _s(m,3)),this.setAttribute("uv",new _s(f,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new id(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}}class rd extends fu{constructor(t=1,e=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],t,e),this.type="TetrahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new rd(t.radius,t.detail)}}class sd extends Es{constructor(t=1,e=.4,n=12,i=48,r=2*Math.PI){super(),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:n,tubularSegments:i,arc:r},n=Math.floor(n),i=Math.floor(i);const s=[],a=[],o=[],l=[],c=new Ci,h=new Ci,u=new Ci;for(let s=0;s<=n;s++)for(let d=0;d<=i;d++){const p=d/i*r,m=s/n*Math.PI*2;h.x=(t+e*Math.cos(m))*Math.cos(p),h.y=(t+e*Math.cos(m))*Math.sin(p),h.z=e*Math.sin(m),a.push(h.x,h.y,h.z),c.x=t*Math.cos(p),c.y=t*Math.sin(p),u.subVectors(h,c).normalize(),o.push(u.x,u.y,u.z),l.push(d/i),l.push(s/n)}for(let t=1;t<=n;t++)for(let e=1;e<=i;e++){const n=(i+1)*t+e-1,r=(i+1)*(t-1)+e-1,a=(i+1)*(t-1)+e,o=(i+1)*t+e;s.push(n,r,o),s.push(r,a,o)}this.setIndex(s),this.setAttribute("position",new _s(a,3)),this.setAttribute("normal",new _s(o,3)),this.setAttribute("uv",new _s(l,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new sd(t.radius,t.tube,t.radialSegments,t.tubularSegments,t.arc)}}class ad extends Es{constructor(t=1,e=.4,n=64,i=8,r=2,s=3){super(),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,tubularSegments:n,radialSegments:i,p:r,q:s},n=Math.floor(n),i=Math.floor(i);const a=[],o=[],l=[],c=[],h=new Ci,u=new Ci,d=new Ci,p=new Ci,m=new Ci,f=new Ci,g=new Ci;for(let a=0;a<=n;++a){const _=a/n*r*Math.PI*2;v(_,r,s,t,d),v(_+.01,r,s,t,p),f.subVectors(p,d),g.addVectors(p,d),m.crossVectors(f,g),g.crossVectors(m,f),m.normalize(),g.normalize();for(let t=0;t<=i;++t){const r=t/i*Math.PI*2,s=-e*Math.cos(r),p=e*Math.sin(r);h.x=d.x+(s*g.x+p*m.x),h.y=d.y+(s*g.y+p*m.y),h.z=d.z+(s*g.z+p*m.z),o.push(h.x,h.y,h.z),u.subVectors(h,d).normalize(),l.push(u.x,u.y,u.z),c.push(a/n),c.push(t/i)}}for(let t=1;t<=n;t++)for(let e=1;e<=i;e++){const n=(i+1)*(t-1)+(e-1),r=(i+1)*t+(e-1),s=(i+1)*t+e,o=(i+1)*(t-1)+e;a.push(n,r,o),a.push(r,s,o)}function v(t,e,n,i,r){const s=Math.cos(t),a=Math.sin(t),o=n/e*t,l=Math.cos(o);r.x=i*(2+l)*.5*s,r.y=i*(2+l)*a*.5,r.z=i*Math.sin(o)*.5}this.setIndex(a),this.setAttribute("position",new _s(o,3)),this.setAttribute("normal",new _s(l,3)),this.setAttribute("uv",new _s(c,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new ad(t.radius,t.tube,t.tubularSegments,t.radialSegments,t.p,t.q)}}class od extends Es{constructor(t=new su(new Ci(-1,-1,0),new Ci(-1,1,0),new Ci(1,1,0)),e=64,n=1,i=8,r=!1){super(),this.type="TubeGeometry",this.parameters={path:t,tubularSegments:e,radius:n,radialSegments:i,closed:r};const s=t.computeFrenetFrames(e,r);this.tangents=s.tangents,this.normals=s.normals,this.binormals=s.binormals;const a=new Ci,o=new Ci,l=new Jn;let c=new Ci;const h=[],u=[],d=[],p=[];function m(r){c=t.getPointAt(r/e,c);const l=s.normals[r],d=s.binormals[r];for(let t=0;t<=i;t++){const e=t/i*Math.PI*2,r=Math.sin(e),s=-Math.cos(e);o.x=s*l.x+r*d.x,o.y=s*l.y+r*d.y,o.z=s*l.z+r*d.z,o.normalize(),u.push(o.x,o.y,o.z),a.x=c.x+n*o.x,a.y=c.y+n*o.y,a.z=c.z+n*o.z,h.push(a.x,a.y,a.z)}}!function(){for(let t=0;t<e;t++)m(t);m(!1===r?e:0),function(){for(let t=0;t<=e;t++)for(let n=0;n<=i;n++)l.x=t/e,l.y=n/i,d.push(l.x,l.y)}(),function(){for(let t=1;t<=e;t++)for(let e=1;e<=i;e++){const n=(i+1)*(t-1)+(e-1),r=(i+1)*t+(e-1),s=(i+1)*t+e,a=(i+1)*(t-1)+e;p.push(n,r,a),p.push(r,s,a)}}()}(),this.setIndex(p),this.setAttribute("position",new _s(h,3)),this.setAttribute("normal",new _s(u,3)),this.setAttribute("uv",new _s(d,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}toJSON(){const t=super.toJSON();return t.path=this.parameters.path.toJSON(),t}static fromJSON(t){return new od((new ou[t.path.type]).fromJSON(t.path),t.tubularSegments,t.radius,t.radialSegments,t.closed)}}class ld extends Es{constructor(t=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:t},null!==t){const e=[],n=new Set,i=new Ci,r=new Ci;if(null!==t.index){const s=t.attributes.position,a=t.index;let o=t.groups;0===o.length&&(o=[{start:0,count:a.count,materialIndex:0}]);for(let t=0,l=o.length;t<l;++t){const l=o[t],c=l.start;for(let t=c,o=c+l.count;t<o;t+=3)for(let o=0;o<3;o++){const l=a.getX(t+o),c=a.getX(t+(o+1)%3);i.fromBufferAttribute(s,l),r.fromBufferAttribute(s,c),!0===cd(i,r,n)&&(e.push(i.x,i.y,i.z),e.push(r.x,r.y,r.z))}}}else{const s=t.attributes.position;for(let t=0,a=s.count/3;t<a;t++)for(let a=0;a<3;a++){const o=3*t+a,l=3*t+(a+1)%3;i.fromBufferAttribute(s,o),r.fromBufferAttribute(s,l),!0===cd(i,r,n)&&(e.push(i.x,i.y,i.z),e.push(r.x,r.y,r.z))}}this.setAttribute("position",new _s(e,3))}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}}function cd(t,e,n){const i=`${t.x},${t.y},${t.z}-${e.x},${e.y},${e.z}`,r=`${e.x},${e.y},${e.z}-${t.x},${t.y},${t.z}`;return!0!==n.has(i)&&!0!==n.has(r)&&(n.add(i),n.add(r),!0)}var hd=Object.freeze({__proto__:null,BoxGeometry:ks,CapsuleGeometry:uu,CircleGeometry:du,ConeGeometry:mu,CylinderGeometry:pu,DodecahedronGeometry:gu,EdgesGeometry:Mu,ExtrudeGeometry:Ku,IcosahedronGeometry:Qu,LatheGeometry:hu,OctahedronGeometry:td,PlaneGeometry:ha,PolyhedronGeometry:fu,RingGeometry:ed,ShapeGeometry:nd,SphereGeometry:id,TetrahedronGeometry:rd,TorusGeometry:sd,TorusKnotGeometry:ad,TubeGeometry:od,WireframeGeometry:ld});class ud extends ts{static get type(){return"ShadowMaterial"}constructor(t){super(),this.isShadowMaterial=!0,this.color=new Kr(0),this.transparent=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.fog=t.fog,this}}class dd extends Xs{static get type(){return"RawShaderMaterial"}constructor(t){super(t),this.isRawShaderMaterial=!0}}class pd extends ts{static get type(){return"MeshStandardMaterial"}constructor(t){super(),this.isMeshStandardMaterial=!0,this.defines={STANDARD:""},this.color=new Kr(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new fr,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.envMapIntensity=t.envMapIntensity,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class md extends pd{static get type(){return"MeshPhysicalMaterial"}constructor(t){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new Jn(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Wn(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Kr(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new Kr(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Kr(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(t)}get anisotropy(){return this._anisotropy}set anisotropy(t){this._anisotropy>0!=t>0&&this.version++,this._anisotropy=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get dispersion(){return this._dispersion}set dispersion(t){this._dispersion>0!=t>0&&this.version++,this._dispersion=t}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=t.anisotropy,this.anisotropyRotation=t.anisotropyRotation,this.anisotropyMap=t.anisotropyMap,this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.dispersion=t.dispersion,this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}class fd extends ts{static get type(){return"MeshPhongMaterial"}constructor(t){super(),this.isMeshPhongMaterial=!0,this.color=new Kr(16777215),this.specular=new Kr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new fr,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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.specular.copy(t.specular),this.shininess=t.shininess,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class gd extends ts{static get type(){return"MeshToonMaterial"}constructor(t){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.color=new Kr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.gradientMap=t.gradientMap,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}class vd extends ts{static get type(){return"MeshNormalMaterial"}constructor(t){super(),this.isMeshNormalMaterial=!0,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this}}class _d extends ts{static get type(){return"MeshLambertMaterial"}constructor(t){super(),this.isMeshLambertMaterial=!0,this.color=new Kr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Kr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new fr,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(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class xd extends ts{static get type(){return"MeshMatcapMaterial"}constructor(t){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.color=new Kr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Jn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={MATCAP:""},this.color.copy(t.color),this.matcap=t.matcap,this.map=t.map,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.flatShading=t.flatShading,this.fog=t.fog,this}}class yd extends fh{static get type(){return"LineDashedMaterial"}constructor(t){super(),this.isLineDashedMaterial=!0,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(t)}copy(t){return super.copy(t),this.scale=t.scale,this.dashSize=t.dashSize,this.gapSize=t.gapSize,this}}function Md(t,e,n){return!t||!n&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)}function Sd(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function bd(t){const e=t.length,n=new Array(e);for(let t=0;t!==e;++t)n[t]=t;return n.sort((function(e,n){return t[e]-t[n]})),n}function Td(t,e,n){const i=t.length,r=new t.constructor(i);for(let s=0,a=0;a!==i;++s){const i=n[s]*e;for(let n=0;n!==e;++n)r[a++]=t[i+n]}return r}function wd(t,e,n,i){let r=1,s=t[0];for(;void 0!==s&&void 0===s[i];)s=t[r++];if(void 0===s)return;let a=s[i];if(void 0!==a)if(Array.isArray(a))do{a=s[i],void 0!==a&&(e.push(s.time),n.push.apply(n,a)),s=t[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[i],void 0!==a&&(e.push(s.time),a.toArray(n,n.length)),s=t[r++]}while(void 0!==s);else do{a=s[i],void 0!==a&&(e.push(s.time),n.push(a)),s=t[r++]}while(void 0!==s)}const Ed={convertArray:Md,isTypedArray:Sd,getKeyframeOrder:bd,sortedArray:Td,flattenJSON:wd,subclip:function(t,e,n,i,r=30){const s=t.clone();s.name=e;const a=[];for(let t=0;t<s.tracks.length;++t){const e=s.tracks[t],o=e.getValueSize(),l=[],c=[];for(let t=0;t<e.times.length;++t){const s=e.times[t]*r;if(!(s<n||s>=i)){l.push(e.times[t]);for(let n=0;n<o;++n)c.push(e.values[t*o+n])}}0!==l.length&&(e.times=Md(l,e.times.constructor),e.values=Md(c,e.values.constructor),a.push(e))}s.tracks=a;let o=1/0;for(let t=0;t<s.tracks.length;++t)o>s.tracks[t].times[0]&&(o=s.tracks[t].times[0]);for(let t=0;t<s.tracks.length;++t)s.tracks[t].shift(-1*o);return s.resetDuration(),s},makeClipAdditive:function(t,e=0,n=t,i=30){i<=0&&(i=30);const r=n.tracks.length,s=e/i;for(let e=0;e<r;++e){const i=n.tracks[e],r=i.ValueTypeName;if("bool"===r||"string"===r)continue;const a=t.tracks.find((function(t){return t.name===i.name&&t.ValueTypeName===r}));if(void 0===a)continue;let o=0;const l=i.getValueSize();i.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(o=l/3);let c=0;const h=a.getValueSize();a.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(c=h/3);const u=i.times.length-1;let d;if(s<=i.times[0]){const t=o,e=l-o;d=i.values.slice(t,e)}else if(s>=i.times[u]){const t=u*l+o,e=t+l-o;d=i.values.slice(t,e)}else{const t=i.createInterpolant(),e=o,n=l-o;t.evaluate(s),d=t.resultBuffer.slice(e,n)}if("quaternion"===r){(new Ri).fromArray(d).normalize().conjugate().toArray(d)}const p=a.times.length;for(let t=0;t<p;++t){const e=t*h+c;if("quaternion"===r)Ri.multiplyQuaternionsFlat(a.values,e,d,0,a.values,e);else{const t=h-2*c;for(let n=0;n<t;++n)a.values[e+n]-=d[n]}}}return t.blendMode=ze,t}};class Ad{constructor(t,e,n,i){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==i?i:new e.constructor(n),this.sampleValues=e,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(t){const e=this.parameterPositions;let n=this._cachedIndex,i=e[n],r=e[n-1];t:{e:{let s;n:{i:if(!(t<i)){for(let s=n+2;;){if(void 0===i){if(t<r)break i;return n=e.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===s)break;if(r=i,i=e[++n],t<i)break e}s=e.length;break n}if(t>=r)break t;{const a=e[1];t<a&&(n=2,r=a);for(let s=n-2;;){if(void 0===r)return this._cachedIndex=0,this.copySampleValue_(0);if(n===s)break;if(i=r,r=e[--n-1],t>=r)break e}s=n,n=0}}for(;n<s;){const i=n+s>>>1;t<e[i]?s=i:n=i+1}if(i=e[n],r=e[n-1],void 0===r)return this._cachedIndex=0,this.copySampleValue_(0);if(void 0===i)return n=e.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,r,i)}return this.interpolate_(n,r,t,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(t){const e=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=t*i;for(let t=0;t!==i;++t)e[t]=n[r+t];return e}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}class Rd extends Ad{constructor(t,e,n,i){super(t,e,n,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:Ne,endingEnd:Ne}}intervalChanged_(t,e,n){const i=this.parameterPositions;let r=t-2,s=t+1,a=i[r],o=i[s];if(void 0===a)switch(this.getSettings_().endingStart){case Oe:r=t,a=2*e-n;break;case Fe:r=i.length-2,a=e+i[r]-i[r+1];break;default:r=t,a=n}if(void 0===o)switch(this.getSettings_().endingEnd){case Oe:s=t,o=2*n-e;break;case Fe:s=1,o=n+i[1]-i[0];break;default:s=t-1,o=e}const l=.5*(n-e),c=this.valueSize;this._weightPrev=l/(e-a),this._weightNext=l/(o-n),this._offsetPrev=r*c,this._offsetNext=s*c}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=t*a,l=o-a,c=this._offsetPrev,h=this._offsetNext,u=this._weightPrev,d=this._weightNext,p=(n-e)/(i-e),m=p*p,f=m*p,g=-u*f+2*u*m-u*p,v=(1+u)*f+(-1.5-2*u)*m+(-.5+u)*p+1,_=(-1-d)*f+(1.5+d)*m+.5*p,x=d*f-d*m;for(let t=0;t!==a;++t)r[t]=g*s[c+t]+v*s[l+t]+_*s[o+t]+x*s[h+t];return r}}class Cd extends Ad{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=t*a,l=o-a,c=(n-e)/(i-e),h=1-c;for(let t=0;t!==a;++t)r[t]=s[l+t]*h+s[o+t]*c;return r}}class Id extends Ad{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t){return this.copySampleValue_(t-1)}}class Pd{constructor(t,e,n,i){if(void 0===t)throw new Error("THREE.KeyframeTrack: track name is undefined");if(void 0===e||0===e.length)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+t);this.name=t,this.times=Md(e,this.TimeBufferType),this.values=Md(n,this.ValueBufferType),this.setInterpolation(i||this.DefaultInterpolation)}static toJSON(t){const e=t.constructor;let n;if(e.toJSON!==this.toJSON)n=e.toJSON(t);else{n={name:t.name,times:Md(t.times,Array),values:Md(t.values,Array)};const e=t.getInterpolation();e!==t.DefaultInterpolation&&(n.interpolation=e)}return n.type=t.ValueTypeName,n}InterpolantFactoryMethodDiscrete(t){return new Id(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodLinear(t){return new Cd(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodSmooth(t){return new Rd(this.times,this.values,this.getValueSize(),t)}setInterpolation(t){let e;switch(t){case Le:e=this.InterpolantFactoryMethodDiscrete;break;case Ue:e=this.InterpolantFactoryMethodLinear;break;case De:e=this.InterpolantFactoryMethodSmooth}if(void 0===e){const e="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant){if(t===this.DefaultInterpolation)throw new Error(e);this.setInterpolation(this.DefaultInterpolation)}return console.warn("THREE.KeyframeTrack:",e),this}return this.createInterpolant=e,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Le;case this.InterpolantFactoryMethodLinear:return Ue;case this.InterpolantFactoryMethodSmooth:return De}}getValueSize(){return this.values.length/this.times.length}shift(t){if(0!==t){const e=this.times;for(let n=0,i=e.length;n!==i;++n)e[n]+=t}return this}scale(t){if(1!==t){const e=this.times;for(let n=0,i=e.length;n!==i;++n)e[n]*=t}return this}trim(t,e){const n=this.times,i=n.length;let r=0,s=i-1;for(;r!==i&&n[r]<t;)++r;for(;-1!==s&&n[s]>e;)--s;if(++s,0!==r||s!==i){r>=s&&(s=Math.max(s,1),r=s-1);const t=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*t,s*t)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);const n=this.times,i=this.values,r=n.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let s=null;for(let e=0;e!==r;e++){const i=n[e];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,e,i),t=!1;break}if(null!==s&&s>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,e,i,s),t=!1;break}s=i}if(void 0!==i&&Sd(i))for(let e=0,n=i.length;e!==n;++e){const n=i[e];if(isNaN(n)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,e,n),t=!1;break}}return t}optimize(){const t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===De,r=t.length-1;let s=1;for(let a=1;a<r;++a){let r=!1;const o=t[a];if(o!==t[a+1]&&(1!==a||o!==t[0]))if(i)r=!0;else{const t=a*n,i=t-n,s=t+n;for(let a=0;a!==n;++a){const n=e[t+a];if(n!==e[i+a]||n!==e[s+a]){r=!0;break}}}if(r){if(a!==s){t[s]=t[a];const i=a*n,r=s*n;for(let t=0;t!==n;++t)e[r+t]=e[i+t]}++s}}if(r>0){t[s]=t[r];for(let t=r*n,i=s*n,a=0;a!==n;++a)e[i+a]=e[t+a];++s}return s!==t.length?(this.times=t.slice(0,s),this.values=e.slice(0,s*n)):(this.times=t,this.values=e),this}clone(){const t=this.times.slice(),e=this.values.slice(),n=new(0,this.constructor)(this.name,t,e);return n.createInterpolant=this.createInterpolant,n}}Pd.prototype.TimeBufferType=Float32Array,Pd.prototype.ValueBufferType=Float32Array,Pd.prototype.DefaultInterpolation=Ue;class Ld extends Pd{constructor(t,e,n){super(t,e,n)}}Ld.prototype.ValueTypeName="bool",Ld.prototype.ValueBufferType=Array,Ld.prototype.DefaultInterpolation=Le,Ld.prototype.InterpolantFactoryMethodLinear=void 0,Ld.prototype.InterpolantFactoryMethodSmooth=void 0;class Ud extends Pd{}Ud.prototype.ValueTypeName="color";class Dd extends Pd{}Dd.prototype.ValueTypeName="number";class Nd extends Ad{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-e)/(i-e);let l=t*a;for(let t=l+a;l!==t;l+=4)Ri.slerpFlat(r,0,s,l-a,s,l,o);return r}}class Od extends Pd{InterpolantFactoryMethodLinear(t){return new Nd(this.times,this.values,this.getValueSize(),t)}}Od.prototype.ValueTypeName="quaternion",Od.prototype.InterpolantFactoryMethodSmooth=void 0;class Fd extends Pd{constructor(t,e,n){super(t,e,n)}}Fd.prototype.ValueTypeName="string",Fd.prototype.ValueBufferType=Array,Fd.prototype.DefaultInterpolation=Le,Fd.prototype.InterpolantFactoryMethodLinear=void 0,Fd.prototype.InterpolantFactoryMethodSmooth=void 0;class Bd extends Pd{}Bd.prototype.ValueTypeName="vector";class zd{constructor(t="",e=-1,n=[],i=2500){this.name=t,this.tracks=n,this.duration=e,this.blendMode=i,this.uuid=Gn(),this.duration<0&&this.resetDuration()}static parse(t){const e=[],n=t.tracks,i=1/(t.fps||1);for(let t=0,r=n.length;t!==r;++t)e.push(kd(n[t]).scale(i));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r}static toJSON(t){const e=[],n=t.tracks,i={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let t=0,i=n.length;t!==i;++t)e.push(Pd.toJSON(n[t]));return i}static CreateFromMorphTargetSequence(t,e,n,i){const r=e.length,s=[];for(let t=0;t<r;t++){let a=[],o=[];a.push((t+r-1)%r,t,(t+1)%r),o.push(0,1,0);const l=bd(a);a=Td(a,1,l),o=Td(o,1,l),i||0!==a[0]||(a.push(r),o.push(o[0])),s.push(new Dd(".morphTargetInfluences["+e[t].name+"]",a,o).scale(1/n))}return new this(t,-1,s)}static findByName(t,e){let n=t;if(!Array.isArray(t)){const e=t;n=e.geometry&&e.geometry.animations||e.animations}for(let t=0;t<n.length;t++)if(n[t].name===e)return n[t];return null}static CreateClipsFromMorphTargetSequences(t,e,n){const i={},r=/^([\w-]*?)([\d]+)$/;for(let e=0,n=t.length;e<n;e++){const n=t[e],s=n.name.match(r);if(s&&s.length>1){const t=s[1];let e=i[t];e||(i[t]=e=[]),e.push(n)}}const s=[];for(const t in i)s.push(this.CreateFromMorphTargetSequence(t,i[t],e,n));return s}static parseAnimation(t,e){if(!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(t,e,n,i,r){if(0!==n.length){const s=[],a=[];wd(n,s,a,i),0!==s.length&&r.push(new t(e,s,a))}},i=[],r=t.name||"default",s=t.fps||30,a=t.blendMode;let o=t.length||-1;const l=t.hierarchy||[];for(let t=0;t<l.length;t++){const r=l[t].keys;if(r&&0!==r.length)if(r[0].morphTargets){const t={};let e;for(e=0;e<r.length;e++)if(r[e].morphTargets)for(let n=0;n<r[e].morphTargets.length;n++)t[r[e].morphTargets[n]]=-1;for(const n in t){const t=[],s=[];for(let i=0;i!==r[e].morphTargets.length;++i){const i=r[e];t.push(i.time),s.push(i.morphTarget===n?1:0)}i.push(new Dd(".morphTargetInfluence["+n+"]",t,s))}o=t.length*s}else{const s=".bones["+e[t].name+"]";n(Bd,s+".position",r,"pos",i),n(Od,s+".quaternion",r,"rot",i),n(Bd,s+".scale",r,"scl",i)}}if(0===i.length)return null;return new this(r,o,i,a)}resetDuration(){let t=0;for(let e=0,n=this.tracks.length;e!==n;++e){const n=this.tracks[e];t=Math.max(t,n.times[n.times.length-1])}return this.duration=t,this}trim(){for(let t=0;t<this.tracks.length;t++)this.tracks[t].trim(0,this.duration);return this}validate(){let t=!0;for(let e=0;e<this.tracks.length;e++)t=t&&this.tracks[e].validate();return t}optimize(){for(let t=0;t<this.tracks.length;t++)this.tracks[t].optimize();return this}clone(){const t=[];for(let e=0;e<this.tracks.length;e++)t.push(this.tracks[e].clone());return new this.constructor(this.name,this.duration,t,this.blendMode)}toJSON(){return this.constructor.toJSON(this)}}function kd(t){if(void 0===t.type)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const e=function(t){switch(t.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return Dd;case"vector":case"vector2":case"vector3":case"vector4":return Bd;case"color":return Ud;case"quaternion":return Od;case"bool":case"boolean":return Ld;case"string":return Fd}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+t)}(t.type);if(void 0===t.times){const e=[],n=[];wd(t.keys,e,n,"value"),t.times=e,t.values=n}return void 0!==e.parse?e.parse(t):new e(t.name,t.times,t.values,t.interpolation)}const Vd={enabled:!1,files:{},add:function(t,e){!1!==this.enabled&&(this.files[t]=e)},get:function(t){if(!1!==this.enabled)return this.files[t]},remove:function(t){delete this.files[t]},clear:function(){this.files={}}};class Hd{constructor(t,e,n){const i=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=n,this.itemStart=function(t){o++,!1===s&&void 0!==i.onStart&&i.onStart(t,a,o),s=!0},this.itemEnd=function(t){a++,void 0!==i.onProgress&&i.onProgress(t,a,o),a===o&&(s=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(t){void 0!==i.onError&&i.onError(t)},this.resolveURL=function(t){return r?r(t):t},this.setURLModifier=function(t){return r=t,this},this.addHandler=function(t,e){return l.push(t,e),this},this.removeHandler=function(t){const e=l.indexOf(t);return-1!==e&&l.splice(e,2),this},this.getHandler=function(t){for(let e=0,n=l.length;e<n;e+=2){const n=l[e],i=l[e+1];if(n.global&&(n.lastIndex=0),n.test(t))return i}return null}}}const Gd=new Hd;class Wd{constructor(t){this.manager=void 0!==t?t:Gd,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(t,e){const n=this;return new Promise((function(i,r){n.load(t,i,e,r)}))}parse(){}setCrossOrigin(t){return this.crossOrigin=t,this}setWithCredentials(t){return this.withCredentials=t,this}setPath(t){return this.path=t,this}setResourcePath(t){return this.resourcePath=t,this}setRequestHeader(t){return this.requestHeader=t,this}}Wd.DEFAULT_MATERIAL_NAME="__DEFAULT";const Xd={};class jd extends Error{constructor(t,e){super(t),this.response=e}}class qd extends Wd{constructor(t){super(t)}load(t,e,n,i){void 0===t&&(t=""),void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=Vd.get(t);if(void 0!==r)return this.manager.itemStart(t),setTimeout((()=>{e&&e(r),this.manager.itemEnd(t)}),0),r;if(void 0!==Xd[t])return void Xd[t].push({onLoad:e,onProgress:n,onError:i});Xd[t]=[],Xd[t].push({onLoad:e,onProgress:n,onError:i});const s=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(s).then((e=>{if(200===e.status||0===e.status){if(0===e.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body||void 0===e.body.getReader)return e;const n=Xd[t],i=e.body.getReader(),r=e.headers.get("X-File-Size")||e.headers.get("Content-Length"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(t){!function e(){i.read().then((({done:i,value:r})=>{if(i)t.close();else{o+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let t=0,e=n.length;t<e;t++){const e=n[t];e.onProgress&&e.onProgress(i)}t.enqueue(r),e()}}),(e=>{t.error(e)}))}()}});return new Response(l)}throw new jd(`fetch for "${e.url}" responded with ${e.status}: ${e.statusText}`,e)})).then((t=>{switch(o){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"document":return t.text().then((t=>(new DOMParser).parseFromString(t,a)));case"json":return t.json();default:if(void 0===a)return t.text();{const e=/charset="?([^;"\s]*)"?/i.exec(a),n=e&&e[1]?e[1].toLowerCase():void 0,i=new TextDecoder(n);return t.arrayBuffer().then((t=>i.decode(t)))}}})).then((e=>{Vd.add(t,e);const n=Xd[t];delete Xd[t];for(let t=0,i=n.length;t<i;t++){const i=n[t];i.onLoad&&i.onLoad(e)}})).catch((e=>{const n=Xd[t];if(void 0===n)throw this.manager.itemError(t),e;delete Xd[t];for(let t=0,i=n.length;t<i;t++){const i=n[t];i.onError&&i.onError(e)}this.manager.itemError(t)})).finally((()=>{this.manager.itemEnd(t)})),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}}class Yd extends Wd{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new qd(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e=[];for(let n=0;n<t.length;n++){const i=zd.parse(t[n]);e.push(i)}return e}}class Zd extends Wd{constructor(t){super(t)}load(t,e,n,i){const r=this,s=[],a=new Bh,o=new qd(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(r.withCredentials);let l=0;function c(c){o.load(t[c],(function(t){const n=r.parse(t,!0);s[c]={width:n.width,height:n.height,format:n.format,mipmaps:n.mipmaps},l+=1,6===l&&(1===n.mipmapCount&&(a.minFilter=Mt),a.image=s,a.format=n.format,a.needsUpdate=!0,e&&e(a))}),n,i)}if(Array.isArray(t))for(let e=0,n=t.length;e<n;++e)c(e);else o.load(t,(function(t){const n=r.parse(t,!0);if(n.isCubemap){const t=n.mipmaps.length/n.mipmapCount;for(let e=0;e<t;e++){s[e]={mipmaps:[]};for(let t=0;t<n.mipmapCount;t++)s[e].mipmaps.push(n.mipmaps[e*n.mipmapCount+t]),s[e].format=n.format,s[e].width=n.width,s[e].height=n.height}a.image=s}else a.image.width=n.width,a.image.height=n.height,a.mipmaps=n.mipmaps;1===n.mipmapCount&&(a.minFilter=Mt),a.format=n.format,a.needsUpdate=!0,e&&e(a)}),n,i);return a}}class Jd extends Wd{constructor(t){super(t)}load(t,e,n,i){void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=this,s=Vd.get(t);if(void 0!==s)return r.manager.itemStart(t),setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s;const a=ni("img");function o(){c(),Vd.add(t,this),e&&e(this),r.manager.itemEnd(t)}function l(e){c(),i&&i(e),r.manager.itemError(t),r.manager.itemEnd(t)}function c(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==t.slice(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),r.manager.itemStart(t),a.src=t,a}}class Kd extends Wd{constructor(t){super(t)}load(t,e,n,i){const r=new Qs;r.colorSpace=Je;const s=new Jd(this.manager);s.setCrossOrigin(this.crossOrigin),s.setPath(this.path);let a=0;function o(n){s.load(t[n],(function(t){r.images[n]=t,a++,6===a&&(r.needsUpdate=!0,e&&e(r))}),void 0,i)}for(let e=0;e<t.length;++e)o(e);return r}}class $d extends Wd{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new Bc,a=new qd(this.manager);return a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setPath(this.path),a.setWithCredentials(r.withCredentials),a.load(t,(function(t){let n;try{n=r.parse(t)}catch(t){if(void 0===i)return void console.error(t);i(t)}void 0!==n.image?s.image=n.image:void 0!==n.data&&(s.image.width=n.width,s.image.height=n.height,s.image.data=n.data),s.wrapS=void 0!==n.wrapS?n.wrapS:mt,s.wrapT=void 0!==n.wrapT?n.wrapT:mt,s.magFilter=void 0!==n.magFilter?n.magFilter:Mt,s.minFilter=void 0!==n.minFilter?n.minFilter:Mt,s.anisotropy=void 0!==n.anisotropy?n.anisotropy:1,void 0!==n.colorSpace&&(s.colorSpace=n.colorSpace),void 0!==n.flipY&&(s.flipY=n.flipY),void 0!==n.format&&(s.format=n.format),void 0!==n.type&&(s.type=n.type),void 0!==n.mipmaps&&(s.mipmaps=n.mipmaps,s.minFilter=Tt),1===n.mipmapCount&&(s.minFilter=Mt),void 0!==n.generateMipmaps&&(s.generateMipmaps=n.generateMipmaps),s.needsUpdate=!0,e&&e(s,n)}),n,i),s}}class Qd extends Wd{constructor(t){super(t)}load(t,e,n,i){const r=new yi,s=new Jd(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(t,(function(t){r.image=t,r.needsUpdate=!0,void 0!==e&&e(r)}),n,i),r}}class tp extends Lr{constructor(t,e=1){super(),this.isLight=!0,this.type="Light",this.color=new Kr(t),this.intensity=e}dispose(){}copy(t,e){return super.copy(t,e),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),void 0!==this.shadow&&(e.object.shadow=this.shadow.toJSON()),void 0!==this.target&&(e.object.target=this.target.uuid),e}}class ep extends tp{constructor(t,e,n){super(t,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Lr.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Kr(e)}copy(t,e){return super.copy(t,e),this.groundColor.copy(t.groundColor),this}}const np=new sr,ip=new Ci,rp=new Ci;class sp{constructor(t){this.camera=t,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Jn(512,512),this.map=null,this.mapPass=null,this.matrix=new sr,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new oa,this._frameExtents=new Jn(1,1),this._viewportCount=1,this._viewports=[new Mi(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,n=this.matrix;ip.setFromMatrixPosition(t.matrixWorld),e.position.copy(ip),rp.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(rp),e.updateMatrixWorld(),np.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(np),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(np)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.intensity=t.intensity,this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const t={};return 1!==this.intensity&&(t.intensity=this.intensity),0!==this.bias&&(t.bias=this.bias),0!==this.normalBias&&(t.normalBias=this.normalBias),1!==this.radius&&(t.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}class ap extends sp{constructor(){super(new Js(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(t){const e=this.camera,n=2*Hn*t.angle*this.focus,i=this.mapSize.width/this.mapSize.height,r=t.distance||e.far;n===e.fov&&i===e.aspect&&r===e.far||(e.fov=n,e.aspect=i,e.far=r,e.updateProjectionMatrix()),super.updateMatrices(t)}copy(t){return super.copy(t),this.focus=t.focus,this}}class op extends tp{constructor(t,e,n=0,i=Math.PI/3,r=0,s=2){super(t,e),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Lr.DEFAULT_UP),this.updateMatrix(),this.target=new Lr,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new ap}get power(){return this.intensity*Math.PI}set power(t){this.intensity=t/Math.PI}dispose(){this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}const lp=new sr,cp=new Ci,hp=new Ci;class up extends sp{constructor(){super(new Js(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Jn(4,2),this._viewportCount=6,this._viewports=[new Mi(2,1,1,1),new Mi(0,1,1,1),new Mi(3,1,1,1),new Mi(1,1,1,1),new Mi(3,0,1,1),new Mi(1,0,1,1)],this._cubeDirections=[new Ci(1,0,0),new Ci(-1,0,0),new Ci(0,0,1),new Ci(0,0,-1),new Ci(0,1,0),new Ci(0,-1,0)],this._cubeUps=[new Ci(0,1,0),new Ci(0,1,0),new Ci(0,1,0),new Ci(0,1,0),new Ci(0,0,1),new Ci(0,0,-1)]}updateMatrices(t,e=0){const n=this.camera,i=this.matrix,r=t.distance||n.far;r!==n.far&&(n.far=r,n.updateProjectionMatrix()),cp.setFromMatrixPosition(t.matrixWorld),n.position.copy(cp),hp.copy(n.position),hp.add(this._cubeDirections[e]),n.up.copy(this._cubeUps[e]),n.lookAt(hp),n.updateMatrixWorld(),i.makeTranslation(-cp.x,-cp.y,-cp.z),lp.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(lp)}}class dp extends tp{constructor(t,e,n=0,i=2){super(t,e),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new up}get power(){return 4*this.intensity*Math.PI}set power(t){this.intensity=t/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}class pp extends sp{constructor(){super(new ba(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class mp extends tp{constructor(t,e){super(t,e),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Lr.DEFAULT_UP),this.updateMatrix(),this.target=new Lr,this.shadow=new pp}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}class fp extends tp{constructor(t,e){super(t,e),this.isAmbientLight=!0,this.type="AmbientLight"}}class gp extends tp{constructor(t,e,n=10,i=10){super(t,e),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=n,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(t){this.intensity=t/(this.width*this.height*Math.PI)}copy(t){return super.copy(t),this.width=t.width,this.height=t.height,this}toJSON(t){const e=super.toJSON(t);return e.object.width=this.width,e.object.height=this.height,e}}class vp{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let t=0;t<9;t++)this.coefficients.push(new Ci)}set(t){for(let e=0;e<9;e++)this.coefficients[e].copy(t[e]);return this}zero(){for(let t=0;t<9;t++)this.coefficients[t].set(0,0,0);return this}getAt(t,e){const n=t.x,i=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.282095),e.addScaledVector(s[1],.488603*i),e.addScaledVector(s[2],.488603*r),e.addScaledVector(s[3],.488603*n),e.addScaledVector(s[4],n*i*1.092548),e.addScaledVector(s[5],i*r*1.092548),e.addScaledVector(s[6],.315392*(3*r*r-1)),e.addScaledVector(s[7],n*r*1.092548),e.addScaledVector(s[8],.546274*(n*n-i*i)),e}getIrradianceAt(t,e){const n=t.x,i=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.886227),e.addScaledVector(s[1],1.023328*i),e.addScaledVector(s[2],1.023328*r),e.addScaledVector(s[3],1.023328*n),e.addScaledVector(s[4],.858086*n*i),e.addScaledVector(s[5],.858086*i*r),e.addScaledVector(s[6],.743125*r*r-.247708),e.addScaledVector(s[7],.858086*n*r),e.addScaledVector(s[8],.429043*(n*n-i*i)),e}add(t){for(let e=0;e<9;e++)this.coefficients[e].add(t.coefficients[e]);return this}addScaledSH(t,e){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(t.coefficients[n],e);return this}scale(t){for(let e=0;e<9;e++)this.coefficients[e].multiplyScalar(t);return this}lerp(t,e){for(let n=0;n<9;n++)this.coefficients[n].lerp(t.coefficients[n],e);return this}equals(t){for(let e=0;e<9;e++)if(!this.coefficients[e].equals(t.coefficients[e]))return!1;return!0}copy(t){return this.set(t.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(t,e=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].fromArray(t,e+3*i);return this}toArray(t=[],e=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].toArray(t,e+3*i);return t}static getBasisAt(t,e){const n=t.x,i=t.y,r=t.z;e[0]=.282095,e[1]=.488603*i,e[2]=.488603*r,e[3]=.488603*n,e[4]=1.092548*n*i,e[5]=1.092548*i*r,e[6]=.315392*(3*r*r-1),e[7]=1.092548*n*r,e[8]=.546274*(n*n-i*i)}}class _p extends tp{constructor(t=new vp,e=1){super(void 0,e),this.isLightProbe=!0,this.sh=t}copy(t){return super.copy(t),this.sh.copy(t.sh),this}fromJSON(t){return this.intensity=t.intensity,this.sh.fromArray(t.sh),this}toJSON(t){const e=super.toJSON(t);return e.object.sh=this.sh.toArray(),e}}class xp extends Wd{constructor(t){super(t),this.textures={}}load(t,e,n,i){const r=this,s=new qd(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e=this.textures;function n(t){return void 0===e[t]&&console.warn("THREE.MaterialLoader: Undefined texture",t),e[t]}const i=this.createMaterialFromType(t.type);if(void 0!==t.uuid&&(i.uuid=t.uuid),void 0!==t.name&&(i.name=t.name),void 0!==t.color&&void 0!==i.color&&i.color.setHex(t.color),void 0!==t.roughness&&(i.roughness=t.roughness),void 0!==t.metalness&&(i.metalness=t.metalness),void 0!==t.sheen&&(i.sheen=t.sheen),void 0!==t.sheenColor&&(i.sheenColor=(new Kr).setHex(t.sheenColor)),void 0!==t.sheenRoughness&&(i.sheenRoughness=t.sheenRoughness),void 0!==t.emissive&&void 0!==i.emissive&&i.emissive.setHex(t.emissive),void 0!==t.specular&&void 0!==i.specular&&i.specular.setHex(t.specular),void 0!==t.specularIntensity&&(i.specularIntensity=t.specularIntensity),void 0!==t.specularColor&&void 0!==i.specularColor&&i.specularColor.setHex(t.specularColor),void 0!==t.shininess&&(i.shininess=t.shininess),void 0!==t.clearcoat&&(i.clearcoat=t.clearcoat),void 0!==t.clearcoatRoughness&&(i.clearcoatRoughness=t.clearcoatRoughness),void 0!==t.dispersion&&(i.dispersion=t.dispersion),void 0!==t.iridescence&&(i.iridescence=t.iridescence),void 0!==t.iridescenceIOR&&(i.iridescenceIOR=t.iridescenceIOR),void 0!==t.iridescenceThicknessRange&&(i.iridescenceThicknessRange=t.iridescenceThicknessRange),void 0!==t.transmission&&(i.transmission=t.transmission),void 0!==t.thickness&&(i.thickness=t.thickness),void 0!==t.attenuationDistance&&(i.attenuationDistance=t.attenuationDistance),void 0!==t.attenuationColor&&void 0!==i.attenuationColor&&i.attenuationColor.setHex(t.attenuationColor),void 0!==t.anisotropy&&(i.anisotropy=t.anisotropy),void 0!==t.anisotropyRotation&&(i.anisotropyRotation=t.anisotropyRotation),void 0!==t.fog&&(i.fog=t.fog),void 0!==t.flatShading&&(i.flatShading=t.flatShading),void 0!==t.blending&&(i.blending=t.blending),void 0!==t.combine&&(i.combine=t.combine),void 0!==t.side&&(i.side=t.side),void 0!==t.shadowSide&&(i.shadowSide=t.shadowSide),void 0!==t.opacity&&(i.opacity=t.opacity),void 0!==t.transparent&&(i.transparent=t.transparent),void 0!==t.alphaTest&&(i.alphaTest=t.alphaTest),void 0!==t.alphaHash&&(i.alphaHash=t.alphaHash),void 0!==t.depthFunc&&(i.depthFunc=t.depthFunc),void 0!==t.depthTest&&(i.depthTest=t.depthTest),void 0!==t.depthWrite&&(i.depthWrite=t.depthWrite),void 0!==t.colorWrite&&(i.colorWrite=t.colorWrite),void 0!==t.blendSrc&&(i.blendSrc=t.blendSrc),void 0!==t.blendDst&&(i.blendDst=t.blendDst),void 0!==t.blendEquation&&(i.blendEquation=t.blendEquation),void 0!==t.blendSrcAlpha&&(i.blendSrcAlpha=t.blendSrcAlpha),void 0!==t.blendDstAlpha&&(i.blendDstAlpha=t.blendDstAlpha),void 0!==t.blendEquationAlpha&&(i.blendEquationAlpha=t.blendEquationAlpha),void 0!==t.blendColor&&void 0!==i.blendColor&&i.blendColor.setHex(t.blendColor),void 0!==t.blendAlpha&&(i.blendAlpha=t.blendAlpha),void 0!==t.stencilWriteMask&&(i.stencilWriteMask=t.stencilWriteMask),void 0!==t.stencilFunc&&(i.stencilFunc=t.stencilFunc),void 0!==t.stencilRef&&(i.stencilRef=t.stencilRef),void 0!==t.stencilFuncMask&&(i.stencilFuncMask=t.stencilFuncMask),void 0!==t.stencilFail&&(i.stencilFail=t.stencilFail),void 0!==t.stencilZFail&&(i.stencilZFail=t.stencilZFail),void 0!==t.stencilZPass&&(i.stencilZPass=t.stencilZPass),void 0!==t.stencilWrite&&(i.stencilWrite=t.stencilWrite),void 0!==t.wireframe&&(i.wireframe=t.wireframe),void 0!==t.wireframeLinewidth&&(i.wireframeLinewidth=t.wireframeLinewidth),void 0!==t.wireframeLinecap&&(i.wireframeLinecap=t.wireframeLinecap),void 0!==t.wireframeLinejoin&&(i.wireframeLinejoin=t.wireframeLinejoin),void 0!==t.rotation&&(i.rotation=t.rotation),void 0!==t.linewidth&&(i.linewidth=t.linewidth),void 0!==t.dashSize&&(i.dashSize=t.dashSize),void 0!==t.gapSize&&(i.gapSize=t.gapSize),void 0!==t.scale&&(i.scale=t.scale),void 0!==t.polygonOffset&&(i.polygonOffset=t.polygonOffset),void 0!==t.polygonOffsetFactor&&(i.polygonOffsetFactor=t.polygonOffsetFactor),void 0!==t.polygonOffsetUnits&&(i.polygonOffsetUnits=t.polygonOffsetUnits),void 0!==t.dithering&&(i.dithering=t.dithering),void 0!==t.alphaToCoverage&&(i.alphaToCoverage=t.alphaToCoverage),void 0!==t.premultipliedAlpha&&(i.premultipliedAlpha=t.premultipliedAlpha),void 0!==t.forceSinglePass&&(i.forceSinglePass=t.forceSinglePass),void 0!==t.visible&&(i.visible=t.visible),void 0!==t.toneMapped&&(i.toneMapped=t.toneMapped),void 0!==t.userData&&(i.userData=t.userData),void 0!==t.vertexColors&&("number"==typeof t.vertexColors?i.vertexColors=t.vertexColors>0:i.vertexColors=t.vertexColors),void 0!==t.uniforms)for(const e in t.uniforms){const r=t.uniforms[e];switch(i.uniforms[e]={},r.type){case"t":i.uniforms[e].value=n(r.value);break;case"c":i.uniforms[e].value=(new Kr).setHex(r.value);break;case"v2":i.uniforms[e].value=(new Jn).fromArray(r.value);break;case"v3":i.uniforms[e].value=(new Ci).fromArray(r.value);break;case"v4":i.uniforms[e].value=(new Mi).fromArray(r.value);break;case"m3":i.uniforms[e].value=(new Kn).fromArray(r.value);break;case"m4":i.uniforms[e].value=(new sr).fromArray(r.value);break;default:i.uniforms[e].value=r.value}}if(void 0!==t.defines&&(i.defines=t.defines),void 0!==t.vertexShader&&(i.vertexShader=t.vertexShader),void 0!==t.fragmentShader&&(i.fragmentShader=t.fragmentShader),void 0!==t.glslVersion&&(i.glslVersion=t.glslVersion),void 0!==t.extensions)for(const e in t.extensions)i.extensions[e]=t.extensions[e];if(void 0!==t.lights&&(i.lights=t.lights),void 0!==t.clipping&&(i.clipping=t.clipping),void 0!==t.size&&(i.size=t.size),void 0!==t.sizeAttenuation&&(i.sizeAttenuation=t.sizeAttenuation),void 0!==t.map&&(i.map=n(t.map)),void 0!==t.matcap&&(i.matcap=n(t.matcap)),void 0!==t.alphaMap&&(i.alphaMap=n(t.alphaMap)),void 0!==t.bumpMap&&(i.bumpMap=n(t.bumpMap)),void 0!==t.bumpScale&&(i.bumpScale=t.bumpScale),void 0!==t.normalMap&&(i.normalMap=n(t.normalMap)),void 0!==t.normalMapType&&(i.normalMapType=t.normalMapType),void 0!==t.normalScale){let e=t.normalScale;!1===Array.isArray(e)&&(e=[e,e]),i.normalScale=(new Jn).fromArray(e)}return void 0!==t.displacementMap&&(i.displacementMap=n(t.displacementMap)),void 0!==t.displacementScale&&(i.displacementScale=t.displacementScale),void 0!==t.displacementBias&&(i.displacementBias=t.displacementBias),void 0!==t.roughnessMap&&(i.roughnessMap=n(t.roughnessMap)),void 0!==t.metalnessMap&&(i.metalnessMap=n(t.metalnessMap)),void 0!==t.emissiveMap&&(i.emissiveMap=n(t.emissiveMap)),void 0!==t.emissiveIntensity&&(i.emissiveIntensity=t.emissiveIntensity),void 0!==t.specularMap&&(i.specularMap=n(t.specularMap)),void 0!==t.specularIntensityMap&&(i.specularIntensityMap=n(t.specularIntensityMap)),void 0!==t.specularColorMap&&(i.specularColorMap=n(t.specularColorMap)),void 0!==t.envMap&&(i.envMap=n(t.envMap)),void 0!==t.envMapRotation&&i.envMapRotation.fromArray(t.envMapRotation),void 0!==t.envMapIntensity&&(i.envMapIntensity=t.envMapIntensity),void 0!==t.reflectivity&&(i.reflectivity=t.reflectivity),void 0!==t.refractionRatio&&(i.refractionRatio=t.refractionRatio),void 0!==t.lightMap&&(i.lightMap=n(t.lightMap)),void 0!==t.lightMapIntensity&&(i.lightMapIntensity=t.lightMapIntensity),void 0!==t.aoMap&&(i.aoMap=n(t.aoMap)),void 0!==t.aoMapIntensity&&(i.aoMapIntensity=t.aoMapIntensity),void 0!==t.gradientMap&&(i.gradientMap=n(t.gradientMap)),void 0!==t.clearcoatMap&&(i.clearcoatMap=n(t.clearcoatMap)),void 0!==t.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=n(t.clearcoatRoughnessMap)),void 0!==t.clearcoatNormalMap&&(i.clearcoatNormalMap=n(t.clearcoatNormalMap)),void 0!==t.clearcoatNormalScale&&(i.clearcoatNormalScale=(new Jn).fromArray(t.clearcoatNormalScale)),void 0!==t.iridescenceMap&&(i.iridescenceMap=n(t.iridescenceMap)),void 0!==t.iridescenceThicknessMap&&(i.iridescenceThicknessMap=n(t.iridescenceThicknessMap)),void 0!==t.transmissionMap&&(i.transmissionMap=n(t.transmissionMap)),void 0!==t.thicknessMap&&(i.thicknessMap=n(t.thicknessMap)),void 0!==t.anisotropyMap&&(i.anisotropyMap=n(t.anisotropyMap)),void 0!==t.sheenColorMap&&(i.sheenColorMap=n(t.sheenColorMap)),void 0!==t.sheenRoughnessMap&&(i.sheenRoughnessMap=n(t.sheenRoughnessMap)),i}setTextures(t){return this.textures=t,this}createMaterialFromType(t){return xp.createMaterialFromType(t)}static createMaterialFromType(t){return new{ShadowMaterial:ud,SpriteMaterial:lc,RawShaderMaterial:dd,ShaderMaterial:Xs,PointsMaterial:Ch,MeshPhysicalMaterial:md,MeshStandardMaterial:pd,MeshPhongMaterial:fd,MeshToonMaterial:gd,MeshNormalMaterial:vd,MeshLambertMaterial:_d,MeshDepthMaterial:Ol,MeshDistanceMaterial:Fl,MeshBasicMaterial:es,MeshMatcapMaterial:xd,LineDashedMaterial:yd,LineBasicMaterial:fh,Material:ts}[t]}}class yp{static decodeText(t){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(t);let e="";for(let n=0,i=t.length;n<i;n++)e+=String.fromCharCode(t[n]);try{return decodeURIComponent(escape(e))}catch(t){return e}}static extractUrlBase(t){const e=t.lastIndexOf("/");return-1===e?"./":t.slice(0,e+1)}static resolveURL(t,e){return"string"!=typeof t||""===t?"":(/^https?:\/\//i.test(e)&&/^\//.test(t)&&(e=e.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(t)||/^data:.*,.*$/i.test(t)||/^blob:.*$/i.test(t)?t:e+t)}}class Mp extends Es{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(t){return super.copy(t),this.instanceCount=t.instanceCount,this}toJSON(){const t=super.toJSON();return t.instanceCount=this.instanceCount,t.isInstancedBufferGeometry=!0,t}}class Sp extends Wd{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new qd(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e={},n={};function i(t,i){if(void 0!==e[i])return e[i];const r=t.interleavedBuffers[i],s=function(t,e){if(void 0!==n[e])return n[e];const i=t.arrayBuffers,r=i[e],s=new Uint32Array(r).buffer;return n[e]=s,s}(t,r.buffer),a=ei(r.type,s),o=new sc(a,r.stride);return o.uuid=r.uuid,e[i]=o,o}const r=t.isInstancedBufferGeometry?new Mp:new Es,s=t.data.index;if(void 0!==s){const t=ei(s.type,s.array);r.setIndex(new cs(t,1))}const a=t.data.attributes;for(const e in a){const n=a[e];let s;if(n.isInterleavedBufferAttribute){const e=i(t.data,n.data);s=new oc(e,n.itemSize,n.offset,n.normalized)}else{const t=ei(n.type,n.array);s=new(n.isInstancedBufferAttribute?Hc:cs)(t,n.itemSize,n.normalized)}void 0!==n.name&&(s.name=n.name),void 0!==n.usage&&s.setUsage(n.usage),r.setAttribute(e,s)}const o=t.data.morphAttributes;if(o)for(const e in o){const n=o[e],s=[];for(let e=0,r=n.length;e<r;e++){const r=n[e];let a;if(r.isInterleavedBufferAttribute){const e=i(t.data,r.data);a=new oc(e,r.itemSize,r.offset,r.normalized)}else{const t=ei(r.type,r.array);a=new cs(t,r.itemSize,r.normalized)}void 0!==r.name&&(a.name=r.name),s.push(a)}r.morphAttributes[e]=s}t.data.morphTargetsRelative&&(r.morphTargetsRelative=!0);const l=t.data.groups||t.data.drawcalls||t.data.offsets;if(void 0!==l)for(let t=0,e=l.length;t!==e;++t){const e=l[t];r.addGroup(e.start,e.count,e.materialIndex)}const c=t.data.boundingSphere;if(void 0!==c){const t=new Ci;void 0!==c.center&&t.fromArray(c.center),r.boundingSphere=new Ji(t,c.radius)}return t.name&&(r.name=t.name),t.userData&&(r.userData=t.userData),r}}class bp extends Wd{constructor(t){super(t)}load(t,e,n,i){const r=this,s=""===this.path?yp.extractUrlBase(t):this.path;this.resourcePath=this.resourcePath||s;const a=new qd(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(t,(function(n){let s=null;try{s=JSON.parse(n)}catch(e){return void 0!==i&&i(e),void console.error("THREE:ObjectLoader: Can't parse "+t+".",e.message)}const a=s.metadata;if(void 0===a||void 0===a.type||"geometry"===a.type.toLowerCase())return void 0!==i&&i(new Error("THREE.ObjectLoader: Can't load "+t)),void console.error("THREE.ObjectLoader: Can't load "+t);r.parse(s,e)}),n,i)}async loadAsync(t,e){const n=""===this.path?yp.extractUrlBase(t):this.path;this.resourcePath=this.resourcePath||n;const i=new qd(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials);const r=await i.loadAsync(t,e),s=JSON.parse(r),a=s.metadata;if(void 0===a||void 0===a.type||"geometry"===a.type.toLowerCase())throw new Error("THREE.ObjectLoader: Can't load "+t);return await this.parseAsync(s)}parse(t,e){const n=this.parseAnimations(t.animations),i=this.parseShapes(t.shapes),r=this.parseGeometries(t.geometries,i),s=this.parseImages(t.images,(function(){void 0!==e&&e(l)})),a=this.parseTextures(t.textures,s),o=this.parseMaterials(t.materials,a),l=this.parseObject(t.object,r,o,a,n),c=this.parseSkeletons(t.skeletons,l);if(this.bindSkeletons(l,c),this.bindLightTargets(l),void 0!==e){let t=!1;for(const e in s)if(s[e].data instanceof HTMLImageElement){t=!0;break}!1===t&&e(l)}return l}async parseAsync(t){const e=this.parseAnimations(t.animations),n=this.parseShapes(t.shapes),i=this.parseGeometries(t.geometries,n),r=await this.parseImagesAsync(t.images),s=this.parseTextures(t.textures,r),a=this.parseMaterials(t.materials,s),o=this.parseObject(t.object,i,a,s,e),l=this.parseSkeletons(t.skeletons,o);return this.bindSkeletons(o,l),this.bindLightTargets(o),o}parseShapes(t){const e={};if(void 0!==t)for(let n=0,i=t.length;n<i;n++){const i=(new Su).fromJSON(t[n]);e[i.uuid]=i}return e}parseSkeletons(t,e){const n={},i={};if(e.traverse((function(t){t.isBone&&(i[t.uuid]=t)})),void 0!==t)for(let e=0,r=t.length;e<r;e++){const r=(new Vc).fromJSON(t[e],i);n[r.uuid]=r}return n}parseGeometries(t,e){const n={};if(void 0!==t){const i=new Sp;for(let r=0,s=t.length;r<s;r++){let s;const a=t[r];switch(a.type){case"BufferGeometry":case"InstancedBufferGeometry":s=i.parse(a);break;default:a.type in hd?s=hd[a.type].fromJSON(a,e):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${a.type}"`)}s.uuid=a.uuid,void 0!==a.name&&(s.name=a.name),void 0!==a.userData&&(s.userData=a.userData),n[a.uuid]=s}}return n}parseMaterials(t,e){const n={},i={};if(void 0!==t){const r=new xp;r.setTextures(e);for(let e=0,s=t.length;e<s;e++){const s=t[e];void 0===n[s.uuid]&&(n[s.uuid]=r.parse(s)),i[s.uuid]=n[s.uuid]}}return i}parseAnimations(t){const e={};if(void 0!==t)for(let n=0;n<t.length;n++){const i=t[n],r=zd.parse(i);e[r.uuid]=r}return e}parseImages(t,e){const n=this,i={};let r;function s(t){if("string"==typeof t){const e=t;return function(t){return n.manager.itemStart(t),r.load(t,(function(){n.manager.itemEnd(t)}),void 0,(function(){n.manager.itemError(t),n.manager.itemEnd(t)}))}(/^(\/\/)|([a-z]+:(\/\/)?)/i.test(e)?e:n.resourcePath+e)}return t.data?{data:ei(t.type,t.data),width:t.width,height:t.height}:null}if(void 0!==t&&t.length>0){const n=new Hd(e);r=new Jd(n),r.setCrossOrigin(this.crossOrigin);for(let e=0,n=t.length;e<n;e++){const n=t[e],r=n.url;if(Array.isArray(r)){const t=[];for(let e=0,n=r.length;e<n;e++){const n=s(r[e]);null!==n&&(n instanceof HTMLImageElement?t.push(n):t.push(new Bc(n.data,n.width,n.height)))}i[n.uuid]=new vi(t)}else{const t=s(n.url);i[n.uuid]=new vi(t)}}}return i}async parseImagesAsync(t){const e=this,n={};let i;async function r(t){if("string"==typeof t){const n=t,r=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(n)?n:e.resourcePath+n;return await i.loadAsync(r)}return t.data?{data:ei(t.type,t.data),width:t.width,height:t.height}:null}if(void 0!==t&&t.length>0){i=new Jd(this.manager),i.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e<i;e++){const i=t[e],s=i.url;if(Array.isArray(s)){const t=[];for(let e=0,n=s.length;e<n;e++){const n=s[e],i=await r(n);null!==i&&(i instanceof HTMLImageElement?t.push(i):t.push(new Bc(i.data,i.width,i.height)))}n[i.uuid]=new vi(t)}else{const t=await r(i.url);n[i.uuid]=new vi(t)}}}return n}parseTextures(t,e){function n(t,e){return"number"==typeof t?t:(console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",t),e[t])}const i={};if(void 0!==t)for(let r=0,s=t.length;r<s;r++){const s=t[r];void 0===s.image&&console.warn('THREE.ObjectLoader: No "image" specified for',s.uuid),void 0===e[s.image]&&console.warn("THREE.ObjectLoader: Undefined image",s.image);const a=e[s.image],o=a.data;let l;Array.isArray(o)?(l=new Qs,6===o.length&&(l.needsUpdate=!0)):(l=o&&o.data?new Bc:new yi,o&&(l.needsUpdate=!0)),l.source=a,l.uuid=s.uuid,void 0!==s.name&&(l.name=s.name),void 0!==s.mapping&&(l.mapping=n(s.mapping,Tp)),void 0!==s.channel&&(l.channel=s.channel),void 0!==s.offset&&l.offset.fromArray(s.offset),void 0!==s.repeat&&l.repeat.fromArray(s.repeat),void 0!==s.center&&l.center.fromArray(s.center),void 0!==s.rotation&&(l.rotation=s.rotation),void 0!==s.wrap&&(l.wrapS=n(s.wrap[0],wp),l.wrapT=n(s.wrap[1],wp)),void 0!==s.format&&(l.format=s.format),void 0!==s.internalFormat&&(l.internalFormat=s.internalFormat),void 0!==s.type&&(l.type=s.type),void 0!==s.colorSpace&&(l.colorSpace=s.colorSpace),void 0!==s.minFilter&&(l.minFilter=n(s.minFilter,Ep)),void 0!==s.magFilter&&(l.magFilter=n(s.magFilter,Ep)),void 0!==s.anisotropy&&(l.anisotropy=s.anisotropy),void 0!==s.flipY&&(l.flipY=s.flipY),void 0!==s.generateMipmaps&&(l.generateMipmaps=s.generateMipmaps),void 0!==s.premultiplyAlpha&&(l.premultiplyAlpha=s.premultiplyAlpha),void 0!==s.unpackAlignment&&(l.unpackAlignment=s.unpackAlignment),void 0!==s.compareFunction&&(l.compareFunction=s.compareFunction),void 0!==s.userData&&(l.userData=s.userData),i[s.uuid]=l}return i}parseObject(t,e,n,i,r){let s,a,o;function l(t){return void 0===e[t]&&console.warn("THREE.ObjectLoader: Undefined geometry",t),e[t]}function c(t){if(void 0!==t){if(Array.isArray(t)){const e=[];for(let i=0,r=t.length;i<r;i++){const r=t[i];void 0===n[r]&&console.warn("THREE.ObjectLoader: Undefined material",r),e.push(n[r])}return e}return void 0===n[t]&&console.warn("THREE.ObjectLoader: Undefined material",t),n[t]}}function h(t){return void 0===i[t]&&console.warn("THREE.ObjectLoader: Undefined texture",t),i[t]}switch(t.type){case"Scene":s=new rc,void 0!==t.background&&(Number.isInteger(t.background)?s.background=new Kr(t.background):s.background=h(t.background)),void 0!==t.environment&&(s.environment=h(t.environment)),void 0!==t.fog&&("Fog"===t.fog.type?s.fog=new ic(t.fog.color,t.fog.near,t.fog.far):"FogExp2"===t.fog.type&&(s.fog=new nc(t.fog.color,t.fog.density)),""!==t.fog.name&&(s.fog.name=t.fog.name)),void 0!==t.backgroundBlurriness&&(s.backgroundBlurriness=t.backgroundBlurriness),void 0!==t.backgroundIntensity&&(s.backgroundIntensity=t.backgroundIntensity),void 0!==t.backgroundRotation&&s.backgroundRotation.fromArray(t.backgroundRotation),void 0!==t.environmentIntensity&&(s.environmentIntensity=t.environmentIntensity),void 0!==t.environmentRotation&&s.environmentRotation.fromArray(t.environmentRotation);break;case"PerspectiveCamera":s=new Js(t.fov,t.aspect,t.near,t.far),void 0!==t.focus&&(s.focus=t.focus),void 0!==t.zoom&&(s.zoom=t.zoom),void 0!==t.filmGauge&&(s.filmGauge=t.filmGauge),void 0!==t.filmOffset&&(s.filmOffset=t.filmOffset),void 0!==t.view&&(s.view=Object.assign({},t.view));break;case"OrthographicCamera":s=new ba(t.left,t.right,t.top,t.bottom,t.near,t.far),void 0!==t.zoom&&(s.zoom=t.zoom),void 0!==t.view&&(s.view=Object.assign({},t.view));break;case"AmbientLight":s=new fp(t.color,t.intensity);break;case"DirectionalLight":s=new mp(t.color,t.intensity),s.target=t.target||"";break;case"PointLight":s=new dp(t.color,t.intensity,t.distance,t.decay);break;case"RectAreaLight":s=new gp(t.color,t.intensity,t.width,t.height);break;case"SpotLight":s=new op(t.color,t.intensity,t.distance,t.angle,t.penumbra,t.decay),s.target=t.target||"";break;case"HemisphereLight":s=new ep(t.color,t.groundColor,t.intensity);break;case"LightProbe":s=(new _p).fromJSON(t);break;case"SkinnedMesh":a=l(t.geometry),o=c(t.material),s=new Oc(a,o),void 0!==t.bindMode&&(s.bindMode=t.bindMode),void 0!==t.bindMatrix&&s.bindMatrix.fromArray(t.bindMatrix),void 0!==t.skeleton&&(s.skeleton=t.skeleton);break;case"Mesh":a=l(t.geometry),o=c(t.material),s=new Bs(a,o);break;case"InstancedMesh":a=l(t.geometry),o=c(t.material);const e=t.count,n=t.instanceMatrix,i=t.instanceColor;s=new Jc(a,o,e),s.instanceMatrix=new Hc(new Float32Array(n.array),16),void 0!==i&&(s.instanceColor=new Hc(new Float32Array(i.array),i.itemSize));break;case"BatchedMesh":a=l(t.geometry),o=c(t.material),s=new mh(t.maxInstanceCount,t.maxVertexCount,t.maxIndexCount,o),s.geometry=a,s.perObjectFrustumCulled=t.perObjectFrustumCulled,s.sortObjects=t.sortObjects,s._drawRanges=t.drawRanges,s._reservedRanges=t.reservedRanges,s._visibility=t.visibility,s._active=t.active,s._bounds=t.bounds.map((t=>{const e=new Li;e.min.fromArray(t.boxMin),e.max.fromArray(t.boxMax);const n=new Ji;return n.radius=t.sphereRadius,n.center.fromArray(t.sphereCenter),{boxInitialized:t.boxInitialized,box:e,sphereInitialized:t.sphereInitialized,sphere:n}})),s._maxInstanceCount=t.maxInstanceCount,s._maxVertexCount=t.maxVertexCount,s._maxIndexCount=t.maxIndexCount,s._geometryInitialized=t.geometryInitialized,s._geometryCount=t.geometryCount,s._matricesTexture=h(t.matricesTexture.uuid),void 0!==t.colorsTexture&&(s._colorsTexture=h(t.colorsTexture.uuid));break;case"LOD":s=new Ec;break;case"Line":s=new bh(l(t.geometry),c(t.material));break;case"LineLoop":s=new Rh(l(t.geometry),c(t.material));break;case"LineSegments":s=new Ah(l(t.geometry),c(t.material));break;case"PointCloud":case"Points":s=new Dh(l(t.geometry),c(t.material));break;case"Sprite":s=new Sc(c(t.material));break;case"Group":s=new jl;break;case"Bone":s=new Fc;break;default:s=new Lr}if(s.uuid=t.uuid,void 0!==t.name&&(s.name=t.name),void 0!==t.matrix?(s.matrix.fromArray(t.matrix),void 0!==t.matrixAutoUpdate&&(s.matrixAutoUpdate=t.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(void 0!==t.position&&s.position.fromArray(t.position),void 0!==t.rotation&&s.rotation.fromArray(t.rotation),void 0!==t.quaternion&&s.quaternion.fromArray(t.quaternion),void 0!==t.scale&&s.scale.fromArray(t.scale)),void 0!==t.up&&s.up.fromArray(t.up),void 0!==t.castShadow&&(s.castShadow=t.castShadow),void 0!==t.receiveShadow&&(s.receiveShadow=t.receiveShadow),t.shadow&&(void 0!==t.shadow.intensity&&(s.shadow.intensity=t.shadow.intensity),void 0!==t.shadow.bias&&(s.shadow.bias=t.shadow.bias),void 0!==t.shadow.normalBias&&(s.shadow.normalBias=t.shadow.normalBias),void 0!==t.shadow.radius&&(s.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&s.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(s.shadow.camera=this.parseObject(t.shadow.camera))),void 0!==t.visible&&(s.visible=t.visible),void 0!==t.frustumCulled&&(s.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(s.renderOrder=t.renderOrder),void 0!==t.userData&&(s.userData=t.userData),void 0!==t.layers&&(s.layers.mask=t.layers),void 0!==t.children){const a=t.children;for(let t=0;t<a.length;t++)s.add(this.parseObject(a[t],e,n,i,r))}if(void 0!==t.animations){const e=t.animations;for(let t=0;t<e.length;t++){const n=e[t];s.animations.push(r[n])}}if("LOD"===t.type){void 0!==t.autoUpdate&&(s.autoUpdate=t.autoUpdate);const e=t.levels;for(let t=0;t<e.length;t++){const n=e[t],i=s.getObjectByProperty("uuid",n.object);void 0!==i&&s.addLevel(i,n.distance,n.hysteresis)}}return s}bindSkeletons(t,e){0!==Object.keys(e).length&&t.traverse((function(t){if(!0===t.isSkinnedMesh&&void 0!==t.skeleton){const n=e[t.skeleton];void 0===n?console.warn("THREE.ObjectLoader: No skeleton found with UUID:",t.skeleton):t.bind(n,t.bindMatrix)}}))}bindLightTargets(t){t.traverse((function(e){if(e.isDirectionalLight||e.isSpotLight){const n=e.target,i=t.getObjectByProperty("uuid",n);e.target=void 0!==i?i:new Lr}}))}}const Tp={UVMapping:ot,CubeReflectionMapping:lt,CubeRefractionMapping:ct,EquirectangularReflectionMapping:ht,EquirectangularRefractionMapping:ut,CubeUVReflectionMapping:dt},wp={RepeatWrapping:pt,ClampToEdgeWrapping:mt,MirroredRepeatWrapping:ft},Ep={NearestFilter:gt,NearestMipmapNearestFilter:vt,NearestMipmapLinearFilter:xt,LinearFilter:Mt,LinearMipmapNearestFilter:St,LinearMipmapLinearFilter:Tt};class Ap extends Wd{constructor(t){super(t),this.isImageBitmapLoader=!0,"undefined"==typeof createImageBitmap&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),"undefined"==typeof fetch&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(t){return this.options=t,this}load(t,e,n,i){void 0===t&&(t=""),void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=this,s=Vd.get(t);if(void 0!==s)return r.manager.itemStart(t),s.then?void s.then((n=>{e&&e(n),r.manager.itemEnd(t)})).catch((t=>{i&&i(t)})):(setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader;const o=fetch(t,a).then((function(t){return t.blob()})).then((function(t){return createImageBitmap(t,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(n){return Vd.add(t,n),e&&e(n),r.manager.itemEnd(t),n})).catch((function(e){i&&i(e),Vd.remove(t),r.manager.itemError(t),r.manager.itemEnd(t)}));Vd.add(t,o),r.manager.itemStart(t)}}let Rp;class Cp{static getContext(){return void 0===Rp&&(Rp=new(window.AudioContext||window.webkitAudioContext)),Rp}static setContext(t){Rp=t}}class Ip extends Wd{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new qd(this.manager);function a(e){i?i(e):console.error(e),r.manager.itemError(t)}s.setResponseType("arraybuffer"),s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(t,(function(t){try{const n=t.slice(0);Cp.getContext().decodeAudioData(n,(function(t){e(t)})).catch(a)}catch(t){a(t)}}),n,i)}}const Pp=new sr,Lp=new sr,Up=new sr;class Dp{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Js,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Js,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(t){const e=this._cache;if(e.focus!==t.focus||e.fov!==t.fov||e.aspect!==t.aspect*this.aspect||e.near!==t.near||e.far!==t.far||e.zoom!==t.zoom||e.eyeSep!==this.eyeSep){e.focus=t.focus,e.fov=t.fov,e.aspect=t.aspect*this.aspect,e.near=t.near,e.far=t.far,e.zoom=t.zoom,e.eyeSep=this.eyeSep,Up.copy(t.projectionMatrix);const n=e.eyeSep/2,i=n*e.near/e.focus,r=e.near*Math.tan(Vn*e.fov*.5)/e.zoom;let s,a;Lp.elements[12]=-n,Pp.elements[12]=n,s=-r*e.aspect+i,a=r*e.aspect+i,Up.elements[0]=2*e.near/(a-s),Up.elements[8]=(a+s)/(a-s),this.cameraL.projectionMatrix.copy(Up),s=-r*e.aspect-i,a=r*e.aspect-i,Up.elements[0]=2*e.near/(a-s),Up.elements[8]=(a+s)/(a-s),this.cameraR.projectionMatrix.copy(Up)}this.cameraL.matrixWorld.copy(t.matrixWorld).multiply(Lp),this.cameraR.matrixWorld.copy(t.matrixWorld).multiply(Pp)}}class Np{constructor(t=!0){this.autoStart=t,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Op(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let t=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const e=Op();t=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=t}return t}}function Op(){return performance.now()}const Fp=new Ci,Bp=new Ri,zp=new Ci,kp=new Ci;class Vp extends Lr{constructor(){super(),this.type="AudioListener",this.context=Cp.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Np}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(t){return null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=t,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(t){return this.gain.gain.setTargetAtTime(t,this.context.currentTime,.01),this}updateMatrixWorld(t){super.updateMatrixWorld(t);const e=this.context.listener,n=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Fp,Bp,zp),kp.set(0,0,-1).applyQuaternion(Bp),e.positionX){const t=this.context.currentTime+this.timeDelta;e.positionX.linearRampToValueAtTime(Fp.x,t),e.positionY.linearRampToValueAtTime(Fp.y,t),e.positionZ.linearRampToValueAtTime(Fp.z,t),e.forwardX.linearRampToValueAtTime(kp.x,t),e.forwardY.linearRampToValueAtTime(kp.y,t),e.forwardZ.linearRampToValueAtTime(kp.z,t),e.upX.linearRampToValueAtTime(n.x,t),e.upY.linearRampToValueAtTime(n.y,t),e.upZ.linearRampToValueAtTime(n.z,t)}else e.setPosition(Fp.x,Fp.y,Fp.z),e.setOrientation(kp.x,kp.y,kp.z,n.x,n.y,n.z)}}class Hp extends Lr{constructor(t){super(),this.type="Audio",this.listener=t,this.context=t.context,this.gain=this.context.createGain(),this.gain.connect(t.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(t){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=t,this.connect(),this}setMediaElementSource(t){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(t),this.connect(),this}setMediaStreamSource(t){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(t),this.connect(),this}setBuffer(t){return this.buffer=t,this.sourceType="buffer",this.autoplay&&this.play(),this}play(t=0){if(!0===this.isPlaying)return void console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.Audio: this Audio has no playback control.");this._startedAt=this.context.currentTime+t;const e=this.context.createBufferSource();return e.buffer=this.buffer,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd,e.onended=this.onEnded.bind(this),e.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=e,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;console.warn("THREE.Audio: this Audio has no playback control.")}stop(t=0){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(this.context.currentTime+t),this.source.onended=null),this.isPlaying=!1,this;console.warn("THREE.Audio: this Audio has no playback control.")}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t<e;t++)this.filters[t-1].connect(this.filters[t]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this._connected=!0,this}disconnect(){if(!1!==this._connected){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t<e;t++)this.filters[t-1].disconnect(this.filters[t]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this._connected=!1,this}}getFilters(){return this.filters}setFilters(t){return t||(t=[]),!0===this._connected?(this.disconnect(),this.filters=t.slice(),this.connect()):this.filters=t.slice(),this}setDetune(t){return this.detune=t,!0===this.isPlaying&&void 0!==this.source.detune&&this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,.01),this}getDetune(){return this.detune}getFilter(){return this.getFilters()[0]}setFilter(t){return this.setFilters(t?[t]:[])}setPlaybackRate(t){if(!1!==this.hasPlaybackControl)return this.playbackRate=t,!0===this.isPlaying&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this;console.warn("THREE.Audio: this Audio has no playback control.")}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1}getLoop(){return!1===this.hasPlaybackControl?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop}setLoop(t){if(!1!==this.hasPlaybackControl)return this.loop=t,!0===this.isPlaying&&(this.source.loop=this.loop),this;console.warn("THREE.Audio: this Audio has no playback control.")}setLoopStart(t){return this.loopStart=t,this}setLoopEnd(t){return this.loopEnd=t,this}getVolume(){return this.gain.gain.value}setVolume(t){return this.gain.gain.setTargetAtTime(t,this.context.currentTime,.01),this}}const Gp=new Ci,Wp=new Ri,Xp=new Ci,jp=new Ci;class qp extends Hp{constructor(t){super(t),this.panner=this.context.createPanner(),this.panner.panningModel="HRTF",this.panner.connect(this.gain)}connect(){super.connect(),this.panner.connect(this.gain)}disconnect(){super.disconnect(),this.panner.disconnect(this.gain)}getOutput(){return this.panner}getRefDistance(){return this.panner.refDistance}setRefDistance(t){return this.panner.refDistance=t,this}getRolloffFactor(){return this.panner.rolloffFactor}setRolloffFactor(t){return this.panner.rolloffFactor=t,this}getDistanceModel(){return this.panner.distanceModel}setDistanceModel(t){return this.panner.distanceModel=t,this}getMaxDistance(){return this.panner.maxDistance}setMaxDistance(t){return this.panner.maxDistance=t,this}setDirectionalCone(t,e,n){return this.panner.coneInnerAngle=t,this.panner.coneOuterAngle=e,this.panner.coneOuterGain=n,this}updateMatrixWorld(t){if(super.updateMatrixWorld(t),!0===this.hasPlaybackControl&&!1===this.isPlaying)return;this.matrixWorld.decompose(Gp,Wp,Xp),jp.set(0,0,1).applyQuaternion(Wp);const e=this.panner;if(e.positionX){const t=this.context.currentTime+this.listener.timeDelta;e.positionX.linearRampToValueAtTime(Gp.x,t),e.positionY.linearRampToValueAtTime(Gp.y,t),e.positionZ.linearRampToValueAtTime(Gp.z,t),e.orientationX.linearRampToValueAtTime(jp.x,t),e.orientationY.linearRampToValueAtTime(jp.y,t),e.orientationZ.linearRampToValueAtTime(jp.z,t)}else e.setPosition(Gp.x,Gp.y,Gp.z),e.setOrientation(jp.x,jp.y,jp.z)}}class Yp{constructor(t,e=2048){this.analyser=t.context.createAnalyser(),this.analyser.fftSize=e,this.data=new Uint8Array(this.analyser.frequencyBinCount),t.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let t=0;const e=this.getFrequencyData();for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}}class Zp{constructor(t,e,n){let i,r,s;switch(this.binding=t,this.valueSize=n,e){case"quaternion":i=this._slerp,r=this._slerpAdditive,s=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(6*n),this._workIndex=5;break;case"string":case"bool":i=this._select,r=this._select,s=this._setAdditiveIdentityOther,this.buffer=new Array(5*n);break;default:i=this._lerp,r=this._lerpAdditive,s=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(5*n)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=r,this._setIdentity=s,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(t,e){const n=this.buffer,i=this.valueSize,r=t*i+i;let s=this.cumulativeWeight;if(0===s){for(let t=0;t!==i;++t)n[r+t]=n[t];s=e}else{s+=e;const t=e/s;this._mixBufferRegion(n,r,0,t,i)}this.cumulativeWeight=s}accumulateAdditive(t){const e=this.buffer,n=this.valueSize,i=n*this._addIndex;0===this.cumulativeWeightAdditive&&this._setIdentity(),this._mixBufferRegionAdditive(e,i,0,t,n),this.cumulativeWeightAdditive+=t}apply(t){const e=this.valueSize,n=this.buffer,i=t*e+e,r=this.cumulativeWeight,s=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){const t=e*this._origIndex;this._mixBufferRegion(n,i,t,1-r,e)}s>0&&this._mixBufferRegionAdditive(n,i,this._addIndex*e,1,e);for(let t=e,r=e+e;t!==r;++t)if(n[t]!==n[t+e]){a.setValue(n,i);break}}saveOriginalState(){const t=this.binding,e=this.buffer,n=this.valueSize,i=n*this._origIndex;t.getValue(e,i);for(let t=n,r=i;t!==r;++t)e[t]=e[i+t%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=3*this.valueSize;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let n=t;n<e;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const t=this._origIndex*this.valueSize,e=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[e+n]=this.buffer[t+n]}_select(t,e,n,i,r){if(i>=.5)for(let i=0;i!==r;++i)t[e+i]=t[n+i]}_slerp(t,e,n,i){Ri.slerpFlat(t,e,t,e,t,n,i)}_slerpAdditive(t,e,n,i,r){const s=this._workIndex*r;Ri.multiplyQuaternionsFlat(t,s,t,e,t,n),Ri.slerpFlat(t,e,t,e,t,s,i)}_lerp(t,e,n,i,r){const s=1-i;for(let a=0;a!==r;++a){const r=e+a;t[r]=t[r]*s+t[n+a]*i}}_lerpAdditive(t,e,n,i,r){for(let s=0;s!==r;++s){const r=e+s;t[r]=t[r]+t[n+s]*i}}}const Jp="\\[\\]\\.:\\/",Kp=new RegExp("["+Jp+"]","g"),$p="[^"+Jp+"]",Qp="[^"+Jp.replace("\\.","")+"]",tm=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",$p)+/(WCOD+)?/.source.replace("WCOD",Qp)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",$p)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",$p)+"$"),em=["material","materials","bones","map"];class nm{constructor(t,e,n){this.path=e,this.parsedPath=n||nm.parseTrackName(e),this.node=nm.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,n){return t&&t.isAnimationObjectGroup?new nm.Composite(t,e,n):new nm(t,e,n)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(Kp,"")}static parseTrackName(t){const e=tm.exec(t);if(null===e)throw new Error("PropertyBinding: Cannot parse trackName: "+t);const n={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const t=n.nodeName.substring(i+1);-1!==em.indexOf(t)&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=t)}if(null===n.propertyName||0===n.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return n}static findNode(t,e){if(void 0===e||""===e||"."===e||-1===e||e===t.name||e===t.uuid)return t;if(t.skeleton){const n=t.skeleton.getBoneByName(e);if(void 0!==n)return n}if(t.children){const n=function(t){for(let i=0;i<t.length;i++){const r=t[i];if(r.name===e||r.uuid===e)return r;const s=n(r.children);if(s)return s}return null},i=n(t.children);if(i)return i}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(t,e){t[e]=this.targetObject[this.propertyName]}_getValue_array(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)t[e++]=n[i]}_getValue_arrayElement(t,e){t[e]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(t,e){this.resolvedProperty.toArray(t,e)}_setValue_direct(t,e){this.targetObject[this.propertyName]=t[e]}_setValue_direct_setNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=t[e++]}_setValue_array_setNeedsUpdate(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=t[e++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(t,e){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=t[e++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(t,e){this.resolvedProperty[this.propertyIndex]=t[e]}_setValue_arrayElement_setNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(t,e){this.resolvedProperty.fromArray(t,e)}_setValue_fromArray_setNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(t,e){this.bind(),this.getValue(t,e)}_setValue_unbound(t,e){this.bind(),this.setValue(t,e)}bind(){let t=this.node;const e=this.parsedPath,n=e.objectName,i=e.propertyName;let r=e.propertyIndex;if(t||(t=nm.findNode(this.rootNode,e.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t)return void console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");if(n){let i=e.objectIndex;switch(n){case"materials":if(!t.material)return void console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);if(!t.material.materials)return void console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);t=t.material.materials;break;case"bones":if(!t.skeleton)return void console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);t=t.skeleton.bones;for(let e=0;e<t.length;e++)if(t[e].name===i){i=e;break}break;case"map":if("map"in t){t=t.map;break}if(!t.material)return void console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);if(!t.material.map)return void console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);t=t.material.map;break;default:if(void 0===t[n])return void console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);t=t[n]}if(void 0!==i){if(void 0===t[i])return void console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,t);t=t[i]}}const s=t[i];if(void 0===s){const n=e.nodeName;return void console.error("THREE.PropertyBinding: Trying to update property for track: "+n+"."+i+" but it wasn't found.",t)}let a=this.Versioning.None;this.targetObject=t,void 0!==t.needsUpdate?a=this.Versioning.NeedsUpdate:void 0!==t.matrixWorldNeedsUpdate&&(a=this.Versioning.MatrixWorldNeedsUpdate);let o=this.BindingType.Direct;if(void 0!==r){if("morphTargetInfluences"===i){if(!t.geometry)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);if(!t.geometry.morphAttributes)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);void 0!==t.morphTargetDictionary[r]&&(r=t.morphTargetDictionary[r])}o=this.BindingType.ArrayElement,this.resolvedProperty=s,this.propertyIndex=r}else void 0!==s.fromArray&&void 0!==s.toArray?(o=this.BindingType.HasFromToArray,this.resolvedProperty=s):Array.isArray(s)?(o=this.BindingType.EntireArray,this.resolvedProperty=s):this.propertyName=i;this.getValue=this.GetterByBindingType[o],this.setValue=this.SetterByBindingTypeAndVersioning[o][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}nm.Composite=class{constructor(t,e,n){const i=n||nm.parseTrackName(e);this._targetGroup=t,this._bindings=t.subscribe_(e,i)}getValue(t,e){this.bind();const n=this._targetGroup.nCachedObjects_,i=this._bindings[n];void 0!==i&&i.getValue(t,e)}setValue(t,e){const n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,r=n.length;i!==r;++i)n[i].setValue(t,e)}bind(){const t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,n=t.length;e!==n;++e)t[e].bind()}unbind(){const t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,n=t.length;e!==n;++e)t[e].unbind()}},nm.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},nm.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},nm.prototype.GetterByBindingType=[nm.prototype._getValue_direct,nm.prototype._getValue_array,nm.prototype._getValue_arrayElement,nm.prototype._getValue_toArray],nm.prototype.SetterByBindingTypeAndVersioning=[[nm.prototype._setValue_direct,nm.prototype._setValue_direct_setNeedsUpdate,nm.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[nm.prototype._setValue_array,nm.prototype._setValue_array_setNeedsUpdate,nm.prototype._setValue_array_setMatrixWorldNeedsUpdate],[nm.prototype._setValue_arrayElement,nm.prototype._setValue_arrayElement_setNeedsUpdate,nm.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[nm.prototype._setValue_fromArray,nm.prototype._setValue_fromArray_setNeedsUpdate,nm.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class im{constructor(){this.isAnimationObjectGroup=!0,this.uuid=Gn(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;const t={};this._indicesByUUID=t;for(let e=0,n=arguments.length;e!==n;++e)t[arguments[e].uuid]=e;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};const e=this;this.stats={objects:{get total(){return e._objects.length},get inUse(){return this.total-e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}add(){const t=this._objects,e=this._indicesByUUID,n=this._paths,i=this._parsedPaths,r=this._bindings,s=r.length;let a,o=t.length,l=this.nCachedObjects_;for(let c=0,h=arguments.length;c!==h;++c){const h=arguments[c],u=h.uuid;let d=e[u];if(void 0===d){d=o++,e[u]=d,t.push(h);for(let t=0,e=s;t!==e;++t)r[t].push(new nm(h,n[t],i[t]))}else if(d<l){a=t[d];const o=--l,c=t[o];e[c.uuid]=d,t[d]=c,e[u]=o,t[o]=h;for(let t=0,e=s;t!==e;++t){const e=r[t],s=e[o];let a=e[d];e[d]=s,void 0===a&&(a=new nm(h,n[t],i[t])),e[o]=a}}else t[d]!==a&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=l}remove(){const t=this._objects,e=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_;for(let s=0,a=arguments.length;s!==a;++s){const a=arguments[s],o=a.uuid,l=e[o];if(void 0!==l&&l>=r){const s=r++,c=t[s];e[c.uuid]=l,t[l]=c,e[o]=s,t[s]=a;for(let t=0,e=i;t!==e;++t){const e=n[t],i=e[s],r=e[l];e[l]=i,e[s]=r}}}this.nCachedObjects_=r}uncache(){const t=this._objects,e=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_,s=t.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,l=e[o];if(void 0!==l)if(delete e[o],l<r){const a=--r,o=t[a],c=--s,h=t[c];e[o.uuid]=l,t[l]=o,e[h.uuid]=a,t[a]=h,t.pop();for(let t=0,e=i;t!==e;++t){const e=n[t],i=e[a],r=e[c];e[l]=i,e[a]=r,e.pop()}}else{const r=--s,a=t[r];r>0&&(e[a.uuid]=l),t[l]=a,t.pop();for(let t=0,e=i;t!==e;++t){const e=n[t];e[l]=e[r],e.pop()}}}this.nCachedObjects_=r}subscribe_(t,e){const n=this._bindingsIndicesByPath;let i=n[t];const r=this._bindings;if(void 0!==i)return r[i];const s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,h=new Array(l);i=r.length,n[t]=i,s.push(t),a.push(e),r.push(h);for(let n=c,i=o.length;n!==i;++n){const i=o[n];h[n]=new nm(i,t,e)}return h}unsubscribe_(t){const e=this._bindingsIndicesByPath,n=e[t];if(void 0!==n){const i=this._paths,r=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a];e[t[a]]=n,s[n]=o,s.pop(),r[n]=r[a],r.pop(),i[n]=i[a],i.pop()}}}class rm{constructor(t,e,n=null,i=e.blendMode){this._mixer=t,this._clip=e,this._localRoot=n,this.blendMode=i;const r=e.tracks,s=r.length,a=new Array(s),o={endingStart:Ne,endingEnd:Ne};for(let t=0;t!==s;++t){const e=r[t].createInterpolant(null);a[t]=e,e.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(t){return this._startTime=t,this}setLoop(t,e){return this.loop=t,this.repetitions=e,this}setEffectiveWeight(t){return this.weight=t,this._effectiveWeight=this.enabled?t:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(t){return this._scheduleFading(t,0,1)}fadeOut(t){return this._scheduleFading(t,1,0)}crossFadeFrom(t,e,n){if(t.fadeOut(e),this.fadeIn(e),n){const n=this._clip.duration,i=t._clip.duration,r=i/n,s=n/i;t.warp(1,r,e),this.warp(s,1,e)}return this}crossFadeTo(t,e,n){return t.crossFadeFrom(this,e,n)}stopFading(){const t=this._weightInterpolant;return null!==t&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}setEffectiveTimeScale(t){return this.timeScale=t,this._effectiveTimeScale=this.paused?0:t,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(t){return this.timeScale=this._clip.duration/t,this.stopWarping()}syncWith(t){return this.time=t.time,this.timeScale=t.timeScale,this.stopWarping()}halt(t){return this.warp(this._effectiveTimeScale,0,t)}warp(t,e,n){const i=this._mixer,r=i.time,s=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=r,o[1]=r+n,l[0]=t/s,l[1]=e/s,this}stopWarping(){const t=this._timeScaleInterpolant;return null!==t&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(t,e,n,i){if(!this.enabled)return void this._updateWeight(t);const r=this._startTime;if(null!==r){const i=(t-r)*n;i<0||0===n?e=0:(this._startTime=null,e=n*i)}e*=this._updateTimeScale(t);const s=this._updateTime(e),a=this._updateWeight(t);if(a>0){const t=this._interpolants,e=this._propertyBindings;if(this.blendMode===ze)for(let n=0,i=t.length;n!==i;++n)t[n].evaluate(s),e[n].accumulateAdditive(a);else for(let n=0,r=t.length;n!==r;++n)t[n].evaluate(s),e[n].accumulate(i,a)}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const n=this._weightInterpolant;if(null!==n){const i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const n=this._timeScaleInterpolant;if(null!==n){e*=n.evaluate(t)[0],t>n.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e}_updateTime(t){const e=this._clip.duration,n=this.loop;let i=this.time+t,r=this._loopCount;const s=2202===n;if(0===t)return-1===r||!s||1&~r?i:e-i;if(2200===n){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(i>=e)i=e;else{if(!(i<0)){this.time=i;break t}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(-1===r&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),i>=e||i<0){const n=Math.floor(i/e);i-=e*n,r+=Math.abs(n);const a=this.repetitions-r;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=t>0?e:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(1===a){const e=t<0;this._setEndings(e,!e,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n})}}else this.time=i;if(s&&!(1&~r))return e-i}return i}_setEndings(t,e,n){const i=this._interpolantSettings;n?(i.endingStart=Oe,i.endingEnd=Oe):(i.endingStart=t?this.zeroSlopeAtStart?Oe:Ne:Fe,i.endingEnd=e?this.zeroSlopeAtEnd?Oe:Ne:Fe)}_scheduleFading(t,e,n){const i=this._mixer,r=i.time;let s=this._weightInterpolant;null===s&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=e,a[1]=r+t,o[1]=n,this}}const sm=new Float32Array(1);class am extends Bn{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(t,e){const n=t._localRoot||this._root,i=t._clip.tracks,r=i.length,s=t._propertyBindings,a=t._interpolants,o=n.uuid,l=this._bindingsByRootAndName;let c=l[o];void 0===c&&(c={},l[o]=c);for(let t=0;t!==r;++t){const r=i[t],l=r.name;let h=c[l];if(void 0!==h)++h.referenceCount,s[t]=h;else{if(h=s[t],void 0!==h){null===h._cacheIndex&&(++h.referenceCount,this._addInactiveBinding(h,o,l));continue}const i=e&&e._propertyBindings[t].binding.parsedPath;h=new Zp(nm.create(n,l,i),r.ValueTypeName,r.getValueSize()),++h.referenceCount,this._addInactiveBinding(h,o,l),s[t]=h}a[t].resultBuffer=h.buffer}}_activateAction(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){const e=(t._localRoot||this._root).uuid,n=t._clip.uuid,i=this._actionsByClip[n];this._bindAction(t,i&&i.knownActions[0]),this._addInactiveAction(t,n,e)}const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==n.useCount++&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(t)}}_deactivateAction(t){if(this._isActiveAction(t)){const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==--n.useCount&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(t)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}}_isActiveAction(t){const e=t._cacheIndex;return null!==e&&e<this._nActiveActions}_addInactiveAction(t,e,n){const i=this._actions,r=this._actionsByClip;let s=r[e];if(void 0===s)s={knownActions:[t],actionByRoot:{}},t._byClipCacheIndex=0,r[e]=s;else{const e=s.knownActions;t._byClipCacheIndex=e.length,e.push(t)}t._cacheIndex=i.length,i.push(t),s.actionByRoot[n]=t}_removeInactiveAction(t){const e=this._actions,n=e[e.length-1],i=t._cacheIndex;n._cacheIndex=i,e[i]=n,e.pop(),t._cacheIndex=null;const r=t._clip.uuid,s=this._actionsByClip,a=s[r],o=a.knownActions,l=o[o.length-1],c=t._byClipCacheIndex;l._byClipCacheIndex=c,o[c]=l,o.pop(),t._byClipCacheIndex=null;delete a.actionByRoot[(t._localRoot||this._root).uuid],0===o.length&&delete s[r],this._removeInactiveBindingsForAction(t)}_removeInactiveBindingsForAction(t){const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==--n.referenceCount&&this._removeInactiveBinding(n)}}_lendAction(t){const e=this._actions,n=t._cacheIndex,i=this._nActiveActions++,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_takeBackAction(t){const e=this._actions,n=t._cacheIndex,i=--this._nActiveActions,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_addInactiveBinding(t,e,n){const i=this._bindingsByRootAndName,r=this._bindings;let s=i[e];void 0===s&&(s={},i[e]=s),s[n]=t,t._cacheIndex=r.length,r.push(t)}_removeInactiveBinding(t){const e=this._bindings,n=t.binding,i=n.rootNode.uuid,r=n.path,s=this._bindingsByRootAndName,a=s[i],o=e[e.length-1],l=t._cacheIndex;o._cacheIndex=l,e[l]=o,e.pop(),delete a[r],0===Object.keys(a).length&&delete s[i]}_lendBinding(t){const e=this._bindings,n=t._cacheIndex,i=this._nActiveBindings++,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_takeBackBinding(t){const e=this._bindings,n=t._cacheIndex,i=--this._nActiveBindings,r=e[i];t._cacheIndex=i,e[i]=t,r._cacheIndex=n,e[n]=r}_lendControlInterpolant(){const t=this._controlInterpolants,e=this._nActiveControlInterpolants++;let n=t[e];return void 0===n&&(n=new Cd(new Float32Array(2),new Float32Array(2),1,sm),n.__cacheIndex=e,t[e]=n),n}_takeBackControlInterpolant(t){const e=this._controlInterpolants,n=t.__cacheIndex,i=--this._nActiveControlInterpolants,r=e[i];t.__cacheIndex=i,e[i]=t,r.__cacheIndex=n,e[n]=r}clipAction(t,e,n){const i=e||this._root,r=i.uuid;let s="string"==typeof t?zd.findByName(i,t):t;const a=null!==s?s.uuid:t,o=this._actionsByClip[a];let l=null;if(void 0===n&&(n=null!==s?s.blendMode:Be),void 0!==o){const t=o.actionByRoot[r];if(void 0!==t&&t.blendMode===n)return t;l=o.knownActions[0],null===s&&(s=l._clip)}if(null===s)return null;const c=new rm(this,s,e,n);return this._bindAction(c,l),this._addInactiveAction(c,a,r),c}existingAction(t,e){const n=e||this._root,i=n.uuid,r="string"==typeof t?zd.findByName(n,t):t,s=r?r.uuid:t,a=this._actionsByClip[s];return void 0!==a&&a.actionByRoot[i]||null}stopAllAction(){const t=this._actions;for(let e=this._nActiveActions-1;e>=0;--e)t[e].stop();return this}update(t){t*=this.timeScale;const e=this._actions,n=this._nActiveActions,i=this.time+=t,r=Math.sign(t),s=this._accuIndex^=1;for(let a=0;a!==n;++a){e[a]._update(i,t,r,s)}const a=this._bindings,o=this._nActiveBindings;for(let t=0;t!==o;++t)a[t].apply(s);return this}setTime(t){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(t)}getRoot(){return this._root}uncacheClip(t){const e=this._actions,n=t.uuid,i=this._actionsByClip,r=i[n];if(void 0!==r){const t=r.knownActions;for(let n=0,i=t.length;n!==i;++n){const i=t[n];this._deactivateAction(i);const r=i._cacheIndex,s=e[e.length-1];i._cacheIndex=null,i._byClipCacheIndex=null,s._cacheIndex=r,e[r]=s,e.pop(),this._removeInactiveBindingsForAction(i)}delete i[n]}}uncacheRoot(t){const e=t.uuid,n=this._actionsByClip;for(const t in n){const i=n[t].actionByRoot[e];void 0!==i&&(this._deactivateAction(i),this._removeInactiveAction(i))}const i=this._bindingsByRootAndName[e];if(void 0!==i)for(const t in i){const e=i[t];e.restoreOriginalState(),this._removeInactiveBinding(e)}}uncacheAction(t,e){const n=this.existingAction(t,e);null!==n&&(this._deactivateAction(n),this._removeInactiveAction(n))}}class om{constructor(t){this.value=t}clone(){return new om(void 0===this.value.clone?this.value:this.value.clone())}}let lm=0;class cm extends Bn{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:lm++}),this.name="",this.usage=wn,this.uniforms=[]}add(t){return this.uniforms.push(t),this}remove(t){const e=this.uniforms.indexOf(t);return-1!==e&&this.uniforms.splice(e,1),this}setName(t){return this.name=t,this}setUsage(t){return this.usage=t,this}dispose(){return this.dispatchEvent({type:"dispose"}),this}copy(t){this.name=t.name,this.usage=t.usage;const e=t.uniforms;this.uniforms.length=0;for(let t=0,n=e.length;t<n;t++){const n=Array.isArray(e[t])?e[t]:[e[t]];for(let t=0;t<n.length;t++)this.uniforms.push(n[t].clone())}return this}clone(){return(new this.constructor).copy(this)}}class hm extends sc{constructor(t,e,n=1){super(t,e),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}clone(t){const e=super.clone(t);return e.meshPerAttribute=this.meshPerAttribute,e}toJSON(t){const e=super.toJSON(t);return e.isInstancedInterleavedBuffer=!0,e.meshPerAttribute=this.meshPerAttribute,e}}class um{constructor(t,e,n,i,r){this.isGLBufferAttribute=!0,this.name="",this.buffer=t,this.type=e,this.itemSize=n,this.elementSize=i,this.count=r,this.version=0}set needsUpdate(t){!0===t&&this.version++}setBuffer(t){return this.buffer=t,this}setType(t,e){return this.type=t,this.elementSize=e,this}setItemSize(t){return this.itemSize=t,this}setCount(t){return this.count=t,this}}const dm=new sr;class pm{constructor(t,e,n=0,i=1/0){this.ray=new rr(t,e),this.near=n,this.far=i,this.camera=null,this.layers=new gr,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(t,e){this.ray.set(t,e)}setFromCamera(t,e){e.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(t.x,t.y,.5).unproject(e).sub(this.ray.origin).normalize(),this.camera=e):e.isOrthographicCamera?(this.ray.origin.set(t.x,t.y,(e.near+e.far)/(e.near-e.far)).unproject(e),this.ray.direction.set(0,0,-1).transformDirection(e.matrixWorld),this.camera=e):console.error("THREE.Raycaster: Unsupported camera type: "+e.type)}setFromXRController(t){return dm.identity().extractRotation(t.matrixWorld),this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(dm),this}intersectObject(t,e=!0,n=[]){return fm(t,this,n,e),n.sort(mm),n}intersectObjects(t,e=!0,n=[]){for(let i=0,r=t.length;i<r;i++)fm(t[i],this,n,e);return n.sort(mm),n}}function mm(t,e){return t.distance-e.distance}function fm(t,e,n,i){let r=!0;if(t.layers.test(e.layers)){!1===t.raycast(e,n)&&(r=!1)}if(!0===r&&!0===i){const i=t.children;for(let t=0,r=i.length;t<r;t++)fm(i[t],e,n,!0)}}class gm{constructor(t=1,e=0,n=0){return this.radius=t,this.phi=e,this.theta=n,this}set(t,e,n){return this.radius=t,this.phi=e,this.theta=n,this}copy(t){return this.radius=t.radius,this.phi=t.phi,this.theta=t.theta,this}makeSafe(){const t=1e-6;return this.phi=Math.max(t,Math.min(Math.PI-t,this.phi)),this}setFromVector3(t){return this.setFromCartesianCoords(t.x,t.y,t.z)}setFromCartesianCoords(t,e,n){return this.radius=Math.sqrt(t*t+e*e+n*n),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Math.atan2(t,n),this.phi=Math.acos(Wn(e/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}}class vm{constructor(t=1,e=0,n=0){return this.radius=t,this.theta=e,this.y=n,this}set(t,e,n){return this.radius=t,this.theta=e,this.y=n,this}copy(t){return this.radius=t.radius,this.theta=t.theta,this.y=t.y,this}setFromVector3(t){return this.setFromCartesianCoords(t.x,t.y,t.z)}setFromCartesianCoords(t,e,n){return this.radius=Math.sqrt(t*t+n*n),this.theta=Math.atan2(t,n),this.y=e,this}clone(){return(new this.constructor).copy(this)}}class _m{constructor(t,e,n,i){_m.prototype.isMatrix2=!0,this.elements=[1,0,0,1],void 0!==t&&this.set(t,e,n,i)}identity(){return this.set(1,0,0,1),this}fromArray(t,e=0){for(let n=0;n<4;n++)this.elements[n]=t[n+e];return this}set(t,e,n,i){const r=this.elements;return r[0]=t,r[2]=e,r[1]=n,r[3]=i,this}}const xm=new Jn;class ym{constructor(t=new Jn(1/0,1/0),e=new Jn(-1/0,-1/0)){this.isBox2=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromPoints(t){this.makeEmpty();for(let e=0,n=t.length;e<n;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const n=xm.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(n),this.max.copy(t).add(n),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y}getCenter(t){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}containsPoint(t){return t.x>=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,xm).distanceTo(t)}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const Mm=new Ci,Sm=new Ci;class bm{constructor(t=new Ci,e=new Ci){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){Mm.subVectors(t,this.start),Sm.subVectors(this.end,this.start);const n=Sm.dot(Sm);let i=Sm.dot(Mm)/n;return e&&(i=Wn(i,0,1)),i}closestPointToPoint(t,e,n){const i=this.closestPointToPointParameter(t,e);return this.delta(n).multiplyScalar(i).add(this.start)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}}const Tm=new Ci;class wm extends Lr{constructor(t,e){super(),this.light=t,this.matrixAutoUpdate=!1,this.color=e,this.type="SpotLightHelper";const n=new Es,i=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let t=0,e=1,n=32;t<n;t++,e++){const r=t/n*Math.PI*2,s=e/n*Math.PI*2;i.push(Math.cos(r),Math.sin(r),1,Math.cos(s),Math.sin(s),1)}n.setAttribute("position",new _s(i,3));const r=new fh({fog:!1,toneMapped:!1});this.cone=new Ah(n,r),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),this.parent?(this.parent.updateWorldMatrix(!0),this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)):this.matrix.copy(this.light.matrixWorld),this.matrixWorld.copy(this.light.matrixWorld);const t=this.light.distance?this.light.distance:1e3,e=t*Math.tan(this.light.angle);this.cone.scale.set(e,e,t),Tm.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(Tm),void 0!==this.color?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}}const Em=new Ci,Am=new sr,Rm=new sr;class Cm extends Ah{constructor(t){const e=Im(t),n=new Es,i=[],r=[],s=new Kr(0,0,1),a=new Kr(0,1,0);for(let t=0;t<e.length;t++){const n=e[t];n.parent&&n.parent.isBone&&(i.push(0,0,0),i.push(0,0,0),r.push(s.r,s.g,s.b),r.push(a.r,a.g,a.b))}n.setAttribute("position",new _s(i,3)),n.setAttribute("color",new _s(r,3));super(n,new fh({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0})),this.isSkeletonHelper=!0,this.type="SkeletonHelper",this.root=t,this.bones=e,this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1}updateMatrixWorld(t){const e=this.bones,n=this.geometry,i=n.getAttribute("position");Rm.copy(this.root.matrixWorld).invert();for(let t=0,n=0;t<e.length;t++){const r=e[t];r.parent&&r.parent.isBone&&(Am.multiplyMatrices(Rm,r.matrixWorld),Em.setFromMatrixPosition(Am),i.setXYZ(n,Em.x,Em.y,Em.z),Am.multiplyMatrices(Rm,r.parent.matrixWorld),Em.setFromMatrixPosition(Am),i.setXYZ(n+1,Em.x,Em.y,Em.z),n+=2)}n.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(t)}dispose(){this.geometry.dispose(),this.material.dispose()}}function Im(t){const e=[];!0===t.isBone&&e.push(t);for(let n=0;n<t.children.length;n++)e.push.apply(e,Im(t.children[n]));return e}class Pm extends Bs{constructor(t,e,n){super(new id(e,4,2),new es({wireframe:!0,fog:!1,toneMapped:!1})),this.light=t,this.color=n,this.type="PointLightHelper",this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1,this.update()}dispose(){this.geometry.dispose(),this.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),void 0!==this.color?this.material.color.set(this.color):this.material.color.copy(this.light.color)}}const Lm=new Ci,Um=new Kr,Dm=new Kr;class Nm extends Lr{constructor(t,e,n){super(),this.light=t,this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.color=n,this.type="HemisphereLightHelper";const i=new td(e);i.rotateY(.5*Math.PI),this.material=new es({wireframe:!0,fog:!1,toneMapped:!1}),void 0===this.color&&(this.material.vertexColors=!0);const r=i.getAttribute("position"),s=new Float32Array(3*r.count);i.setAttribute("color",new cs(s,3)),this.add(new Bs(i,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){const t=this.children[0];if(void 0!==this.color)this.material.color.set(this.color);else{const e=t.geometry.getAttribute("color");Um.copy(this.light.color),Dm.copy(this.light.groundColor);for(let t=0,n=e.count;t<n;t++){const i=t<n/2?Um:Dm;e.setXYZ(t,i.r,i.g,i.b)}e.needsUpdate=!0}this.light.updateWorldMatrix(!0,!1),t.lookAt(Lm.setFromMatrixPosition(this.light.matrixWorld).negate())}}class Om extends Ah{constructor(t=10,e=10,n=4473924,i=8947848){n=new Kr(n),i=new Kr(i);const r=e/2,s=t/e,a=t/2,o=[],l=[];for(let t=0,c=0,h=-a;t<=e;t++,h+=s){o.push(-a,0,h,a,0,h),o.push(h,0,-a,h,0,a);const e=t===r?n:i;e.toArray(l,c),c+=3,e.toArray(l,c),c+=3,e.toArray(l,c),c+=3,e.toArray(l,c),c+=3}const c=new Es;c.setAttribute("position",new _s(o,3)),c.setAttribute("color",new _s(l,3));super(c,new fh({vertexColors:!0,toneMapped:!1})),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class Fm extends Ah{constructor(t=10,e=16,n=8,i=64,r=4473924,s=8947848){r=new Kr(r),s=new Kr(s);const a=[],o=[];if(e>1)for(let n=0;n<e;n++){const i=n/e*(2*Math.PI),l=Math.sin(i)*t,c=Math.cos(i)*t;a.push(0,0,0),a.push(l,0,c);const h=1&n?r:s;o.push(h.r,h.g,h.b),o.push(h.r,h.g,h.b)}for(let e=0;e<n;e++){const l=1&e?r:s,c=t-t/n*e;for(let t=0;t<i;t++){let e=t/i*(2*Math.PI),n=Math.sin(e)*c,r=Math.cos(e)*c;a.push(n,0,r),o.push(l.r,l.g,l.b),e=(t+1)/i*(2*Math.PI),n=Math.sin(e)*c,r=Math.cos(e)*c,a.push(n,0,r),o.push(l.r,l.g,l.b)}}const l=new Es;l.setAttribute("position",new _s(a,3)),l.setAttribute("color",new _s(o,3));super(l,new fh({vertexColors:!0,toneMapped:!1})),this.type="PolarGridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}const Bm=new Ci,zm=new Ci,km=new Ci;class Vm extends Lr{constructor(t,e,n){super(),this.light=t,this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.color=n,this.type="DirectionalLightHelper",void 0===e&&(e=1);let i=new Es;i.setAttribute("position",new _s([-e,e,0,e,e,0,e,-e,0,-e,-e,0,-e,e,0],3));const r=new fh({fog:!1,toneMapped:!1});this.lightPlane=new bh(i,r),this.add(this.lightPlane),i=new Es,i.setAttribute("position",new _s([0,0,0,0,0,1],3)),this.targetLine=new bh(i,r),this.add(this.targetLine),this.update()}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),Bm.setFromMatrixPosition(this.light.matrixWorld),zm.setFromMatrixPosition(this.light.target.matrixWorld),km.subVectors(zm,Bm),this.lightPlane.lookAt(zm),void 0!==this.color?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color)),this.targetLine.lookAt(zm),this.targetLine.scale.z=km.length()}}const Hm=new Ci,Gm=new js;class Wm extends Ah{constructor(t){const e=new Es,n=new fh({color:16777215,vertexColors:!0,toneMapped:!1}),i=[],r=[],s={};function a(t,e){o(t),o(e)}function o(t){i.push(0,0,0),r.push(0,0,0),void 0===s[t]&&(s[t]=[]),s[t].push(i.length/3-1)}a("n1","n2"),a("n2","n4"),a("n4","n3"),a("n3","n1"),a("f1","f2"),a("f2","f4"),a("f4","f3"),a("f3","f1"),a("n1","f1"),a("n2","f2"),a("n3","f3"),a("n4","f4"),a("p","n1"),a("p","n2"),a("p","n3"),a("p","n4"),a("u1","u2"),a("u2","u3"),a("u3","u1"),a("c","t"),a("p","c"),a("cn1","cn2"),a("cn3","cn4"),a("cf1","cf2"),a("cf3","cf4"),e.setAttribute("position",new _s(i,3)),e.setAttribute("color",new _s(r,3)),super(e,n),this.type="CameraHelper",this.camera=t,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=s,this.update();const l=new Kr(16755200),c=new Kr(16711680),h=new Kr(43775),u=new Kr(16777215),d=new Kr(3355443);this.setColors(l,c,h,u,d)}setColors(t,e,n,i,r){const s=this.geometry.getAttribute("color");s.setXYZ(0,t.r,t.g,t.b),s.setXYZ(1,t.r,t.g,t.b),s.setXYZ(2,t.r,t.g,t.b),s.setXYZ(3,t.r,t.g,t.b),s.setXYZ(4,t.r,t.g,t.b),s.setXYZ(5,t.r,t.g,t.b),s.setXYZ(6,t.r,t.g,t.b),s.setXYZ(7,t.r,t.g,t.b),s.setXYZ(8,t.r,t.g,t.b),s.setXYZ(9,t.r,t.g,t.b),s.setXYZ(10,t.r,t.g,t.b),s.setXYZ(11,t.r,t.g,t.b),s.setXYZ(12,t.r,t.g,t.b),s.setXYZ(13,t.r,t.g,t.b),s.setXYZ(14,t.r,t.g,t.b),s.setXYZ(15,t.r,t.g,t.b),s.setXYZ(16,t.r,t.g,t.b),s.setXYZ(17,t.r,t.g,t.b),s.setXYZ(18,t.r,t.g,t.b),s.setXYZ(19,t.r,t.g,t.b),s.setXYZ(20,t.r,t.g,t.b),s.setXYZ(21,t.r,t.g,t.b),s.setXYZ(22,t.r,t.g,t.b),s.setXYZ(23,t.r,t.g,t.b),s.setXYZ(24,e.r,e.g,e.b),s.setXYZ(25,e.r,e.g,e.b),s.setXYZ(26,e.r,e.g,e.b),s.setXYZ(27,e.r,e.g,e.b),s.setXYZ(28,e.r,e.g,e.b),s.setXYZ(29,e.r,e.g,e.b),s.setXYZ(30,e.r,e.g,e.b),s.setXYZ(31,e.r,e.g,e.b),s.setXYZ(32,n.r,n.g,n.b),s.setXYZ(33,n.r,n.g,n.b),s.setXYZ(34,n.r,n.g,n.b),s.setXYZ(35,n.r,n.g,n.b),s.setXYZ(36,n.r,n.g,n.b),s.setXYZ(37,n.r,n.g,n.b),s.setXYZ(38,i.r,i.g,i.b),s.setXYZ(39,i.r,i.g,i.b),s.setXYZ(40,r.r,r.g,r.b),s.setXYZ(41,r.r,r.g,r.b),s.setXYZ(42,r.r,r.g,r.b),s.setXYZ(43,r.r,r.g,r.b),s.setXYZ(44,r.r,r.g,r.b),s.setXYZ(45,r.r,r.g,r.b),s.setXYZ(46,r.r,r.g,r.b),s.setXYZ(47,r.r,r.g,r.b),s.setXYZ(48,r.r,r.g,r.b),s.setXYZ(49,r.r,r.g,r.b),s.needsUpdate=!0}update(){const t=this.geometry,e=this.pointMap;Gm.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),Xm("c",e,t,Gm,0,0,-1),Xm("t",e,t,Gm,0,0,1),Xm("n1",e,t,Gm,-1,-1,-1),Xm("n2",e,t,Gm,1,-1,-1),Xm("n3",e,t,Gm,-1,1,-1),Xm("n4",e,t,Gm,1,1,-1),Xm("f1",e,t,Gm,-1,-1,1),Xm("f2",e,t,Gm,1,-1,1),Xm("f3",e,t,Gm,-1,1,1),Xm("f4",e,t,Gm,1,1,1),Xm("u1",e,t,Gm,.7,1.1,-1),Xm("u2",e,t,Gm,-.7,1.1,-1),Xm("u3",e,t,Gm,0,2,-1),Xm("cf1",e,t,Gm,-1,0,1),Xm("cf2",e,t,Gm,1,0,1),Xm("cf3",e,t,Gm,0,-1,1),Xm("cf4",e,t,Gm,0,1,1),Xm("cn1",e,t,Gm,-1,0,-1),Xm("cn2",e,t,Gm,1,0,-1),Xm("cn3",e,t,Gm,0,-1,-1),Xm("cn4",e,t,Gm,0,1,-1),t.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}}function Xm(t,e,n,i,r,s,a){Hm.set(r,s,a).unproject(i);const o=e[t];if(void 0!==o){const t=n.getAttribute("position");for(let e=0,n=o.length;e<n;e++)t.setXYZ(o[e],Hm.x,Hm.y,Hm.z)}}const jm=new Li;class qm extends Ah{constructor(t,e=16776960){const n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),i=new Float32Array(24),r=new Es;r.setIndex(new cs(n,1)),r.setAttribute("position",new cs(i,3)),super(r,new fh({color:e,toneMapped:!1})),this.object=t,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(t){if(void 0!==t&&console.warn("THREE.BoxHelper: .update() has no longer arguments."),void 0!==this.object&&jm.setFromObject(this.object),jm.isEmpty())return;const e=jm.min,n=jm.max,i=this.geometry.attributes.position,r=i.array;r[0]=n.x,r[1]=n.y,r[2]=n.z,r[3]=e.x,r[4]=n.y,r[5]=n.z,r[6]=e.x,r[7]=e.y,r[8]=n.z,r[9]=n.x,r[10]=e.y,r[11]=n.z,r[12]=n.x,r[13]=n.y,r[14]=e.z,r[15]=e.x,r[16]=n.y,r[17]=e.z,r[18]=e.x,r[19]=e.y,r[20]=e.z,r[21]=n.x,r[22]=e.y,r[23]=e.z,i.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(t){return this.object=t,this.update(),this}copy(t,e){return super.copy(t,e),this.object=t.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class Ym extends Ah{constructor(t,e=16776960){const n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),i=new Es;i.setIndex(new cs(n,1)),i.setAttribute("position",new _s([1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3)),super(i,new fh({color:e,toneMapped:!1})),this.box=t,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(t){const e=this.box;e.isEmpty()||(e.getCenter(this.position),e.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(t))}dispose(){this.geometry.dispose(),this.material.dispose()}}class Zm extends bh{constructor(t,e=1,n=16776960){const i=n,r=new Es;r.setAttribute("position",new _s([1,-1,0,-1,1,0,-1,-1,0,1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],3)),r.computeBoundingSphere(),super(r,new fh({color:i,toneMapped:!1})),this.type="PlaneHelper",this.plane=t,this.size=e;const s=new Es;s.setAttribute("position",new _s([1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],3)),s.computeBoundingSphere(),this.add(new Bs(s,new es({color:i,opacity:.2,transparent:!0,depthWrite:!1,toneMapped:!1})))}updateMatrixWorld(t){this.position.set(0,0,0),this.scale.set(.5*this.size,.5*this.size,1),this.lookAt(this.plane.normal),this.translateZ(-this.plane.constant),super.updateMatrixWorld(t)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}}const Jm=new Ci;let Km,$m;class Qm extends Lr{constructor(t=new Ci(0,0,1),e=new Ci(0,0,0),n=1,i=16776960,r=.2*n,s=.2*r){super(),this.type="ArrowHelper",void 0===Km&&(Km=new Es,Km.setAttribute("position",new _s([0,0,0,0,1,0],3)),$m=new pu(0,.5,1,5,1),$m.translate(0,-.5,0)),this.position.copy(e),this.line=new bh(Km,new fh({color:i,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new Bs($m,new es({color:i,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(t),this.setLength(n,r,s)}setDirection(t){if(t.y>.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{Jm.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(Jm,e)}}setLength(t,e=.2*t,n=.2*e){this.line.scale.set(1,Math.max(1e-4,t-e),1),this.line.updateMatrix(),this.cone.scale.set(n,e,n),this.cone.position.y=t,this.cone.updateMatrix()}setColor(t){this.line.material.color.set(t),this.cone.material.color.set(t)}copy(t){return super.copy(t,!1),this.line.copy(t.line),this.cone.copy(t.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class tf extends Ah{constructor(t=1){const e=[0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t],n=new Es;n.setAttribute("position",new _s(e,3)),n.setAttribute("color",new _s([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(n,new fh({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(t,e,n){const i=new Kr,r=this.geometry.attributes.color.array;return i.set(t),i.toArray(r,0),i.toArray(r,3),i.set(e),i.toArray(r,6),i.toArray(r,9),i.set(n),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class ef{constructor(){this.type="ShapePath",this.color=new Kr,this.subPaths=[],this.currentPath=null}moveTo(t,e){return this.currentPath=new cu,this.subPaths.push(this.currentPath),this.currentPath.moveTo(t,e),this}lineTo(t,e){return this.currentPath.lineTo(t,e),this}quadraticCurveTo(t,e,n,i){return this.currentPath.quadraticCurveTo(t,e,n,i),this}bezierCurveTo(t,e,n,i,r,s){return this.currentPath.bezierCurveTo(t,e,n,i,r,s),this}splineThru(t){return this.currentPath.splineThru(t),this}toShapes(t){function e(t,e){const n=e.length;let i=!1;for(let r=n-1,s=0;s<n;r=s++){let n=e[r],a=e[s],o=a.x-n.x,l=a.y-n.y;if(Math.abs(l)>Number.EPSILON){if(l<0&&(n=e[s],o=-o,a=e[r],l=-l),t.y<n.y||t.y>a.y)continue;if(t.y===n.y){if(t.x===n.x)return!0}else{const e=l*(t.x-n.x)-o*(t.y-n.y);if(0===e)return!0;if(e<0)continue;i=!i}}else{if(t.y!==n.y)continue;if(a.x<=t.x&&t.x<=n.x||n.x<=t.x&&t.x<=a.x)return!0}}return i}const n=Yu.isClockWise,i=this.subPaths;if(0===i.length)return[];let r,s,a;const o=[];if(1===i.length)return s=i[0],a=new Su,a.curves=s.curves,o.push(a),o;let l=!n(i[0].getPoints());l=t?!l:l;const c=[],h=[];let u,d,p=[],m=0;h[m]=void 0,p[m]=[];for(let e=0,a=i.length;e<a;e++)s=i[e],u=s.getPoints(),r=n(u),r=t?!r:r,r?(!l&&h[m]&&m++,h[m]={s:new Su,p:u},h[m].s.curves=s.curves,l&&m++,p[m]=[]):p[m].push({h:s,p:u[0]});if(!h[0])return function(t){const e=[];for(let n=0,i=t.length;n<i;n++){const i=t[n],r=new Su;r.curves=i.curves,e.push(r)}return e}(i);if(h.length>1){let t=!1,n=0;for(let t=0,e=h.length;t<e;t++)c[t]=[];for(let i=0,r=h.length;i<r;i++){const r=p[i];for(let s=0;s<r.length;s++){const a=r[s];let o=!0;for(let r=0;r<h.length;r++)e(a.p,h[r].p)&&(i!==r&&n++,o?(o=!1,c[r].push(a)):t=!0);o&&c[i].push(a)}}n>0&&!1===t&&(p=c)}for(let t=0,e=h.length;t<e;t++){a=h[t].s,o.push(a),d=p[t];for(let t=0,e=d.length;t<e;t++)a.holes.push(d[t].h)}return o}}class nf extends Bn{constructor(t,e=null){super(),this.object=t,this.domElement=e,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(){}disconnect(){}dispose(){}update(){}}class rf extends bi{constructor(t=1,e=1,n=1,i={}){console.warn('THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.'),super(t,e,{...i,count:n}),this.isWebGLMultipleRenderTargets=!0}get texture(){return this.textures}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:t}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=t);export{et as ACESFilmicToneMapping,y as AddEquation,J as AddOperation,ze as AdditiveAnimationBlendMode,g as AdditiveBlending,it as AgXToneMapping,Bt as AlphaFormat,Tn as AlwaysCompare,V as AlwaysDepth,gn as AlwaysStencilFunc,fp as AmbientLight,rm as AnimationAction,zd as AnimationClip,Yd as AnimationLoader,am as AnimationMixer,im as AnimationObjectGroup,Ed as AnimationUtils,Wh as ArcCurve,Xl as ArrayCamera,Qm as ArrowHelper,st as AttachedBindMode,Hp as Audio,Yp as AudioAnalyser,Cp as AudioContext,Vp as AudioListener,Ip as AudioLoader,tf as AxesHelper,d as BackSide,Ge as BasicDepthPacking,o as BasicShadowMap,mh as BatchedMesh,Fc as Bone,Ld as BooleanKeyframeTrack,ym as Box2,Li as Box3,Ym as Box3Helper,ks as BoxGeometry,qm as BoxHelper,cs as BufferAttribute,Es as BufferGeometry,Sp as BufferGeometryLoader,At as ByteType,Vd as Cache,js as Camera,Wm as CameraHelper,Vh as CanvasTexture,uu as CapsuleGeometry,Jh as CatmullRomCurve3,tt as CineonToneMapping,du as CircleGeometry,mt as ClampToEdgeWrapping,Np as Clock,Kr as Color,Ud as ColorKeyframeTrack,ai as ColorManagement,zh as CompressedArrayTexture,kh as CompressedCubeTexture,Bh as CompressedTexture,Zd as CompressedTextureLoader,mu as ConeGeometry,B as ConstantAlphaFactor,O as ConstantColorFactor,nf as Controls,$s as CubeCamera,lt as CubeReflectionMapping,ct as CubeRefractionMapping,Qs as CubeTexture,Kd as CubeTextureLoader,dt as CubeUVReflectionMapping,tu as CubicBezierCurve,eu as CubicBezierCurve3,Rd as CubicInterpolant,r as CullFaceBack,s as CullFaceFront,a as CullFaceFrontBack,i as CullFaceNone,Hh as Curve,lu as CurvePath,x as CustomBlending,nt as CustomToneMapping,pu as CylinderGeometry,vm as Cylindrical,Ei as Data3DTexture,Ti as DataArrayTexture,Bc as DataTexture,$d as DataTextureLoader,as as DataUtils,sn as DecrementStencilOp,on as DecrementWrapStencilOp,Gd as DefaultLoadingManager,Gt as DepthFormat,Wt as DepthStencilFormat,Ya as DepthTexture,at as DetachedBindMode,mp as DirectionalLight,Vm as DirectionalLightHelper,Id as DiscreteInterpolant,gu as DodecahedronGeometry,p as DoubleSide,P as DstAlphaFactor,U as DstColorFactor,Ln as DynamicCopyUsage,En as DynamicDrawUsage,Cn as DynamicReadUsage,Mu as EdgesGeometry,Gh as EllipseCurve,xn as EqualCompare,W as EqualDepth,un as EqualStencilFunc,ht as EquirectangularReflectionMapping,ut as EquirectangularRefractionMapping,fr as Euler,Bn as EventDispatcher,Ku as ExtrudeGeometry,qd as FileLoader,vs as Float16BufferAttribute,_s as Float32BufferAttribute,Lt as FloatType,ic as Fog,nc as FogExp2,Fh as FramebufferTexture,u as FrontSide,oa as Frustum,um as GLBufferAttribute,Dn as GLSL1,Nn as GLSL3,Mn as GreaterCompare,j as GreaterDepth,bn as GreaterEqualCompare,X as GreaterEqualDepth,fn as GreaterEqualStencilFunc,pn as GreaterStencilFunc,Om as GridHelper,jl as Group,Ut as HalfFloatType,ep as HemisphereLight,Nm as HemisphereLightHelper,Qu as IcosahedronGeometry,Ap as ImageBitmapLoader,Jd as ImageLoader,fi as ImageUtils,rn as IncrementStencilOp,an as IncrementWrapStencilOp,Hc as InstancedBufferAttribute,Mp as InstancedBufferGeometry,hm as InstancedInterleavedBuffer,Jc as InstancedMesh,ps as Int16BufferAttribute,fs as Int32BufferAttribute,hs as Int8BufferAttribute,It as IntType,sc as InterleavedBuffer,oc as InterleavedBufferAttribute,Ad as Interpolant,Le as InterpolateDiscrete,Ue as InterpolateLinear,De as InterpolateSmooth,ln as InvertStencilOp,en as KeepStencilOp,Pd as KeyframeTrack,Ec as LOD,hu as LatheGeometry,gr as Layers,_n as LessCompare,H as LessDepth,yn as LessEqualCompare,G as LessEqualDepth,dn as LessEqualStencilFunc,hn as LessStencilFunc,tp as Light,_p as LightProbe,bh as Line,bm as Line3,fh as LineBasicMaterial,nu as LineCurve,iu as LineCurve3,yd as LineDashedMaterial,Rh as LineLoop,Ah as LineSegments,Mt as LinearFilter,Cd as LinearInterpolant,wt as LinearMipMapLinearFilter,bt as LinearMipMapNearestFilter,Tt as LinearMipmapLinearFilter,St as LinearMipmapNearestFilter,Ke as LinearSRGBColorSpace,$ as LinearToneMapping,$e as LinearTransfer,Wd as Loader,yp as LoaderUtils,Hd as LoadingManager,Ce as LoopOnce,Pe as LoopPingPong,Ie as LoopRepeat,Ht as LuminanceAlphaFormat,Vt as LuminanceFormat,e as MOUSE,ts as Material,xp as MaterialLoader,Zn as MathUtils,_m as Matrix2,Kn as Matrix3,sr as Matrix4,T as MaxEquation,Bs as Mesh,es as MeshBasicMaterial,Ol as MeshDepthMaterial,Fl as MeshDistanceMaterial,_d as MeshLambertMaterial,xd as MeshMatcapMaterial,vd as MeshNormalMaterial,fd as MeshPhongMaterial,md as MeshPhysicalMaterial,pd as MeshStandardMaterial,gd as MeshToonMaterial,b as MinEquation,ft as MirroredRepeatWrapping,Z as MixOperation,_ as MultiplyBlending,Y as MultiplyOperation,gt as NearestFilter,yt as NearestMipMapLinearFilter,_t as NearestMipMapNearestFilter,xt as NearestMipmapLinearFilter,vt as NearestMipmapNearestFilter,rt as NeutralToneMapping,vn as NeverCompare,k as NeverDepth,cn as NeverStencilFunc,m as NoBlending,Ze as NoColorSpace,K as NoToneMapping,Be as NormalAnimationBlendMode,f as NormalBlending,Sn as NotEqualCompare,q as NotEqualDepth,mn as NotEqualStencilFunc,Dd as NumberKeyframeTrack,Lr as Object3D,bp as ObjectLoader,Ye as ObjectSpaceNormalMap,td as OctahedronGeometry,E as OneFactor,z as OneMinusConstantAlphaFactor,F as OneMinusConstantColorFactor,L as OneMinusDstAlphaFactor,D as OneMinusDstColorFactor,I as OneMinusSrcAlphaFactor,R as OneMinusSrcColorFactor,ba as OrthographicCamera,l as PCFShadowMap,c as PCFSoftShadowMap,Na as PMREMGenerator,cu as Path,Js as PerspectiveCamera,ra as Plane,ha as PlaneGeometry,Zm as PlaneHelper,dp as PointLight,Pm as PointLightHelper,Dh as Points,Ch as PointsMaterial,Fm as PolarGridHelper,fu as PolyhedronGeometry,qp as PositionalAudio,nm as PropertyBinding,Zp as PropertyMixer,ru as QuadraticBezierCurve,su as QuadraticBezierCurve3,Ri as Quaternion,Od as QuaternionKeyframeTrack,Nd as QuaternionLinearInterpolant,Ae as RED_GREEN_RGTC2_Format,we as RED_RGTC1_Format,t as REVISION,We as RGBADepthPacking,kt as RGBAFormat,Jt as RGBAIntegerFormat,xe as RGBA_ASTC_10x10_Format,ge as RGBA_ASTC_10x5_Format,ve as RGBA_ASTC_10x6_Format,_e as RGBA_ASTC_10x8_Format,ye as RGBA_ASTC_12x10_Format,Me as RGBA_ASTC_12x12_Format,le as RGBA_ASTC_4x4_Format,ce as RGBA_ASTC_5x4_Format,he as RGBA_ASTC_5x5_Format,ue as RGBA_ASTC_6x5_Format,de as RGBA_ASTC_6x6_Format,pe as RGBA_ASTC_8x5_Format,me as RGBA_ASTC_8x6_Format,fe as RGBA_ASTC_8x8_Format,Se as RGBA_BPTC_Format,oe as RGBA_ETC2_EAC_Format,re as RGBA_PVRTC_2BPPV1_Format,ie as RGBA_PVRTC_4BPPV1_Format,$t as RGBA_S3TC_DXT1_Format,Qt as RGBA_S3TC_DXT3_Format,te as RGBA_S3TC_DXT5_Format,Xe as RGBDepthPacking,zt as RGBFormat,Zt as RGBIntegerFormat,be as RGB_BPTC_SIGNED_Format,Te as RGB_BPTC_UNSIGNED_Format,se as RGB_ETC1_Format,ae as RGB_ETC2_Format,ne as RGB_PVRTC_2BPPV1_Format,ee as RGB_PVRTC_4BPPV1_Format,Kt as RGB_S3TC_DXT1_Format,je as RGDepthPacking,qt as RGFormat,Yt as RGIntegerFormat,dd as RawShaderMaterial,rr as Ray,pm as Raycaster,gp as RectAreaLight,Xt as RedFormat,jt as RedIntegerFormat,Q as ReinhardToneMapping,Si as RenderTarget,pt as RepeatWrapping,nn as ReplaceStencilOp,S as ReverseSubtractEquation,ed as RingGeometry,Re as SIGNED_RED_GREEN_RGTC2_Format,Ee as SIGNED_RED_RGTC1_Format,Je as SRGBColorSpace,Qe as SRGBTransfer,rc as Scene,ua as ShaderChunk,pa as ShaderLib,Xs as ShaderMaterial,ud as ShadowMaterial,Su as Shape,nd as ShapeGeometry,ef as ShapePath,Yu as ShapeUtils,Rt as ShortType,Vc as Skeleton,Cm as SkeletonHelper,Oc as SkinnedMesh,vi as Source,Ji as Sphere,id as SphereGeometry,gm as Spherical,vp as SphericalHarmonics3,au as SplineCurve,op as SpotLight,wm as SpotLightHelper,Sc as Sprite,lc as SpriteMaterial,C as SrcAlphaFactor,N as SrcAlphaSaturateFactor,A as SrcColorFactor,Pn as StaticCopyUsage,wn as StaticDrawUsage,Rn as StaticReadUsage,Dp as StereoCamera,Un as StreamCopyUsage,An as StreamDrawUsage,In as StreamReadUsage,Fd as StringKeyframeTrack,M as SubtractEquation,v as SubtractiveBlending,n as TOUCH,qe as TangentSpaceNormalMap,rd as TetrahedronGeometry,yi as Texture,Qd as TextureLoader,Hl as TextureUtils,sd as TorusGeometry,ad as TorusKnotGeometry,jr as Triangle,He as TriangleFanDrawMode,Ve as TriangleStripDrawMode,ke as TrianglesDrawMode,od as TubeGeometry,ot as UVMapping,ms as Uint16BufferAttribute,gs as Uint32BufferAttribute,us as Uint8BufferAttribute,ds as Uint8ClampedBufferAttribute,om as Uniform,cm as UniformsGroup,da as UniformsLib,Ws as UniformsUtils,Et as UnsignedByteType,Ot as UnsignedInt248Type,Ft as UnsignedInt5999Type,Pt as UnsignedIntType,Dt as UnsignedShort4444Type,Nt as UnsignedShort5551Type,Ct as UnsignedShortType,h as VSMShadowMap,Jn as Vector2,Ci as Vector3,Mi as Vector4,Bd as VectorKeyframeTrack,Oh as VideoTexture,Ai as WebGL3DRenderTarget,wi as WebGLArrayRenderTarget,On as WebGLCoordinateSystem,ta as WebGLCubeRenderTarget,rf as WebGLMultipleRenderTargets,bi as WebGLRenderTarget,ec as WebGLRenderer,Wl as WebGLUtils,Fn as WebGPUCoordinateSystem,ld as WireframeGeometry,Fe as WrapAroundEnding,Ne as ZeroCurvatureEnding,w as ZeroFactor,Oe as ZeroSlopeEnding,tn as ZeroStencilOp,ii as createCanvasElement}; diff --git a/server/Cargo.toml b/server/Cargo.toml new file mode 100644 index 0000000..530532a --- /dev/null +++ b/server/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "server" +edition.workspace = true +version.workspace = true + +[[bin]] +name = "server" +path = "src/main.rs" + +[[bin]] +name = "precompute" +path = "src/bin/precompute.rs" + +[dependencies] +app = { workspace = true, features = ["ssr"] } +domain = { workspace = true } +pipeline = { workspace = true } +storage = { workspace = true } +providers = { workspace = true } +llm = { workspace = true } +leptos = { workspace = true, features = ["ssr"] } +leptos_axum = { workspace = true } +axum = { workspace = true } +tower-http = { workspace = true } +tokio = { workspace = true } +tokio-stream = { workspace = true } +futures = { workspace = true } +serde_json = { workspace = true } +anyhow = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +dotenvy = { workspace = true } diff --git a/server/src/bin/precompute.rs b/server/src/bin/precompute.rs new file mode 100644 index 0000000..3a5a349 --- /dev/null +++ b/server/src/bin/precompute.rs @@ -0,0 +1,49 @@ +//! Precompute and cache 3D layouts for demo queries. +//! +//! Usage: +//! cargo run --bin precompute -- "성수 대림창고" "어니언 성수" "블루보틀 성수" + +#[path = "../config.rs"] +mod config; + +use domain::Place; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let _ = dotenvy::dotenv(); + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "info,pipeline=debug,providers=debug".into()), + ) + .init(); + + let pipeline = config::init_pipeline_from_env().await?; + pipeline.store.health_check().await?; + + let args: Vec<String> = std::env::args().skip(1).collect(); + let queries: Vec<String> = if args.is_empty() { + vec!["성수 대림창고".into(), "어니언 성수".into(), "블루보틀 성수".into()] + } else { + args + }; + + for q in queries { + tracing::info!(query = %q, "searching place"); + let candidates = pipeline.search_places(&q).await?; + let Some(first) = candidates.into_iter().next() else { + tracing::warn!(query = %q, "no candidates found"); + continue; + }; + let place = Place::from_candidate(&first); + tracing::info!(place_id = %place.id, name = %place.name, "running full analysis"); + let layout = pipeline.run_sync(place).await?; + tracing::info!( + place_id = %layout.place_id, + floors = layout.floors.len(), + confidence = layout.confidence, + "layout saved" + ); + } + Ok(()) +} diff --git a/server/src/config.rs b/server/src/config.rs new file mode 100644 index 0000000..501807a --- /dev/null +++ b/server/src/config.rs @@ -0,0 +1,113 @@ +use llm::{LlmClient, LlmProviderConfig, ProviderKind}; +use pipeline::{Pipeline, PipelineConfig}; +use storage::{StorageConfig, Store}; + +fn env_or(key: &str, default: &str) -> String { + std::env::var(key) + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| default.to_string()) +} + +fn init_llm_from_env() -> anyhow::Result<LlmClient> { + if let Ok(raw_json) = std::env::var("LLM_PROVIDERS") { + let trimmed = raw_json.trim(); + if !trimmed.is_empty() { + let client = LlmClient::from_json_str(trimmed)?; + let summary: Vec<String> = client + .providers() + .iter() + .map(|p| format!("{}:{} (weight={})", p.provider.as_str(), p.model, p.weight)) + .collect(); + tracing::info!(providers = ?summary, "initialized multi-provider LLM client from LLM_PROVIDERS"); + return Ok(client); + } + } + + let provider_str = env_or("LLM_PROVIDER", &env_or("PROVIDER", "cpa")); + let provider = match provider_str.to_lowercase().as_str() { + "strata" => ProviderKind::Strata, + "cpa" | "cliproxy" | "cli-proxy" => ProviderKind::Cpa, + other => ProviderKind::Custom(other.to_string()), + }; + let weight: u32 = env_or("LLM_WEIGHT", &env_or("WEIGHT", "1")) + .parse() + .unwrap_or(1); + + LlmClient::from_providers(vec![LlmProviderConfig { + provider, + endpoint: env_or( + "OPENAI_COMPATIBLE_API_ENDPOINT", + "http://126.dahyeon.us:8317", + ), + api_key: env_or("OPENAI_COMPATIBLE_API_KEY", ""), + model: env_or("LLM_MODEL", &env_or("MODEL", "gpt-6.1-sol")), + weight, + }]) +} + +pub async fn init_pipeline_from_env() -> anyhow::Result<Pipeline> { + let _ = dotenvy::dotenv(); + + let storage_cfg = StorageConfig { + mongodb_uri: env_or( + "MONGODB_CONNECTION_STRING", + &env_or("MONGODB_URI", "mongodb://localhost:27017"), + ), + mongodb_db: env_or("MONGODB_DB", "make_space"), + minio_endpoint: env_or("MINIO_ENDPOINT", "http://localhost:9000"), + minio_access_key: env_or("MINIO_ACCESS_KEY", "minioadmin"), + minio_secret_key: env_or("MINIO_SECRET_KEY", "minioadmin"), + minio_bucket: env_or("MINIO_BUCKET", "make-space-photos"), + }; + let store = Store::connect(&storage_cfg).await?; + if let Err(e) = store.ensure_indexes().await { + tracing::warn!("MongoDB index creation skipped (is MongoDB reachable?): {e}"); + } + + let llm = init_llm_from_env()?; + let health_results = llm.health_check_all().await; + for h in &health_results { + if h.healthy { + tracing::info!( + provider = h.provider.as_str(), + endpoint = %h.endpoint, + model = %h.model, + weight = h.weight, + latency_ms = h.latency_ms, + detail = %h.detail, + "LLM provider health check passed" + ); + } else { + tracing::warn!( + provider = h.provider.as_str(), + endpoint = %h.endpoint, + model = %h.model, + weight = h.weight, + latency_ms = h.latency_ms, + error = %h.detail, + "LLM provider health check failed (will remain in failover pool)" + ); + } + } + + let pipe_cfg = PipelineConfig { + kakao_api_key: std::env::var("KAKAO_REST_API_KEY").unwrap_or_default(), + ncp_client_id: env_or( + "X-NCP-APIGW-API-KEY-ID", + &env_or("X_NCP_APIGW_API_KEY_ID", &env_or("NCP_CLIENT_ID", "")), + ), + ncp_client_secret: env_or( + "X-NCP-APIGW-API-KEY", + &env_or("X_NCP_APIGW_API_KEY", &env_or("NCP_CLIENT_SECRET", "")), + ), + browser_scraper_url: std::env::var("BROWSER_SCRAPER_URL") + .ok() + .filter(|s| !s.trim().is_empty()), + max_photos_per_source: env_or("MAX_PHOTOS_PER_SOURCE", "30").parse().unwrap_or(30), + max_photos_total: env_or("MAX_PHOTOS_TOTAL", "80").parse().unwrap_or(80), + }; + + Ok(Pipeline::new(store, llm, pipe_cfg)) +} diff --git a/server/src/main.rs b/server/src/main.rs new file mode 100644 index 0000000..7e710e3 --- /dev/null +++ b/server/src/main.rs @@ -0,0 +1,244 @@ +mod config; + +use std::convert::Infallible; +use std::time::Duration; + +use axum::extract::{Path, State}; +use axum::http::{header, StatusCode}; +use axum::response::sse::{Event, KeepAlive, Sse}; +use axum::response::{IntoResponse, Response}; +use axum::routing::get; +use axum::Router; +use domain::JobEvent; +use futures::stream::{self, StreamExt}; +use leptos::config::get_configuration; +use leptos::prelude::provide_context; +use leptos_axum::{generate_route_list, LeptosRoutes}; +use pipeline::Pipeline; +use tokio_stream::wrappers::BroadcastStream; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let _ = dotenvy::dotenv(); + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "info,server=debug,pipeline=debug,providers=debug".into()), + ) + .init(); + + let pipeline = config::init_pipeline_from_env().await?; + let conf = get_configuration(None)?; + let leptos_options = conf.leptos_options; + let addr = leptos_options.site_addr; + let routes = generate_route_list(app::App); + + let pipe_for_ctx = pipeline.clone(); + let app_router = Router::new() + .route("/health/live", get(health_live)) + .route("/health/ready", get(health_check)) + .route("/api/health", get(health_check)) + .route("/api/jobs/{id}/events", get(job_events_sse)) + .route("/api/photos/{id}", get(serve_photo)) + .with_state(pipeline) + .leptos_routes_with_context( + &leptos_options, + routes, + move || { + provide_context(pipe_for_ctx.clone()); + }, + { + let opts = leptos_options.clone(); + move || app::shell(opts.clone()) + }, + ) + .fallback(leptos_axum::file_and_error_handler(app::shell)) + .with_state(leptos_options); + + tracing::info!("listening on http://{addr}"); + let listener = tokio::net::TcpListener::bind(&addr).await?; + axum::serve(listener, app_router.into_make_service()).await?; + Ok(()) +} + +async fn job_events_sse( + State(pipeline): State<Pipeline>, + Path(job_id): Path<String>, +) -> Sse<impl futures::Stream<Item = Result<Event, Infallible>>> { + let (past, rx_opt) = prepare_job_subscription(pipeline.subscribe_job(&job_id).await); + let already_done = past.iter().any(|e| e.is_terminal()); + + let past_stream = stream::iter(past).map(|ev| { + let json = serde_json::to_string(&ev).unwrap_or_default(); + Ok::<_, Infallible>(Event::default().data(json)) + }); + + let live_stream = match rx_opt { + Some(rx) if !already_done => BroadcastStream::new(rx) + .filter_map(|item| async move { item.ok() }) + .map(|ev| { + let done = ev.is_terminal(); + let json = serde_json::to_string(&ev).unwrap_or_default(); + (done, Ok::<_, Infallible>(Event::default().data(json))) + }) + .scan(false, |finished, (done, ev)| { + let emit = if *finished { None } else { Some(ev) }; + if done { + *finished = true; + } + futures::future::ready(emit) + }) + .left_stream(), + _ => stream::empty().right_stream(), + }; + + Sse::new(past_stream.chain(live_stream)).keep_alive( + KeepAlive::new() + .interval(Duration::from_secs(10)) + .text("keep-alive"), + ) +} + +type JobSubscription = ( + Vec<JobEvent>, + Option<tokio::sync::broadcast::Receiver<JobEvent>>, +); + +fn prepare_job_subscription(subscription: anyhow::Result<JobSubscription>) -> JobSubscription { + let (mut past, receiver) = match subscription { + Ok(subscription) => subscription, + Err(error) => { + tracing::warn!(%error, "could not subscribe to analysis job"); + return ( + vec![JobEvent::Error { + message: "분석 진행 상태를 불러오지 못했습니다. 잠시 후 다시 시도해 주세요." + .into(), + }], + None, + ); + } + }; + // A stored job may outlive its process. Replaying only its nonterminal history + // would make EventSource reconnect forever, resetting the client's retry counter. + if receiver.is_none() && !past.iter().any(JobEvent::is_terminal) { + let message = if past.is_empty() { + "분석 작업을 찾을 수 없습니다. 장소에서 분석을 다시 시작해 주세요." + } else { + "분석 작업이 중단됐습니다. 장소에서 분석을 다시 시작해 주세요." + }; + past.push(JobEvent::Error { + message: message.into(), + }); + } + (past, receiver) +} + +async fn health_live() -> Response { + ( + StatusCode::OK, + [(header::CONTENT_TYPE, "application/json")], + r#"{"status":"ok"}"#, + ) + .into_response() +} + +async fn health_check(State(pipeline): State<Pipeline>) -> Response { + let storage_ok = pipeline.store.health_check().await.is_ok(); + let llm_providers = pipeline.llm.health_check_all().await; + let any_llm_healthy = llm_providers.iter().any(|p| p.healthy); + let status = if storage_ok && any_llm_healthy { + StatusCode::OK + } else { + StatusCode::SERVICE_UNAVAILABLE + }; + let body = serde_json::json!({ + "status": if status == StatusCode::OK { "ok" } else { "degraded" }, + "storage_healthy": storage_ok, + "llm_providers": llm_providers, + }); + ( + status, + [(header::CONTENT_TYPE, "application/json")], + body.to_string(), + ) + .into_response() +} + +async fn serve_photo(State(pipeline): State<Pipeline>, Path(photo_id): Path<String>) -> Response { + let Ok(Some(photo)) = pipeline.store.get_photo(&photo_id).await else { + return StatusCode::NOT_FOUND.into_response(); + }; + match pipeline.store.get_blob(&photo.object_key).await { + Ok(bytes) => ( + StatusCode::OK, + [ + (header::CONTENT_TYPE, "image/jpeg"), + (header::CACHE_CONTROL, "public, max-age=86400"), + ], + bytes, + ) + .into_response(), + Err(_) => StatusCode::NOT_FOUND.into_response(), + } +} + +#[cfg(test)] +mod job_events_tests { + use super::*; + + #[test] + fn missing_job_returns_a_terminal_error() { + let (events, receiver) = prepare_job_subscription(Ok((Vec::new(), None))); + assert!(receiver.is_none()); + assert_eq!(events.len(), 1); + assert!( + matches!(&events[0], JobEvent::Error { message } if message.contains("찾을 수 없습니다")) + ); + } + + #[test] + fn interrupted_job_keeps_history_then_terminates() { + let past = vec![ + JobEvent::Started { + place_id: "place-1".into(), + }, + JobEvent::LayoutDraft { attempt: 1 }, + ]; + let (events, receiver) = prepare_job_subscription(Ok((past, None))); + assert!(receiver.is_none()); + assert_eq!(events.len(), 3); + assert!(matches!(events[0], JobEvent::Started { .. })); + assert!(matches!(events[1], JobEvent::LayoutDraft { .. })); + assert!(matches!(&events[2], JobEvent::Error { message } if message.contains("중단"))); + } + + #[test] + fn subscription_failure_returns_a_user_facing_terminal_error() { + let (events, receiver) = + prepare_job_subscription(Err(anyhow::anyhow!("private storage error"))); + assert!(receiver.is_none()); + assert_eq!(events.len(), 1); + assert!(matches!(&events[0], JobEvent::Error { message } if !message.contains("private"))); + } + + #[test] + fn live_job_and_finished_job_are_not_marked_as_interrupted() { + let (_sender, receiver) = tokio::sync::broadcast::channel(2); + let (events, receiver) = prepare_job_subscription(Ok((Vec::new(), Some(receiver)))); + assert!(events.is_empty()); + assert!(receiver.is_some()); + for terminal in [ + JobEvent::Done { + place_id: "place-1".into(), + }, + JobEvent::Error { + message: "analysis failed".into(), + }, + ] { + let (events, receiver) = prepare_job_subscription(Ok((vec![terminal], None))); + assert!(receiver.is_none()); + assert_eq!(events.len(), 1); + assert!(events[0].is_terminal()); + } + } +} diff --git a/style/main.css b/style/main.css new file mode 100644 index 0000000..ae5fecb --- /dev/null +++ b/style/main.css @@ -0,0 +1,373 @@ +@font-face { + font-family: "SUIT Variable"; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url("/fonts/SUIT-Variable.woff2") format("woff2"); +} + +/* Aurora semantic tokens, adapted for the Make-Space workspace. */ +:root { + color-scheme: light; + --color-bg-canvas: oklch(0.955 0.003 260); + --color-bg-surface: oklch(1 0 0); + --color-bg-raised: oklch(0.958 0.004 260); + --color-bg-hover: oklch(0.94 0.009 260); + --color-bg-pressed: oklch(0.91 0.012 260); + --color-fg-primary: oklch(0.23 0.012 260); + --color-fg-secondary: oklch(0.38 0.014 260); + --color-fg-muted: oklch(0.47 0.015 260); + --color-stroke-subtle: oklch(0.23 0.012 260 / 0.1); + --color-stroke-strong: oklch(0.23 0.012 260 / 0.26); + --color-accent-action: oklch(0.5 0.18 259); + --color-accent-action-hover: oklch(0.48 0.18 259); + --color-accent-action-pressed: oklch(0.44 0.17 259); + --color-accent-action-soft: oklch(0.5 0.18 259 / 0.08); + --color-accent-danger: oklch(0.48 0.17 24); + --color-accent-danger-soft: oklch(0.48 0.17 24 / 0.06); + --color-semantic-success: oklch(0.42 0.1 145); + --font-ui: "SUIT Variable", "Segoe UI Variable", "Apple SD Gothic Neo", "Malgun Gothic", sans-serif; + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-5: 20px; + --space-6: 24px; + --radius-control: 12px; + --radius-surface: 20px; + --radius-overlay: 24px; + --shadow-surface: 0 1px 2px oklch(0.23 0.012 260 / 0.04); + --shadow-control: 0 1px 3px oklch(0.23 0.012 260 / 0.08); + --duration-hover: 110ms; + --ease-standard: cubic-bezier(0.2, 0, 0, 1); +} + +* { box-sizing: border-box; } +html { scroll-padding-top: 128px; } +body { margin: 0; min-width: 0; background: var(--color-bg-canvas); color: var(--color-fg-primary); font-family: var(--font-ui); font-size: 14px; line-height: 1.55; -webkit-font-smoothing: antialiased; word-break: keep-all; overflow-wrap: anywhere; } +button, input, select { font: inherit; } +button, summary { cursor: pointer; } +button, a { touch-action: manipulation; -webkit-tap-highlight-color: transparent; } +button, a, input, select { transition: background-color var(--duration-hover) var(--ease-standard), color var(--duration-hover) var(--ease-standard), border-color var(--duration-hover) var(--ease-standard); } +button:disabled { cursor: default; opacity: .6; } +a { color: inherit; text-decoration: none; } +button { color: inherit; } +button[hidden], [hidden] { display: none !important; } +:focus-visible { outline: 2px solid var(--color-accent-action); outline-offset: 3px; } +::selection { background: var(--color-accent-action-soft); } +img, svg { max-width: 100%; } +h1, h2, h3, h4, strong { font-weight: 600; } +.icon { display: inline-block; width: 20px; height: 20px; flex: 0 0 20px; vertical-align: middle; } +.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; } +.skip-link { position: fixed; top: 8px; left: 16px; z-index: 100; transform: translateY(-180%); padding: 12px 16px; border-radius: 12px; color: white; background: var(--color-accent-action); } +.skip-link:focus { transform: none; } +.app-shell { --page-gutter: 28px; --context-header: calc(64px + env(safe-area-inset-top, 0px)); min-height: 100dvh; } +.topbar { position: sticky; top: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: var(--context-header); padding: calc(8px + env(safe-area-inset-top, 0px)) max(var(--page-gutter), env(safe-area-inset-right, 0px)) 8px max(var(--page-gutter), env(safe-area-inset-left, 0px)); border-bottom: 1px solid var(--color-stroke-subtle); background: var(--color-bg-surface); } +.brand { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; flex-shrink: 0; } +.brand-mark { color: var(--color-accent-action); } +.brand-mark .icon { width: 24px; height: 24px; } +.brand-title { font-size: 18px; font-weight: 600; letter-spacing: -.5px; white-space: nowrap; } +.topbar-nav { display: flex; align-items: center; gap: 4px; } +.topbar-nav a { display: grid; place-items: center; min-width: 44px; min-height: 44px; padding: 9px 14px; border-radius: 10px; color: var(--color-fg-muted); font-size: 14px; white-space: nowrap; } +.topbar-nav a[aria-current="page"] { color: var(--color-accent-action); background: var(--color-accent-action-soft); font-weight: 600; } +.topbar-nav a:hover { background: var(--color-bg-hover); } +.main-body { width: 100%; max-width: 1280px; margin: 0 auto; padding: 32px max(var(--page-gutter), env(safe-area-inset-right, 0px)) max(32px, env(safe-area-inset-bottom, 0px)) max(var(--page-gutter), env(safe-area-inset-left, 0px)); } +.main-body:has(.place-page) { padding-top: 0; } +.home-wrap, .recent-page { width: 100%; max-width: 840px; margin: 0 auto; } +.search-column, .results-column { min-width: 0; } +.page-heading { margin-bottom: 20px; } +.page-heading h1 { margin: 0; font-size: 24px; line-height: 32px; letter-spacing: -.6px; } +.page-heading p { margin: 6px 0 0; color: var(--color-fg-muted); } +.search-panel { padding: 16px; background: var(--color-bg-surface); border-radius: var(--radius-surface); } +.search-bar { display: flex; gap: 8px; } +.search-field { display: flex; align-items: center; flex: 1; min-width: 0; gap: 8px; padding-left: 12px; background: var(--color-bg-raised); border: 1px solid transparent; border-radius: var(--radius-control); } +.search-field > .icon { color: var(--color-fg-muted); width: 18px; height: 18px; flex-basis: 18px; } +.search-field:focus-within { border-color: var(--color-accent-action); background: var(--color-bg-surface); box-shadow: 0 0 0 3px var(--color-accent-action-soft); } +.search-input { width: 100%; min-width: 0; min-height: 48px; padding: 10px 0; outline: 0; border: 0; background: transparent; color: var(--color-fg-primary); font-size: 16px; } +.search-input::-webkit-search-cancel-button { display: none; } +.search-input::placeholder { color: var(--color-fg-muted); opacity: 1; } +.search-clear, .icon-button { display: inline-flex; align-items: center; justify-content: center; min-width: 44px; min-height: 44px; padding: 10px; background: transparent; border: 0; border-radius: 10px; } +.search-clear:hover, .icon-button:hover { background: var(--color-bg-hover); } +.btn-primary, .btn-secondary, .btn-close, .chip, .tab, .zone-chip { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 44px; padding: 10px 14px; border: 1px solid transparent; border-radius: var(--radius-control); font-size: 14px; line-height: 22px; } +.btn-primary { flex-shrink: 0; min-width: 68px; color: white; background: var(--color-accent-action); font-weight: 600; } +.btn-primary:hover:not(:disabled) { background: var(--color-accent-action-hover); } +.btn-primary:active:not(:disabled) { background: var(--color-accent-action-pressed); } +.btn-secondary { background: var(--color-bg-surface); border-color: var(--color-stroke-subtle); box-shadow: var(--shadow-surface); } +.btn-secondary:hover:not(:disabled), .btn-close:hover { background: var(--color-bg-hover); } +.quick-row { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; margin-top: 12px; } +.quick-label { color: var(--color-fg-muted); font-size: 12px; margin-right: 4px; } +.chip { color: var(--color-fg-secondary); background: var(--color-bg-raised); font-size: 13px; padding-inline: 10px; } +.chip:hover { background: var(--color-bg-hover); } +.discovery-home[data-has-results="true"] .search-column { position: sticky; top: var(--context-header); z-index: 20; padding-block: 8px; background: var(--color-bg-canvas); } +.discovery-home[data-has-results="true"] .search-panel { padding: 0; background: transparent; } +.discovery-home[data-has-results="true"] .search-field { background: var(--color-bg-surface); } +.search-results { margin-top: 20px; } +.search-results:not(:has(.results-heading, .candidate-row, .loading-box, .empty-box, .alert-error)) { display: none; } +.results-heading { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; } +.results-title { margin: 0; font-size: 16px; line-height: 24px; } +.results-count { color: var(--color-fg-muted); font-size: 13px; } +.applied-query { margin: 0 0 12px; padding: 10px 12px; border-left: 2px solid var(--color-accent-action); color: var(--color-fg-secondary); font-size: 13px; } +.candidate-list { display: grid; gap: 8px; } +.candidate-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; width: 100%; min-width: 0; padding: 16px 18px; text-align: left; border: 1px solid transparent; border-radius: var(--radius-surface); color: var(--color-fg-primary); background: var(--color-bg-surface); box-shadow: var(--shadow-surface); } +.candidate-row:hover:not(:disabled) { border-color: var(--color-stroke-strong); } +.candidate-row:active:not(:disabled) { background: var(--color-bg-hover); } +.candidate-row:disabled { opacity: .75; } +.candidate-row[aria-busy="true"] { border-color: var(--color-accent-action); background: var(--color-accent-action-soft); } +.candidate-copy { display: flex; flex: 1; flex-direction: column; min-width: 0; gap: 3px; } +.candidate-name { display: block; margin: 0; font-size: 16px; font-weight: 600; line-height: 24px; letter-spacing: -.3px; } +.candidate-category { font-size: 12px; color: var(--color-fg-muted); } +.candidate-addr { color: var(--color-fg-secondary); font-size: 13px; line-height: 21px; } +.candidate-arrow { color: var(--color-fg-muted); font-size: 24px; font-weight: 400; } +.candidate-state { display: flex; align-items: center; gap: 8px; color: var(--color-fg-muted); font-size: 12px; } +.candidate-state:empty { display: none; } +.candidate-status { width: fit-content; margin-top: 5px; padding: 2px 7px; background: var(--color-accent-action-soft); color: var(--color-accent-action); border-radius: 6px; font-size: 12px; } +.discovery-help { margin-top: 28px; border-top: 1px solid var(--color-stroke-subtle); color: var(--color-fg-muted); font-size: 13px; } +summary { min-height: 44px; padding-block: 10px; } +.discovery-help summary { width: fit-content; } +.discovery-help ol { margin: 0; padding-left: 22px; line-height: 1.9; } +.discovery-help p { margin-top: 12px; } +.recent-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 20px; } +.recent-heading .page-heading { margin: 0; } +.recent-title-count { color: var(--color-fg-muted); font-size: 18px; font-variant-numeric: tabular-nums; } +.recent-heading p { font-size: 13px; } +.recent-refresh { flex-shrink: 0; font-size: 13px; padding-inline: 10px; } +.recent-grid { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 12px; } +.recent-meta { display: flex; flex-wrap: wrap; gap: 8px; color: var(--color-fg-secondary); font-size: 13px; margin-top: 5px; } +.recent-date { color: var(--color-fg-muted); font-size: 12px; } +.page-footnote { color: var(--color-fg-muted); font-size: 12px; margin-top: 20px; } +.place-header { position: sticky; top: 0; z-index: 35; display: flex; align-items: center; gap: 8px; min-height: var(--context-header); margin: 0 calc(-1 * var(--page-gutter)) 12px; padding: calc(8px + env(safe-area-inset-top, 0px)) var(--page-gutter) 8px; background: var(--color-bg-surface); border-bottom: 1px solid var(--color-stroke-subtle); } +.place-title-row { min-width: 0; flex: 1; } +.place-title-row h1 { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; margin: 0; font-size: 18px; line-height: 24px; letter-spacing: -.5px; } +.place-menu { position: relative; flex: 0 0 auto; } +.place-menu > summary { list-style: none; } +.place-menu > summary::-webkit-details-marker { display: none; } +.place-menu-content { position: absolute; top: calc(100% + 8px); right: 0; z-index: 40; width: min(320px, calc(100vw - 32px)); max-height: calc(100dvh - var(--context-header) - 16px); overflow-y: auto; overscroll-behavior-y: contain; padding: 16px; border: 1px solid var(--color-stroke-subtle); background: var(--color-bg-surface); border-radius: 16px; box-shadow: 0 8px 32px oklch(.23 .012 260 / .12); } +.menu-category, .place-addr { margin: 0 0 8px; font-size: 13px; color: var(--color-fg-muted); } +.menu-action { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 44px; width: 100%; padding: 10px 8px; text-align: left; border: 0; border-radius: 8px; background: transparent; font-size: 14px; } +.menu-action:hover { background: var(--color-bg-raised); } +.copy-status { color: var(--color-accent-action); font-size: 12px; margin: 4px 0; } +.copy-status:empty { display: none; } +.workspace-switcher { display: none; } +.workspace-warning { display: flex; align-items: center; gap: 6px; margin: 0 0 12px; color: var(--color-fg-muted); font-size: 13px; line-height: 20px; } +.workspace-warning .icon { width: 16px; height: 16px; flex-basis: 16px; } +.workspace-grid { display: grid; grid-template-columns: minmax(0,1.45fr) minmax(280px,1fr); gap: 20px; align-items: start; } +.viewport-col, .summary-col { min-width: 0; display: flex; flex-direction: column; gap: 16px; } +.summary-col { position: sticky; top: calc(var(--context-header) + 12px); max-height: calc(100dvh - var(--context-header) - 24px); overflow-y: auto; overscroll-behavior-y: contain; scrollbar-width: thin; padding-bottom: 2px; } +.viewport-toolbar { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px; padding: 4px; border-radius: 14px; background: var(--color-bg-surface); } +.floor-tabs { display: flex; flex-wrap: wrap; gap: 2px; min-width: 0; } +.tab { min-width: 44px; border: 0; border-radius: 10px; padding: 10px; font-size: 13px; white-space: nowrap; background: transparent; color: var(--color-fg-muted); } +.tab:hover { background: var(--color-bg-hover); } +.floor-tabs .tab[aria-pressed="true"] { background: var(--color-bg-raised); color: var(--color-fg-primary); font-weight: 600; } +.view-modes { display: flex; flex-shrink: 0; padding: 2px; gap: 2px; border-radius: 10px; background: var(--color-bg-raised); } +.view-modes .tab { min-height: 44px; min-width: 44px; padding: 8px 10px; } +.view-modes .tab[aria-pressed="true"] { background: var(--color-bg-surface); color: var(--color-fg-primary); box-shadow: var(--shadow-control); font-weight: 600; } +.floor-select-label { flex: 1; min-width: 100px; max-width: 220px; } +.floor-select { width: 100%; min-height: 44px; padding: 8px 10px; border: 1px solid var(--color-stroke-subtle); border-radius: 10px; background: var(--color-bg-surface); color: var(--color-fg-primary); font-size: 16px; } +.scene-dialog[open] { display: block; position: static; width: 100%; max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; overflow: visible; } +.canvas-holder { position: relative; height: clamp(360px,60svh,620px); overflow: hidden; border: 1px solid var(--color-stroke-subtle); border-radius: var(--radius-surface); background: oklch(.965 .004 260); } +.scene-canvas { display: block; width: 100%; height: 100%; } +.scene-tools { position: absolute; top: 12px; right: 12px; display: flex; align-items: center; gap: 4px; padding: 3px; border-radius: 12px; background: var(--color-bg-surface); border: 1px solid var(--color-stroke-subtle); box-shadow: var(--shadow-control); } +.scene-tool { display: inline-grid; place-items: center; min-width: 44px; min-height: 44px; padding: 6px; border: 0; border-radius: 8px; color: var(--color-fg-secondary); background: transparent; font-size: 20px; } +.scene-tool:hover { background: var(--color-bg-raised); } +.scene-expand { font-size: 12px; padding-inline: 10px; } +.scene-interaction-toggle { display: none; position: absolute; bottom: 12px; right: 12px; min-height: 44px; padding: 10px 14px; border: 1px solid var(--color-stroke-strong); border-radius: 12px; background: var(--color-bg-surface); font-size: 13px; font-weight: 600; box-shadow: var(--shadow-control); } +.scene-interaction-toggle[aria-pressed="true"] { background: var(--color-accent-action); border-color: var(--color-accent-action); color: white; } +.canvas-hint { position: absolute; left: 12px; bottom: 12px; max-width: calc(100% - 24px); padding: 8px 10px; border-radius: 8px; background: oklch(1 0 0 / .94); color: var(--color-fg-muted); font-size: 12px; line-height: 18px; pointer-events: none; } +.hint-touch { display: none; } +.scene-failure { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 24px; text-align: center; background: var(--color-bg-raised); } +.scene-failure p { margin: 0; color: var(--color-fg-muted); } +.scene-failure > div { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; } +.selected-zone-mobile { display: none; } +.floor-notes { display: grid; gap: 12px; } +.floor-note-card, .summary-card { padding: 20px; border-radius: var(--radius-surface); background: var(--color-bg-surface); } +.floor-note-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 12px; } +.floor-note-head h3 { font-size: 15px; margin: 0; } +.floor-note-head > span { font-size: 12px; color: var(--color-fg-muted); } +.zone-chips, .tag-row { display: flex; flex-wrap: wrap; gap: 6px; } +.zone-chip { justify-content: flex-start; text-align: left; padding: 10px 12px; color: var(--color-fg-secondary); font-size: 13px; background: var(--color-bg-raised); } +.zone-chip .icon { width: 16px; height: 16px; flex-basis: 16px; } +.zone-chip:hover { background: var(--color-bg-hover); } +.zone-chip[aria-pressed="true"] { color: var(--color-accent-action); border-color: var(--color-accent-action); background: var(--color-accent-action-soft); } +.zone-empty { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 8px 10px; color: var(--color-fg-muted); border: 1px dashed var(--color-stroke-subtle); border-radius: 10px; font-size: 12px; } +.zone-empty > span { font-size: 12px; white-space: nowrap; } +.summary-card > h3, .gallery-heading h3 { margin: 0 0 16px; font-size: 16px; } +.metric-grid { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 8px; } +.metric { min-width: 0; padding: 12px; border-radius: 12px; background: var(--color-bg-raised); } +.metric-label { display: block; color: var(--color-fg-muted); font-size: 12px; } +.metric-val { display: block; margin-top: 4px; font-size: 18px; line-height: 28px; font-variant-numeric: tabular-nums; } +.summary-floor-count { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 4px 12px; margin-top: 14px; font-size: 13px; } +.summary-floor-count > span { color: var(--color-fg-muted); } +.summary-section { margin-top: 18px; padding-top: 18px; border-top: 1px solid var(--color-stroke-subtle); } +.summary-section h4 { margin: 0 0 10px; font-size: 13px; } +.evidence-warning, .summary-details, .bullet-list, .photo-caption { font-size: 13px; line-height: 1.75; } +.evidence-warning { margin: 0; color: var(--color-fg-secondary); } +.summary-details { margin-top: 8px; color: var(--color-fg-muted); } +.summary-details summary { color: var(--color-fg-secondary); } +.summary-details p { margin: 8px 0; } +.confidence-explanation, .accessibility-note { font-size: 12px; color: var(--color-fg-muted); line-height: 1.7; } +.badge { display: inline-flex; align-items: center; min-height: 26px; padding: 4px 8px; border-radius: 6px; color: var(--color-fg-secondary); background: var(--color-bg-raised); font-size: 12px; line-height: 18px; } +.fact-list { margin: 0; font-size: 13px; } +.fact-list > div { display: flex; justify-content: space-between; gap: 12px; padding: 5px 0; } +.fact-list dt { color: var(--color-fg-muted); } +.fact-list dd { margin: 0; text-align: right; } +.bullet-list { margin: 0; padding-left: 18px; color: var(--color-fg-secondary); } +.bullet-list li + li { margin-top: 6px; } +.pin-drawer-head, .gallery-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; } +.pin-drawer-head h3 { margin: 4px 0 0; font-size: 15px; } +.btn-close { flex-shrink: 0; min-width: 44px; padding: 10px; background: var(--color-bg-raised); color: var(--color-fg-secondary); } +.photo-count, .gallery-heading > span { margin: 4px 0 12px; color: var(--color-fg-muted); font-size: 12px; } +.selected-photo-preview { display: block; width: 100%; padding: 0; border: 0; border-radius: 12px; overflow: hidden; background: var(--color-bg-raised); } +.image-shell { position: relative; display: flex; justify-content: center; align-items: center; min-width: 0; width: 100%; background: var(--color-bg-raised); } +.image-shell img { display: block; width: 100%; object-fit: cover; } +.selected-photo-preview img { height: 180px; } +.image-fallback { display: flex; align-items: center; justify-content: center; gap: 8px; min-height: 120px; padding: 16px; color: var(--color-fg-muted); font-size: 13px; } +.photo-caption p { margin: 10px 0 6px; } +.photo-source { display: inline-flex; align-items: center; min-height: 44px; color: var(--color-accent-action); font-size: 13px; text-decoration: underline; text-underline-offset: 3px; } +.photo-navigation { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-top: 12px; font-size: 13px; font-variant-numeric: tabular-nums; } +.photo-navigation .btn-secondary { min-width: 64px; } +.gallery-grid { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 8px; } +.gallery-item { position: relative; display: block; padding: 0; min-height: 80px; overflow: hidden; border: 0; border-radius: 10px; background: var(--color-bg-raised); } +.gallery-item img { height: 86px; } +.gallery-source { display: block; padding: 4px; font-size: 12px; line-height: 18px; color: var(--color-fg-secondary); } +.gallery-all { width: 100%; margin-top: 12px; } +dialog::backdrop { background: oklch(.18 .01 260 / .48); } +.photo-dialog { position: fixed; inset: 0; width: min(720px,calc(100vw - 40px)); max-width: none; max-height: calc(100dvh - 48px); margin: auto; padding: 0; color: var(--color-fg-primary); background: var(--color-bg-surface); border: 1px solid var(--color-stroke-subtle); border-radius: var(--radius-overlay); box-shadow: 0 20px 80px oklch(.23 .012 260 / .15); overflow-y: auto; overscroll-behavior: contain; } +.photo-dialog[open] { display: flex; flex-direction: column; } +.dialog-header, .scene-dialog-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 20px; background: var(--color-bg-surface); border-bottom: 1px solid var(--color-stroke-subtle); } +.dialog-header { position: sticky; top: 0; z-index: 2; flex-shrink: 0; } +.dialog-header h2 { margin: 0; font-size: 17px; line-height: 24px; } +.photo-dialog-body { padding: 16px 20px max(20px,env(safe-area-inset-bottom,0px)); min-height: 0; } +.photo-viewer { overflow: hidden; border-radius: 12px; } +.photo-viewer img { width: 100%; height: min(48dvh,480px); object-fit: contain; } +.photo-thumbnails { display: flex; gap: 8px; margin-top: 14px; overflow-x: auto; padding: 4px; scrollbar-width: thin; } +.photo-thumbnails button { flex: 0 0 64px; padding: 0; border: 2px solid transparent; border-radius: 8px; overflow: hidden; background: var(--color-bg-raised); } +.photo-thumbnails button[aria-pressed="true"] { border-color: var(--color-accent-action); } +.photo-thumbnails img { height: 56px; } +.scene-dialog:modal { display: flex; flex-direction: column; position: fixed; inset: 0; z-index: 50; width: 100%; height: 100dvh; max-width: none; max-height: 100dvh; margin: 0; padding: 0; overflow: hidden; background: var(--color-bg-canvas); } +.scene-dialog:modal .canvas-holder { flex: 1; min-height: 0; height: auto; margin: 12px max(12px,env(safe-area-inset-right,0px)) max(12px,env(safe-area-inset-bottom,0px)) max(12px,env(safe-area-inset-left,0px)); } +.scene-dialog:modal .scene-dialog-header { padding-top: calc(8px + env(safe-area-inset-top,0px)); } +.scene-dialog:modal .scene-tools { right: 16px; } +.progress-panel { padding: 16px 20px; margin-bottom: 16px; border-radius: var(--radius-surface); background: var(--color-bg-surface); } +.progress-head { display: flex; align-items: center; gap: 10px; font-size: 14px; } +.spinner { display: inline-block; width: 16px; height: 16px; flex: 0 0 16px; border: 2px solid var(--color-accent-action-soft); border-top-color: var(--color-accent-action); border-radius: 50%; animation: spin .8s linear infinite; } +@keyframes spin { to { transform: rotate(360deg); } } +.progress-steps { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); list-style: none; gap: 8px; padding: 0; margin: 16px 0 0; font-size: 12px; color: var(--color-fg-muted); } +.progress-steps li { padding-top: 8px; border-top: 3px solid var(--color-stroke-subtle); } +.progress-steps li[aria-current="step"] { color: var(--color-accent-action); border-color: var(--color-accent-action); font-weight: 600; } +.progress-steps li.complete { border-color: var(--color-semantic-success); } +.progress-details { font-size: 13px; color: var(--color-fg-muted); margin-top: 8px; } +.progress-details ul { margin-top: 0; padding-left: 20px; max-height: 180px; overflow: auto; } +.analysis-placeholder { padding: 24px; text-align: center; color: var(--color-fg-muted); } +.analysis-placeholder a { display: inline-flex; align-items: center; min-height: 44px; color: var(--color-accent-action); } +.loading-box, .empty-box, .recent-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; min-height: 144px; padding: 28px 20px; text-align: center; border-radius: var(--radius-surface); background: var(--color-bg-surface); color: var(--color-fg-muted); } +.loading-box { flex-direction: row; gap: 12px; } +.empty-box p, .recent-empty p { margin: 0; } +.recent-empty h1, .recent-empty h2 { margin: 0; font-size: 18px; color: var(--color-fg-primary); } +.recent-empty .btn-primary { margin-top: 12px; } +.alert-error { padding: 16px; margin: 0 0 16px; border: 1px solid oklch(.48 .17 24 / .2); border-radius: 14px; background: var(--color-accent-danger-soft); color: var(--color-accent-danger); font-size: 14px; } +.alert-error p { margin: 0 0 10px; } +.alert-error .btn-secondary { margin-right: 8px; } + +@media (pointer: coarse) { + .scene-interaction-toggle { display: inline-flex; } + .hint-pointer { display: none; } + .hint-touch { display: inline; } + .canvas-hint { right: 124px; max-width: none; padding: 6px 8px; } +} +@media (min-width: 640px) and (max-width: 1099px) and (min-height: 500px) { + .app-shell { --page-gutter: 20px; } + .workspace-grid { grid-template-columns: minmax(0,1.35fr) minmax(260px,1fr); gap: 16px; } + .summary-card, .floor-note-card { padding: 16px; } + .viewport-toolbar { gap: 4px; } + .view-modes { margin-left: auto; } + .canvas-holder { height: clamp(380px,62svh,600px); } + .scene-tools { gap: 0; top: 8px; right: 8px; } +} +@media (max-width: 639px), (max-height: 499px) { + .app-shell { --page-gutter: 16px; } + .main-body { padding-top: 20px; } + .topbar-nav a { padding-inline: 10px; font-size: 13px; } + .brand-title { font-size: 16px; } + .brand { gap: 6px; } + .brand-mark .icon { width: 22px; height: 22px; } + .page-heading h1 { font-size: 22px; } + .search-panel { padding: 12px; } + .quick-label { width: 100%; } + .quick-row { gap: 6px; } + .chip { font-size: 12px; padding-inline: 9px; } + .candidate-row { padding: 14px 16px; } + .candidate-name { font-size: 16px; } + .recent-grid { grid-template-columns: minmax(0,1fr); gap: 8px; } + .recent-refresh span { display: none; } + .recent-refresh { min-width: 44px; } + .place-header { margin-bottom: 0; } + .workspace-switcher { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 4px; position: sticky; top: var(--context-header); z-index: 25; padding: 4px; margin: 8px 0 10px; border-radius: 14px; background: var(--color-bg-surface); box-shadow: 0 0 0 8px var(--color-bg-canvas); } + .workspace-switcher button { min-height: 44px; padding: 8px; border: 0; border-radius: 10px; background: transparent; color: var(--color-fg-muted); font-size: 14px; } + .workspace-switcher button[aria-pressed="true"] { background: var(--color-bg-raised); color: var(--color-fg-primary); font-weight: 600; } + .workspace-warning { font-size: 12px; margin-bottom: 10px; } + .workspace-grid { grid-template-columns: minmax(0,1fr); gap: 0; } + .workspace-grid[data-mobile-panel="layout"] #info-panel, .workspace-grid[data-mobile-panel="info"] #layout-panel { display: none; } + .viewport-col { gap: 12px; } + .summary-col { position: static; max-height: none; overflow: visible; } + .selected-zone-panel { display: none; } + .viewport-toolbar { gap: 4px; } + .tab { padding-inline: 9px; font-size: 12px; } + .view-modes .tab { min-height: 44px; padding-inline: 9px; } + .view-modes { margin-left: auto; } + .canvas-holder { height: clamp(360px,56svh,520px); } + .scene-tools { top: 8px; right: 8px; gap: 0; } + .floor-note-card, .summary-card { padding: 16px; } + .selected-zone-mobile { display: flex; align-items: center; gap: 8px; min-height: 52px; padding: 12px; text-align: left; color: var(--color-accent-action); background: var(--color-accent-action-soft); border: 1px solid var(--color-stroke-subtle); border-radius: 12px; font-size: 13px; } + .selected-zone-mobile > span:last-child { margin-left: auto; white-space: nowrap; } + .photo-dialog { inset: auto 0 0; width: 100%; max-height: calc(100dvh - max(20px,env(safe-area-inset-top,0px))); margin: 0; border-radius: 24px 24px 0 0; } + .dialog-header { padding: 12px 16px; } + .dialog-header h2 { font-size: 16px; } + .photo-dialog-body { padding: 12px 16px max(16px,env(safe-area-inset-bottom,0px)); } + .photo-viewer img { height: min(42dvh,360px); } +} +@media (max-width: 359px) { + .app-shell { --page-gutter: 12px; } + .brand-title { font-size: 15px; } + .brand-mark { display: none; } + .topbar { gap: 6px; } + .topbar-nav a { padding-inline: 8px; } + .search-bar { gap: 6px; } + .search-field { padding-left: 8px; gap: 4px; } + .search-field > .icon { display: none; } + .search-clear { min-width: 44px; padding-inline: 8px; } + .btn-primary { min-width: 56px; padding-inline: 10px; } + .quick-row { gap: 4px; } + .chip { padding-inline: 8px; } + .viewport-toolbar { align-items: stretch; } + .view-modes { flex: 1 1 100%; } + .view-modes .tab { flex: 1; } + .scene-expand { padding-inline: 8px; } +} +@media (max-height: 499px) { + .canvas-holder { height: 320px; } + .photo-dialog { max-height: 100dvh; } + .photo-viewer img { height: 50dvh; } +} +/* Two physical segments keep controls clear of the hinge. */ +@media (horizontal-viewport-segments: 2) and (vertical-viewport-segments: 1) { + .main-body:has(.place-page) { max-width: none; padding-inline: 0; } + .place-header { margin-inline: 0; display: grid; grid-template-columns: 44px minmax(0,1fr) 44px; width: env(viewport-segment-width 0 0); padding-inline: 12px; } + .workspace-switcher { display: none; } + .workspace-warning { margin-inline: 16px; width: calc(env(viewport-segment-width 0 0) - 32px); } + .workspace-grid { grid-template-columns: env(viewport-segment-width 0 0) calc(env(viewport-segment-left 1 0) - env(viewport-segment-right 0 0)) env(viewport-segment-width 1 0); gap: 0; } + .workspace-grid[data-mobile-panel] #layout-panel { display: flex; grid-column: 1; padding-inline: 16px; } + .workspace-grid[data-mobile-panel] #info-panel { display: flex; grid-column: 3; padding-inline: 16px; } + .topbar, .home-wrap, .recent-page { width: env(viewport-segment-width 0 0); margin-left: 0; } + .main-body:not(:has(.place-page)) { max-width: none; padding-inline: 0; } + .home-wrap, .recent-page { padding-inline: 16px; } + .recent-grid { grid-template-columns: 1fr; } + .photo-dialog { width: calc(env(viewport-segment-width 0 0) - 24px); left: 12px; right: auto; } +} +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; } +} +@media (forced-colors: active) { + .tab[aria-pressed="true"], .zone-chip[aria-pressed="true"], .workspace-switcher button[aria-pressed="true"] { outline: 2px solid Highlight; } + .btn-primary, .btn-secondary, .candidate-row, .chip, .zone-chip, .search-field, .scene-tool, .scene-interaction-toggle { border: 1px solid ButtonText; } + .summary-card, .floor-note-card { border: 1px solid CanvasText; } +}