@needle-tools/engine 4.7.2 → 4.7.3-next.1603bb0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/{needle-engine.bundle-CnzaSk8v.min.js → needle-engine.bundle-6bPQlS1q.min.js} +23 -23
  2. package/dist/{needle-engine.bundle-DALjvqho.js → needle-engine.bundle-CL5SiInU.js} +89 -76
  3. package/dist/{needle-engine.bundle-RNpCdQTu.umd.cjs → needle-engine.bundle-Dm9L7JpU.umd.cjs} +26 -26
  4. package/dist/needle-engine.d.ts +15 -15
  5. package/dist/needle-engine.js +2 -2
  6. package/dist/needle-engine.min.js +1 -1
  7. package/dist/needle-engine.umd.cjs +1 -1
  8. package/dist/{postprocessing-TkXiVrjY.min.js → postprocessing-BzY0H7ry.min.js} +8 -8
  9. package/dist/{postprocessing-CNCT892s.umd.cjs → postprocessing-Dw2OCMp4.umd.cjs} +8 -8
  10. package/dist/{postprocessing-qvgDnYKK.js → postprocessing-vKBVFpSz.js} +9 -9
  11. package/lib/engine-components/OrbitControls.d.ts +12 -0
  12. package/lib/engine-components/OrbitControls.js +14 -0
  13. package/lib/engine-components/OrbitControls.js.map +1 -1
  14. package/lib/engine-components/Skybox.d.ts +1 -0
  15. package/lib/engine-components/Skybox.js +13 -17
  16. package/lib/engine-components/Skybox.js.map +1 -1
  17. package/lib/engine-components/postprocessing/PostProcessingHandler.js +1 -1
  18. package/lib/engine-components/postprocessing/PostProcessingHandler.js.map +1 -1
  19. package/lib/engine-components/postprocessing/Volume.d.ts +3 -1
  20. package/lib/engine-components/postprocessing/Volume.js +2 -0
  21. package/lib/engine-components/postprocessing/Volume.js.map +1 -1
  22. package/package.json +2 -2
  23. package/plugins/vite/logger.client.js +68 -30
  24. package/plugins/vite/logger.js +5 -5
  25. package/src/engine-components/OrbitControls.ts +16 -0
  26. package/src/engine-components/Skybox.ts +14 -20
  27. package/src/engine-components/postprocessing/PostProcessingHandler.ts +1 -1
  28. package/src/engine-components/postprocessing/Volume.ts +2 -1
@@ -1,4 +1,4 @@
1
- "use strict";var Hx=Object.defineProperty;var i_=o=>{throw TypeError(o)};var qx=(o,t,e)=>t in o?Hx(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>qx(o,typeof t!="symbol"?t+"":t,e),zf=(o,t,e)=>t.has(o)||i_("Cannot "+e);var ce=(o,t,e)=>(zf(o,t,"read from private field"),e?e.call(o):t.get(o)),on=(o,t,e)=>t.has(o)?i_("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(o):t.set(o,e),rn=(o,t,e,i)=>(zf(o,t,"write to private field"),i?i.call(o,e):t.set(o,e),e),Ol=(o,t,e)=>(zf(o,t,"access private method"),e);const d=require("./three-B_hneGZr.umd.cjs"),le=require("./gltf-progressive-C6QbvrB4.umd.cjs"),H=require("./three-examples-DUcCNw9s.umd.cjs"),ae=require("./vendor-Cavtu3CP.umd.cjs"),ne=require("./three-mesh-ui-CQiIQIlA.umd.cjs"),Xx=require("./postprocessing-CNCT892s.umd.cjs");var Nf=typeof document<"u"?document.currentScript:null;const $f=new Map;function Kt(o=(t=>(t=globalThis.location)==null?void 0:t.hostname)()){if($f.has(o))return $f.get(o);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(o);return $f.set(o,e),e===!0}function s0(){return window.location.hostname.includes("glitch.me")}const Qx='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',Yx=btoa(Qx),Kx="data:image/svg+xml;base64,"+Yx,o0=Kx,Zx=`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" version="1.1" viewBox="0 0 1014 282" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m665.95 132.73v44.88l-10.56-8.4c-0.8-0.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18 0.4-6.06 1.2s-3.54 1.8-4.98 3-2.56 2.5-3.36 3.9-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c0.32 0.24 0.56 0.44 0.72 0.6s0.36 0.32 0.6 0.48c0.96-1.2 2.14-2.28 3.54-3.24s2.92-1.76 4.56-2.4 3.34-1.14 5.1-1.5 3.44-0.54 5.04-0.54c1.44 0 2.92 0.04 4.44 0.12s2.84 0.28 3.96 0.6c4.56 1.12 7.8 3.12 9.72 6s2.88 6.56 2.88 11.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m732.38 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m795.93 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m858.57 97.21c0.64 0.48 0.96 1.16 0.96 2.04v74.88c-0.08 1.04-0.12 2.12-0.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18s-2.06-1.66-2.46-1.98c-1.76 2.48-4.26 4.44-7.5 5.88s-7.02 2.16-11.34 2.16c-3.84 0-7.4-0.7-10.68-2.1s-6.14-3.44-8.58-6.12-4.34-5.94-5.7-9.78-2.04-8.16-2.04-12.96c0-4.32 0.78-8.34 2.34-12.06s3.6-6.92 6.12-9.6 5.38-4.78 8.58-6.3 6.48-2.28 9.84-2.28c2.56 0 4.82 0.22 6.78 0.66s3.68 1.06 5.16 1.86 2.78 1.74 3.9 2.82 2.16 2.22 3.12 3.42v-35.04l10.68 8.64zm-27.96 67.92c3.6 0 6.52-0.68 8.76-2.04s3.98-3.06 5.22-5.1 2.1-4.22 2.58-6.54 0.72-4.44 0.72-6.36v-1.2c0-1.12-0.22-2.7-0.66-4.74s-1.28-4.06-2.52-6.06-3-3.7-5.28-5.1-5.22-2.02-8.82-1.86c-3.44 0-6.26 0.74-8.46 2.22s-3.96 3.26-5.28 5.34-2.24 4.2-2.76 6.36-0.78 3.92-0.78 5.28c0 1.84 0.24 3.92 0.72 6.24s1.36 4.48 2.64 6.48 3.04 3.68 5.28 5.04 5.12 2.04 8.64 2.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m882.81 97.09c0.64 0.48 0.96 1.12 0.96 1.92l-0.12 41.04v37.08l-10.56-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-77.88l10.8 8.64z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m950.36 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.8559 0 0 .7642 45.348 36.475)"> <g transform="translate(2.7114)"> <path d="m3.935 173.02c-0.331 0-0.497-0.402-0.497-1.207v-51.002c0-0.738 0.138-1.107 0.414-1.107h1.781c0.277 0 0.415 0.335 0.415 1.006v5.935c0 0.336 0.027 0.553 0.083 0.654 0.055 0.101 0.151-0.017 0.289-0.352 0.912-1.744 1.754-3.236 2.527-4.477 0.773-1.24 1.554-2.179 2.341-2.816s1.65-0.956 2.588-0.956c1.685 0 3.011 0.922 3.977 2.766 0.967 1.845 1.602 3.84 1.905 5.986 0.056 0.268 0.139 0.369 0.249 0.302s0.221-0.235 0.331-0.503c0.939-1.811 1.802-3.353 2.589-4.628 0.787-1.274 1.581-2.246 2.382-2.917s1.671-1.006 2.61-1.006c2.016 0 3.569 1.392 4.66 4.175 1.09 2.783 1.636 6.421 1.636 10.915v37.925c0 0.871-0.18 1.307-0.539 1.307h-1.739c-0.138 0-0.249-0.1-0.332-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.338-6.321-1.015-8.3-0.676-1.978-1.76-2.967-3.251-2.967-0.884 0-1.726 0.386-2.527 1.157s-1.519 1.727-2.154 2.867-1.201 2.213-1.699 3.219c-0.248 0.469-0.421 0.905-0.517 1.308-0.097 0.402-0.145 0.972-0.145 1.71v37.221c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.166 0-0.29-0.1-0.373-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.332-6.321-0.994-8.3-0.663-1.978-1.754-2.967-3.273-2.967-1.242 0-2.375 0.704-3.396 2.112-1.022 1.409-2.223 3.555-3.604 6.439v39.031c0 0.805-0.18 1.207-0.539 1.207h-1.698z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m53.642 166.28c-1.077 2.549-2.237 4.477-3.479 5.785-1.243 1.307-2.61 1.961-4.101 1.961-2.154 0-3.853-1.324-5.095-3.973-1.243-2.649-1.864-6.187-1.864-10.613 0-3.488 0.4-6.489 1.201-9.004s1.988-4.51 3.562-5.985c1.574-1.476 3.521-2.414 5.841-2.817l3.686-0.704c0.221-0.067 0.394-0.218 0.518-0.453 0.124-0.234 0.187-0.587 0.187-1.056v-2.917c0-3.89-0.504-6.975-1.512-9.255s-2.354-3.42-4.039-3.42c-1.298 0-2.472 0.72-3.521 2.162s-2.002 3.572-2.858 6.388c-0.083 0.268-0.159 0.453-0.228 0.554-0.069 0.1-0.172 0.083-0.311-0.051l-1.698-1.71c-0.083-0.134-0.138-0.285-0.166-0.453-0.027-0.167 0.014-0.452 0.125-0.855 0.856-3.353 2.009-6.052 3.459-8.098 1.449-2.045 3.224-3.068 5.322-3.068 1.74 0 3.211 0.687 4.412 2.062s2.112 3.37 2.734 5.986c0.621 2.615 0.932 5.7 0.932 9.255v35.712c0 0.536-0.035 0.888-0.104 1.056s-0.2 0.251-0.393 0.251h-1.533c-0.166 0-0.29-0.117-0.373-0.352-0.083-0.234-0.124-0.553-0.124-0.955l-0.083-5.231c-0.055-0.939-0.221-1.006-0.497-0.202zm0.456-19.314c0-1.14-0.194-1.643-0.58-1.509l-3.107 0.603c-1.436 0.202-2.686 0.638-3.749 1.308-1.063 0.671-1.953 1.543-2.671 2.616s-1.257 2.33-1.616 3.772-0.538 3.102-0.538 4.98c0 3.152 0.455 5.616 1.367 7.393 0.911 1.778 2.14 2.666 3.686 2.666 0.939 0 1.85-0.419 2.734-1.257s1.671-1.895 2.361-3.169c0.663-1.408 1.181-2.85 1.553-4.326 0.373-1.475 0.56-2.883 0.56-4.225v-8.852z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m79.034 173.02c-0.166 0-0.297-0.117-0.394-0.352-0.096-0.234-0.145-0.553-0.145-0.955v-4.628c0-0.536-0.041-0.838-0.124-0.905s-0.207 0.1-0.373 0.503c-0.276 0.67-0.69 1.593-1.242 2.766-0.553 1.174-1.271 2.23-2.154 3.169-0.884 0.939-1.961 1.408-3.231 1.408-1.74 0-3.314-0.989-4.722-2.967-1.409-1.979-2.534-4.963-3.376-8.953-0.843-3.991-1.264-8.937-1.264-14.838 0-5.701 0.415-10.68 1.243-14.939s1.988-7.595 3.479-10.009c1.492-2.415 3.204-3.622 5.137-3.622 1.436 0 2.616 0.57 3.541 1.71 0.926 1.14 1.719 2.381 2.382 3.722 0.249 0.47 0.414 0.637 0.497 0.503s0.125-0.536 0.125-1.207v-23.841c0-0.805 0.151-1.208 0.455-1.208h1.864c0.276 0 0.414 0.369 0.414 1.107v72.128c0 0.537-0.041 0.905-0.124 1.107-0.083 0.201-0.235 0.301-0.455 0.301h-1.533zm-0.621-42.049c-0.939-2.213-1.885-3.94-2.838-5.181s-2.009-1.861-3.169-1.861c-1.463 0-2.768 0.889-3.914 2.666s-2.044 4.376-2.693 7.796-0.973 7.578-0.973 12.474c0 5.097 0.338 9.272 1.015 12.524 0.676 3.253 1.567 5.651 2.672 7.193 1.104 1.543 2.305 2.314 3.603 2.314 1.188 0 2.258-0.704 3.211-2.113 0.952-1.408 1.705-3.118 2.257-5.13s0.829-3.957 0.829-5.835v-24.847z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m89.514 149.38c0 3.42 0.345 6.606 1.035 9.557 0.691 2.951 1.609 5.315 2.755 7.092s2.437 2.666 3.873 2.666c1.519 0 2.837-0.738 3.956-2.213 1.118-1.476 2.064-3.655 2.837-6.539 0.083-0.336 0.166-0.52 0.249-0.554 0.083-0.033 0.179 0.017 0.29 0.151l1.408 1.912c0.221 0.268 0.235 0.67 0.041 1.207-0.69 2.548-1.47 4.661-2.34 6.337-0.87 1.677-1.857 2.935-2.962 3.773-1.104 0.838-2.319 1.257-3.645 1.257-2.043 0-3.838-1.14-5.385-3.42-1.546-2.28-2.761-5.482-3.645-9.607-0.884-4.124-1.325-8.836-1.325-14.134 0-5.901 0.455-10.931 1.367-15.089 0.911-4.158 2.14-7.377 3.686-9.658 1.547-2.28 3.3-3.42 5.261-3.42 1.988 0 3.714 1.073 5.178 3.219 1.463 2.146 2.595 5.231 3.396 9.255s1.201 8.886 1.201 14.587c0 0.469-0.02 0.939-0.062 1.408-0.041 0.469-0.214 0.704-0.517 0.704h-16.362c-0.083 0-0.152 0.151-0.207 0.453-0.056 0.302-0.083 0.654-0.083 1.056zm13.752-6.237c0.304 0 0.497-0.1 0.58-0.302 0.083-0.201 0.124-0.57 0.124-1.106 0-3.219-0.283-6.187-0.849-8.903s-1.367-4.896-2.402-6.539c-1.036-1.643-2.272-2.464-3.708-2.464-1.629 0-2.996 0.955-4.101 2.867-1.104 1.911-1.94 4.342-2.506 7.293s-0.849 6.002-0.849 9.154h13.711z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m148.54 119.7c0.165 0 0.283 0.117 0.352 0.352s0.076 0.52 0.02 0.855l-6.254 50.902c-0.028 0.47-0.104 0.788-0.228 0.956s-0.297 0.251-0.518 0.251h-1.615c-0.442 0-0.718-0.402-0.829-1.207l-5.26-40.138c-0.111-0.604-0.201-0.905-0.27-0.905s-0.131 0.301-0.186 0.905l-5.012 40.138c-0.028 0.47-0.097 0.788-0.207 0.956-0.111 0.168-0.277 0.251-0.497 0.251h-1.74c-0.442 0-0.718-0.402-0.829-1.207l-6.503-50.801c-0.055-0.403-0.048-0.721 0.021-0.956s0.2-0.352 0.393-0.352h1.823c0.166 0 0.297 0.067 0.393 0.201 0.097 0.134 0.159 0.403 0.187 0.805l5.302 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.219-41.949c0.055-0.268 0.124-0.47 0.207-0.604s0.193-0.201 0.331-0.201h1.533c0.138 0 0.262 0.067 0.373 0.201 0.11 0.134 0.179 0.403 0.207 0.805l5.468 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.053-41.849c0.055-0.335 0.138-0.57 0.249-0.704 0.11-0.134 0.234-0.201 0.373-0.201h1.284z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m156.49 171.51c0 0.604-0.042 1.006-0.125 1.208-0.082 0.201-0.262 0.301-0.538 0.301h-1.533c-0.221 0-0.366-0.083-0.435-0.251s-0.103-0.486-0.103-0.956v-50.902c0-0.805 0.152-1.207 0.456-1.207h1.822c0.304 0 0.456 0.402 0.456 1.207v50.6zm0.165-63.979c0 1.207-0.207 1.811-0.621 1.811h-1.905c-0.221 0-0.366-0.135-0.435-0.403s-0.104-0.67-0.104-1.207v-7.847c0-1.006 0.18-1.509 0.539-1.509h1.988c0.359 0 0.538 0.47 0.538 1.409v7.746z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m168.3 124.83c-0.221 0-0.331 0.269-0.331 0.805v33.801c0 3.42 0.221 5.667 0.663 6.74 0.441 1.073 1.09 1.609 1.946 1.609h3.024c0.138 0 0.242 0.084 0.311 0.252 0.069 0.167 0.103 0.419 0.103 0.754v2.716c0 0.537-0.138 0.906-0.414 1.107-0.248 0.067-0.614 0.134-1.098 0.201-0.483 0.067-0.959 0.118-1.429 0.151-0.469 0.034-0.828 0.05-1.077 0.05-1.712 0-2.934-0.955-3.665-2.867-0.732-1.911-1.098-5.013-1.098-9.305v-35.108c0-0.604-0.124-0.906-0.373-0.906h-3.521c-0.248 0-0.373-0.268-0.373-0.804v-3.521c0-0.537 0.111-0.805 0.332-0.805h3.686c0.166 0 0.263-0.268 0.29-0.805l0.415-16.095c0-0.805 0.124-1.207 0.372-1.207h1.492c0.303 0 0.455 0.436 0.455 1.307v15.995c0 0.537 0.097 0.805 0.29 0.805h5.468c0.221 0 0.331 0.268 0.331 0.805v3.521c0 0.536-0.124 0.804-0.373 0.804h-5.426z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m179.4 173.02c-0.331 0-0.497-0.402-0.497-1.207v-72.329c0-0.738 0.138-1.107 0.414-1.107h1.782c0.276 0 0.414 0.336 0.414 1.006v27.162c0 0.335 0.034 0.536 0.103 0.603s0.159-0.033 0.27-0.302c0.994-1.81 1.898-3.319 2.713-4.526 0.814-1.208 1.629-2.113 2.444-2.717 0.814-0.603 1.691-0.905 2.63-0.905 2.182 0 3.839 1.375 4.971 4.125 1.132 2.749 1.698 6.404 1.698 10.965v37.925c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.165 0-0.29-0.1-0.373-0.301-0.082-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.366-6.321-1.097-8.3-0.732-1.978-1.899-2.967-3.501-2.967-0.883 0-1.705 0.318-2.464 0.956-0.76 0.637-1.526 1.576-2.299 2.816-0.773 1.241-1.643 2.834-2.61 4.779v39.031c0 0.805-0.179 1.207-0.538 1.207h-1.699z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> </g> <g transform="matrix(.80638 0 0 .80638 452.53 65.421)" fill-rule="nonzero"> <path d="m79.32 36.98v150.76l15.68-13.2 6.59-156.31-22.27 18.75z" fill="url(#f)"/> <path d="m79.32 36.98-22.27-18.75 6.59 156.31 15.68 13.2v-150.76z" fill="url(#e)"/> <path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z" fill="url(#d)"/> <path d="m25.19 104.83-25.19-14.59 16.97 53.86 16.85 9.77-8.63-49.04z" fill="url(#c)"/> <path d="M43.86,82.5L18.69,67.98L0,90.24L25.18,104.83L43.86,82.5Z" fill="#9c3"/> <path d="m134.82 78.69-9.97 56.5 15.58-9.04 19.57-62.05-25.18 14.59z" fill="url(#b)"/> <path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z" fill="url(#a)"/> <path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33 25.19-14.59z" fill="#ffe113"/> <path d="M101.59,18.23L79.32,0L57.05,18.23L79.32,36.98L101.59,18.23Z" fill="#f3e600"/> </g> <defs> <linearGradient id="f" x2="1" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)" gradientUnits="userSpaceOnUse"><stop stop-color="#62d399" offset="0"/><stop stop-color="#acd842" offset=".51"/><stop stop-color="#d7db0a" offset=".9"/><stop stop-color="#d7db0a" offset="1"/></linearGradient> <linearGradient id="e" x2="1" gradientTransform="matrix(-1.6,-162.13,162.13,-1.6,69.68,178.9)" gradientUnits="userSpaceOnUse"><stop stop-color="#0ba398" offset="0"/><stop stop-color="#4ca352" offset=".5"/><stop stop-color="#76a30a" offset="1"/></linearGradient> <linearGradient id="d" x2="1" gradientTransform="matrix(-1.9,-67.98,67.98,-1.9,36.6,152.17)" gradientUnits="userSpaceOnUse"><stop stop-color="#36a382" offset="0"/><stop stop-color="#36a382" offset=".19"/><stop stop-color="#49a459" offset=".54"/><stop stop-color="#76a30b" offset="1"/></linearGradient> <linearGradient id="c" x2="1" gradientTransform="matrix(2.18,-62.38,62.38,2.18,15.82,153.24)" gradientUnits="userSpaceOnUse"><stop stop-color="#267880" offset="0"/><stop stop-color="#457a5c" offset=".51"/><stop stop-color="#717516" offset="1"/></linearGradient> <linearGradient id="b" x2="1" gradientTransform="matrix(13.85,-71.96,71.96,13.85,135.08,135.43)" gradientUnits="userSpaceOnUse"><stop stop-color="#b0d939" offset="0"/><stop stop-color="#eadb04" offset="1"/></linearGradient> <linearGradient id="a" x2="1" gradientTransform="matrix(26.159 -64.737 64.737 26.159 107.42 128.14)" gradientUnits="userSpaceOnUse"><stop stop-color="#74af52" offset="0"/><stop stop-color="#74af52" offset=".17"/><stop stop-color="#99be32" offset=".48"/><stop stop-color="#c0c40a" offset="1"/></linearGradient> </defs> </svg>`;btoa(Zx);const Jx='<svg viewBox="0 0 509 154" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M665.95 132.73v44.88l-10.56-8.4c-.8-.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18.4-6.06 1.2-1.88.8-3.54 1.8-4.98 3-1.44 1.2-2.56 2.5-3.36 3.9-.8 1.4-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-.72-.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c.32.24.56.44.72.6.16.16.36.32.6.48.96-1.2 2.14-2.28 3.54-3.24 1.4-.96 2.92-1.76 4.56-2.4 1.64-.64 3.34-1.14 5.1-1.5 1.76-.36 3.44-.54 5.04-.54 1.44 0 2.92.04 4.44.12 1.52.08 2.84.28 3.96.6 4.56 1.12 7.8 3.12 9.72 6 1.92 2.88 2.88 6.56 2.88 11.04ZM732.38 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM795.93 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM858.57 97.21c.64.48.96 1.16.96 2.04v74.88c-.08 1.04-.12 2.12-.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18-1.24-1-2.06-1.66-2.46-1.98-1.76 2.48-4.26 4.44-7.5 5.88-3.24 1.44-7.02 2.16-11.34 2.16-3.84 0-7.4-.7-10.68-2.1-3.28-1.4-6.14-3.44-8.58-6.12-2.44-2.68-4.34-5.94-5.7-9.78-1.36-3.84-2.04-8.16-2.04-12.96 0-4.32.78-8.34 2.34-12.06 1.56-3.72 3.6-6.92 6.12-9.6 2.52-2.68 5.38-4.78 8.58-6.3 3.2-1.52 6.48-2.28 9.84-2.28 2.56 0 4.82.22 6.78.66 1.96.44 3.68 1.06 5.16 1.86s2.78 1.74 3.9 2.82a35.92 35.92 0 0 1 3.12 3.42V88.57l10.68 8.64Zm-27.96 67.92c3.6 0 6.52-.68 8.76-2.04 2.24-1.36 3.98-3.06 5.22-5.1a20.5 20.5 0 0 0 2.58-6.54c.48-2.32.72-4.44.72-6.36v-1.2c0-1.12-.22-2.7-.66-4.74-.44-2.04-1.28-4.06-2.52-6.06s-3-3.7-5.28-5.1c-2.28-1.4-5.22-2.02-8.82-1.86-3.44 0-6.26.74-8.46 2.22-2.2 1.48-3.96 3.26-5.28 5.34-1.32 2.08-2.24 4.2-2.76 6.36-.52 2.16-.78 3.92-.78 5.28 0 1.84.24 3.92.72 6.24.48 2.32 1.36 4.48 2.64 6.48s3.04 3.68 5.28 5.04c2.24 1.36 5.12 2.04 8.64 2.04ZM882.81 97.09c.64.48.96 1.12.96 1.92l-.12 41.04v37.08l-10.56-8.4c-.72-.64-1.08-1.44-1.08-2.4V88.45l10.8 8.64ZM950.36 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14Z" style="fill-rule:nonzero" transform="translate(-452.406 -63.709) scale(1.00797)"/><path d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75Z" style="fill:url(#a);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98Z" style="fill:url(#b);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33Z" style="fill:url(#c);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04Z" style="fill:url(#d);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5Z" style="fill:#9c3;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59Z" style="fill:url(#e);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5Z" style="fill:url(#f);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1Z" style="fill:#ffe113;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75Z" style="fill:#f3e600;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><defs><linearGradient id="a" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)"><stop offset="0" style="stop-color:#62d399;stop-opacity:1"/><stop offset=".51" style="stop-color:#acd842;stop-opacity:1"/><stop offset=".9" style="stop-color:#d7db0a;stop-opacity:1"/><stop offset="1" style="stop-color:#d7db0a;stop-opacity:1"/></linearGradient><linearGradient id="b" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-90.565 123.412 54.953) scale(162.14)"><stop offset="0" style="stop-color:#0ba398;stop-opacity:1"/><stop offset=".5" style="stop-color:#4ca352;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30a;stop-opacity:1"/></linearGradient><linearGradient id="c" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="scale(-68) rotate(88.4 .881 -1.396)"><stop offset="0" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".19" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".54" style="stop-color:#49a459;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30b;stop-opacity:1"/></linearGradient><linearGradient id="d" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-88 87.255 68.431) scale(62.42)"><stop offset="0" style="stop-color:#267880;stop-opacity:1"/><stop offset=".51" style="stop-color:#457a5c;stop-opacity:1"/><stop offset="1" style="stop-color:#717516;stop-opacity:1"/></linearGradient><linearGradient id="e" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-79.1 149.53 -14.065) scale(73.28)"><stop offset="0" style="stop-color:#b0d939;stop-opacity:1"/><stop offset="1" style="stop-color:#eadb04;stop-opacity:1"/></linearGradient><linearGradient id="f" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-67.997 148.705 -15.558) scale(69.8226)"><stop offset="0" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".17" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".48" style="stop-color:#99be32;stop-opacity:1"/><stop offset="1" style="stop-color:#c0c40a;stop-opacity:1"/></linearGradient></defs></svg>',eS=btoa(Jx),tS="data:image/svg+xml;charset=utf-8;base64,"+eS,iS=tS,n_=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var he=(o=>(o.ContextRegistered="ContextRegistered",o.ContextCreationStart="ContextCreationStart",o.ContextCreated="ContextCreated",o.ContextFirstFrameRendered="ContextFirstFrameRendered",o.ContextDestroying="ContextDestroying",o.ContextDestroyed="ContextDestroyed",o.MissingCamera="MissingCamera",o.ContextClearing="ContextClearing",o.ContextCleared="ContextCleared",o))(he||{});class re{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(t){globalThis["NeedleEngine.Context.Current"]=t}static get All(){return this.Registered}static register(t){this.Registered.indexOf(t)===-1&&(n_&&console.warn("Registering context"),this.Registered.push(t),this.dispatchCallback("ContextRegistered",t))}static unregister(t){const e=this.Registered.indexOf(t);e!==-1&&(n_&&console.warn("Unregistering context"),this.Registered.splice(e,1))}static registerCallback(t,e){this._callbacks[t]||(this._callbacks[t]=[]),this._callbacks[t].push(e)}static unregisterCallback(t,e){if(!this._callbacks[t])return;const i=this._callbacks[t].indexOf(e);i!==-1&&this._callbacks[t].splice(i,1)}static dispatchCallback(t,e,i){if(!this._callbacks[t])return!0;const n={event:t,context:e};if(i)for(const a in i)n[a]=i[a];const s=new Array;return this._callbacks[t].forEach(a=>{const l=a(n);l instanceof Promise&&s.push(l)}),Promise.all(s)}static addContextCreatedCallback(t){this.registerCallback("ContextCreated",t)}static addContextDestroyedCallback(t){this.registerCallback("ContextDestroyed",t)}}r(re,"Registered",[]),r(re,"_callbacks",{});const r0=()=>o=>o;function nS(o){return r0()(o)}function sS(){return!!S("debug")}class ki{constructor(t,e){r(this,"_factory");r(this,"_cache",[]);r(this,"_maxSize");r(this,"_index",0);this._factory=t,this._maxSize=e}get(){const t=this._index%this._maxSize;return this._index++,this._cache.length<=t&&(this._cache[t]=this._factory()),this._cache[t]}}let Jo=!1;const qp=new Array;typeof window<"u"&&setTimeout(()=>{if(Jo){const o={},t=new URL(window.location.href),e=new URL(t);e.searchParams.append("console","");const i=e.toString().replace(/=$|=(?=&)/g,"");for(const s of qp){const a=new URL(t);a.searchParams.append(s,""),o[s]=a.toString().replace(/=$|=(?=&)/g,"")}console.log(`🌵 ?help: Debug Options for Needle Engine.
1
+ "use strict";var Hx=Object.defineProperty;var i_=o=>{throw TypeError(o)};var qx=(o,t,e)=>t in o?Hx(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var r=(o,t,e)=>qx(o,typeof t!="symbol"?t+"":t,e),zf=(o,t,e)=>t.has(o)||i_("Cannot "+e);var ce=(o,t,e)=>(zf(o,t,"read from private field"),e?e.call(o):t.get(o)),on=(o,t,e)=>t.has(o)?i_("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(o):t.set(o,e),rn=(o,t,e,i)=>(zf(o,t,"write to private field"),i?i.call(o,e):t.set(o,e),e),Ol=(o,t,e)=>(zf(o,t,"access private method"),e);const d=require("./three-B_hneGZr.umd.cjs"),le=require("./gltf-progressive-C6QbvrB4.umd.cjs"),H=require("./three-examples-DUcCNw9s.umd.cjs"),ae=require("./vendor-Cavtu3CP.umd.cjs"),ne=require("./three-mesh-ui-CQiIQIlA.umd.cjs"),Xx=require("./postprocessing-Dw2OCMp4.umd.cjs");var Nf=typeof document<"u"?document.currentScript:null;const $f=new Map;function Kt(o=(t=>(t=globalThis.location)==null?void 0:t.hostname)()){if($f.has(o))return $f.get(o);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(o);return $f.set(o,e),e===!0}function s0(){return window.location.hostname.includes("glitch.me")}const Qx='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',Yx=btoa(Qx),Kx="data:image/svg+xml;base64,"+Yx,o0=Kx,Zx=`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" version="1.1" viewBox="0 0 1014 282" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m665.95 132.73v44.88l-10.56-8.4c-0.8-0.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18 0.4-6.06 1.2s-3.54 1.8-4.98 3-2.56 2.5-3.36 3.9-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c0.32 0.24 0.56 0.44 0.72 0.6s0.36 0.32 0.6 0.48c0.96-1.2 2.14-2.28 3.54-3.24s2.92-1.76 4.56-2.4 3.34-1.14 5.1-1.5 3.44-0.54 5.04-0.54c1.44 0 2.92 0.04 4.44 0.12s2.84 0.28 3.96 0.6c4.56 1.12 7.8 3.12 9.72 6s2.88 6.56 2.88 11.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m732.38 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m795.93 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m858.57 97.21c0.64 0.48 0.96 1.16 0.96 2.04v74.88c-0.08 1.04-0.12 2.12-0.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18s-2.06-1.66-2.46-1.98c-1.76 2.48-4.26 4.44-7.5 5.88s-7.02 2.16-11.34 2.16c-3.84 0-7.4-0.7-10.68-2.1s-6.14-3.44-8.58-6.12-4.34-5.94-5.7-9.78-2.04-8.16-2.04-12.96c0-4.32 0.78-8.34 2.34-12.06s3.6-6.92 6.12-9.6 5.38-4.78 8.58-6.3 6.48-2.28 9.84-2.28c2.56 0 4.82 0.22 6.78 0.66s3.68 1.06 5.16 1.86 2.78 1.74 3.9 2.82 2.16 2.22 3.12 3.42v-35.04l10.68 8.64zm-27.96 67.92c3.6 0 6.52-0.68 8.76-2.04s3.98-3.06 5.22-5.1 2.1-4.22 2.58-6.54 0.72-4.44 0.72-6.36v-1.2c0-1.12-0.22-2.7-0.66-4.74s-1.28-4.06-2.52-6.06-3-3.7-5.28-5.1-5.22-2.02-8.82-1.86c-3.44 0-6.26 0.74-8.46 2.22s-3.96 3.26-5.28 5.34-2.24 4.2-2.76 6.36-0.78 3.92-0.78 5.28c0 1.84 0.24 3.92 0.72 6.24s1.36 4.48 2.64 6.48 3.04 3.68 5.28 5.04 5.12 2.04 8.64 2.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m882.81 97.09c0.64 0.48 0.96 1.12 0.96 1.92l-0.12 41.04v37.08l-10.56-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-77.88l10.8 8.64z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m950.36 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.8559 0 0 .7642 45.348 36.475)"> <g transform="translate(2.7114)"> <path d="m3.935 173.02c-0.331 0-0.497-0.402-0.497-1.207v-51.002c0-0.738 0.138-1.107 0.414-1.107h1.781c0.277 0 0.415 0.335 0.415 1.006v5.935c0 0.336 0.027 0.553 0.083 0.654 0.055 0.101 0.151-0.017 0.289-0.352 0.912-1.744 1.754-3.236 2.527-4.477 0.773-1.24 1.554-2.179 2.341-2.816s1.65-0.956 2.588-0.956c1.685 0 3.011 0.922 3.977 2.766 0.967 1.845 1.602 3.84 1.905 5.986 0.056 0.268 0.139 0.369 0.249 0.302s0.221-0.235 0.331-0.503c0.939-1.811 1.802-3.353 2.589-4.628 0.787-1.274 1.581-2.246 2.382-2.917s1.671-1.006 2.61-1.006c2.016 0 3.569 1.392 4.66 4.175 1.09 2.783 1.636 6.421 1.636 10.915v37.925c0 0.871-0.18 1.307-0.539 1.307h-1.739c-0.138 0-0.249-0.1-0.332-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.338-6.321-1.015-8.3-0.676-1.978-1.76-2.967-3.251-2.967-0.884 0-1.726 0.386-2.527 1.157s-1.519 1.727-2.154 2.867-1.201 2.213-1.699 3.219c-0.248 0.469-0.421 0.905-0.517 1.308-0.097 0.402-0.145 0.972-0.145 1.71v37.221c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.166 0-0.29-0.1-0.373-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.332-6.321-0.994-8.3-0.663-1.978-1.754-2.967-3.273-2.967-1.242 0-2.375 0.704-3.396 2.112-1.022 1.409-2.223 3.555-3.604 6.439v39.031c0 0.805-0.18 1.207-0.539 1.207h-1.698z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m53.642 166.28c-1.077 2.549-2.237 4.477-3.479 5.785-1.243 1.307-2.61 1.961-4.101 1.961-2.154 0-3.853-1.324-5.095-3.973-1.243-2.649-1.864-6.187-1.864-10.613 0-3.488 0.4-6.489 1.201-9.004s1.988-4.51 3.562-5.985c1.574-1.476 3.521-2.414 5.841-2.817l3.686-0.704c0.221-0.067 0.394-0.218 0.518-0.453 0.124-0.234 0.187-0.587 0.187-1.056v-2.917c0-3.89-0.504-6.975-1.512-9.255s-2.354-3.42-4.039-3.42c-1.298 0-2.472 0.72-3.521 2.162s-2.002 3.572-2.858 6.388c-0.083 0.268-0.159 0.453-0.228 0.554-0.069 0.1-0.172 0.083-0.311-0.051l-1.698-1.71c-0.083-0.134-0.138-0.285-0.166-0.453-0.027-0.167 0.014-0.452 0.125-0.855 0.856-3.353 2.009-6.052 3.459-8.098 1.449-2.045 3.224-3.068 5.322-3.068 1.74 0 3.211 0.687 4.412 2.062s2.112 3.37 2.734 5.986c0.621 2.615 0.932 5.7 0.932 9.255v35.712c0 0.536-0.035 0.888-0.104 1.056s-0.2 0.251-0.393 0.251h-1.533c-0.166 0-0.29-0.117-0.373-0.352-0.083-0.234-0.124-0.553-0.124-0.955l-0.083-5.231c-0.055-0.939-0.221-1.006-0.497-0.202zm0.456-19.314c0-1.14-0.194-1.643-0.58-1.509l-3.107 0.603c-1.436 0.202-2.686 0.638-3.749 1.308-1.063 0.671-1.953 1.543-2.671 2.616s-1.257 2.33-1.616 3.772-0.538 3.102-0.538 4.98c0 3.152 0.455 5.616 1.367 7.393 0.911 1.778 2.14 2.666 3.686 2.666 0.939 0 1.85-0.419 2.734-1.257s1.671-1.895 2.361-3.169c0.663-1.408 1.181-2.85 1.553-4.326 0.373-1.475 0.56-2.883 0.56-4.225v-8.852z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m79.034 173.02c-0.166 0-0.297-0.117-0.394-0.352-0.096-0.234-0.145-0.553-0.145-0.955v-4.628c0-0.536-0.041-0.838-0.124-0.905s-0.207 0.1-0.373 0.503c-0.276 0.67-0.69 1.593-1.242 2.766-0.553 1.174-1.271 2.23-2.154 3.169-0.884 0.939-1.961 1.408-3.231 1.408-1.74 0-3.314-0.989-4.722-2.967-1.409-1.979-2.534-4.963-3.376-8.953-0.843-3.991-1.264-8.937-1.264-14.838 0-5.701 0.415-10.68 1.243-14.939s1.988-7.595 3.479-10.009c1.492-2.415 3.204-3.622 5.137-3.622 1.436 0 2.616 0.57 3.541 1.71 0.926 1.14 1.719 2.381 2.382 3.722 0.249 0.47 0.414 0.637 0.497 0.503s0.125-0.536 0.125-1.207v-23.841c0-0.805 0.151-1.208 0.455-1.208h1.864c0.276 0 0.414 0.369 0.414 1.107v72.128c0 0.537-0.041 0.905-0.124 1.107-0.083 0.201-0.235 0.301-0.455 0.301h-1.533zm-0.621-42.049c-0.939-2.213-1.885-3.94-2.838-5.181s-2.009-1.861-3.169-1.861c-1.463 0-2.768 0.889-3.914 2.666s-2.044 4.376-2.693 7.796-0.973 7.578-0.973 12.474c0 5.097 0.338 9.272 1.015 12.524 0.676 3.253 1.567 5.651 2.672 7.193 1.104 1.543 2.305 2.314 3.603 2.314 1.188 0 2.258-0.704 3.211-2.113 0.952-1.408 1.705-3.118 2.257-5.13s0.829-3.957 0.829-5.835v-24.847z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m89.514 149.38c0 3.42 0.345 6.606 1.035 9.557 0.691 2.951 1.609 5.315 2.755 7.092s2.437 2.666 3.873 2.666c1.519 0 2.837-0.738 3.956-2.213 1.118-1.476 2.064-3.655 2.837-6.539 0.083-0.336 0.166-0.52 0.249-0.554 0.083-0.033 0.179 0.017 0.29 0.151l1.408 1.912c0.221 0.268 0.235 0.67 0.041 1.207-0.69 2.548-1.47 4.661-2.34 6.337-0.87 1.677-1.857 2.935-2.962 3.773-1.104 0.838-2.319 1.257-3.645 1.257-2.043 0-3.838-1.14-5.385-3.42-1.546-2.28-2.761-5.482-3.645-9.607-0.884-4.124-1.325-8.836-1.325-14.134 0-5.901 0.455-10.931 1.367-15.089 0.911-4.158 2.14-7.377 3.686-9.658 1.547-2.28 3.3-3.42 5.261-3.42 1.988 0 3.714 1.073 5.178 3.219 1.463 2.146 2.595 5.231 3.396 9.255s1.201 8.886 1.201 14.587c0 0.469-0.02 0.939-0.062 1.408-0.041 0.469-0.214 0.704-0.517 0.704h-16.362c-0.083 0-0.152 0.151-0.207 0.453-0.056 0.302-0.083 0.654-0.083 1.056zm13.752-6.237c0.304 0 0.497-0.1 0.58-0.302 0.083-0.201 0.124-0.57 0.124-1.106 0-3.219-0.283-6.187-0.849-8.903s-1.367-4.896-2.402-6.539c-1.036-1.643-2.272-2.464-3.708-2.464-1.629 0-2.996 0.955-4.101 2.867-1.104 1.911-1.94 4.342-2.506 7.293s-0.849 6.002-0.849 9.154h13.711z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m148.54 119.7c0.165 0 0.283 0.117 0.352 0.352s0.076 0.52 0.02 0.855l-6.254 50.902c-0.028 0.47-0.104 0.788-0.228 0.956s-0.297 0.251-0.518 0.251h-1.615c-0.442 0-0.718-0.402-0.829-1.207l-5.26-40.138c-0.111-0.604-0.201-0.905-0.27-0.905s-0.131 0.301-0.186 0.905l-5.012 40.138c-0.028 0.47-0.097 0.788-0.207 0.956-0.111 0.168-0.277 0.251-0.497 0.251h-1.74c-0.442 0-0.718-0.402-0.829-1.207l-6.503-50.801c-0.055-0.403-0.048-0.721 0.021-0.956s0.2-0.352 0.393-0.352h1.823c0.166 0 0.297 0.067 0.393 0.201 0.097 0.134 0.159 0.403 0.187 0.805l5.302 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.219-41.949c0.055-0.268 0.124-0.47 0.207-0.604s0.193-0.201 0.331-0.201h1.533c0.138 0 0.262 0.067 0.373 0.201 0.11 0.134 0.179 0.403 0.207 0.805l5.468 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.053-41.849c0.055-0.335 0.138-0.57 0.249-0.704 0.11-0.134 0.234-0.201 0.373-0.201h1.284z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m156.49 171.51c0 0.604-0.042 1.006-0.125 1.208-0.082 0.201-0.262 0.301-0.538 0.301h-1.533c-0.221 0-0.366-0.083-0.435-0.251s-0.103-0.486-0.103-0.956v-50.902c0-0.805 0.152-1.207 0.456-1.207h1.822c0.304 0 0.456 0.402 0.456 1.207v50.6zm0.165-63.979c0 1.207-0.207 1.811-0.621 1.811h-1.905c-0.221 0-0.366-0.135-0.435-0.403s-0.104-0.67-0.104-1.207v-7.847c0-1.006 0.18-1.509 0.539-1.509h1.988c0.359 0 0.538 0.47 0.538 1.409v7.746z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m168.3 124.83c-0.221 0-0.331 0.269-0.331 0.805v33.801c0 3.42 0.221 5.667 0.663 6.74 0.441 1.073 1.09 1.609 1.946 1.609h3.024c0.138 0 0.242 0.084 0.311 0.252 0.069 0.167 0.103 0.419 0.103 0.754v2.716c0 0.537-0.138 0.906-0.414 1.107-0.248 0.067-0.614 0.134-1.098 0.201-0.483 0.067-0.959 0.118-1.429 0.151-0.469 0.034-0.828 0.05-1.077 0.05-1.712 0-2.934-0.955-3.665-2.867-0.732-1.911-1.098-5.013-1.098-9.305v-35.108c0-0.604-0.124-0.906-0.373-0.906h-3.521c-0.248 0-0.373-0.268-0.373-0.804v-3.521c0-0.537 0.111-0.805 0.332-0.805h3.686c0.166 0 0.263-0.268 0.29-0.805l0.415-16.095c0-0.805 0.124-1.207 0.372-1.207h1.492c0.303 0 0.455 0.436 0.455 1.307v15.995c0 0.537 0.097 0.805 0.29 0.805h5.468c0.221 0 0.331 0.268 0.331 0.805v3.521c0 0.536-0.124 0.804-0.373 0.804h-5.426z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m179.4 173.02c-0.331 0-0.497-0.402-0.497-1.207v-72.329c0-0.738 0.138-1.107 0.414-1.107h1.782c0.276 0 0.414 0.336 0.414 1.006v27.162c0 0.335 0.034 0.536 0.103 0.603s0.159-0.033 0.27-0.302c0.994-1.81 1.898-3.319 2.713-4.526 0.814-1.208 1.629-2.113 2.444-2.717 0.814-0.603 1.691-0.905 2.63-0.905 2.182 0 3.839 1.375 4.971 4.125 1.132 2.749 1.698 6.404 1.698 10.965v37.925c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.165 0-0.29-0.1-0.373-0.301-0.082-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.366-6.321-1.097-8.3-0.732-1.978-1.899-2.967-3.501-2.967-0.883 0-1.705 0.318-2.464 0.956-0.76 0.637-1.526 1.576-2.299 2.816-0.773 1.241-1.643 2.834-2.61 4.779v39.031c0 0.805-0.179 1.207-0.538 1.207h-1.699z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> </g> <g transform="matrix(.80638 0 0 .80638 452.53 65.421)" fill-rule="nonzero"> <path d="m79.32 36.98v150.76l15.68-13.2 6.59-156.31-22.27 18.75z" fill="url(#f)"/> <path d="m79.32 36.98-22.27-18.75 6.59 156.31 15.68 13.2v-150.76z" fill="url(#e)"/> <path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z" fill="url(#d)"/> <path d="m25.19 104.83-25.19-14.59 16.97 53.86 16.85 9.77-8.63-49.04z" fill="url(#c)"/> <path d="M43.86,82.5L18.69,67.98L0,90.24L25.18,104.83L43.86,82.5Z" fill="#9c3"/> <path d="m134.82 78.69-9.97 56.5 15.58-9.04 19.57-62.05-25.18 14.59z" fill="url(#b)"/> <path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z" fill="url(#a)"/> <path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33 25.19-14.59z" fill="#ffe113"/> <path d="M101.59,18.23L79.32,0L57.05,18.23L79.32,36.98L101.59,18.23Z" fill="#f3e600"/> </g> <defs> <linearGradient id="f" x2="1" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)" gradientUnits="userSpaceOnUse"><stop stop-color="#62d399" offset="0"/><stop stop-color="#acd842" offset=".51"/><stop stop-color="#d7db0a" offset=".9"/><stop stop-color="#d7db0a" offset="1"/></linearGradient> <linearGradient id="e" x2="1" gradientTransform="matrix(-1.6,-162.13,162.13,-1.6,69.68,178.9)" gradientUnits="userSpaceOnUse"><stop stop-color="#0ba398" offset="0"/><stop stop-color="#4ca352" offset=".5"/><stop stop-color="#76a30a" offset="1"/></linearGradient> <linearGradient id="d" x2="1" gradientTransform="matrix(-1.9,-67.98,67.98,-1.9,36.6,152.17)" gradientUnits="userSpaceOnUse"><stop stop-color="#36a382" offset="0"/><stop stop-color="#36a382" offset=".19"/><stop stop-color="#49a459" offset=".54"/><stop stop-color="#76a30b" offset="1"/></linearGradient> <linearGradient id="c" x2="1" gradientTransform="matrix(2.18,-62.38,62.38,2.18,15.82,153.24)" gradientUnits="userSpaceOnUse"><stop stop-color="#267880" offset="0"/><stop stop-color="#457a5c" offset=".51"/><stop stop-color="#717516" offset="1"/></linearGradient> <linearGradient id="b" x2="1" gradientTransform="matrix(13.85,-71.96,71.96,13.85,135.08,135.43)" gradientUnits="userSpaceOnUse"><stop stop-color="#b0d939" offset="0"/><stop stop-color="#eadb04" offset="1"/></linearGradient> <linearGradient id="a" x2="1" gradientTransform="matrix(26.159 -64.737 64.737 26.159 107.42 128.14)" gradientUnits="userSpaceOnUse"><stop stop-color="#74af52" offset="0"/><stop stop-color="#74af52" offset=".17"/><stop stop-color="#99be32" offset=".48"/><stop stop-color="#c0c40a" offset="1"/></linearGradient> </defs> </svg>`;btoa(Zx);const Jx='<svg viewBox="0 0 509 154" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M665.95 132.73v44.88l-10.56-8.4c-.8-.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18.4-6.06 1.2-1.88.8-3.54 1.8-4.98 3-1.44 1.2-2.56 2.5-3.36 3.9-.8 1.4-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-.72-.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c.32.24.56.44.72.6.16.16.36.32.6.48.96-1.2 2.14-2.28 3.54-3.24 1.4-.96 2.92-1.76 4.56-2.4 1.64-.64 3.34-1.14 5.1-1.5 1.76-.36 3.44-.54 5.04-.54 1.44 0 2.92.04 4.44.12 1.52.08 2.84.28 3.96.6 4.56 1.12 7.8 3.12 9.72 6 1.92 2.88 2.88 6.56 2.88 11.04ZM732.38 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM795.93 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM858.57 97.21c.64.48.96 1.16.96 2.04v74.88c-.08 1.04-.12 2.12-.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18-1.24-1-2.06-1.66-2.46-1.98-1.76 2.48-4.26 4.44-7.5 5.88-3.24 1.44-7.02 2.16-11.34 2.16-3.84 0-7.4-.7-10.68-2.1-3.28-1.4-6.14-3.44-8.58-6.12-2.44-2.68-4.34-5.94-5.7-9.78-1.36-3.84-2.04-8.16-2.04-12.96 0-4.32.78-8.34 2.34-12.06 1.56-3.72 3.6-6.92 6.12-9.6 2.52-2.68 5.38-4.78 8.58-6.3 3.2-1.52 6.48-2.28 9.84-2.28 2.56 0 4.82.22 6.78.66 1.96.44 3.68 1.06 5.16 1.86s2.78 1.74 3.9 2.82a35.92 35.92 0 0 1 3.12 3.42V88.57l10.68 8.64Zm-27.96 67.92c3.6 0 6.52-.68 8.76-2.04 2.24-1.36 3.98-3.06 5.22-5.1a20.5 20.5 0 0 0 2.58-6.54c.48-2.32.72-4.44.72-6.36v-1.2c0-1.12-.22-2.7-.66-4.74-.44-2.04-1.28-4.06-2.52-6.06s-3-3.7-5.28-5.1c-2.28-1.4-5.22-2.02-8.82-1.86-3.44 0-6.26.74-8.46 2.22-2.2 1.48-3.96 3.26-5.28 5.34-1.32 2.08-2.24 4.2-2.76 6.36-.52 2.16-.78 3.92-.78 5.28 0 1.84.24 3.92.72 6.24.48 2.32 1.36 4.48 2.64 6.48s3.04 3.68 5.28 5.04c2.24 1.36 5.12 2.04 8.64 2.04ZM882.81 97.09c.64.48.96 1.12.96 1.92l-.12 41.04v37.08l-10.56-8.4c-.72-.64-1.08-1.44-1.08-2.4V88.45l10.8 8.64ZM950.36 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14Z" style="fill-rule:nonzero" transform="translate(-452.406 -63.709) scale(1.00797)"/><path d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75Z" style="fill:url(#a);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98Z" style="fill:url(#b);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33Z" style="fill:url(#c);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04Z" style="fill:url(#d);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5Z" style="fill:#9c3;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59Z" style="fill:url(#e);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5Z" style="fill:url(#f);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1Z" style="fill:#ffe113;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75Z" style="fill:#f3e600;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><defs><linearGradient id="a" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)"><stop offset="0" style="stop-color:#62d399;stop-opacity:1"/><stop offset=".51" style="stop-color:#acd842;stop-opacity:1"/><stop offset=".9" style="stop-color:#d7db0a;stop-opacity:1"/><stop offset="1" style="stop-color:#d7db0a;stop-opacity:1"/></linearGradient><linearGradient id="b" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-90.565 123.412 54.953) scale(162.14)"><stop offset="0" style="stop-color:#0ba398;stop-opacity:1"/><stop offset=".5" style="stop-color:#4ca352;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30a;stop-opacity:1"/></linearGradient><linearGradient id="c" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="scale(-68) rotate(88.4 .881 -1.396)"><stop offset="0" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".19" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".54" style="stop-color:#49a459;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30b;stop-opacity:1"/></linearGradient><linearGradient id="d" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-88 87.255 68.431) scale(62.42)"><stop offset="0" style="stop-color:#267880;stop-opacity:1"/><stop offset=".51" style="stop-color:#457a5c;stop-opacity:1"/><stop offset="1" style="stop-color:#717516;stop-opacity:1"/></linearGradient><linearGradient id="e" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-79.1 149.53 -14.065) scale(73.28)"><stop offset="0" style="stop-color:#b0d939;stop-opacity:1"/><stop offset="1" style="stop-color:#eadb04;stop-opacity:1"/></linearGradient><linearGradient id="f" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-67.997 148.705 -15.558) scale(69.8226)"><stop offset="0" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".17" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".48" style="stop-color:#99be32;stop-opacity:1"/><stop offset="1" style="stop-color:#c0c40a;stop-opacity:1"/></linearGradient></defs></svg>',eS=btoa(Jx),tS="data:image/svg+xml;charset=utf-8;base64,"+eS,iS=tS,n_=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var he=(o=>(o.ContextRegistered="ContextRegistered",o.ContextCreationStart="ContextCreationStart",o.ContextCreated="ContextCreated",o.ContextFirstFrameRendered="ContextFirstFrameRendered",o.ContextDestroying="ContextDestroying",o.ContextDestroyed="ContextDestroyed",o.MissingCamera="MissingCamera",o.ContextClearing="ContextClearing",o.ContextCleared="ContextCleared",o))(he||{});class re{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(t){globalThis["NeedleEngine.Context.Current"]=t}static get All(){return this.Registered}static register(t){this.Registered.indexOf(t)===-1&&(n_&&console.warn("Registering context"),this.Registered.push(t),this.dispatchCallback("ContextRegistered",t))}static unregister(t){const e=this.Registered.indexOf(t);e!==-1&&(n_&&console.warn("Unregistering context"),this.Registered.splice(e,1))}static registerCallback(t,e){this._callbacks[t]||(this._callbacks[t]=[]),this._callbacks[t].push(e)}static unregisterCallback(t,e){if(!this._callbacks[t])return;const i=this._callbacks[t].indexOf(e);i!==-1&&this._callbacks[t].splice(i,1)}static dispatchCallback(t,e,i){if(!this._callbacks[t])return!0;const n={event:t,context:e};if(i)for(const a in i)n[a]=i[a];const s=new Array;return this._callbacks[t].forEach(a=>{const l=a(n);l instanceof Promise&&s.push(l)}),Promise.all(s)}static addContextCreatedCallback(t){this.registerCallback("ContextCreated",t)}static addContextDestroyedCallback(t){this.registerCallback("ContextDestroyed",t)}}r(re,"Registered",[]),r(re,"_callbacks",{});const r0=()=>o=>o;function nS(o){return r0()(o)}function sS(){return!!S("debug")}class ki{constructor(t,e){r(this,"_factory");r(this,"_cache",[]);r(this,"_maxSize");r(this,"_index",0);this._factory=t,this._maxSize=e}get(){const t=this._index%this._maxSize;return this._index++,this._cache.length<=t&&(this._cache[t]=this._factory()),this._cache[t]}}let Jo=!1;const qp=new Array;typeof window<"u"&&setTimeout(()=>{if(Jo){const o={},t=new URL(window.location.href),e=new URL(t);e.searchParams.append("console","");const i=e.toString().replace(/=$|=(?=&)/g,"");for(const s of qp){const a=new URL(t);a.searchParams.append(s,""),o[s]=a.toString().replace(/=$|=(?=&)/g,"")}console.log(`🌵 ?help: Debug Options for Needle Engine.
2
2
  Append any of these parameters to the URL to enable specific debug options.
3
3
  Example: ${i} will show an onscreen console window.`);const n=Jo===!0?"":` (containing "${Jo}")`;console.group("Available URL parameters:"+n);for(const s of Object.keys(o).sort())typeof Jo=="string"&&!s.toLowerCase().includes(Jo.toLowerCase())||(console.groupCollapsed(s),console.log("Reload with this flag enabled:"),console.log(o[s]),console.groupEnd());console.groupEnd()}},100);function Zc(){var o;return new URLSearchParams((o=globalThis.location)==null?void 0:o.search)}function S(o){Jo&&!qp.includes(o)&&qp.push(o);const t=Zc();if(t.has(o)){const e=t.get(o);if(e){const i=Number(e);return isNaN(i)?e:i}else return!0}return!1}Jo=S("help");function oS(o,t){const e=Zc();e.has(o)?e.set(o,t):e.append(o,t),document.location.search=e.toString()}function Oc(o,t,e=!0){const i=Zc();i.has(o)?t===null?i.delete(o):i.set(o,t):t!==null&&i.append(o,t),e?a0(o,i):Vm(o,i)}function Xp(o,t,e){o.has(t)?o.set(t,e.toString()):o.append(t,e.toString())}function a0(o,t,e){window.history.pushState(e,o,"?"+t.toString())}function Vm(o,t,e){window.history.replaceState(e,o,"?"+t.toString())}function rS(o){for(var t="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=e.length,n=0;n<o;n++)t+=e.charAt(Math.floor(Math.random()*i));return t}function aS(o,t){return Math.floor(Math.random()*(t-o+1))+o}const s_=["smol","tiny","giant","interesting","smart","bright","dull","extreme","beautiful","pretty","dark","epic","salty","silly","funny","lame","lazy","loud","lucky","mad","mean","mighty","mysterious","nasty","odd","old","powerful","quiet","rapid","scary","shiny","shy","silly","smooth","sour","spicy","stupid","sweet","tasty","terrible","ugly","unusual","vast","wet","wild","witty","wrong","zany","zealous","zippy","zombie","zorro"],o_=["cat","dog","mouse","pig","cow","horse","sheep","chicken","duck","goat","panda","tiger","lion","elephant","monkey","bird","fish","snake","frog","turtle","hamster","penguin","kangaroo","whale","dolphin","crocodile","snail","ant","bee","beetle","butterfly","dragon","eagle","fish","giraffe","lizard","panda","penguin","rabbit","snake","spider","tiger","zebra"];function l0(){const o=s_[Math.floor(Math.random()*s_.length)],t=o_[Math.floor(Math.random()*o_.length)];return o+"_"+t}function c0(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function za(o,t,e=!0,i=!1){var n;if(t==null)return null;if(t.userData&&t.userData.guid===o)return t;if(t.guid==o)return t;if(i&&(n=t.userData)!=null&&n.components){for(const s of t.userData.components)if(s.guid===o)return s}if(e){if(t.scenes)for(const s in t.scenes){const a=t.scenes[s],l=za(o,a,e,i);if(l)return l}if(t.children)for(const s in t.children){const a=t.children[s],l=za(o,a,e,i);if(l)return l}}}function Jc(o,t){if(o!=null&&typeof o=="object"){let e;Array.isArray(o)?e=[]:(e=Object.create(o),Object.assign(e,o));for(const i of Object.keys(o)){const n=o[i];t&&!t(o,i,n)?e[i]=n:(n==null?void 0:n.clone)!==void 0&&typeof n.clone=="function"?e[i]=n.clone():e[i]=Jc(n,t)}return e}return o}function Jn(o){return new Promise((t,e)=>{setTimeout(t,o)})}function eh(o,t){if(o<=0)return Promise.resolve();if(t||(t=re.Current),!t)return Promise.reject("No context");const e=t.time.frameCount+o;return new Promise((i,n)=>{if(!t)return n("No context");const s=()=>{t.time.frameCount>=e&&(t.pre_update_callbacks.splice(t.pre_update_callbacks.indexOf(s),1),i())};t.pre_update_callbacks.push(s)})}const Kh=S("debugresolveurl"),h0="rel:";function lS(o,t){return Eo(o,t)}function Eo(o,t){if(t===void 0)return Kh&&console.warn("getPath: uri is undefined, returning uri",t),t;if(t.startsWith("./"))return t;if(t.startsWith("http"))return Kh&&console.warn("getPath: uri is absolute, returning uri",t),t;if(o===void 0)return Kh&&console.warn("getPath: source is undefined, returning uri",t),t;t.startsWith(h0)&&(t=t.substring(4));const e=o.lastIndexOf("/");if(e>=0){const i=o.substring(0,e+1);for(;i.endsWith("/")&&t.startsWith("/");)t=t.substring(1);const n=i+t;return Kh&&console.log("source:",o,`changed uri
4
4
  from`,t,`
@@ -142,7 +142,7 @@ Open this page to get the console: `+t.toString())}const o=exports.DeviceUtiliti
142
142
  #__vconsole .vc-mask {
143
143
  overflow: hidden;
144
144
  }
145
- `,wi==null||wi.prepend(i),o===!0&&Hm()<=0&&L0(),console.log("🌵 Debug console has loaded")}},t.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),Rl=!1,Xt=null},t.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(t)}function aC(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(e){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const l=location.protocol+"//"+location.host+location.pathname+"/"+n,c=encodeURIComponent(l);o.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(h)}),o.on("show",function(){const e=t();e&&e.src!==o.fullUrl&&(e.src=o.fullUrl)}),o.on("hide",function(){const e=t();e&&(e.src="")}),o.on("addTopBar",function(e){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(o.fullUrl,"_blank"),Xt==null||Xt.hide()}}),i.push({name:"Reload",onClick:function(n){const s=t();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=t();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),e(i)}),o}function lC(){const o=document.querySelector("#__vconsole .vc-switch");return o||null}function cC(){const o=document.querySelector("#__vconsole");return o||null}const j0=S("debugdefines");To('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');To('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');To('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');To('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');To('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.7.2";');To('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');To('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Aug 04 2025 15:10:31 GMT+0000 (Coordinated Universal Time)";');To('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const _n="4.7.2",Fu="undefined",tg="Mon Aug 04 2025 15:10:31 GMT+0000 (Coordinated Universal Time)";j0&&console.log(`Engine version: ${_n} (generator: ${Fu})
145
+ `,wi==null||wi.prepend(i),o===!0&&Hm()<=0&&L0(),console.log("🌵 Debug console has loaded")}},t.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),Rl=!1,Xt=null},t.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(t)}function aC(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(e){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const l=location.protocol+"//"+location.host+location.pathname+"/"+n,c=encodeURIComponent(l);o.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(h)}),o.on("show",function(){const e=t();e&&e.src!==o.fullUrl&&(e.src=o.fullUrl)}),o.on("hide",function(){const e=t();e&&(e.src="")}),o.on("addTopBar",function(e){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(o.fullUrl,"_blank"),Xt==null||Xt.hide()}}),i.push({name:"Reload",onClick:function(n){const s=t();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=t();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),e(i)}),o}function lC(){const o=document.querySelector("#__vconsole .vc-switch");return o||null}function cC(){const o=document.querySelector("#__vconsole");return o||null}const j0=S("debugdefines");To('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');To('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');To('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');To('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');To('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.7.3-alpha";');To('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');To('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Aug 06 2025 09:23:38 GMT+0000 (Coordinated Universal Time)";');To('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const _n="4.7.3-alpha",Fu="undefined",tg="Wed Aug 06 2025 09:23:38 GMT+0000 (Coordinated Universal Time)";j0&&console.log(`Engine version: ${_n} (generator: ${Fu})
146
146
  Project built at ${tg}`);const ba=NEEDLE_PUBLIC_KEY,Es="needle_isActiveInHierarchy",er="builtin_components",cc="needle_editor_guid";function To(o){try{(0,eval)(o)}catch(t){j0&&console.error(t)}}let B0,m_=null;function bn(){return B0}function ig(o){if(o==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}m_!==o&&(m_=o,B0=new o)}const Si=Symbol("shadowDomOwner"),hC=S("debugpatch");function Uu(o,t,e,i){const n=hC===t;if(!e&&!i)return;const s=t+"___needle";uC(o,t,e,i);const a=Object.getOwnPropertyDescriptor(o,t),l=o[t];n&&console.log("Patch",o.constructor.name,t,a,l),a?(n&&console.log("Apply patch with existing descriptor",o.constructor.name,t,a),typeof a.value=="function"&&(o[t]=y_(a.value,o,t))):(n&&console.log("Create patch with new property",o.constructor.name,t,a),Object.defineProperty(o,t,{set:function(c){if(typeof c=="function")this[s]=y_(c,o,t);else{const h=this[s];F0(o,t,this,h,c),this[s]=c,U0(o,t,this,h,c)}},get:function(){const c=this[s];return typeof c=="function"&&c[s]?c[s]:c}}))}function dC(o,t,e){const i=ng(o,t);if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];s.prefix===e&&(s.prefix=null),s.postfix===e&&(s.postfix=null),!s.prefix&&!s.postfix&&i.splice(n,1)}}const g_=Symbol("Needle:Patches:WrappedFunction");function y_(o,t,e){if(o[g_])return o;const i=function(...n){F0(t,e,this,...n);const s=o.apply(this,n);return U0(t,e,this,s,...n),s};return i[g_]=!0,i}const Rd="Needle:Patches";function im(){return globalThis[Rd]||(globalThis[Rd]=new WeakMap),globalThis[Rd]}function ng(o,t){const e=im().get(o);return e?e.get(t):null}function uC(o,t,e,i){let n=im().get(o);n||(n=new Map,im().set(o,n));let s=n.get(t);s||(s=[],n.set(t,s)),s.push({prefix:e,postfix:i})}function F0(o,t,e,...i){var s;if(!e)return;const n=ng(o,t);if(n)for(const a of n)(s=a.prefix)==null||s.call(e,...i)}function U0(o,t,e,i,...n){var a;if(!e)return;const s=ng(o,t);if(s)for(const l of s)(a=l.postfix)==null||a.call(e,i,...n)}const $a=[];function zu(o){$a.indexOf(o)===-1&&$a.push(o)}function fC(o){const t=$a.indexOf(o);t!==-1&&$a.splice(t,1)}const Va=[];function sg(o){Va.indexOf(o)===-1&&Va.push(o)}function pC(o){const t=Va.indexOf(o);t!==-1&&Va.splice(t,1)}function z0(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:o}));for(let t=0;t<$a.length;t++)$a[t](o)}function N0(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:o}));for(let t=0;t<Va.length;t++)Va[t](o)}const et=S("debuginput");var Nu=(o=>(o.Mouse="mouse",o.Touch="touch",o.Controller="controller",o.Hand="hand",o))(Nu||{}),Re=(o=>(o.PointerDown="pointerdown",o.PointerUp="pointerup",o.PointerMove="pointermove",o.KeyDown="keydown",o.KeyUp="keyup",o.KeyPressed="keypress",o))(Re||{});class ys extends PointerEvent{constructor(e,i,n){super(e,n);r(this,"clientZ");r(this,"deviceIndex");r(this,"origin");r(this,"source");r(this,"mode");r(this,"_ray");r(this,"space");r(this,"isClick",!1);r(this,"isDoubleClick",!1);r(this,"_used",!1);r(this,"_pointerid");r(this,"_pointerType");r(this,"_type");r(this,"metadata",{});r(this,"intersections",new Array);r(this,"_immediatePropagationStopped",!1);r(this,"_propagationStopped",!1);this.clientZ=n.clientZ,this._pointerid=n.pointerId,this._pointerType=n.pointerType,this._type=e,this.deviceIndex=n.deviceIndex,this.origin=n.origin,this.source=i,this.mode=n.mode,this._ray=n.ray,this.space=n.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new d.Ray(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),et&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Xl extends KeyboardEvent{constructor(e,i,n){super(e,n);r(this,"source");this.source=i}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class mC{constructor(t){r(this,"key");r(this,"keyType");r(this,"source");this.key=t.key,this.keyType=t.type,this.source=t}}var ri=(o=>(o[o.Early=-100]="Early",o[o.Default=0]="Default",o[o.Late=100]="Late",o))(ri||{});class $0{constructor(t){r(this,"_eventListeners",{});r(this,"_doubleClickTimeThreshold",.2);r(this,"_longPressTimeThreshold",1);r(this,"_setCursorTypes",[]);r(this,"context");r(this,"_pointerDown",[!1]);r(this,"_pointerUp",[!1]);r(this,"_pointerClick",[!1]);r(this,"_pointerDoubleClick",[!1]);r(this,"_pointerPressed",[!1]);r(this,"_pointerPositions",[new d.Vector2]);r(this,"_pointerPositionsLastFrame",[new d.Vector2]);r(this,"_pointerPositionsDelta",[new d.Vector2]);r(this,"_pointerPositionsRC",[new d.Vector2]);r(this,"_pointerPositionDown",[new d.Vector3]);r(this,"_pointerDownTime",[]);r(this,"_pointerUpTime",[]);r(this,"_pointerUpTimestamp",[]);r(this,"_pointerIds",[]);r(this,"_pointerTypes",[""]);r(this,"_mouseWheelChanged",[!1]);r(this,"_mouseWheelDeltaY",[0]);r(this,"_pointerEvent",[]);r(this,"_pointerEventsPressed",[]);r(this,"_pointerSpace",[]);r(this,"_pressedStack",new Map);r(this,"_htmlEventSource");r(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1});r(this,"_receivedPointerMoveEventsThisFrame",new Array);r(this,"onEndOfFrame",()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0});r(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType});r(this,"keysPressed",{});r(this,"onKeyDown",t=>{if(et&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(e&&e.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const i=new Xl("keydown",t,t);this.onDispatchEvent(i)});r(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(!e)return;e.pressed=!0,e.frame=this.context.time.frameCount+1;const i=new Xl("keypress",t,t);this.onDispatchEvent(i)});r(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(!e)return;e.pressed=!1,e.frame=this.context.time.frameCount+1;const i=new Xl("keyup",t,t);this.onDispatchEvent(i)});r(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)});r(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const e=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=e+t.deltaY});r(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const e=this.getPointerId(t);et&&Ee(`pointer down #${e}, identifier:${t.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(e,t.clientX,t.clientY),n=new ys("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:i,pressure:t.pressure});this.onDown(n)});r(this,"onPointerMove",t=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(t.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(t.pointerId);let e=t.button;t.pointerType==="mouse"&&(e=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(t,e);e===-1&&(e=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,t.clientX,t.clientY),s=new ys("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:e,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:n,pressure:t.pressure});this.onMove(s)});r(this,"onPointerCancel",t=>{this.context.isInAR||(et&&console.log("Pointer cancel",t),this.onPointerUp(t))});r(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const e=this.getPointerId(t),i=new ys("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(e,t.clientX,t.clientY),pressure:t.pressure});this.onUp(i),this._pointerIds[e]=-1,et&&console.log("ID="+e,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])});r(this,"onTouchStart",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),a=new ys("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onDown(a)}});r(this,"onTouchMove",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),a=new ys("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onMove(a)}});r(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),s=new ys("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(s),this._pointerIds[n]=-1}});r(this,"tempNearPlaneVector",new d.Vector3);r(this,"tempFarPlaneVector",new d.Vector3);r(this,"tempLookMatrix",new d.Matrix4);this.context=t,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(t,e,i){if(this._eventListeners[t]||(this._eventListeners[t]=[]),!e||typeof e!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;(i==null?void 0:i.queue)!=null&&(n=i.queue);const s=this._eventListeners[t],a=s.find(l=>l.priority===n);a?a.listeners.push({callback:e,options:i}):(s.push({priority:n,listeners:[{callback:e,options:i}]}),s.sort((l,c)=>l.priority-c.priority))}removeEventListener(t,e,i){if(!this._eventListeners[t]||!e)return;const n=this._eventListeners[t];if((i==null?void 0:i.queue)!=null){const s=n.find(l=>l.priority===i.queue);if(!s)return;const a=s.listeners.findIndex(l=>l.callback===e);a>=0&&s.listeners.splice(a,1)}else for(const s of n){const a=s.listeners.findIndex(l=>l.callback===e);a>=0&&s.listeners.splice(a,1)}}dispatchEvent(t){var i,n,s,a;let e=!1;if(t instanceof Xl){const l=this._eventListeners[t.type];if(l)for(const c of l)for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((n=(i=u.options)==null?void 0:i.signal)!=null&&n.aborted){c.listeners.splice(h,1),h--;continue}u.options.once&&(c.listeners.splice(h,1),h--),u.callback(t)}}if(t instanceof ys){const l=this._eventListeners[t.type];if(l)for(const c of l){if(e)break;for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((a=(s=u.options)==null?void 0:s.signal)!=null&&a.aborted){c.listeners.splice(h,1),h--;continue}if(t.immediatePropagationStopped){e=!0,et&&console.log("immediatePropagationStopped",t.type);break}else t.propagationStopped&&(e=!0,et&&console.log("propagationStopped",t.type));u.options.once&&(c.listeners.splice(h,1),h--),u.callback(t)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(t=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[t]||null}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(t){this._setCursorTypes.push(t),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(t){for(let e=this._setCursorTypes.length-1;e>=0;e--)if(this._setCursorTypes[e]===t){this._setCursorTypes.splice(e,1),this.updateCursor();break}}updateCursor(){var t;((t=this._setCursorTypes)==null?void 0:t.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(t){for(const e of this._pointerEventsPressed)if(e.pointerId===t&&e.used)return!0;return!1}getPointerPressedCount(){let t=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&t++;return t}getPointerPosition(t){return t>=this._pointerPositions.length?null:this._pointerPositions[t]}getPointerPositionLastFrame(t){return t>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[t]}getPointerPositionDelta(t){return t>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[t]}getPointerPositionRC(t){return t>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[t]}getPointerDown(t){return t>=this._pointerDown.length?!1:this._pointerDown[t]}getPointerUp(t){return t>=this._pointerUp.length?!1:this._pointerUp[t]}getPointerPressed(t){return t>=this._pointerPressed.length?!1:this._pointerPressed[t]}getPointerClicked(t){return t>=this._pointerClick.length?!1:this._pointerClick[t]}getPointerDoubleClicked(t){return t>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[t]}getPointerDownTime(t){return t>=this._pointerDownTime.length?-1:this._pointerDownTime[t]}getPointerUpTime(t){return t>=this._pointerUpTime.length?-1:this._pointerUpTime[t]}getPointerLongPress(t){return t>=this._pointerDownTime.length?!1:this.getPointerPressed(t)&&this.context.time.time-this._pointerDownTime[t]>this._longPressTimeThreshold}getIsMouse(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="mouse"}getIsTouch(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="touch"}getTouchesPressedCount(){let t=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&this.getIsTouch(e)&&t++;return t}getMouseWheelChanged(t=0){return t>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[t]}getMouseWheelDeltaY(t=0){return t>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[t]}getPointerEvent(t){if(!(t>=this._pointerEvent.length))return this._pointerEvent[t]??void 0}*foreachPointerId(t){for(let e=0;e<this._pointerTypes.length;e++)if(this._pointerIsActive(e)){if(t!==void 0){const i=this._pointerTypes[e];if(Array.isArray(t)){let n=!1;for(const s of t)if(i===s){n=!0;break}if(!n)continue}else if(t!==i)continue}yield e}}*foreachTouchId(){for(let t=0;t<this._pointerTypes.length;t++)this._pointerTypes[t]==="touch"&&this._pointerIsActive[t]&&(yield t)}_pointerIsActive(t){return t<0?!1:this._pointerPressed[t]||this._pointerDown[t]||this._pointerUp[t]}onDownButton(t,e){let i=this._pressedStack.get(t);i||(i=[],this._pressedStack.set(t,i)),i.push(e)}onReleaseButton(t,e){const i=this._pressedStack.get(t);if(!i)return;const n=i.indexOf(e);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(t){const e=this._pressedStack.get(t);if(e)return e[0]}getLatestPressedButtonForPointer(t){const e=this._pressedStack.get(t);if(e)return e[e.length-1]}getKeyDown(t){if(t!==void 0)return this.isKeyDown(t);for(const e in this.keysPressed){const i=this.keysPressed[e];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(t){if(t!==void 0)return this.isKeyPressed(t);for(const e in this.keysPressed){const i=this.keysPressed[e];if(i.pressed)return i.key}return null}getKeyUp(t){if(t!==void 0)return this.isKeyUp(t);for(const e in this.keysPressed){const i=this.keysPressed[e];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[t];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[t];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[t];return i&&i.pressed||!1}getCodeForCommonKeyName(t){if(t.length===1){if(t>="0"&&t<="9")return["Digit"+t];if(t>="a"&&t<="z")return["Key"+t.toUpperCase()];if(t==" ")return["Space"]}switch(t){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(t){switch(t.type){case"pointerdown":et&&Ee("Create Pointer down"),this.onDownButton(t.deviceIndex,t.button),this.onDown(t);break;case"pointermove":et&&Ee("Create Pointer move"),this.onMove(t);break;case"pointerup":et&&Ee("Create Pointer up"),this.onUp(t),this.onReleaseButton(t.deviceIndex,t.button);break}}convertScreenspaceToRaycastSpace(t){return t.x=(t.x-this.context.domX)/this.context.domWidth*2-1,t.y=-((t.y-this.context.domY)/this.context.domHeight)*2+1,t}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var t,e;for(const i in this._eventListeners)this._eventListeners[i].length=0;window.removeEventListener("contextmenu",this.onContextMenu),(t=this._htmlEventSource)==null||t.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),(e=this._htmlEventSource)==null||e.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const t=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);t>=0&&this.context.post_render_callbacks.splice(t,1),this.unbindEvents()}canReceiveInput(t){var e;return t.target===((e=this.context.renderer)==null?void 0:e.domElement)||t.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&t.target===document.body&&exports.DeviceUtilities.isMozillaXR()?!0:(et&&console.warn("CanReceiveInput:False for",t.target),!1)}getPointerId(t,e){return t.pointerType==="mouse"?0+(e??t.button):this.getPointerIndex(t.pointerId)}getButtonName(t){const e=t.button;if(t.pointerType==="mouse")switch(e){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(t,e,i){let n=this._pointerSpace[t];n||(n=new d.Object3D,this._pointerSpace[t]=n),this._pointerSpace[t]=n;const s=this.context.mainCamera;if(s){const a=this.tempNearPlaneVector.set(e,i,-1);this.convertScreenspaceToRaycastSpace(a);const l=this.tempFarPlaneVector.set(a.x,a.y,1);a.unproject(s),l.unproject(s);const c=s.worldUp||V(0,1,0).applyQuaternion(_e(s));this.tempLookMatrix.lookAt(l,a,c),n.position.set(a.x,a.y,a.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(t){if(this.context.isInXR)return!0;const e=this.context.domElement.getBoundingClientRect(),i=t.clientX,n=t.clientY,s=i>=e.x&&i<=e.right&&n>=e.y&&n<=e.bottom;return et&&!s&&console.log("Not in rect",e,i,n),s}onDown(t){const e=t.pointerId;if(this.getPointerPressed(e)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${e}`,et?t:""),et&&console.log(t.pointerType,"DOWN",e),!!this.isInRect(t)){for(this.setPointerState(e,this._pointerPressed,!0),this.setPointerState(e,this._pointerDown,!0),this.setPointerStateT(e,this._pointerEvent,t.source);e>=this._pointerTypes.length;)this._pointerTypes.push(t.pointerType);for(this._pointerTypes[e]=t.pointerType;e>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new d.Vector3);for(this._pointerPositionDown[e].set(t.clientX,t.clientY,t.clientZ??0);e>=this._pointerPositions.length;)this._pointerPositions.push(new d.Vector2);this._pointerPositions[e].set(t.clientX,t.clientY),e>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(t),this._pointerEventsPressed.push(t),this.onDispatchEvent(t)}}onMove(t){const e=t.pointerId,i=this.getPointerPressed(e);i===!1&&!this.isInRect(t)||t.pointerType==="touch"&&!i||(this.updatePointerPosition(t),this.setPointerStateT(e,this._pointerEvent,t.source),this.onDispatchEvent(t))}onUp(t){const e=t.pointerId;if(!this.getPointerPressed(e)){et&&console.log(t.pointerType,"UP",e,"was not down");return}et&&console.log(t.pointerType,"UP",e),this.setPointerState(e,this._pointerPressed,!1),this.setPointerStateT(e,this._pointerEvent,t.source),this.setPointerState(e,this._pointerUp,!0),this.updatePointerPosition(t);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===e){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[e]){et&&me("Received pointer up event without matching down event for button: "+e),console.warn("Received pointer up event without matching down event for button: "+e);return}const n=this._pointerUpTime[e],s=this._pointerDownTime[e],a=this.context.time.realtimeSinceStartup,l=a-s;if(e>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[e]=a,l<1){let c=t.clientX-this._pointerPositionDown[e].x,h=t.clientY-this._pointerPositionDown[e].y,u=0;if(t.isSpatial&&t.clientZ!=null&&(u=t.clientZ-this._pointerPositionDown[e].z,c*=200,h*=200,u*=200),Math.abs(c)<5&&Math.abs(h)<5&&Math.abs(u)<5){this.setPointerState(e,this._pointerClick,!0),t.isClick=!0;const f=a-n;et&&console.log("CLICK",e,c,h,u,f),f<this._doubleClickTimeThreshold&&f>0&&(this.setPointerState(e,this._pointerDoubleClick,!0),t.isDoubleClick=!0)}}this.onDispatchEvent(t)}updatePointerPosition(t){const e=t.pointerId;for(;e>=this._pointerPositions.length;)this._pointerPositions.push(new d.Vector2);for(;e>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new d.Vector2);for(;e>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new d.Vector2);const i=this._pointerPositionsLastFrame[e];i.copy(this._pointerPositions[e]);const n=this._pointerPositionsDelta[e];let s=t.clientX-i.x,a=t.clientY-i.y;if(t.source instanceof MouseEvent||t.source instanceof TouchEvent){const u=t.source;s===0&&u.movementX!==0&&(s=u.movementX||0),a===0&&u.movementY!==0&&(a=u.movementY||0)}n.x+=s,n.y+=a,this._pointerPositions[e].x=t.clientX,this._pointerPositions[e].y=t.clientY;const l=t.clientX,c=t.clientY;for(;e>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new d.Vector2);const h=this._pointerPositionsRC[e];h.set(l,c),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(t){let e=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===t)return i;e===-1&&this._pointerIds[i]===-1&&(e=i)}return e!==-1?(this._pointerIds[e]=t,e):(et&&console.log("PUSH pointerId:",t),this._pointerIds.push(t),this._pointerIds.length-1)}setPointerState(t,e,i){e[t]=i}setPointerStateT(t,e,i){return e[t]=i,i}onDispatchEvent(t){const e=X.Current;try{X.Current=this.context,this.dispatchEvent(t)}finally{X.Current=e}}}const Aa=new d.Matrix4().makeRotationY(Math.PI),Ni=new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI),gC=S("debugwebxr");class yC{constructor(){r(this,"priority",-1e5);r(this,"gameObject");if(this.gameObject=new d.Object3D,this.gameObject.name="Implicit XR Rig",gC){const t=dg(16733661);t.position.y+=.5,this.gameObject.add(t)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const hs=S("debugwebxr"),Jh=S("debugcustomgesture"),_C="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",bC="generic-trigger",vC=new d.Quaternion().setFromEuler(new d.Euler(d.MathUtils.degToRad(0),d.MathUtils.degToRad(-90),d.MathUtils.degToRad(-90))),wC=new d.Vector3(.04,-.04,0);class og{constructor(t,e,i){r(this,"xr");r(this,"inputSource");r(this,"index",0);r(this,"emitEvents",!0);r(this,"_connected",!0);r(this,"_isTracking",!1);r(this,"__gamepad");r(this,"__hand");r(this,"__side");r(this,"_hitTestSource");r(this,"_hasSelectEvent",!1);r(this,"_isMxInk",!1);r(this,"_isMetaQuestTouchController",!1);r(this,"_handJointPoses",new Map);r(this,"_gripMatrix",new d.Matrix4);r(this,"_gripPosition",new d.Vector3);r(this,"_gripQuaternion",new d.Quaternion);r(this,"_linearVelocity",new d.Vector3);r(this,"_rayPositionRaw",new d.Vector3);r(this,"_rayRotationRaw",new d.Quaternion);r(this,"_rayMatrix",new d.Matrix4);r(this,"_rayPosition",new d.Vector3);r(this,"_rayQuaternion",new d.Quaternion);r(this,"_gripWorldPosition",new d.Vector3);r(this,"_gripWorldQuaternion",new d.Quaternion);r(this,"_rayWorldPosition",new d.Vector3);r(this,"_rayWorldQuaternion",new d.Quaternion);r(this,"_pinchPosition",new d.Vector3);r(this,"_ray");r(this,"_hand_wristDotUp");r(this,"_object");r(this,"_gripSpaceObject");r(this,"_raySpaceObject");r(this,"model",null);r(this,"_debugAxesHelper",new d.AxesHelper(.15));r(this,"_debugGripAxesHelper",new d.AxesHelper(.07));r(this,"_debugRayAxesHelper",new d.AxesHelper(.07));r(this,"_hitTestSourcePromise",null);r(this,"onPointerHits",t=>{});r(this,"_needleGamepadButtons",{});r(this,"_buttonMap",new Map);r(this,"_motioncontroller");r(this,"_layout");r(this,"getMotionController");r(this,"emitPointerDownEvent",!0);r(this,"emitPointerUpEvent",!0);r(this,"emitPointerMoveEvent",!0);r(this,"pointerMoveDistanceThreshold",.03);r(this,"pointerMoveAngleThreshold",.05);r(this,"_selectButtonIndex");r(this,"_squeezeButtonIndex");r(this,"onSelectStart",t=>{var n,s,a,l;if(!this.emitPointerDownEvent||this.inputSource!==t.inputSource)return;this.onUpdateFrame(t.frame),this._hasSelectEvent=!0;const e=(n=this._layout)==null?void 0:n.selectComponentId,i=(l=(a=(s=this._layout)==null?void 0:s.components[e])==null?void 0:a.gamepadIndices)==null?void 0:l.button;i!==void 0&&(this._selectButtonIndex=i),!Jh&&(hs&&$.DrawDirection(this.rayWorldPosition,V(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Re.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,t))});r(this,"onSelectEnd",t=>{this.emitPointerUpEvent&&(Jh||this.inputSource===t.inputSource&&this.emitPointerEvent(Re.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,t))});r(this,"onSequeezeStart",t=>{var e,i,n;this.emitPointerDownEvent&&this.inputSource===t.inputSource&&(this._squeezeButtonIndex=(n=(i=(e=this._layout)==null?void 0:e.components["xr-standard-squeeze"])==null?void 0:i.gamepadIndices)==null?void 0:n.button,this._squeezeButtonIndex!==void 0&&(hs&&$.DrawDirection(this.rayWorldPosition,V(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Re.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,t)))});r(this,"onSequeezeEnd",t=>{this.emitPointerUpEvent&&this.inputSource===t.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Re.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,t)});r(this,"states",{});r(this,"_didMoveLastFrame",!1);r(this,"_lastPointerMovePosition",new d.Vector3);r(this,"_lastPointerMoveQuaternion",new d.Quaternion);r(this,"pointerInit");this.xr=t,this.inputSource=e,this.index=i,this._object=new d.Object3D,this._object.name=`NeedleXRController_${i}`,hs&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new d.Object3D,this._raySpaceObject=new d.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new d.Ray,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.__gamepad??(this.__gamepad=this.inputSource.gamepad)}get isHand(){return this.hand!=null}get hand(){return this.__hand??(this.__hand=this.inputSource.hand)}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??(this.__side=this.inputSource.handedness)}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(t,e){var n;if(e=e||this.xr.frame,!this.hand||!(e!=null&&e.getJointPose)||!this.xr.referenceSpace)return null;let i=(n=this._handJointPoses)==null?void 0:n.get(t);return i||(i=e.getJointPose(t,this.xr.referenceSpace),i&&this._handJointPoses.set(t,i),i)}get gripPosition(){return V(this._gripPosition)}get gripQuaternion(){return un(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return V(this._linearVelocity).applyQuaternion(Ni)}get rayPosition(){return V(this._rayPosition)}get rayQuaternion(){return un(this._rayQuaternion)}get gripWorldPosition(){return V(this._gripWorldPosition)}get gripWorldQuaternion(){return un(this._gripWorldQuaternion)}get rayWorldPosition(){return V(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPositionRaw),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return un(this._rayWorldQuaternion)}get pinchPosition(){return V(this._pinchPosition)}updateRayWorldQuaternion(){var i;const t=(i=this.xr.context.mainCamera)==null?void 0:i.parent,e=t?_e(t):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Ni),e&&this._rayWorldQuaternion.premultiply(e)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(V(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var e;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const t=(e=this.handObject)==null?void 0:e.joints.wrist;if(t){const i=V(0,1,0).applyQuaternion(t.quaternion),n=V(0,1,0).dot(i);return this._hand_wristDotUp=n}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var t;return this.isHandUpsideDown&&((t=this.getGesture("pinch"))==null?void 0:t.isDown)}get object(){return this._object}async getModelUrl(){var t;return(t=this.getMotionController)==null?void 0:t.then(e=>(e==null?void 0:e.assetUrl)||null)}_requestHitTestSource(){var t;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((t=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:t.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null))))??null:null}onUpdate(t){this.onUpdateFrame(t),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var s;$.DrawSphere(this.rayWorldPosition,.003),$.DrawDirection(this.rayWorldPosition,V(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
147
147
  `);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
148
148
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
@@ -163,12 +163,12 @@ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for
163
163
  `+Jt);const s=await Promise.resolve().then(()=>require("./vendor-Cavtu3CP.umd.cjs")).then(f=>f.index),a=((h=s.default)==null?void 0:h.WebsocketBuilder)??s.WebsocketBuilder,l=((u=s.default)==null?void 0:u.ExponentialBackoff)??s.ExponentialBackoff,c=new a(Jt).withMaxRetries(10).withBackoff(new l(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=c,this.connected=!0,j()||ei?console.log(`⊞ Connected to networking backend
164
164
  `+Jt):console.debug("⊞ Connected to networking backend",Jt),n(!0),this.onSendQueued(fn.OnConnection)}).onClose(f=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let p="Websocket connection closed...";Jt!=null&&Jt.includes("/socket")||(p+=' Do you perhaps mean to connect to "/socket"?'),console.error(p)}).onError(f=>{console.error("⊠ Websocket connection failed..."),n(!1)}).onRetry(()=>{console.log("→ Retry connecting to networking websocket")}).build();c.addEventListener(s.WebsocketEvent.message,(f,p)=>{this.onMessage(f,p)})})}onMessage(t,e){const i=e.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const s of n)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(n);return}catch(n){ei&&i==="pong"?console.log("<<",i):j()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(t){td&&console.log("<< bin",this.context.time.frame);const e=await t.arrayBuffer();var i=new Uint8Array(e);const n=new ae.ByteBuffer(i),s=n.getBufferIdentifier(),a=this._listenersBinary[s],l=W0(n),c=G0(l);if(c&&typeof c=="string"&&(this._state[c]=l),!a)return;const h=l??n;for(const u of a)u(h)}handleIncomingStringMessage(t){var n,s;if(ei&&console.log("<<",t.key??t),t.key)switch(t.key){case"connection-start-info":if(t.data){const c=t.data;c&&(console.assert(c.id!==void 0&&c.id!==null&&c.id.length>0,"server did not send connection id",c.id),console.debug("Your id is: "+c.id,this.context.alias??""),this._connectionId=c.id)}else console.warn("Expected connection id in "+t.key);break;case"joined-room":if(ei&&console.log(t),t){this._isInRoom=!0;const c=t;this._currentRoomName=c.room,this._currentRoomViewId=c.viewId,this._currentRoomAllowEditing=c.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...c.inRoom),(td||j())&&console.debug("Joined Needle Engine Room: "+c.room);const h=new URL(window.location.href);h.searchParams.has("room")&&h.searchParams.delete("room"),h.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
165
165
  ${h.href}`)}this.onSendQueued(fn.OnRoomJoin);break;case"left-room":const a=t;a.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(td||j())&&console.debug("Left Needle Engine Room: "+a.room));break;case"user-joined-room":if(t.data){const c=t.data;this._currentInRoom.push(c.userId),ei&&console.log(c.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(t.data){const c=t.data,h=this._currentInRoom.indexOf(c.userId);h>=0&&(ei&&console.log(c.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(h,1)),c.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":ei&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const l=(n=t.data)==null?void 0:n.time;l&&(this._currentDelay=this.context.time.time-l),ei&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+((s=this._currentInRoom)==null?void 0:s.length));break}const e=t.data;e&&(this._state[e.guid]=e);let i=this._listeners[t.key];if(i){i=[...i];for(const a of i)try{a(t.data)}catch(l){console.error('Error invoking callback for "'+t.key+'"',l)}}}toMessage(t,e){return{key:t,data:e}}sendWithWebsocket(t,e,i=fn.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[i]||[];s.push(()=>this.sendWithWebsocket(t,e,i)),this._waitingForSocket[i]=s;return}const n=JSON.stringify(this.toMessage(t,e));ei&&console.log(">>",t),this._ws.send(n)}onSendQueued(t){const e=this._waitingForSocket[t];if(e){for(const i of e)i();e.length=0}}}const hc=S("debugwebxr");class Xf{constructor(t,e){r(this,"controllerStates",[]);r(this,"userId");r(this,"context");r(this,"userStateEvtName");r(this,"onReceivedControllerState",t=>{hc&&console.log(`XRSync: Received change for ${this.userId}: ${t.type} ${t.handedness}; tracked=${t.isTracking}`);let e=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===t.index){this.controllerStates[i]=t,e=!0;break}e||this.controllerStates.push(t)});this.userId=t,this.context=e,this.userStateEvtName="xr-sync-user-state-"+t,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(t){if(this.context.connection.isConnected!=!1){for(let e=this.controllerStates.length-1;e>=0;e--){const i=this.controllerStates[e];let n=!1;for(let s=0;s<t.controllers.length;s++)t.controllers[s].index===i.index&&(n=!0);n||(hc&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(e,1),this.sendControllerRemoved(i))}for(const e of t.controllers)this.updateControllerStates(e)}}onExitXR(t){for(const e of this.controllerStates)this.sendControllerRemoved(e);this.controllerStates.length=0}sendControllerRemoved(t){t.isTracking=!1,t.guid="",this.context.connection.send(this.userStateEvtName,t),this.context.connection.sendDeleteRemoteState(t.guid)}updateControllerStates(t){const e=this.controllerStates.find(i=>i.index===t.index);if(e){let i=!1;i||(i=e.isTracking!=t.isTracking),i&&(e.isTracking=t.isTracking,this.context.connection.send(this.userStateEvtName,e))}else{const i={guid:this.userId+"-"+t.index,isTracking:t.isTracking,handedness:t.side,index:t.index,type:t.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),hc&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class K0{constructor(t){r(this,"context");r(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(hc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Xf(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new Xf(t,this.context))}});r(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t==null||t.dispose(),this._states.delete(this.context.connection.connectionId)}});r(this,"onOtherUserJoinedRoom",t=>{const e=t.userId;this._states.has(e)||(hc&&console.log("XRSync: Remote user joined room",e),this._states.set(e,new Xf(e,this.context)))});r(this,"onOtherUserLeftRoom",t=>{const e=t.userId;if(!this._states.has(e)){const i=this._states.get(e);i==null||i.dispose(),this._states.delete(e)}});r(this,"_states",new Map);this.context=t,this.context.connection.beginListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ee.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ee.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ee.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(t){return t?this._states.has(t):!1}isTracking(t,e){if(!t)return;const i=this._states.get(t);if(!i)return;const n=i.controllerStates.find(s=>s.handedness===e);return(n==null?void 0:n.isTracking)||!1}getDeviceType(t,e){if(!t)return;const i=this._states.get(t);if(!i)return;const n=i.controllerStates.find(s=>s.handedness===e);return(n==null?void 0:n.type)||"unknown"}destroy(){this.context.connection.stopListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ee.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ee.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ee.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(t){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e==null||e.update(t)}}onExitXR(t){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e==null||e.onExitXR(t)}}}class P_{constructor(){r(this,"_fadeToColorQuad");r(this,"_fadeToColorMaterial");r(this,"_requestedFadeValue",0);r(this,"_transitionPromise",null);r(this,"_transitionResolve",null);this._fadeToColorMaterial=new d.MeshBasicMaterial({color:0,transparent:!0,depthTest:!1,fog:!1,side:d.DoubleSide}),this._fadeToColorQuad=new d.Mesh(new d.PlaneGeometry(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(t,e){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==t&&n.opacity>0?t.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const s=this._requestedFadeValue;n.opacity=z.lerp(n.opacity,s,e/.03),Math.abs(n.opacity-s)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const t=new Promise(e=>{this._transitionResolve=e});return this._transitionPromise=t,t}}var Or=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(Or||{}),Qc,om;class Lo{static createText(t,e){let i=null;const n=(e==null?void 0:e.font)||EC((e==null?void 0:e.familyFamily)||null);n instanceof H.Font?i=Ol(this,Qc,om).call(this,t,n,e):i==null&&(i=new d.BufferGeometry);const s=(e==null?void 0:e.color)||16777215,a=new d.Mesh(i,(e==null?void 0:e.material)??new d.MeshStandardMaterial({color:s}));return this.applyDefaultObjectOptions(a,e),n instanceof Promise?n.then(l=>{a.geometry=Ol(this,Qc,om).call(this,t,l,e),e!=null&&e.onGeometry&&e.onGeometry(a)}):e!=null&&e.onGeometry&&e.onGeometry(a),a}static createOccluder(t){const e=new d.MeshBasicMaterial({colorWrite:!1,depthWrite:!0,side:d.DoubleSide});return this.createPrimitive(t,{material:e})}static createPrimitive(t,e){let i;const n=(e==null?void 0:e.color)||16777215;switch(t){case"Quad":case 0:{const s=new d.PlaneGeometry(1,1,1,1),a=(e==null?void 0:e.material)??new d.MeshStandardMaterial({color:n});e!=null&&e.texture&&"map"in a&&(a.map=e.texture),i=new d.Mesh(s,a),i.name="Quad"}break;case"Cube":case 1:{const s=new d.BoxGeometry(1,1,1),a=(e==null?void 0:e.material)??new d.MeshStandardMaterial({color:n});e!=null&&e.texture&&"map"in a&&(a.map=e.texture),i=new d.Mesh(s,a),i.name="Cube"}break;case 10:case"RoundedCube":{const s=RC(1,1,1,.1,2),a=(e==null?void 0:e.material)??new d.MeshStandardMaterial({color:n});e!=null&&e.texture&&"map"in a&&(a.map=e.texture),i=new d.Mesh(s,a),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new d.SphereGeometry(.5,16,16),a=(e==null?void 0:e.material)??new d.MeshStandardMaterial({color:n});e!=null&&e.texture&&"map"in a&&(a.map=e.texture),i=new d.Mesh(s,a),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new d.CylinderGeometry(.5,.5,1,32),a=(e==null?void 0:e.material)??new d.MeshStandardMaterial({color:n});e!=null&&e.texture&&"map"in a&&(a.map=e.texture),i=new d.Mesh(s,a),i.name="Cylinder"}break;case"ShaderBall":i=new d.Group,i.name="ShaderBall",TC(i,e);break}return this.applyDefaultObjectOptions(i,e),i}static createSprite(t){const i=new d.SpriteMaterial({color:16777215});t!=null&&t.texture&&"map"in i&&(i.map=t.texture);const n=new d.Sprite(i);return this.applyDefaultObjectOptions(n,t),n}static applyDefaultObjectOptions(t,e){t.receiveShadow=!0,t.castShadow=!0,e!=null&&e.name&&(t.name=e.name),e!=null&&e.position&&(Array.isArray(e.position)?t.position.set(e.position[0],e.position[1],e.position[2]):t.position.set(e.position.x,e.position.y,e.position.z)),e!=null&&e.rotation&&(Array.isArray(e.rotation)?t.rotation.set(e.rotation[0],e.rotation[1],e.rotation[2]):t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z)),e!=null&&e.scale&&(typeof e.scale=="number"?t.scale.set(e.scale,e.scale,e.scale):Array.isArray(e.scale)?t.scale.set(e.scale[0],e.scale[1],e.scale[2]):t.scale.set(e.scale.x,e.scale.y,e.scale.z)),(e==null?void 0:e.receiveShadow)!=null&&(t.receiveShadow=e.receiveShadow),(e==null?void 0:e.castShadow)!=null&&(t.castShadow=e.castShadow),e!=null&&e.parent&&e.parent.add(t)}}Qc=new WeakSet,om=function(t,e,i){const n=(i==null?void 0:i.depth)||.1;return new H.TextGeometry(t,{font:e,size:1,depth:n,height:n,bevelEnabled:(i==null?void 0:i.bevel)||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})},on(Lo,Qc);function RC(o,t,e,i,n){const s=new d.Shape,a=1e-5,l=i-a;s.absarc(a,a,a,-Math.PI/2,-Math.PI,!0),s.absarc(a,t-l*2,a,Math.PI,Math.PI/2,!0),s.absarc(o-l*2,t-l*2,a,Math.PI/2,0,!0),s.absarc(o-l*2,a,a,0,-Math.PI/2,!0);const c=new d.ExtrudeGeometry(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:l,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(h,u)=>{const f=[];for(let p=0;p<u.length;p+=3)f.push(new d.Vector2(u[p]/o,u[p+1]/t));return f},generateSideWallUV:(h,u,f,p,g,y)=>{const b=[];return b.push(new d.Vector2(u[f]/o,u[f+1]/t)),b.push(new d.Vector2(u[p]/o,u[p+1]/t)),b.push(new d.Vector2(u[g]/o,u[g+1]/t)),b.push(new d.Vector2(u[y]/o,u[y+1]/t)),b}}});return c.scale(1,1,1-i),c.center(),c.index||c.setIndex(Array.from({length:c.attributes.position.count},(h,u)=>u)),c.computeVertexNormals(),c}const id=new Map;function EC(o){let t="";switch(o){default:case"OpenSans":t="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":t="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(id.has(t)){const n=id.get(t);if(n)return n}const e=new H.FontLoader,i=new Promise((n,s)=>{e.load(t,a=>{id.set(t,a),n(a)},void 0,s)});return id.set(t,i),i}let Qf=!1,Yf=null;function TC(o,t){if(Yf===null){const e="https://cdn.needle.tools/static/models/shaderball.glb",i=new H.GLTFLoader,n=le.createLoaders(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),Qf=!0,Yf=i.loadAsync(e).then(s=>{const a=s.scene;return a.position.y-=.5,a}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),O_())).finally(()=>{Qf=!1})}if(Qf){const e=O_();e.name="ShaderBall-Placeholder";const i=e.children[0];(i==null?void 0:i.type)==="Mesh"&&M_(i,t),o.add(e)}Yf.then(e=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=e.clone(),n=i.children[0];(n==null?void 0:n.type)==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),M_(n,t)),o.add(i)})}function M_(o,t){var i;if((t==null?void 0:t.color)||(t==null?void 0:t.material)||(t==null?void 0:t.texture)){const n=(t==null?void 0:t.material)??((i=o.material)==null?void 0:i.clone())??new d.MeshStandardMaterial;t.color&&"color"in n&&n.color instanceof d.Color&&n.color.set(t.color),t!=null&&t.texture&&"map"in n&&(n.map=t.texture),o.material=n}}function O_(){return new d.Group().add(Lo.createPrimitive("Sphere",{material:new d.MeshBasicMaterial({transparent:!0,opacity:.1})}))}const wc=class wc{constructor(t,e,i){r(this,"_session");r(this,"_mode");r(this,"_init");r(this,"_renderer");r(this,"_camera");r(this,"_scene");r(this,"onEnd",()=>{var t;(t=this._session)==null||t.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()});r(this,"_lastTime",0);r(this,"onFrame",(t,e)=>{const i=t-this._lastTime;this.update(t,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)});r(this,"_objects",[]);this._mode=t,this._init=e,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new d.WebGLRenderer({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new d.PerspectiveCamera,this._scene=new d.Scene,this._scene.fog=new d.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(t,e){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!e)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(t,e);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new wc(t,e,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await Jn(100)),this._active=null}get isAR(){return this._mode==="immersive-ar"}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const t={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,t}async onBeforeHandoff(){await Jn(1e3),this._scene.clear()}setupScene(){this._scene.background=new d.Color(0),this._scene.add(new d.GridHelper(5,10,1118481,1118481));const t=new d.DirectionalLight(16777215,1);t.position.set(0,20,0),t.castShadow=!1,this._scene.add(t);const e=new d.DirectionalLight(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const i=new d.PointLight(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let s=0;s<100;s++){const a=new d.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8});this.isAR&&(a.emissive=new d.Color(Math.random(),Math.random(),Math.random()),a.emissiveIntensity=Math.random());const l=z.random(0,1)>.5?Or.Sphere:Or.Cube,c=Lo.createPrimitive(l,{material:a});c.position.x=z.random(-n,n),c.position.y=z.random(-2,n),c.position.z=z.random(-n,n),c.rotation.x=z.random(0,Math.PI*2),c.rotation.y=z.random(0,Math.PI*2),c.rotation.z=z.random(0,Math.PI*2),c.scale.multiplyScalar(.5+Math.random()*10);const h=c.position.distanceTo(this._camera.position)-c.scale.x;h<1&&c.position.multiplyScalar(1+1/h),this._objects.push(c),this._scene.add(c)}}update(t,e){const i=t*4e-4;for(let n=0;n<this._objects.length;n++){const s=this._objects[n];s.position.y+=Math.sin(i+n*.5)*.005,s.rotateY(.002)}}};r(wc,"_active",null),r(wc,"_requestInFlight",!1);let Wa=wc;var Rc;(o=>{const t=[];function e(){if(!(t!=null&&t.length))return!1;for(const s of t)s.exportAndOpen();return!0}o.exportAndOpen=e;function i(s){t.push(s)}o.registerExporter=i;function n(s){if(!t)return;const a=t.indexOf(s);a>=0&&t.splice(a,1)}o.unregisterExporter=n})(Rc||(Rc={}));const He=S("debugwebxr"),k_=S("stats");let Kf=0;function AC(o){let t=null;const e=o;return e.getAROverlayContainer?t=e.getAROverlayContainer():t=o,t}LC();async function LC(){var o;if(S("debugasap")){let t=globalThis["needle:XRSession"];if(t instanceof Promise){delete globalThis["needle:XRSession"],re.addContextCreatedCallback(async e=>{if(!t)return;_r(!0);const i=await t;if(i){const n=J.getDefaultSessionInit("immersive-vr");J.setSession("immersive-vr",i,n,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");t=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(o=navigator.xr)==null||o.addEventListener("sessiongranted",async()=>{_r(!0),console.log("Received Session Granted..."),await Jn(100);const t=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,i=e?JSON.parse(e):null;let n=null;if(Z0()&&(await Wa.start(t||"immersive-vr",i||J.getDefaultSessionInit("immersive-vr")),await jC(),n=await Wa.handoff()),n)J.setSession(n.mode,n.session,n.init,X.Current);else if(t&&e){console.log("Session Granted: Restore last session");const s=JSON.parse(e);J.start(t,s).catch(a=>console.warn(a))}else J.start("immersive-vr").catch(s=>console.warn("Session Granted failed:",s))},{once:!0})}}function DC(o,t){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(t))}function IC(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const hg=new Set;re.registerCallback(he.ContextCreationStart,async o=>{hg.add(o.context)});re.registerCallback(he.ContextCreated,async o=>{var e;hg.delete(o.context);const t=((e=o.context)==null?void 0:e.domElement.getAttribute("autostart"))||null;BC(t)});function Z0(){return hg.size>0}function jC(){return new Promise(o=>{const t=Date.now(),e=setInterval(()=>{(!Z0()||Date.now()-t>6e4)&&(clearInterval(e),o())},100)})}exports.DeviceUtilities.isDesktop()&&j()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&J.active&&J.stop()});function BC(o){if(o)switch(o==null?void 0:o.toLowerCase()){case"ar":vn.registerWaitForInteraction(()=>{J.start("ar")});break}}const $e=class $e{constructor(t,e,i,n){r(this,"context");r(this,"session");r(this,"mode");r(this,"controllers",[]);r(this,"_rigScale",1);r(this,"_lastRigScaleUpdate",-1);r(this,"_rigs",[]);r(this,"_viewerHitTestSource",null);r(this,"_defaultRig");r(this,"_xr_scripts");r(this,"_xr_update_scripts",[]);r(this,"_inactive_scripts",[]);r(this,"_controllerAdded");r(this,"_controllerRemoved");r(this,"_originalCameraWorldPosition");r(this,"_originalCameraWorldRotation");r(this,"_originalCameraWorldScale");r(this,"_originalCameraParent");r(this,"_mainCamera",null);r(this,"onRendererSessionSet",()=>{var t;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(t=this.context.mainCameraComponent)==null||t.applyClearFlags())});r(this,"onInputSourceAdded",t=>{if(t.targetRayMode==="screen")return;let e=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===t){e=n;break}if(this.controllers.find(n=>n.inputSource===t)){console.debug("Controller already exists for input source",e);return}else if(this._newControllers.find(n=>n.inputSource===t)){console.debug("Controller already registered for input source",e);return}const i=new og(this,t,e);this._newControllers.push(i)});r(this,"_ended",!1);r(this,"_newControllers",[]);r(this,"onEnd",t=>{var s,a,l;if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),IC(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,Ao(this.onBefore,we.LateUpdate);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);e>=0&&this.context.pre_render_callbacks.splice(e,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var c,h;(c=this.context.mainCameraComponent)==null||c.applyClearFlags(),(h=this.context.mainCameraComponent)==null||h.applyClippingPlane()}),N0({session:this});for(const c of $e._xrEndListeners)c({xr:this});const n=[...this.controllers];for(let c=0;c<n.length;c++)this.disconnectInputSource(n[c].inputSource);this._newControllers.length=0,this.controllers.length=0;for(const c of this._xr_scripts)(s=c==null?void 0:c.onLeaveXR)==null||s.call(c,{xr:this});(a=this.sync)==null||a.onExitXR(this),this.context.mainCamera&&((l=this._originalCameraParent)==null||l.add(this.context.mainCamera),this._originalCameraWorldPosition&&st(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Hi(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Na(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),_r(!1)});r(this,"_didStart",!1);r(this,"onBefore",t=>{var n,s,a,l,c,h,u,f;const e=t.xrFrame;if(!e)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((n=this.rig)==null?void 0:n.isActive)==!1&&(He&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&((s=this._mainCamera)!=null&&s.gameObject)&&((l=(a=this._mainCamera)==null?void 0:a.gameObject)==null?void 0:l.parent)!==this.rig.gameObject&&this.rig.gameObject.add((c=this._mainCamera)==null?void 0:c.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const p=[...this.context.new_scripts_xr];for(let g=0;g<p.length;g++){const y=this.context.new_scripts_xr[g];if(!y||y.destroyed||((h=y.supportsXR)==null?void 0:h.call(y,this.mode))==!1){this.context.new_scripts_xr.splice(g,1);continue}if(!y.activeAndEnabled){this.context.new_scripts_xr.splice(g,1),this.markInactive(y);continue}if(this.addScript(y)){this.invokeCallback_EnterXR(y);for(const b of this.controllers)this.invokeCallback_ControllerAdded(y,b)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const g=ci(this.context.scene.children);if(g){const y=g.getSize(V());if(y.length()>0){const b=this._defaultRig.gameObject;b.position.set(g.min.x+y.x*.5,g.min.y,g.max.z+y.z*.5+1.5);const _=g.getCenter(V());_.y=b.position.y,b.lookAt(_)}}}z0({session:this}),Dr();for(const g of $e._xrStartListeners)g(i);const p=[...this._xr_scripts];He&&console.log("NeedleXRSession start, handle scripts:",p);for(const g of p){if(g.destroyed){this._script_to_remove.push(g);continue}if(!g.activeAndEnabled){this.markInactive(g);continue}this.invokeCallback_EnterXR(g);for(const y of this.controllers)this.invokeCallback_ControllerAdded(g,y)}}this.syncCameraCullingMask();for(const p of this.controllers)p.onUpdate(e);if(this._newControllers.length>0){const p=[...this._newControllers];this._newControllers.length=0;for(const g of p){if(!g.connected){console.warn("New controller is not connected",g);continue}this.controllers.push(g);for(const y of this._xr_scripts){if(y.destroyed){this._script_to_remove.push(y);continue}y.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(y,g)}}this.controllers.sort((g,y)=>g.index-y.index)}He&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(_r(!0),console.error("XRControllers are not added but inputSources are present"));for(const p of this._xr_update_scripts){if(p.destroyed===!0){this._script_to_remove.push(p);continue}if(p.activeAndEnabled===!1){this.markInactive(p);continue}p.onUpdateXR&&p.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const p=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const g of p)!g.destroyed&&this.running&&((u=g.onLeaveXR)==null||u.call(g,i)),this.removeScript(g)}(f=this.sync)==null||f.onUpdate(this),this.onRenderDebug()});r(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)});r(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const t=this.context.renderer;if(t.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const e=t.xr.enabled,i=t.getRenderTarget(),n=this.context.scene.background;t.xr.enabled=!1,t.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):t.render(this.context.scene,this.context.mainCamera),t.xr.enabled=e,t.setRenderTarget(i),this.context.scene.background=n}}});r(this,"_script_to_remove",[]);r(this,"_camera");r(this,"_cameraRenderParent",new d.Object3D().rotateY(Math.PI));r(this,"_previousCameraParent");r(this,"_customforward",!0);r(this,"originalCameraNearPlane");r(this,"_viewerPose");r(this,"_transformOrientation",new d.Quaternion);r(this,"_transformPosition",new d.Vector3);r(this,"_transition");var s,a;DC(t,n.init),this.session=e,this.mode=t,this.context=i,(He||S("console"))&&_r(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(l=>typeof l.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,Ls(this.onBefore,we.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((s=n.init.optionalFeatures)!=null&&s.includes("hit-test")||(a=n.init.requiredFeatures)!=null&&a.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(l=>{var c,h;return(h=(c=e.requestHitTestSource)==null?void 0:c.call(e,{space:l}))==null?void 0:h.then(u=>this._viewerHitTestSource=u).catch(u=>console.error(u))}).catch(l=>console.error(l)),this.context.mainCamera&&(this._originalCameraWorldPosition=Q(this.context.mainCamera,new d.Vector3),this._originalCameraWorldRotation=_e(this.context.mainCamera,new d.Quaternion),this._originalCameraWorldScale=Ue(this.context.mainCamera,new d.Vector3),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new yC,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let l=0;l<e.inputSources.length;l++){const c=e.inputSources[l];if(!c.handedness){console.warn("Input source in xr session has no handedness - ignoring",l);continue}this.onInputSourceAdded(c)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",l=>{for(const c of l.removed)this.disconnectInputSource(c);for(const c of l.added)this.onInputSourceAdded(c)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):He&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}static getXRSync(t){return this._sync||(this._sync=new K0(t)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var t;return((t=this._activeSession)==null?void 0:t.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(t=>t.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(t){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(t).catch(i=>(He&&console.error(i),!1)))??Promise.resolve(!1)}static onSessionRequestStart(t){this._sessionRequestStartListeners.push(t)}static offSessionRequestStart(t){const e=this._sessionRequestStartListeners.indexOf(t);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(t){this._sessionRequestEndListeners.push(t)}static offSessionRequestEnd(t){const e=this._sessionRequestEndListeners.indexOf(t);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(t){this._xrStartListeners.push(t)}static offXRSessionStart(t){const e=this._xrStartListeners.indexOf(t);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(t){this._xrEndListeners.push(t)}static offXRSessionEnd(t){const e=this._xrEndListeners.indexOf(t);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(t){this._controllerAddedListeners.push(t)}static offControllerAdded(t){const e=this._controllerAddedListeners.indexOf(t);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(t){this._controllerRemovedListeners.push(t)}static offControllerRemoved(t){const e=this._controllerRemovedListeners.indexOf(t);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(t,e,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+t),e=="default"&&(e=this.getDefaultSessionInit(t)),navigator.xr.offerSession(t,{...e}).then(n=>$e.setSession(t,n,e,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(t){switch(t){case"immersive-ar":const e=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return exports.DeviceUtilities.isVisionOS()||e.push("hand-tracking"),{optionalFeatures:e};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",t),{}}}static async start(t,e,i){var l,c,h,u;if(exports.DeviceUtilities.isiOS()){if(t==="ar")if(await this.isARSupported())t="immersive-ar";else return Rc.exportAndOpen(),null}else t=="ar"&&(t="immersive-ar");if(j()&&S("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Wa.start(t,e||$e.getDefaultSessionInit(t)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(He||j())&&me("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=X.Current),i||(i=re.All[0]),!i)throw new Error("No Needle Engine Context found");switch(e||(e={}),t){case"immersive-ar":{if(await((l=this.xrSystem)==null?void 0:l.isSessionSupported("immersive-ar"))!==!0)return console.error(t+" is not supported by this browser."),null;const p=this.getDefaultSessionInit(t),g=AC(i.domElement);g&&!exports.DeviceUtilities.isQuest()&&(p.domOverlay={root:g},p.optionalFeatures.push("dom-overlay")),e={...p,...e}}break;case"immersive-vr":{if(await((c=this.xrSystem)==null?void 0:c.isSessionSupported("immersive-vr"))!==!0)return console.error(t+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(t),...e}}break;default:console.warn("No default session init for mode",t);break}e.optionalFeatures??(e.optionalFeatures=[]),e.requiredFeatures??(e.requiredFeatures=[]),await Wa.stop();const n=t=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;He?console.log(`%cRequesting ${t} session`,"font-weight:bold;",e,n):console.log(`%cRequesting ${t} session`,"font-weight:bold;");for(const f of n)f.onBeforeXR&&f.onBeforeXR(t,e);for(const f of this._sessionRequestStartListeners)f({mode:t,init:e});He&&Ee("Requesting "+t+" session ("+Date.now()+")"),this._currentSessionRequest=(h=navigator.xr)==null?void 0:h.requestSession(t,e),this._currentSessionRequestMode=t;const s=await((u=this._currentSessionRequest)==null?void 0:u.catch(f=>{console.error(f,"Code: "+f.code),f.code===9&&me("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&me("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const f of this._sessionRequestEndListeners)f({mode:t,init:e,newSession:s||null});return s?this.setSession(t,s,e,i):(console.warn("XR Session request was rejected"),null)}static setSession(t,e,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=t=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new $e(t,e,n,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),e.addEventListener("end",this.onEnd),He?console.log(`%cStarted ${t} session`,"font-weight:bold;",s):console.log(`%cStarted ${t} session`,"font-weight:bold;"),this._activeSession}static stop(){const t=this._activeSession;t&&(t[this.$_stop_request]===void 0?(He&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),t[this.$_stop_request]=setTimeout(()=>{t.end()})):He&&console.warn("[NeedleXRSession] XR Session stop already requested"))}get sync(){return $e._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(t=>t.side==="left")}get rightController(){return this.controllers.find(t=>t.side==="right")}getController(t){return typeof t=="number"?this.controllers[t]||null:this.controllers.find(e=>e.side===t)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(t=>t.inputSource.targetRayMode==="tracked-pointer")||j()&&exports.DeviceUtilities.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const t=this.frame.getImageTrackingResults();for(const e of t)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const t=this._rigs[0]??null;return t!=null&&t.gameObject&&kr(t.gameObject)||(t==null?void 0:t.isActive)===!1?(this.updateActiveXRRig(),this._rigs[0]??null):t}get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(t){this._rigs.indexOf(t)>=0||(t.priority===void 0&&(t.priority=0),this._rigs.push(t),this.updateActiveXRRig())}removeRig(t){const e=this._rigs.indexOf(t);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(t){const e=this._rigs.indexOf(t),i=this._rigs[0];this._rigs.splice(e,1),this._rigs.unshift(t),t.priority=(i==null?void 0:i.priority)??0,this.updateActiveXRRig()}getUserOffsetInRig(){var i;const t=(i=this.context.mainCamera)==null?void 0:i.position;if(!t||!this.rig)return V(0,0,0);const e=V(t);return e.x*=-1,e.z*=-1,e.applyQuaternion(un(this.rig.gameObject.quaternion)),e}updateActiveXRRig(){const t=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let e=this._rigs[0];e&&e.priority===void 0&&(e.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(kr(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!e||e.isActive===!1||n.priority!==void 0&&n.priority>e.priority)&&(e=n)}}if(t!==e){const i=this._rigs.indexOf(e);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(e)}He&&(t===e?console.log("Updated Active XR Rig:",e,"prev:",t):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(t){if(t)return this.getControllerHitTest(t);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,i=this.frame.getHitTestResults(e);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(t){const e=t.getHitTestSource();if(!e)return null;const i=this.frame.getHitTestResultsForTransientInput(e);for(const n of i)if(n.inputSource===t.inputSource)for(const s of n.results)return this.convertHitTestResult(s);return null}convertHitTestResult(t){const e=this.context.renderer.xr.getReferenceSpace(),i=e&&t.getPose(e);if(i){const n=V(i.transform.position),s=un(i.transform.orientation),a=this.context.mainCamera;if((a==null?void 0:a.parent)!==this._cameraRenderParent&&n.applyMatrix4(Aa),a!=null&&a.parent){n.applyMatrix4(a.parent.matrixWorld),s.multiply(Ni);const l=_e(a.parent);l.premultiply(Ni),s.premultiply(l)}return{hit:t,position:n,quaternion:s}}return null}convertSpace(t){const e=V(t.position);e.applyMatrix4(Aa);const i=un(t.orientation);return i.premultiply(Ni),{position:e,quaternion:i}}disconnectInputSource(t){const e=(i,n,s)=>{if(i.inputSource===t){He&&console.log("Disconnecting controller",i.index),this.controllers.splice(s,1),this.invokeControllerEvent(i,this._controllerRemoved,"removed");const a={xr:this,controller:i,change:"removed"};for(const l of this._xr_scripts)l.onXRControllerRemoved&&l.onXRControllerRemoved(a);i.onDisconnected()}};for(let i=this.controllers.length-1;i>=0;i--){const n=this.controllers[i];e(n,this.controllers,i)}for(let i=this._newControllers.length-1;i>=0;i--){const n=this._newControllers[i];e(n,this._newControllers,i)}}end(){this._ended||this.session.end().catch(t=>console.warn(t))}onRenderDebug(){if(He)for(const t of this.controllers)t.onRenderDebug();if((He||k_)&&this.rig&&(Kf++,Kf>=20)){const t=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;t.add(e.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;t.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,He||k_)for(const s of this.controllers)n+=`
166
- ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking} hts:${s.hasHitTestSource?"yes":"no"}`;Kf=0,$.DrawLabel(t,n,void 0,1/60*20)}}addScript(t){return this._xr_scripts.includes(t)?!1:(He&&console.log("Register new XRScript",t),this._xr_scripts.push(t),typeof t.onUpdateXR=="function"&&this._xr_update_scripts.push(t),!0)}markInactive(t){if(!(this._inactive_scripts.indexOf(t)>=0)){this.removeScript(t,!1),this._inactive_scripts.push(t);for(const e of this.controllers)this.invokeCallback_ControllerRemoved(t,e);this.invokeCallback_LeaveXR(t)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let t=this._inactive_scripts.length-1;t>=0;t--){const e=this._inactive_scripts[t];if(e.activeAndEnabled){this._inactive_scripts.splice(t,1),this.addScript(e),this.invokeCallback_EnterXR(e);for(const i of this.controllers)this.invokeCallback_ControllerAdded(e,i)}}}removeScript(t,e=!0){He&&console.log("Remove XRScript",t);const i=this._xr_scripts.indexOf(t);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(t);if(n>=0&&this._xr_update_scripts.splice(n,1),e){const s=this._inactive_scripts.indexOf(t);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(t){t.onEnterXR&&t.onEnterXR({xr:this})}invokeCallback_ControllerAdded(t,e){t.onXRControllerAdded&&t.onXRControllerAdded({xr:this,controller:e,change:"added"})}invokeCallback_ControllerRemoved(t,e){t.onXRControllerRemoved&&t.onXRControllerRemoved({xr:this,controller:e,change:"removed"})}invokeCallback_LeaveXR(t){t.onLeaveXR&&!t.destroyed&&t.onLeaveXR({xr:this})}syncCameraCullingMask(){var i;const t=this.context.xrCamera,e=(i=this.context.mainCameraComponent)==null?void 0:i.cullingMask;if(t&&e!==void 0){for(const n of t.cameras)n.layers.mask=e;t.layers.mask=e}else if(t){for(const n of t.cameras)n.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(t,e,i){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s)try{s({xr:this,controller:t,change:i})}catch(a){console.error(a)}}}applyCustomForward(){var t;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(t=this._previousCameraParent)==null||t.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const i=Ue(this.rig.gameObject);e*=i.x}this._camera instanceof d.PerspectiveCamera&&this._camera.near>e&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=e)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof d.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const t=this.context.renderer.xr.getReferenceSpace();if(!t){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(t),this._viewerPose){const e=this._viewerPose.transform;this._transformPosition.set(e.position.x,e.position.y,e.position.z),this._transformOrientation.set(e.orientation.x,e.orientation.y,e.orientation.z,e.orientation.w)}}get transition(){return this._transition||(this._transition=new P_),this._transition}fadeTransition(){return this._transition||(this._transition=new P_),this._transition.fadeTransition()}updateFade(t){this._transition&&t instanceof d.PerspectiveCamera&&this._transition.update(t,this.context.time.deltaTime)}onUpdateFade_PostRender(){var t;(t=this._transition)==null||t.remove()}};r($e,"_sync",null),r($e,"_currentSessionRequestMode",null),r($e,"_currentSessionRequest"),r($e,"_activeSession"),r($e,"_sessionRequestStartListeners",[]),r($e,"_sessionRequestEndListeners",[]),r($e,"_xrStartListeners",[]),r($e,"_xrEndListeners",[]),r($e,"_controllerAddedListeners",[]),r($e,"_controllerRemovedListeners",[]),r($e,"$_stop_request",Symbol()),r($e,"onEnd",()=>{He&&console.log("XR Session ended"),$e._activeSession=null});let J=$e;const Zf=S("debugwebxr");class J0{static tryFindAvatarObjects(t,e,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=t.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Zf&&console.log("FOUND AVATAR HEAD",t.name),i.head=new te("",e,t)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Zf&&console.log("FOUND AVATAR LEFT HAND",t.name),i.leftHand=new te("",e,t)),!i.rightHand&&n.includes("right")&&(Zf&&console.log("FOUND AVATAR RIGHT HAND",t.name),i.rightHand=new te("",e,t)));for(let s=0;s<t.children.length;s++){if(i.head&&i.leftHand&&i.rightHand)return;const a=t.children[s];this.tryFindAvatarObjects(a,e,i)}}}const Mt=new d.Vector3,R_=new d.Vector3,E_=new d.Quaternion,FC=S("debuggizmos"),an=8947848,Jf=32,ni=class ni{constructor(){}static isGizmo(t){return t[rm]!==void 0}static setVisible(t){for(const e of Pe.timedObjectsBuffer)e.visible=t}static DrawLabel(t,e,i=.05,n=0,s,a,l){var u;if(!ni.enabled)return null;s||(s=an);const c=((u=J.active)==null?void 0:u.rigScale)??1,h=Pe.getTextLabel(n,e,i*c,s,a);return l instanceof d.Object3D&&l.add(h),h.position.x=t.x,h.position.y=t.y,h.position.z=t.z,h}static DrawRay(t,e,i=an,n=0,s=!0){if(!ni.enabled)return;const a=Pe.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,t.x,t.y,t.z),Mt.set(e.x,e.y,e.z).multiplyScalar(999999999),l.setXYZ(1,t.x+Mt.x,t.y+Mt.y,t.z+Mt.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=s,a.material.depthWrite=!1}static DrawDirection(t,e,i=an,n=0,s=!0,a=1){if(!ni.enabled)return;const l=Pe.getLine(n),c=l.geometry.getAttribute("position");c.setXYZ(0,t.x,t.y,t.z),e.w!==void 0?(Mt.set(0,0,-a),E_.set(e.x,e.y,e.z,e.w),Mt.applyQuaternion(E_)):(Mt.set(e.x,e.y,e.z),Mt.multiplyScalar(a)),c.setXYZ(1,t.x+Mt.x,t.y+Mt.y,t.z+Mt.z),c.needsUpdate=!0,l.material.color.set(i),l.material.depthTest=s,l.material.depthWrite=!1}static DrawLine(t,e,i=an,n=0,s=!0){if(!ni.enabled)return;const a=Pe.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,t.x,t.y,t.z),l.setXYZ(1,e.x,e.y,e.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=s,a.material.depthWrite=!1,a.material.fog=!1}static DrawCircle(t,e,i,n=an,s=0,a=!0){if(!ni.enabled)return;const l=Pe.getCircle(s);l.position.set(t.x,t.y,t.z),l.scale.set(i,i,i),l.quaternion.setFromUnitVectors(this._up,Mt.set(e.x,e.y,e.z).normalize()),l.material.color.set(n),l.material.depthTest=a,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireSphere(t,e,i=an,n=0,s=!0){if(!ni.enabled)return;const a=Pe.getSphere(e,n,!0);Pr(a,t.x,t.y,t.z),a.material.color.set(i),a.material.depthTest=s,a.material.depthWrite=!1,a.material.fog=!1}static DrawSphere(t,e,i=an,n=0,s=!0){if(!ni.enabled)return;const a=Pe.getSphere(e,n,!1);Pr(a,t.x,t.y,t.z),a.material.color.set(i),a.material.depthTest=s,a.material.depthWrite=!1}static DrawWireBox(t,e,i=an,n=0,s=!0){if(!ni.enabled)return;const a=Pe.getBox(n);a.position.set(t.x,t.y,t.z),a.scale.set(e.x,e.y,e.z),a.material.color.set(i),a.material.depthTest=s,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireBox3(t,e=an,i=0,n=!0){if(!ni.enabled)return;const s=Pe.getBox(i);s.position.copy(t.getCenter(Mt)),s.scale.copy(t.getSize(Mt)),s.material.color.set(e),s.material.depthTest=n,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1}static DrawArrow(t,e,i=an,n=0,s=!0,a=!1){if(!ni.enabled)return;const l=Pe.getArrowHead(n);l.position.set(e.x,e.y,e.z),l.quaternion.setFromUnitVectors(this._up.set(0,1,0),Mt.set(e.x,e.y,e.z).sub(R_.set(t.x,t.y,t.z)).normalize());const h=Mt.set(e.x,e.y,e.z).sub(R_.set(t.x,t.y,t.z)).length()*.1;l.scale.set(h,h,h),l.material.color.set(i),l.material.depthTest=s,l.material.wireframe=a,this.DrawLine(t,e,i,n,s)}static DrawWireMesh(t){const e=Pe.getMesh(t.duration??0);"mesh"in t?(e.geometry=t.mesh.geometry,e.matrix.copy(t.mesh.matrixWorld)):(e.geometry=t.geometry,e.matrix.copy(t.matrix)),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1,e.material.color.set(t.color??an),e.material.depthTest=t.depthTest??!0,e.material.wireframe=!0}};r(ni,"enabled",!0),r(ni,"_up",new d.Vector3(0,1,0));let $=ni;const UC=new d.BoxGeometry(1,1,1);function dg(o=null){const t=new d.Color(o??14540253),e=new d.EdgesGeometry(UC);return new d.LineSegments(e,new d.LineBasicMaterial({color:t}))}const rm=Symbol("GizmoCache");class Pe{static ensureFont(){let t=ne.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);if(!t){t=ne.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName);const e=t.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");e==null||e.addEventListener("ready",()=>{ne.__webpack_exports__default.update()})}}static getTextLabel(t,e,i,n,s){this.ensureFont();let a=this.textLabelCache.pop(),l=1;s&&typeof s=="string"&&(s==null?void 0:s.length)>=8&&s.startsWith("#")?(l=parseInt(s.substring(7),16)/255,s=s.substring(0,7),FC&&console.log(s,l)):typeof s=="object"&&s.a!==void 0&&(l=s.a);const c={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:s??void 0,backgroundOpacity:l,textContent:e,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(a)a.set(c);else{a=new ne.__webpack_exports__Text(c);const h=this,u=a;u.setText=function(f){this.set({textContent:f}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(X.Current,a,t,this.textLabelCache),a}static getBox(t){let e=this.boxesCache.pop();if(!e){const i=new d.BoxGeometry(1,1,1);e=new d.Mesh(i)}return this.registerTimedObject(X.Current,e,t,this.boxesCache),e}static getLine(t){let e=this.linesCache.pop();if(!e){e=new d.Line;let i=e.geometry.getAttribute("position");i||(i=new d.BufferAttribute(new Float32Array(6),3),e.geometry.setAttribute("position",i))}return e.frustumCulled=!1,this.registerTimedObject(X.Current,e,t,this.linesCache),e}static getCircle(t){let e=this.circlesCache.pop();if(!e){e=new d.Line;let i=e.geometry.getAttribute("position");if(!i){i=new d.BufferAttribute(new Float32Array(Jf*3),3),e.geometry.setAttribute("position",i);const n=V(0,1,0),s=V(0,0,1),a=V(s);a.cross(n).normalize();const l=V(a),c=Math.PI*2/(Jf-1);for(let h=0;h<Jf+1;h++){const u=c*h;n.copy(l).multiplyScalar(Math.cos(u)*1),a.copy(s).multiplyScalar(Math.sin(u)*1);const f=n.add(a);i.setXYZ(h,f.x,f.y,f.z)}}}return e.frustumCulled=!1,this.registerTimedObject(X.Current,e,t,this.circlesCache),e}static getSphere(t,e,i){let n=this.spheresCache.pop();return n||(n=new d.Mesh(new d.SphereGeometry(1,8,8))),n.scale.set(t,t,t),n.material.wireframe=i,this.registerTimedObject(X.Current,n,e,this.spheresCache),n}static getArrowHead(t){let e=this.arrowHeadsCache.pop();return e||(e=new d.Mesh(new d.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(X.Current,e,t,this.arrowHeadsCache),e}static getMesh(t){let e=this.mesh.pop();return e||(e=new d.Mesh,e.material=new d.MeshBasicMaterial),this.registerTimedObject(X.Current,e,t,this.mesh),e}static registerTimedObject(t,e,i,n){if(!t){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const s=this.contextBeforeRenderCallbacks.get(t),a=this.contextPostRenderCallbacks.get(t);if(s){if(t.pre_render_callbacks[t.pre_render_callbacks.length-1]!==s){const l=t.pre_render_callbacks.indexOf(s);l>=0&&t.pre_render_callbacks.splice(l,1),t.pre_render_callbacks.push(s)}}else{const l=()=>{this.onBeforeRender(t,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(t,l),t.pre_render_callbacks.push(l)}if(a){if(t.post_render_callbacks[t.post_render_callbacks.length-1]!==a){const l=t.post_render_callbacks.indexOf(a);l>=0&&t.post_render_callbacks.splice(l,1),t.post_render_callbacks.push(a)}}else{const l=()=>{this.onPostRender(t,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(t,l),t.post_render_callbacks.push(l)}e.traverse(l=>{l.layers.disableAll(),l.layers.enable(2)}),e.renderOrder=999999,e[rm]=n,e.castShadow=!1,e.receiveShadow=!1,e.isGizmo=!0,this.timedObjectsBuffer.push(e),this.timesBuffer.push(X.Current.time.realtimeSinceStartup+i),t.scene.add(e)}static onBeforeRender(t,e){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,ne.__webpack_exports__default.update());for(let i=0;i<e.length;i++){const n=e[i];if(t.mainCamera&&n instanceof ne.__webpack_exports__default.MeshUIBaseElement){if(kr(n))continue;const s=t.isInVR,a=!1,l=!s;th(n,t.mainCamera,a,l)}}}static onPostRender(t,e,i){const n=t.time.realtimeSinceStartup;for(let s=e.length-1;s>=0;s--){const a=e[s];n>=i[s]-1e-6&&(e.splice(s,1),i.splice(s,1),a.removeFromParent(),kr(a)!=!0&&a[rm].push(a))}}}r(Pe,"familyName","needle-gizmos"),r(Pe,"linesCache",[]),r(Pe,"circlesCache",[]),r(Pe,"spheresCache",[]),r(Pe,"boxesCache",[]),r(Pe,"arrowHeadsCache",[]),r(Pe,"mesh",[]),r(Pe,"textLabelCache",[]),r(Pe,"timedObjectsBuffer",new Array),r(Pe,"timesBuffer",new Array),r(Pe,"contextPostRenderCallbacks",new Map),r(Pe,"contextBeforeRenderCallbacks",new Map),r(Pe,"tmuiNeedsUpdate",!1);const Gt=S("debugphysics"),T_=new d.Layers;class Ds{constructor(){r(this,"ray");r(this,"cam");r(this,"screenPoint");r(this,"raycaster");r(this,"results");r(this,"targets");r(this,"recursive",!0);r(this,"minDistance");r(this,"maxDistance");r(this,"lineThreshold");r(this,"layerMask");r(this,"ignore");r(this,"testObject");r(this,"useAcceleratedRaycast");r(this,"allowSlowRaycastFallback",!0)}screenPointFromOffset(t,e){this.screenPoint===void 0&&(this.screenPoint=new d.Vector2),this.screenPoint.x=t/window.innerWidth*2-1,this.screenPoint.y=-(e/window.innerHeight)*2+1}setLayer(t){T_.set(t),this.layerMask=T_}setMask(t){this.layerMask||(this.layerMask=new d.Layers);const e=this.layerMask;e?e.mask=t:this.layerMask=t}}r(Ds,"AllLayers",4294967295);class ug{constructor(t,e,i){r(this,"distance");r(this,"point");r(this,"object");this.object=t,this.distance=e,this.point=i}}const xc=class xc{constructor(t){r(this,"context");r(this,"engine");r(this,"raycaster",new d.Raycaster);r(this,"defaultRaycastOptions",new Ds);r(this,"targetBuffer",new Array(1));r(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}});r(this,"sphereResults",new Array);r(this,"sphereMask",new d.Layers);r(this,"sphere",new d.Sphere);r(this,"tempBoundingBox",new d.Box3);this.context=t}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(t,e=void 0,i=1/0,n=!0){var s;return((s=this.context.physics.engine)==null?void 0:s.raycast(t,e,{maxDistance:i,solid:n}))??null}raycastPhysicsFastAndGetNormal(t,e=void 0,i=1/0,n=!0){var s;return((s=this.context.physics.engine)==null?void 0:s.raycastAndGetNormal(t,e,{maxDistance:i,solid:n}))??null}sphereOverlapPhysics(t,e){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(t,e))??null}sphereOverlap(t,e,i=!0,n=!1,s=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const a=this.sphereMask;a.enableAll(),a.disable(2);for(const l of this.context.scene.children)this.intersectSphere(l,t,e,a,this.sphereResults,i,n,s);return this.sphereResults.sort((l,c)=>l.distance-c.distance)}raycastFromRay(t,e=null){const i=e??this.defaultRaycastOptions;i.ray=t;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(t=null){Gt&&performance.mark("raycast.start"),t||(t=this.defaultRaycastOptions);const e=t.screenPoint??this.context.input.mousePositionRC,i=t.raycaster??this.raycaster;if(i.near=t.minDistance??0,i.far=t.maxDistance??1/0,i.params=this.defaultThresholds,t.lineThreshold===void 0&&(t.lineThreshold=-1),i.params.Line={threshold:t.lineThreshold},t.ray)i.ray.copy(t.ray);else{const l=t.cam??this.context.mainCamera;if(!l)return Gt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const c=this.context.xrCamera;this.context.isInXR&&c instanceof d.ArrayCamera&&c.cameras.length>0?i.setFromCamera(e,c.cameras[0]):i.setFromCamera(e,l)}let n=t.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let s=t.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),t.layerMask!==void 0?t.layerMask instanceof d.Layers?i.layers.mask=t.layerMask.mask:i.layers.mask=t.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Gt&&console.time("raycast"),s.length=0,xc._raycasting++,this.intersect(this.raycaster,n,s,t),s.sort((l,c)=>l.distance-c.distance);const a=t.ignore;return a!==void 0&&a.length>0&&(s=s.filter(l=>!a.includes(l.object))),xc._raycasting--,Gt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",s!=null&&s.length?[...s]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),s}intersect(t,e,i,n){var s,a,l;for(const c of e){if(!c||c.visible===!1||$.isGizmo(c)||n.lineThreshold!==void 0&&n.lineThreshold<0&&c instanceof d.Line)continue;let h=!0;const u=c,f=u.geometry;if(n.testObject){const p=(s=n.testObject)==null?void 0:s.call(n,c);if(p===!1)continue;p==="continue in children"&&(h=!1)}if(h&&(f&&A_(f)||(h=!1)),h){const p=le.getRaycastMesh(c);p&&(u.geometry=p);const g=i.length;let y=!0;if(n.precise===!1&&(y=!1),y||(y=((l=(a=f.getAttribute("position"))==null?void 0:a.array)==null?void 0:l.length)<64),u instanceof H.GroundedSkybox&&(y=!1),!y&&NC(u,t,i)||(n.useAcceleratedRaycast!==!1?Kd.runMeshBVHRaycast(t,u,i,this.context,n):t.intersectObject(u,!1,i)),Gt&&i.length!=g){const b=i[i.length-1],_=p?8969557:7798784;$.DrawWireSphere(b.point,.1,_,1,!1),$.DrawWireMesh({mesh:c,depthTest:!1,duration:.2,color:_})}u.geometry=f}n.recursive!==!1&&this.intersect(t,c.children,i,n)}return i}intersectSphere(t,e,i,n,s,a,l,c){let h=t&&t.isMesh&&t.layers.test(n)&&!$.isGizmo(t);h&&(h=t.visible),h&&(h=!(t instanceof d.Line)),h&&(h=!(t instanceof H.GroundedSkybox));const u=t,f=u.geometry;if(h&&c){const p=c(t);if(p===!1)return;p==="continue in children"&&(h=!1)}if(f&&A_(f)||(h=!1),h){if(l){const p=this.sphere;p.center.copy(e),p.radius=i;const g=s.length;if(Kd.runMeshBVHRaycast(this.sphere,u,s,this.context,{}),g!=s.length&&!a)return}else if(f.boundingBox||f.computeBoundingBox(),f.boundingBox){u.matrixWorldNeedsUpdate&&u.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(f.boundingBox).applyMatrix4(u.matrixWorld),g=this.sphere;if(g.center.copy(e),g.radius=i,g.intersectsBox(p)){const y=Q(t),b=y.distanceTo(g.center),_=new ug(t,b,y);if(s.push(_),!a)return}}}if(t.children)for(const p of t.children){const g=s.length;if(this.intersectSphere(p,e,i,n,s,a,l,c),g!=s.length&&!a)return}}};r(xc,"_raycasting",0);let Ec=xc;function A_(o){return!(o.index&&o.index.array.length<3)}const qo=new d.Sphere,nd=new d.Plane,zC=new d.Matrix3;function NC(o,t,e){const i=o._computeIntersections;if(!i)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(s,a,l){const c=this,h=c.geometry.boundingSphere;if(h){if(c instanceof H.GroundedSkybox){nd.setFromNormalAndCoplanarPoint(V(0,1,0),V(0,-c.position.y,0)),nd.applyMatrix4(c.matrixWorld,zC);const f=s.ray.intersectPlane(nd,V());if(f){qo.copy(h),qo.applyMatrix4(c.matrixWorld);const g=V(f).sub(s.ray.origin).length(),y=qo.radius*.5;g<y&&a.push({distance:g,point:f,object:c,normal:nd.normal.clone()})}return}qo.copy(h),qo.applyMatrix4(c.matrixWorld);const u=s.ray.intersectSphere(qo,V());if(u){const f=V(u).sub(s.ray.origin),p=f.length();if(p>qo.radius){const g=f.clone().normalize();a.push({distance:p,point:u,object:c,normal:g})}}}}),o._computeIntersections=n,t.intersectObject(o,!1,e),o._computeIntersections=i,!0}var Kd;(o=>{function t(v,w,x,O,E){var R,F,D;if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const M=w.geometry;if(w!=null&&w.isSkinnedMesh){const A=w,T=A.bvhNeedsUpdate;if(!A.staticGenerator)l(),s&&(A.staticGenerator=new s(w),A.staticGenerator.applyWorldTransforms=!1,A.staticGeometry=A.staticGenerator.generate(),M.boundsTree=a==null?void 0:a.call(A.staticGeometry),A.staticGeometryLastUpdate=performance.now()+Math.random()*200,A.bvhNeedsUpdate=!0);else if(M.boundsTree&&(A.autoUpdateMeshBvhInterval!==void 0&&A.autoUpdateMeshBvhInterval>=0||T===!0)){const G=performance.now(),B=G-A.staticGeometryLastUpdate,L=A.autoUpdateMeshBvhInterval??100;(T||B>L)&&(Gt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${B.toFixed(2)}ms`),A.bvhNeedsUpdate=!1,A.staticGeometryLastUpdate=G,(R=A.staticGenerator)==null||R.generate(A.staticGeometry),M.boundsTree.refit())}}else if(!M.boundsTree){h||_();let A=!0;if((O.xr||M[g]===!1||(F=M.getAttribute("position"))!=null&&F.isInterleavedBufferAttribute||M.index&&((D=M.index)!=null&&D.isInterleavedBufferAttribute))&&(A=!1),A&&f){if(M[p]===void 0){let T=null;if(b.length>0){const G=b.shift();G&&!G.running&&(T=G)}if(!T&&y.length<3&&(T=new f,y.push(T)),T!=null&&!T.running){const G=w.name;Gt&&console.log("<<<< worker start",G,T),M[p]="queued",performance.mark("bvh.create.start");const B=M.clone();try{T.generate(B).then(L=>{M[p]="done",M.boundsTree=L}).catch(L=>{M[p]="failed - "+(L==null?void 0:L.message),M[g]=!1,Gt&&console.error("Failed to generate mesh bvh on worker",L)}).finally(()=>{Gt&&console.log(">>>>> worker done",G,{hasBoundsTre:M.boundsTree!=null}),b.push(T),B.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(L){console.error("Failed to generate mesh bvh on worker",L)}}else Gt&&console.warn("No worker available")}}else(!u||!A)&&(l(),n&&(performance.mark("bvh.create.start"),M.boundsTree=new n(M),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(v instanceof d.Raycaster){const A=v,T=w.raycast;if(M.boundsTree)l(),i&&(w.acceleratedRaycast||(w.acceleratedRaycast=i.bind(w),Gt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Gt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:M[p],hasAcceleratedRaycast:i!=null}),E.allowSlowRaycastFallback===!1)return Gt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const G=A.firstHitOnly;return A.firstHitOnly=!1,A.intersectObject(w,!1,x),A.firstHitOnly=G,w.raycast=T,!0}else if(v instanceof d.Sphere){const A=M.boundsTree;if(A){const T=v;if(c.copy(w.matrixWorld).invert(),T.applyMatrix4(c),A.intersectsSphere(T)){const B=Q(w),L=B.distanceTo(T.center),N=new ug(w,L,B);x.push(N)}}return!0}return!1}o.runMeshBVHRaycast=t;let e=!1,i=null,n=null,s=null,a=null;function l(){e||(e=!0,Promise.resolve().then(()=>require("./vendor-Cavtu3CP.umd.cjs")).then(v=>v.index$1).then(v=>{i=v.acceleratedRaycast,n=v.MeshBVH,s=v.StaticGeometryGenerator,a=v.computeBoundsTree}).catch(v=>{(Gt||j())&&console.error("Failed to load BVH library...",v.message)}))}const c=new d.Matrix4;let h=!1,u=!1,f=null;const p=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],b=[];function _(){h=!0,u=!0,Promise.resolve().then(()=>uT).then(v=>{f=v.GenerateMeshBVHWorker}).catch(v=>{(Gt||j())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Kd||(Kd={}));const L_=Symbol("gltf-loader-internal-usage-tracker"),$C=S("debugusers"),Pa=class Pa{constructor(t){r(this,"parser");r(this,"_getDependency");r(this,"_loadingId");r(this,"_loadedObjects",new Set);this.parser=t,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(t){return Pa._loadingProcesses>0}beforeRoot(){Pa._loadingProcesses++;const t=this,e=this._getDependency;return this.parser.getDependency=function(i,n){const s=e.call(this,i,n);return s.then(a=>(a&&(t._loadedObjects.add(a),a[L_]=t._loadingId),a)),s},null}afterRoot(t){Pa._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const e of this._loadedObjects)delete e[L_],e instanceof d.Object3D&&(e.parent||e instanceof d.Mesh&&setTimeout(()=>{$C&&console.warn("> GLTF LOADER: Mesh not used in scene!",e),e.material=null,e.geometry=null},1e3));return null}};r(Pa,"_loadingProcesses",0);let Zd=Pa;class ev{constructor(){window.addEventListener("unhandledrejection",t=>{var i;if(t.defaultPrevented)return;const e=(i=t==null?void 0:t.reason)==null?void 0:i.path;if(e){const n=e[0];n&&n.tagName==="IMG"&&(console.warn(`Could not load image:
166
+ ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking} hts:${s.hasHitTestSource?"yes":"no"}`;Kf=0,$.DrawLabel(t,n,void 0,1/60*20)}}addScript(t){return this._xr_scripts.includes(t)?!1:(He&&console.log("Register new XRScript",t),this._xr_scripts.push(t),typeof t.onUpdateXR=="function"&&this._xr_update_scripts.push(t),!0)}markInactive(t){if(!(this._inactive_scripts.indexOf(t)>=0)){this.removeScript(t,!1),this._inactive_scripts.push(t);for(const e of this.controllers)this.invokeCallback_ControllerRemoved(t,e);this.invokeCallback_LeaveXR(t)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let t=this._inactive_scripts.length-1;t>=0;t--){const e=this._inactive_scripts[t];if(e.activeAndEnabled){this._inactive_scripts.splice(t,1),this.addScript(e),this.invokeCallback_EnterXR(e);for(const i of this.controllers)this.invokeCallback_ControllerAdded(e,i)}}}removeScript(t,e=!0){He&&console.log("Remove XRScript",t);const i=this._xr_scripts.indexOf(t);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(t);if(n>=0&&this._xr_update_scripts.splice(n,1),e){const s=this._inactive_scripts.indexOf(t);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(t){t.onEnterXR&&t.onEnterXR({xr:this})}invokeCallback_ControllerAdded(t,e){t.onXRControllerAdded&&t.onXRControllerAdded({xr:this,controller:e,change:"added"})}invokeCallback_ControllerRemoved(t,e){t.onXRControllerRemoved&&t.onXRControllerRemoved({xr:this,controller:e,change:"removed"})}invokeCallback_LeaveXR(t){t.onLeaveXR&&!t.destroyed&&t.onLeaveXR({xr:this})}syncCameraCullingMask(){var i;const t=this.context.xrCamera,e=(i=this.context.mainCameraComponent)==null?void 0:i.cullingMask;if(t&&e!==void 0){for(const n of t.cameras)n.layers.mask=e;t.layers.mask=e}else if(t){for(const n of t.cameras)n.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(t,e,i){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s)try{s({xr:this,controller:t,change:i})}catch(a){console.error(a)}}}applyCustomForward(){var t;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(t=this._previousCameraParent)==null||t.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const i=Ue(this.rig.gameObject);e*=i.x}this._camera instanceof d.PerspectiveCamera&&this._camera.near>e&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=e)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof d.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const t=this.context.renderer.xr.getReferenceSpace();if(!t){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(t),this._viewerPose){const e=this._viewerPose.transform;this._transformPosition.set(e.position.x,e.position.y,e.position.z),this._transformOrientation.set(e.orientation.x,e.orientation.y,e.orientation.z,e.orientation.w)}}get transition(){return this._transition||(this._transition=new P_),this._transition}fadeTransition(){return this._transition||(this._transition=new P_),this._transition.fadeTransition()}updateFade(t){this._transition&&t instanceof d.PerspectiveCamera&&this._transition.update(t,this.context.time.deltaTime)}onUpdateFade_PostRender(){var t;(t=this._transition)==null||t.remove()}};r($e,"_sync",null),r($e,"_currentSessionRequestMode",null),r($e,"_currentSessionRequest"),r($e,"_activeSession"),r($e,"_sessionRequestStartListeners",[]),r($e,"_sessionRequestEndListeners",[]),r($e,"_xrStartListeners",[]),r($e,"_xrEndListeners",[]),r($e,"_controllerAddedListeners",[]),r($e,"_controllerRemovedListeners",[]),r($e,"$_stop_request",Symbol()),r($e,"onEnd",()=>{He&&console.log("XR Session ended"),$e._activeSession=null});let J=$e;const Zf=S("debugwebxr");class J0{static tryFindAvatarObjects(t,e,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=t.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Zf&&console.log("FOUND AVATAR HEAD",t.name),i.head=new te("",e,t)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Zf&&console.log("FOUND AVATAR LEFT HAND",t.name),i.leftHand=new te("",e,t)),!i.rightHand&&n.includes("right")&&(Zf&&console.log("FOUND AVATAR RIGHT HAND",t.name),i.rightHand=new te("",e,t)));for(let s=0;s<t.children.length;s++){if(i.head&&i.leftHand&&i.rightHand)return;const a=t.children[s];this.tryFindAvatarObjects(a,e,i)}}}const Pt=new d.Vector3,R_=new d.Vector3,E_=new d.Quaternion,FC=S("debuggizmos"),an=8947848,Jf=32,ni=class ni{constructor(){}static isGizmo(t){return t[rm]!==void 0}static setVisible(t){for(const e of Pe.timedObjectsBuffer)e.visible=t}static DrawLabel(t,e,i=.05,n=0,s,a,l){var u;if(!ni.enabled)return null;s||(s=an);const c=((u=J.active)==null?void 0:u.rigScale)??1,h=Pe.getTextLabel(n,e,i*c,s,a);return l instanceof d.Object3D&&l.add(h),h.position.x=t.x,h.position.y=t.y,h.position.z=t.z,h}static DrawRay(t,e,i=an,n=0,s=!0){if(!ni.enabled)return;const a=Pe.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,t.x,t.y,t.z),Pt.set(e.x,e.y,e.z).multiplyScalar(999999999),l.setXYZ(1,t.x+Pt.x,t.y+Pt.y,t.z+Pt.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=s,a.material.depthWrite=!1}static DrawDirection(t,e,i=an,n=0,s=!0,a=1){if(!ni.enabled)return;const l=Pe.getLine(n),c=l.geometry.getAttribute("position");c.setXYZ(0,t.x,t.y,t.z),e.w!==void 0?(Pt.set(0,0,-a),E_.set(e.x,e.y,e.z,e.w),Pt.applyQuaternion(E_)):(Pt.set(e.x,e.y,e.z),Pt.multiplyScalar(a)),c.setXYZ(1,t.x+Pt.x,t.y+Pt.y,t.z+Pt.z),c.needsUpdate=!0,l.material.color.set(i),l.material.depthTest=s,l.material.depthWrite=!1}static DrawLine(t,e,i=an,n=0,s=!0){if(!ni.enabled)return;const a=Pe.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,t.x,t.y,t.z),l.setXYZ(1,e.x,e.y,e.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=s,a.material.depthWrite=!1,a.material.fog=!1}static DrawCircle(t,e,i,n=an,s=0,a=!0){if(!ni.enabled)return;const l=Pe.getCircle(s);l.position.set(t.x,t.y,t.z),l.scale.set(i,i,i),l.quaternion.setFromUnitVectors(this._up,Pt.set(e.x,e.y,e.z).normalize()),l.material.color.set(n),l.material.depthTest=a,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireSphere(t,e,i=an,n=0,s=!0){if(!ni.enabled)return;const a=Pe.getSphere(e,n,!0);Pr(a,t.x,t.y,t.z),a.material.color.set(i),a.material.depthTest=s,a.material.depthWrite=!1,a.material.fog=!1}static DrawSphere(t,e,i=an,n=0,s=!0){if(!ni.enabled)return;const a=Pe.getSphere(e,n,!1);Pr(a,t.x,t.y,t.z),a.material.color.set(i),a.material.depthTest=s,a.material.depthWrite=!1}static DrawWireBox(t,e,i=an,n=0,s=!0){if(!ni.enabled)return;const a=Pe.getBox(n);a.position.set(t.x,t.y,t.z),a.scale.set(e.x,e.y,e.z),a.material.color.set(i),a.material.depthTest=s,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireBox3(t,e=an,i=0,n=!0){if(!ni.enabled)return;const s=Pe.getBox(i);s.position.copy(t.getCenter(Pt)),s.scale.copy(t.getSize(Pt)),s.material.color.set(e),s.material.depthTest=n,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1}static DrawArrow(t,e,i=an,n=0,s=!0,a=!1){if(!ni.enabled)return;const l=Pe.getArrowHead(n);l.position.set(e.x,e.y,e.z),l.quaternion.setFromUnitVectors(this._up.set(0,1,0),Pt.set(e.x,e.y,e.z).sub(R_.set(t.x,t.y,t.z)).normalize());const h=Pt.set(e.x,e.y,e.z).sub(R_.set(t.x,t.y,t.z)).length()*.1;l.scale.set(h,h,h),l.material.color.set(i),l.material.depthTest=s,l.material.wireframe=a,this.DrawLine(t,e,i,n,s)}static DrawWireMesh(t){const e=Pe.getMesh(t.duration??0);"mesh"in t?(e.geometry=t.mesh.geometry,e.matrix.copy(t.mesh.matrixWorld)):(e.geometry=t.geometry,e.matrix.copy(t.matrix)),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1,e.material.color.set(t.color??an),e.material.depthTest=t.depthTest??!0,e.material.wireframe=!0}};r(ni,"enabled",!0),r(ni,"_up",new d.Vector3(0,1,0));let $=ni;const UC=new d.BoxGeometry(1,1,1);function dg(o=null){const t=new d.Color(o??14540253),e=new d.EdgesGeometry(UC);return new d.LineSegments(e,new d.LineBasicMaterial({color:t}))}const rm=Symbol("GizmoCache");class Pe{static ensureFont(){let t=ne.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);if(!t){t=ne.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName);const e=t.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");e==null||e.addEventListener("ready",()=>{ne.__webpack_exports__default.update()})}}static getTextLabel(t,e,i,n,s){this.ensureFont();let a=this.textLabelCache.pop(),l=1;s&&typeof s=="string"&&(s==null?void 0:s.length)>=8&&s.startsWith("#")?(l=parseInt(s.substring(7),16)/255,s=s.substring(0,7),FC&&console.log(s,l)):typeof s=="object"&&s.a!==void 0&&(l=s.a);const c={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:s??void 0,backgroundOpacity:l,textContent:e,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(a)a.set(c);else{a=new ne.__webpack_exports__Text(c);const h=this,u=a;u.setText=function(f){this.set({textContent:f}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(X.Current,a,t,this.textLabelCache),a}static getBox(t){let e=this.boxesCache.pop();if(!e){const i=new d.BoxGeometry(1,1,1);e=new d.Mesh(i)}return this.registerTimedObject(X.Current,e,t,this.boxesCache),e}static getLine(t){let e=this.linesCache.pop();if(!e){e=new d.Line;let i=e.geometry.getAttribute("position");i||(i=new d.BufferAttribute(new Float32Array(6),3),e.geometry.setAttribute("position",i))}return e.frustumCulled=!1,this.registerTimedObject(X.Current,e,t,this.linesCache),e}static getCircle(t){let e=this.circlesCache.pop();if(!e){e=new d.Line;let i=e.geometry.getAttribute("position");if(!i){i=new d.BufferAttribute(new Float32Array(Jf*3),3),e.geometry.setAttribute("position",i);const n=V(0,1,0),s=V(0,0,1),a=V(s);a.cross(n).normalize();const l=V(a),c=Math.PI*2/(Jf-1);for(let h=0;h<Jf+1;h++){const u=c*h;n.copy(l).multiplyScalar(Math.cos(u)*1),a.copy(s).multiplyScalar(Math.sin(u)*1);const f=n.add(a);i.setXYZ(h,f.x,f.y,f.z)}}}return e.frustumCulled=!1,this.registerTimedObject(X.Current,e,t,this.circlesCache),e}static getSphere(t,e,i){let n=this.spheresCache.pop();return n||(n=new d.Mesh(new d.SphereGeometry(1,8,8))),n.scale.set(t,t,t),n.material.wireframe=i,this.registerTimedObject(X.Current,n,e,this.spheresCache),n}static getArrowHead(t){let e=this.arrowHeadsCache.pop();return e||(e=new d.Mesh(new d.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(X.Current,e,t,this.arrowHeadsCache),e}static getMesh(t){let e=this.mesh.pop();return e||(e=new d.Mesh,e.material=new d.MeshBasicMaterial),this.registerTimedObject(X.Current,e,t,this.mesh),e}static registerTimedObject(t,e,i,n){if(!t){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const s=this.contextBeforeRenderCallbacks.get(t),a=this.contextPostRenderCallbacks.get(t);if(s){if(t.pre_render_callbacks[t.pre_render_callbacks.length-1]!==s){const l=t.pre_render_callbacks.indexOf(s);l>=0&&t.pre_render_callbacks.splice(l,1),t.pre_render_callbacks.push(s)}}else{const l=()=>{this.onBeforeRender(t,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(t,l),t.pre_render_callbacks.push(l)}if(a){if(t.post_render_callbacks[t.post_render_callbacks.length-1]!==a){const l=t.post_render_callbacks.indexOf(a);l>=0&&t.post_render_callbacks.splice(l,1),t.post_render_callbacks.push(a)}}else{const l=()=>{this.onPostRender(t,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(t,l),t.post_render_callbacks.push(l)}e.traverse(l=>{l.layers.disableAll(),l.layers.enable(2)}),e.renderOrder=999999,e[rm]=n,e.castShadow=!1,e.receiveShadow=!1,e.isGizmo=!0,this.timedObjectsBuffer.push(e),this.timesBuffer.push(X.Current.time.realtimeSinceStartup+i),t.scene.add(e)}static onBeforeRender(t,e){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,ne.__webpack_exports__default.update());for(let i=0;i<e.length;i++){const n=e[i];if(t.mainCamera&&n instanceof ne.__webpack_exports__default.MeshUIBaseElement){if(kr(n))continue;const s=t.isInVR,a=!1,l=!s;th(n,t.mainCamera,a,l)}}}static onPostRender(t,e,i){const n=t.time.realtimeSinceStartup;for(let s=e.length-1;s>=0;s--){const a=e[s];n>=i[s]-1e-6&&(e.splice(s,1),i.splice(s,1),a.removeFromParent(),kr(a)!=!0&&a[rm].push(a))}}}r(Pe,"familyName","needle-gizmos"),r(Pe,"linesCache",[]),r(Pe,"circlesCache",[]),r(Pe,"spheresCache",[]),r(Pe,"boxesCache",[]),r(Pe,"arrowHeadsCache",[]),r(Pe,"mesh",[]),r(Pe,"textLabelCache",[]),r(Pe,"timedObjectsBuffer",new Array),r(Pe,"timesBuffer",new Array),r(Pe,"contextPostRenderCallbacks",new Map),r(Pe,"contextBeforeRenderCallbacks",new Map),r(Pe,"tmuiNeedsUpdate",!1);const Gt=S("debugphysics"),T_=new d.Layers;class Ds{constructor(){r(this,"ray");r(this,"cam");r(this,"screenPoint");r(this,"raycaster");r(this,"results");r(this,"targets");r(this,"recursive",!0);r(this,"minDistance");r(this,"maxDistance");r(this,"lineThreshold");r(this,"layerMask");r(this,"ignore");r(this,"testObject");r(this,"useAcceleratedRaycast");r(this,"allowSlowRaycastFallback",!0)}screenPointFromOffset(t,e){this.screenPoint===void 0&&(this.screenPoint=new d.Vector2),this.screenPoint.x=t/window.innerWidth*2-1,this.screenPoint.y=-(e/window.innerHeight)*2+1}setLayer(t){T_.set(t),this.layerMask=T_}setMask(t){this.layerMask||(this.layerMask=new d.Layers);const e=this.layerMask;e?e.mask=t:this.layerMask=t}}r(Ds,"AllLayers",4294967295);class ug{constructor(t,e,i){r(this,"distance");r(this,"point");r(this,"object");this.object=t,this.distance=e,this.point=i}}const xc=class xc{constructor(t){r(this,"context");r(this,"engine");r(this,"raycaster",new d.Raycaster);r(this,"defaultRaycastOptions",new Ds);r(this,"targetBuffer",new Array(1));r(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}});r(this,"sphereResults",new Array);r(this,"sphereMask",new d.Layers);r(this,"sphere",new d.Sphere);r(this,"tempBoundingBox",new d.Box3);this.context=t}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(t,e=void 0,i=1/0,n=!0){var s;return((s=this.context.physics.engine)==null?void 0:s.raycast(t,e,{maxDistance:i,solid:n}))??null}raycastPhysicsFastAndGetNormal(t,e=void 0,i=1/0,n=!0){var s;return((s=this.context.physics.engine)==null?void 0:s.raycastAndGetNormal(t,e,{maxDistance:i,solid:n}))??null}sphereOverlapPhysics(t,e){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(t,e))??null}sphereOverlap(t,e,i=!0,n=!1,s=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const a=this.sphereMask;a.enableAll(),a.disable(2);for(const l of this.context.scene.children)this.intersectSphere(l,t,e,a,this.sphereResults,i,n,s);return this.sphereResults.sort((l,c)=>l.distance-c.distance)}raycastFromRay(t,e=null){const i=e??this.defaultRaycastOptions;i.ray=t;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(t=null){Gt&&performance.mark("raycast.start"),t||(t=this.defaultRaycastOptions);const e=t.screenPoint??this.context.input.mousePositionRC,i=t.raycaster??this.raycaster;if(i.near=t.minDistance??0,i.far=t.maxDistance??1/0,i.params=this.defaultThresholds,t.lineThreshold===void 0&&(t.lineThreshold=-1),i.params.Line={threshold:t.lineThreshold},t.ray)i.ray.copy(t.ray);else{const l=t.cam??this.context.mainCamera;if(!l)return Gt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const c=this.context.xrCamera;this.context.isInXR&&c instanceof d.ArrayCamera&&c.cameras.length>0?i.setFromCamera(e,c.cameras[0]):i.setFromCamera(e,l)}let n=t.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let s=t.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),t.layerMask!==void 0?t.layerMask instanceof d.Layers?i.layers.mask=t.layerMask.mask:i.layers.mask=t.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Gt&&console.time("raycast"),s.length=0,xc._raycasting++,this.intersect(this.raycaster,n,s,t),s.sort((l,c)=>l.distance-c.distance);const a=t.ignore;return a!==void 0&&a.length>0&&(s=s.filter(l=>!a.includes(l.object))),xc._raycasting--,Gt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",s!=null&&s.length?[...s]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),s}intersect(t,e,i,n){var s,a,l;for(const c of e){if(!c||c.visible===!1||$.isGizmo(c)||n.lineThreshold!==void 0&&n.lineThreshold<0&&c instanceof d.Line)continue;let h=!0;const u=c,f=u.geometry;if(n.testObject){const p=(s=n.testObject)==null?void 0:s.call(n,c);if(p===!1)continue;p==="continue in children"&&(h=!1)}if(h&&(f&&A_(f)||(h=!1)),h){const p=le.getRaycastMesh(c);p&&(u.geometry=p);const g=i.length;let y=!0;if(n.precise===!1&&(y=!1),y||(y=((l=(a=f.getAttribute("position"))==null?void 0:a.array)==null?void 0:l.length)<64),u instanceof H.GroundedSkybox&&(y=!1),!y&&NC(u,t,i)||(n.useAcceleratedRaycast!==!1?Kd.runMeshBVHRaycast(t,u,i,this.context,n):t.intersectObject(u,!1,i)),Gt&&i.length!=g){const b=i[i.length-1],_=p?8969557:7798784;$.DrawWireSphere(b.point,.1,_,1,!1),$.DrawWireMesh({mesh:c,depthTest:!1,duration:.2,color:_})}u.geometry=f}n.recursive!==!1&&this.intersect(t,c.children,i,n)}return i}intersectSphere(t,e,i,n,s,a,l,c){let h=t&&t.isMesh&&t.layers.test(n)&&!$.isGizmo(t);h&&(h=t.visible),h&&(h=!(t instanceof d.Line)),h&&(h=!(t instanceof H.GroundedSkybox));const u=t,f=u.geometry;if(h&&c){const p=c(t);if(p===!1)return;p==="continue in children"&&(h=!1)}if(f&&A_(f)||(h=!1),h){if(l){const p=this.sphere;p.center.copy(e),p.radius=i;const g=s.length;if(Kd.runMeshBVHRaycast(this.sphere,u,s,this.context,{}),g!=s.length&&!a)return}else if(f.boundingBox||f.computeBoundingBox(),f.boundingBox){u.matrixWorldNeedsUpdate&&u.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(f.boundingBox).applyMatrix4(u.matrixWorld),g=this.sphere;if(g.center.copy(e),g.radius=i,g.intersectsBox(p)){const y=Q(t),b=y.distanceTo(g.center),_=new ug(t,b,y);if(s.push(_),!a)return}}}if(t.children)for(const p of t.children){const g=s.length;if(this.intersectSphere(p,e,i,n,s,a,l,c),g!=s.length&&!a)return}}};r(xc,"_raycasting",0);let Ec=xc;function A_(o){return!(o.index&&o.index.array.length<3)}const qo=new d.Sphere,nd=new d.Plane,zC=new d.Matrix3;function NC(o,t,e){const i=o._computeIntersections;if(!i)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(s,a,l){const c=this,h=c.geometry.boundingSphere;if(h){if(c instanceof H.GroundedSkybox){nd.setFromNormalAndCoplanarPoint(V(0,1,0),V(0,-c.position.y,0)),nd.applyMatrix4(c.matrixWorld,zC);const f=s.ray.intersectPlane(nd,V());if(f){qo.copy(h),qo.applyMatrix4(c.matrixWorld);const g=V(f).sub(s.ray.origin).length(),y=qo.radius*.5;g<y&&a.push({distance:g,point:f,object:c,normal:nd.normal.clone()})}return}qo.copy(h),qo.applyMatrix4(c.matrixWorld);const u=s.ray.intersectSphere(qo,V());if(u){const f=V(u).sub(s.ray.origin),p=f.length();if(p>qo.radius){const g=f.clone().normalize();a.push({distance:p,point:u,object:c,normal:g})}}}}),o._computeIntersections=n,t.intersectObject(o,!1,e),o._computeIntersections=i,!0}var Kd;(o=>{function t(v,w,x,O,E){var R,F,D;if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const M=w.geometry;if(w!=null&&w.isSkinnedMesh){const A=w,T=A.bvhNeedsUpdate;if(!A.staticGenerator)l(),s&&(A.staticGenerator=new s(w),A.staticGenerator.applyWorldTransforms=!1,A.staticGeometry=A.staticGenerator.generate(),M.boundsTree=a==null?void 0:a.call(A.staticGeometry),A.staticGeometryLastUpdate=performance.now()+Math.random()*200,A.bvhNeedsUpdate=!0);else if(M.boundsTree&&(A.autoUpdateMeshBvhInterval!==void 0&&A.autoUpdateMeshBvhInterval>=0||T===!0)){const G=performance.now(),B=G-A.staticGeometryLastUpdate,L=A.autoUpdateMeshBvhInterval??100;(T||B>L)&&(Gt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${B.toFixed(2)}ms`),A.bvhNeedsUpdate=!1,A.staticGeometryLastUpdate=G,(R=A.staticGenerator)==null||R.generate(A.staticGeometry),M.boundsTree.refit())}}else if(!M.boundsTree){h||_();let A=!0;if((O.xr||M[g]===!1||(F=M.getAttribute("position"))!=null&&F.isInterleavedBufferAttribute||M.index&&((D=M.index)!=null&&D.isInterleavedBufferAttribute))&&(A=!1),A&&f){if(M[p]===void 0){let T=null;if(b.length>0){const G=b.shift();G&&!G.running&&(T=G)}if(!T&&y.length<3&&(T=new f,y.push(T)),T!=null&&!T.running){const G=w.name;Gt&&console.log("<<<< worker start",G,T),M[p]="queued",performance.mark("bvh.create.start");const B=M.clone();try{T.generate(B).then(L=>{M[p]="done",M.boundsTree=L}).catch(L=>{M[p]="failed - "+(L==null?void 0:L.message),M[g]=!1,Gt&&console.error("Failed to generate mesh bvh on worker",L)}).finally(()=>{Gt&&console.log(">>>>> worker done",G,{hasBoundsTre:M.boundsTree!=null}),b.push(T),B.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(L){console.error("Failed to generate mesh bvh on worker",L)}}else Gt&&console.warn("No worker available")}}else(!u||!A)&&(l(),n&&(performance.mark("bvh.create.start"),M.boundsTree=new n(M),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(v instanceof d.Raycaster){const A=v,T=w.raycast;if(M.boundsTree)l(),i&&(w.acceleratedRaycast||(w.acceleratedRaycast=i.bind(w),Gt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Gt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:M[p],hasAcceleratedRaycast:i!=null}),E.allowSlowRaycastFallback===!1)return Gt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const G=A.firstHitOnly;return A.firstHitOnly=!1,A.intersectObject(w,!1,x),A.firstHitOnly=G,w.raycast=T,!0}else if(v instanceof d.Sphere){const A=M.boundsTree;if(A){const T=v;if(c.copy(w.matrixWorld).invert(),T.applyMatrix4(c),A.intersectsSphere(T)){const B=Q(w),L=B.distanceTo(T.center),N=new ug(w,L,B);x.push(N)}}return!0}return!1}o.runMeshBVHRaycast=t;let e=!1,i=null,n=null,s=null,a=null;function l(){e||(e=!0,Promise.resolve().then(()=>require("./vendor-Cavtu3CP.umd.cjs")).then(v=>v.index$1).then(v=>{i=v.acceleratedRaycast,n=v.MeshBVH,s=v.StaticGeometryGenerator,a=v.computeBoundsTree}).catch(v=>{(Gt||j())&&console.error("Failed to load BVH library...",v.message)}))}const c=new d.Matrix4;let h=!1,u=!1,f=null;const p=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],b=[];function _(){h=!0,u=!0,Promise.resolve().then(()=>uT).then(v=>{f=v.GenerateMeshBVHWorker}).catch(v=>{(Gt||j())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Kd||(Kd={}));const L_=Symbol("gltf-loader-internal-usage-tracker"),$C=S("debugusers"),Pa=class Pa{constructor(t){r(this,"parser");r(this,"_getDependency");r(this,"_loadingId");r(this,"_loadedObjects",new Set);this.parser=t,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(t){return Pa._loadingProcesses>0}beforeRoot(){Pa._loadingProcesses++;const t=this,e=this._getDependency;return this.parser.getDependency=function(i,n){const s=e.call(this,i,n);return s.then(a=>(a&&(t._loadedObjects.add(a),a[L_]=t._loadingId),a)),s},null}afterRoot(t){Pa._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const e of this._loadedObjects)delete e[L_],e instanceof d.Object3D&&(e.parent||e instanceof d.Mesh&&setTimeout(()=>{$C&&console.warn("> GLTF LOADER: Mesh not used in scene!",e),e.material=null,e.geometry=null},1e3));return null}};r(Pa,"_loadingProcesses",0);let Zd=Pa;class ev{constructor(){window.addEventListener("unhandledrejection",t=>{var i;if(t.defaultPrevented)return;const e=(i=t==null?void 0:t.reason)==null?void 0:i.path;if(e){const n=e[0];n&&n.tagName==="IMG"&&(console.warn(`Could not load image:
167
167
  `+n.src),t.preventDefault())}})}}const $u=S("trackresources");function tv(){return $u==="dispose"}let Ir=!0;$u===0&&(Ir=!1);function VC(o){Ir=o}function iv(){return Ir}const nv=Symbol("disposable");function fg(o,t){o&&(o[nv]=t,br&&console.warn("Set disposable",t,o))}const sv=Symbol("disposed");function WC(o){return o[sv]===!0}function Se(o){var t;if(o){if(o[nv]===!1){br&&console.warn("Object is marked as not disposable",o);return}if(typeof o=="object"&&(o[sv]=!0),o instanceof d.Scene)Se(o.environment),Se(o.background),Se(o.customDepthMaterial),Se(o.customDistanceMaterial);else if(o instanceof d.SkinnedMesh)Se(o.geometry),Se(o.material),Se(o.skeleton),Se(o.bindMatrix),Se(o.bindMatrixInverse),Se(o.customDepthMaterial),Se(o.customDistanceMaterial),o.geometry=null,o.material=null,o.visible=!1;else if(o instanceof d.Mesh)Se(o.geometry),Se(o.material),Se(o.customDepthMaterial),Se(o.customDistanceMaterial),o.geometry=null,o.material=null,o.visible=!1;else if(o instanceof d.BufferGeometry){sa(o);for(const e of Object.keys(o.attributes)){const i=o.attributes[e];Se(i)}}else if(o instanceof d.BufferAttribute||o instanceof d.InterleavedBufferAttribute)br&&console.warn("BufferAttribute dispose not supported",o.count);else if(o instanceof Array)for(const e of o)e instanceof d.Material&&Se(e);else if(o instanceof d.Material){sa(o);for(const i of Object.keys(o)){const n=o[i];n instanceof d.Texture&&(Se(n),o[i]=null)}const e=o.uniforms;if(e)for(const i of Object.keys(e)){const n=e[i];n instanceof d.Texture?(Se(n),e[i]=null):n instanceof d.Uniform$1&&(Se(n.value),n.value=null)}}else o instanceof d.Texture?(sa(o),sa(o.source),((t=o.source)==null?void 0:t.data)instanceof ImageBitmap&&sa(o.source.data)):o instanceof d.Skeleton?(sa(o.boneTexture),o.boneTexture=null):o instanceof d.Bone||!(o instanceof d.Object3D)&&br&&console.warn("Unknown object type",o)}}function sa(o){o&&((br||tv()||$u)&&console.warn("🧨 FREE",o),o instanceof ImageBitmap?o.close():o instanceof d.Source?o.data=null:o.dispose())}function ov(o){(o instanceof d.Mesh||o instanceof d.SkinnedMesh)&&(o.material=null,o.geometry=null)}const GC=new Set;function pg(o,t,e=null,i){if(i||(i=GC,i.clear()),!o)return i;const n=o[Tc];if(n)for(const s of n)i.has(s)||(e==null?void 0:e.call(null,s))!==!1&&(i.add(s),t&&pg(s,!0,e,i));return i}function HC(o){return o[Yl]}const br=S("debugresourceusers")||S("debugmemory"),Tc=Symbol("needle-resource-users"),Yl=Symbol("needle-resource-users-count");function Ft(o,t){Uu(o,t,function(e,i){Ir&&!Ec.raycasting&&(Jd(Tc,this,e,!1),Jd(Tc,this,i,!0))})}Ir&&(Ft(d.Mesh.prototype,"material"),Ft(d.Mesh.prototype,"geometry"),Ft(d.Material.prototype,"map"),Ft(d.Material.prototype,"bumpMap"),Ft(d.Material.prototype,"alphaMap"),Ft(d.Material.prototype,"normalMap"),Ft(d.Material.prototype,"displacementMap"),Ft(d.Material.prototype,"roughnessMap"),Ft(d.Material.prototype,"metalnessMap"),Ft(d.Material.prototype,"emissiveMap"),Ft(d.Material.prototype,"specularMap"),Ft(d.Material.prototype,"envMap"),Ft(d.Material.prototype,"lightMap"),Ft(d.Material.prototype,"aoMap"),Ft(d.Material.prototype,"gradientMap"));function qC(o){if(Ir===!1)return;const t=o[Tc];if(t)for(const e of t)Jd(Tc,e,o,!1)}Ir&&Uu(d.Material.prototype,"dispose",function(){qC(this)});let am=0;function Jd(o,t,e,i){if(am>0)return;if(Array.isArray(e)){for(const s of e)Jd(o,t,s,i);return}if(!e)return;let n=e[o];if(n||(n=new Set),i){if(t&&!n.has(t)){n.add(t);let s=e[Yl]||0;s+=1,e[Yl]=s,br&&console.warn(`🟢 Added user of "${e.type}"`,t,e,s,"users:",n)}}else if(t&&n.has(t)){n.delete(t);let s=e[Yl]||0;s>0&&(s-=1,e[Yl]=s),br&&console.warn(`🔴 Removed user of "${e.type}"`,t,e,s,"users:",n),s<=0&&(Zd.isLoading(e)||($u&&console.warn(`🔴 Removed all user of "${e.type}"`,e),tv()&&Se(e)))}e[o]=n}try{Uu(d.WebGLRenderer.prototype,"render",function(){am++},function(){am--})}catch(o){console.warn("Could not wrap WebGLRenderer.render",o)}const D_=S("debugcomponentevents");class sh{static addComponentLifecylceEventListener(t,e){this.eventListeners.has(t)&&this.eventListeners.set(t,[]);let i=this.eventListeners.get(t);i||(i=[]),i.push(e),this.eventListeners.set(t,i),D_&&console.log("Added event listener for "+t,this.eventListeners)}static removeComponentLifecylceEventListener(t,e){const i=this.eventListeners.get(t);if(!i)return;const n=i.indexOf(e);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(t,e){const i=this.eventListeners.get(t);if(D_&&console.log("Dispatching event "+t,i),!!i)for(const n of i)n(e)}}r(sh,"eventListeners",new Map);const Ac=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),rv=Symbol("isUsingInstancing"),av=Symbol("instancingRenderer"),Kl=Symbol("instancingAutoUpdateBounds");class Wi{static isUsingInstancing(t){return t[rv]===!0}static getRenderer(t){return t[av]||null}setAutoUpdateBounds(t,e){const i=Wi.getRenderer(t);i&&(i[Kl]=e)}static markDirty(t,e=!0){if(t&&(this.isUsingInstancing(t)&&(t[Ac]=!0,t.matrixWorldNeedsUpdate=!0),e))for(const i of t.children)Wi.markDirty(i,!0)}}function Da(o,t){try{t||o()}catch(e){return console.error(e),!1}return!0}const lm=S("debugnewscripts"),XC=S("debughierarchy"),Oe=[];function QC(){return Oe.length>0}function eu(o){if(lm&&console.log("Register new components",o.new_scripts.length,[...o.new_scripts],o.alias?"element: "+o.alias:o.hash,o),o.new_scripts_pre_setup_callbacks.length>0){for(const t of o.new_scripts_pre_setup_callbacks)t&&t();o.new_scripts_pre_setup_callbacks.length=0}if(!(o.new_scripts.length<=0)){Oe.length=0,o.new_scripts.length>0&&Oe.push(...o.new_scripts),o.new_scripts.length=0;for(let t=0;t<Oe.length;t++)try{const e=Oe[t];if(e.isComponent!==!0){(j()||lm)&&console.error(`Registered script is not a Needle Engine component.
168
168
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
169
169
  `,e),Oe.splice(t,1),t--;continue}if(e.destroyed)continue;if(!e.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
170
170
  Did you add and remove a component in the same frame?`),Oe.splice(t,1),t--;continue}e.context=o,dc(e.gameObject),mg(e,o)}catch(e){console.error(e),ws(Oe[t],o),Oe.splice(t,1),t--}for(let t=0;t<Oe.length;t++)try{const e=Oe[t];if(e.destroyed){ws(Oe[t],o),Oe.splice(t,1),t--;continue}if(e.registering)try{e.registering()}catch(i){console.error(i)}e.__internalAwake!==void 0&&(e.gameObject||console.error("Calling awake for a component without a GameObject",e,e.gameObject),dc(e.gameObject),e.activeAndEnabled&&Da(e.__internalAwake.bind(e)))}catch(e){console.error(e),ws(Oe[t],o),Oe.splice(t,1),t--}for(let t=0;t<Oe.length;t++)try{const e=Oe[t];if(e.destroyed||e.enabled===!1||(dc(e.gameObject),e.activeAndEnabled===!1))continue;e.__internalEnable!==void 0&&(e.enabled=!0,Da(e.__internalEnable.bind(e)))}catch(e){console.error(e),ws(Oe[t],o),Oe.splice(t,1),t--}for(let t=0;t<Oe.length;t++)try{const e=Oe[t];if(e.destroyed||!e.gameObject)continue;o.new_script_start.push(e)}catch(e){console.error(e),ws(Oe[t],o),Oe.splice(t,1),t--}Oe.length=0;for(const t of o.new_scripts_post_setup_callbacks)t&&t();o.new_scripts_post_setup_callbacks.length=0}}function YC(o){o&&(o.__internalDisable(!0),ws(o,o.context))}function lv(o,t){for(let e=0;e<o.new_script_start.length;e++)try{const i=o.new_script_start[e];if(t!==void 0&&i.gameObject!==t||i.destroyed||i.activeAndEnabled===!1)continue;Da(i.__internalAwake.bind(i)),i.enabled&&(Da(i.__internalEnable.bind(i)),Da(i.__internalStart.bind(i)),o.new_script_start.splice(e,1),e--)}catch(i){console.error(i),ws(o.new_script_start[e],o),o.new_script_start.splice(e,1),e--}}function mg(o,t){t.scripts.indexOf(o)===-1&&(t.scripts.push(o),o.earlyUpdate&&t.scripts_earlyUpdate.push(o),o.update&&t.scripts_update.push(o),o.lateUpdate&&t.scripts_lateUpdate.push(o),o.onBeforeRender&&t.scripts_onBeforeRender.push(o),o.onAfterRender&&t.scripts_onAfterRender.push(o),o.onPausedChanged&&t.scripts_pausedChanged.push(o),ep(o,null)&&t.new_scripts_xr.push(o),ep(o,"immersive-vr")&&t.scripts_immersive_vr.push(o),ep(o,"immersive-ar")&&t.scripts_immersive_ar.push(o))}function ws(o,t){Bi(o,t.new_scripts),Bi(o,t.new_script_start),Bi(o,t.scripts),Bi(o,t.scripts_earlyUpdate),Bi(o,t.scripts_update),Bi(o,t.scripts_lateUpdate),Bi(o,t.scripts_onBeforeRender),Bi(o,t.scripts_onAfterRender),Bi(o,t.scripts_pausedChanged),Bi(o,t.new_scripts_xr),Bi(o,t.scripts_immersive_vr),Bi(o,t.scripts_immersive_ar),t.stopAllCoroutinesFrom(o)}function Bi(o,t){const e=t.indexOf(o);e>=0&&t.splice(e,1)}function ep(o,t){var e;if(o){const i=o;if(i.onBeforeXR||i.onEnterXR||i.onUpdateXR||i.onLeaveXR||i.onXRControllerAdded||i.onXRControllerRemoved)return!(t!=null&&((e=i.supportsXR)==null?void 0:e.call(i,t))===!1)}return!1}function Ed(o){if(o||(o=re.Current.scene),!o){console.trace("Invalid call - no current context.");return}const t=ol(o);cv(o,t,!0)||(lm||j()?console.error(`Error updating hierarchy
171
- Do you have circular references in your project? <a target="_blank" href="https://docs.needle.tools/circular-reference"> Click here for more information.`,o):console.error('Failed to update active state in hierarchy of "'+o.name+'"',o),console.warn(" ↑ this error might be caused by circular references. Please make sure you don't have files with circular references (e.g. one GLB 1 is loading GLB 2 which is then loading GLB 1 again)."))}function cv(o,t,e,i=0){if(i>1e3)return console.warn("Hierarchy is too deep (> 1000 level) - will abort updating active state"),!1;const n=ol(o);if(t&&(t=n,t&&o.parent)){const c=o.parent;t=c[Es],t===void 0&&(c instanceof d.Scene||(t=!0))}const a=o[Es]!==t;o[Es]=t,a&&(XC&&console.warn("ACTIVE CHANGE",o.name,n,o.visible,t,"changed?"+a,o),KC(o,c=>{t?c.enabled&&(Da(c.__internalAwake.bind(c)),c.enabled&&c.__internalEnable()):c.__didAwake&&c.enabled&&(c.__didEnable=!1,c.onDisable())}));let l=!0;if(o.children)for(const c of o.children)cv(c,t,e,i+1)===!1&&(l=!1);return l}function dc(o){let t=!0,e=o,i=!1;for(;e&&e;){if(e.type==="Scene"&&(i=!0),!ol(e)){t=!1;break}e=e.parent}if(!o){console.error("GO is null");return}o[Es]=t&&i}function KC(o,t){var e;if((e=o.userData)!=null&&e.components)for(const i of o.userData.components)t(i)}const Td=new Map,hv=Symbol("prewarmFlag"),cm=Symbol("waitingForPrewarm"),hm=S("debugprewarm");function ZC(o,t){if(!o||o[hv]===!0||o[cm]===!0)return;Td.has(t)||Td.set(t,[]),o[cm]=!0,Td.get(t).push(o),hm&&console.debug("register prewarm",o.name)}let I_=null,j_=null;function JC(o){if(!o)return;const t=Td.get(o);if(!(t!=null&&t.length))return;const e=o.mainCamera;if(e){hm&&console.log("prewarm",t.length,"objects",[...t]);const i=o.renderer;if(i.compile){const n=o.scene;i.compile(n,e),I_??(I_=new d.WebGLCubeRenderTarget(64)),j_??(j_=new d.CubeCamera(.001,9999999,I_)),j_.update(i,n);for(const s of t)s[hv]=!0,s[cm]=!1;t.length=0,hm&&console.log("prewarm done")}}}re.registerCallback(he.ContextCreated,o=>{const t=o.context;mv(t),uv(t)});const tu=S("debugcomponents"),B_="eff8ba80-635d-11ec-90d6-0242ac120003";class vt{constructor(t){r(this,"_originalSeed");r(this,"_seed");typeof t=="string"&&(t=vt.hash(t)),this._originalSeed=t,this._seed=t}get seed(){return this._seed}set seed(t){this._seed=t}reset(){this._seed=this._originalSeed}generateUUID(t){if(typeof t=="string")return ae.v5(t,B_);const e=this._seed;return this._seed-=1,ae.v5(e.toString(),B_)}initialize(t){typeof t=="string"?this._seed=vt.hash(t):this._seed=t}static createFromString(t){return new vt(this.hash(t))}static hash(t){let e=0;for(let i=0;i<t.length;i++)e=t.charCodeAt(i)+((e<<5)-e);return e}}var dv=(o=>(o.NewInstanceCreated="new-instance-created",o.InstanceDestroyed="instance-destroyed",o))(dv||{});class e1{constructor(t){r(this,"guid");r(this,"dontSave");this.guid=t}}function oh(o,t,e=!0,i){if(!o)return;const n=o;if(Ri(o,e),!t){console.warn("Can not send destroy: No networking connection provided",o.guid);return}if(!t.isConnected){j()&&console.debug("Can not send destroy: not connected",o.guid);return}let s=o.guid;if(!s&&n.uuid&&(s=n.uuid),!s){console.warn("Can not send destroy: failed to find guid",o);return}gg(s,t,i)}function gg(o,t,e){const i=new e1(o);(e==null?void 0:e.saveInRoom)===!1&&(i.dontSave=!0),t.send("instance-destroyed",i,fn.Queued)}function uv(o){o.connection.beginListen("instance-destroyed",t=>{tu&&console.log("[Remote] Destroyed",o.scene,t);const e=xg(t.guid,o.scene);e&&Ri(e)})}class t1{constructor(t,e,i){r(this,"filename");r(this,"hash");r(this,"size");this.filename=t,this.hash=e,this.size=i}}class fv{constructor(t,e){r(this,"guid");r(this,"originalGuid");r(this,"seed");r(this,"visible");r(this,"hostData");r(this,"dontSave");r(this,"parent");r(this,"position");r(this,"rotation");r(this,"scale");r(this,"preventCreation");r(this,"deleteStateOnDisconnect");this.originalGuid=t,this.guid=e}}function yg(o,t,e,i){var c,h;const n=o;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(t.context||(t.context=X.Current),!t.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const s=t?{...t}:null,{instance:a,seed:l}=i1(n,t);if(a){const u=a;if(u.guid){tu&&console.log("[Local] new instance","gameobject:",a==null?void 0:a.guid);const f=new fv(n.guid,u.guid);f.seed=l,t.deleteOnDisconnect===!0&&(f.deleteStateOnDisconnect=!0),s&&(s.position&&(f.position={x:s.position.x,y:s.position.y,z:s.position.z}),s.rotation&&(f.rotation={x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w}),s.scale&&(f.scale={x:s.scale.x,y:s.scale.y,z:s.scale.z})),f.position||(f.position={x:u.position.x,y:u.position.y,z:u.position.z}),f.rotation||(f.rotation={x:u.quaternion.x,y:u.quaternion.y,z:u.quaternion.z,w:u.quaternion.w}),f.scale||(f.scale={x:u.scale.x,y:u.scale.y,z:u.scale.z}),f.visible=n.visible,s!=null&&s.parent&&(typeof s.parent=="string"?f.parent=s.parent:f.parent=s.parent.guid),f.hostData=e,i===!1&&(f.dontSave=!0),!((c=t==null?void 0:t.context)==null?void 0:c.connection)&&j()&&console.debug("Object will be instantiated but it will not be synced: not connected",n.guid),t.context.connection.isInRoom&&fa.push(new WeakRef(u)),(h=t==null?void 0:t.context)==null||h.connection.send("new-instance-created",f)}else console.warn("Missing guid, can not send new instance event",u)}return a}function pv(){return Math.random()*9999999}const fa=new Array;function mv(o){o.connection.beginListen("new-instance-created",async t=>{const e=await n1(t.originalGuid,o.scene);if(t.preventCreation===!0)return;if(!e){console.warn("could not find object that was instantiated: "+t.guid);return}const i=new xn;t.position&&(i.position=new d.Vector3(t.position.x,t.position.y,t.position.z)),t.rotation&&(i.rotation=new d.Quaternion(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w)),t.scale&&(i.scale=new d.Vector3(t.scale.x,t.scale.y,t.scale.z)),i.parent=t.parent,t.seed&&(i.idProvider=new vt(t.seed)),i.visible=t.visible,i.context=o,tu&&o.alias&&console.log("[Remote] instantiate in: "+o.alias);const n=Er(e,i);fa.push(new WeakRef(n)),n&&(t.parent==="scene"&&o.scene.add(n),tu&&console.log("[Remote] new instance","gameobject:",n==null?void 0:n.guid,e))}),o.connection.beginListen("left-room",()=>{fa.length>0&&console.debug(`Left networking room, cleaning up ${fa.length} instantiated objects`);for(const t of fa){const e=t.deref();e&&e.destroy()}fa.length=0})}function i1(o,t){const e=pv(),i=t??new xn;i.idProvider=new vt(e);const n=Er(o,i);return{seed:e,instance:n}}const gv={};function yv(o,t){gv[o]=t}async function n1(o,t){const e=gv[o];if(e!=null){const i=await e(o);if(i)return i}return _v(o,t)}function _v(o,t){if(t===null||!o)return null;if(t.guid===o)return t;if(t.children)for(const e of t.children){const i=_v(o,e);if(i)return i}return null}const rh=S("gizmos"),dt=S("debugextension"),tp=S("debugtypes");class s1{constructor(){r(this,"_types",new Map);tp&&console.warn("TypeStore: Created",this)}add(t,e){tp&&console.warn("ADD TYPE",t);const i=this._types.get(t);i?tp&&i!==e&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",t):this._types.set(t,e)}get(t){return this._types.get(t)||null}getKey(t){for(const[e,i]of this._types)if(i===t)return e;return null}}const o1=Symbol("BuiltInType"),k=new s1,r1=function(o){k.get(o.name)||k.add(o.name,o)},_g=S("debugresolvedependencies"),a1=["/extensions/","extensions/"],l1=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function bg(o,t){_g&&console.log(o,t);const e=[];dm(l1,o,t,e);const i=await Promise.all(e);return typeof t=="string"&&i.length===1?i[0]:i}function bv(o,t){return!o||!t?!1:o["needle:identifier"]!=null&&t["needle:identifier"]!=null?o["needle:identifier"]===t["needle:identifier"]:!1}function c1(o,t){o["needle:identifier"]=t}function dm(o,t,e,i){if(typeof e=="object"&&e!==void 0&&e!==null)for(const n of Object.keys(e)){const s=e[n];if(typeof s=="string"){const a=F_(t,s);if(a!=null)typeof a.then=="function"?i.push(a.then(l=>e[n]=l)):e[n]=a;else{const l=U_(o,t,s);if(l){i.push(l.then(c=>(e[n]=c,c)));continue}}}else if(Array.isArray(s))for(let a=0;a<s.length;a++){const l=s[a],c=F_(t,l);if(c!==null){typeof c.then=="function"?i.push(c.then(h=>s[a]=h)):s[a]=c;continue}for(const h of o){const u=vv(h.prefix,l);if(u>=0){_g&&console.log(h,u,h.dependencyName),i.push(t.getDependency(h.dependencyName,u).then(f=>s[a]=f));break}}typeof l=="object"&&dm(o,t,l,i)}else typeof s=="object"&&dm(o,t,s,i)}else if(typeof e=="string"){const n=U_(o,t,e);n&&i.push(n)}}function F_(o,t){if(o&&o.plugins&&typeof t=="string"){for(const e of a1)if(t.startsWith(e)){let i=t.substring(e.length);const n=i.indexOf("/");n>=0&&(i=i.substring(0,n));const s=o.plugins[i];if(dt&&console.log(i,s),typeof(s==null?void 0:s.resolve)=="function"){const a=t.substring(e.length+i.length+1);return s.resolve(o,a)}break}}return null}function U_(o,t,e){for(const i of o){const n=vv(i.prefix,e);if(n>=0)return _g&&console.warn("GET DEPENDENCY",i,n,i.dependencyName),t.getDependency(i.dependencyName,n)}return null}function vv(o,t){if(typeof t=="string"&&t.startsWith(o)){const e=t.substring(o.length),i=Number.parseInt(e);if(i>=0)return i}return-1}const ip="NEEDLE_persistent_assets";function h1(o){return(o==null?void 0:o.___persistentAsset)===!0}class d1{constructor(t){r(this,"parser");this.parser=t}get name(){return ip}async afterRoot(t){var n,s;if(!((s=(n=this.parser)==null?void 0:n.json)!=null&&s.extensions))return;const e=this.parser.json.extensions[ip];if(!e)return;dt&&console.log(e);const i=new Array;for(const a of e==null?void 0:e.assets){const l=bg(this.parser,a);l&&i.push(l)}await Promise.all(i)}resolve(t,e){const i=Number.parseInt(e);if(i>=0){dt&&console.log(e);const n=t.json.extensions[ip];if(n){const s=n==null?void 0:n.assets[i];if(s&&typeof s=="object"){s.___persistentAsset=!0;const a=s.__type;a&&k.get(a)}return s}}return null}}const Ln=S("debugserializer");class u1{constructor(){r(this,"typeMap",new Map)}register(t,e){if(this.typeMap.has(t)){const i=this.typeMap.get(t);if(i===e)return;Ln&&console.warn("Type: "+t+" is already registered",e,i)}Ln&&console.log("Register type serializer",e.name,e,t),this.typeMap.set(t,e)}getSerializer(t){if(t)return this.typeMap.get(t)}getSerializerForConstructor(t,e=0){if(e>20)return;if(!t||!t.constructor){Ln&&console.log("invalid type");return}const i=t.name,n=this.getSerializer(t);if(n!==void 0)return Ln&&console.log("FOUND SERIALIZER",n==null?void 0:n.name,t.name,t.constructor.name,"for type: "+i,n,t,this.typeMap),n;const s=Object.getPrototypeOf(t);if(s&&s!==t){const a=this.getSerializerForConstructor(s,++e);if(a){const l=s.constructor||s.prototype;Ln&&console.log("FOUND SERIALIZER(in constructor) "+l.constructor.name,l.name,l,a),this.register(l,a)}return a}Ln&&console.warn("No serializer found for "+i,t,t.name,t.constructor.name)}}const iu=new u1;class Ki{constructor(t,e){r(this,"name");if(this.name=e,Array.isArray(t))for(const i of t)iu.register(i,this);else iu.register(t,this)}}class f1{constructor(){r(this,"isDevMode",Kt());r(this,"cache",{})}registerDefinedKeys(t,e){if(this.isDevMode&&this.cache[t]===void 0){this.cache[t]=Object.keys(e);const i=e;i.$serializedTypes&&Object.keys(i.$serializedTypes)&&this.cache[t].push(...Object.keys(i.$serializedTypes)),Ln&&console.log("registerDefinedKeys for "+t,this.cache[t],e)}}getDefinedKey(t,e){return this.cache[t]===void 0?!1:this.cache[t].includes(e)}}class vg{constructor(t){r(this,"root");r(this,"gltf");r(this,"gltfId");r(this,"object");r(this,"target");r(this,"nodeId");r(this,"nodeToObject");r(this,"objectToNode");r(this,"context");r(this,"path");r(this,"type");r(this,"serializable");r(this,"implementationInformation");this.root=t}}function wv(o,t){const e=o.$serializedTypes;if(e===void 0)return null;const i={};for(const s in e){const a=o[s];if(a!=null&&typeof a=="object"){const l=iu.getSerializerForConstructor(a);if(l){i[s]=l.onSerialize(a,t);continue}}i[s]=a}function n(s){const a=k._types;for(const[l,c]of a)if(c===o.constructor)return l;return s.__name||s.constructor.name}return i.name=n(o),typeof o.guid=="string"&&(i.guid=o.guid),i}const Ad=[];function xv(o,t){if(!o)return t;typeof o.$serializedTypes=="object"&&(t||(t={}),Object.assign(t,o.$serializedTypes));const e=Object.getPrototypeOf(o);return xv(e,t)}function nu(o,t,e){if(!o)return!1;if(e.target=o,o.onBeforeDeserialize!==void 0){const n=o.onBeforeDeserialize(t,e);if(typeof n=="boolean")return n}const i=xv(o);if(t){if(typeof t.guid=="string"&&(o.guid=t.guid),i)for(const n in i){let s=function(c){const u=c.type;return u?um(l,u,e,void 0,o[n]):um(l,c,e,void 0,o[n])};const a=i[n],l=t[n];if(Ln&&console.log(n,l,o,a),!(o[n]!==void 0&&l===void 0)&&(e.type=void 0,e.path=n,e.serializable=a,!(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(n,l,e)===!0))){if(a===null)o[n]=l;else{if(Array.isArray(a))for(let c=0;c<a.length;c++){const h=a[c],u=s(h);if(u!==void 0||c===a.length-1){o[n]=u;break}}else o[n]=s(a);Ad.length=0}o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(n,l,e)}}g1(o,t)}return m1(o,t,e.implementationInformation),o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(t,e),!0}const p1=S("noerrors");function m1(o,t,e){var s,a;if(p1||!t||!Kt()||!o||o.constructor&&o.constructor[o1]===!0)return;const i=(s=o.constructor)==null?void 0:s.name,n=Object.getOwnPropertyNames(t);for(const l of n){if(l==="sourceId")continue;const c=o[l];if(c==null)continue;const h=t[l];if((e==null?void 0:e.getDefinedKey(i,l))===!1){const u=l.charAt(0).toUpperCase()+l.slice(1);e.getDefinedKey(i,u)&&(Fn(Mi.Warn,'<strong>Please rename</strong> "'+u+'" to "'+l+'" in '+i),console.warn('Please use lowercase for field: "'+u+'" in '+i,h,o));continue}if(h!=null){if(typeof h=="object"&&(c===void 0||!c.isObject3D)){if(typeof h.node=="number"||typeof h.guid=="string"){if(h.could_not_resolve)continue;if(!(c!==void 0&&Object.keys(c).length>1)){Fn(Mi.Warn,`<strong>Missing serialization for object reference!</strong>
171
+ Do you have circular references in your project? <a target="_blank" href="https://docs.needle.tools/circular-reference"> Click here for more information.`,o):console.error('Failed to update active state in hierarchy of "'+o.name+'"',o),console.warn(" ↑ this error might be caused by circular references. Please make sure you don't have files with circular references (e.g. one GLB 1 is loading GLB 2 which is then loading GLB 1 again)."))}function cv(o,t,e,i=0){if(i>1e3)return console.warn("Hierarchy is too deep (> 1000 level) - will abort updating active state"),!1;const n=ol(o);if(t&&(t=n,t&&o.parent)){const c=o.parent;t=c[Es],t===void 0&&(c instanceof d.Scene||(t=!0))}const a=o[Es]!==t;o[Es]=t,a&&(XC&&console.warn("ACTIVE CHANGE",o.name,n,o.visible,t,"changed?"+a,o),KC(o,c=>{t?c.enabled&&(Da(c.__internalAwake.bind(c)),c.enabled&&c.__internalEnable()):c.__didAwake&&c.enabled&&(c.__didEnable=!1,c.onDisable())}));let l=!0;if(o.children)for(const c of o.children)cv(c,t,e,i+1)===!1&&(l=!1);return l}function dc(o){let t=!0,e=o,i=!1;for(;e&&e;){if(e.type==="Scene"&&(i=!0),!ol(e)){t=!1;break}e=e.parent}if(!o){console.error("GO is null");return}o[Es]=t&&i}function KC(o,t){var e;if((e=o.userData)!=null&&e.components)for(const i of o.userData.components)t(i)}const Td=new Map,hv=Symbol("prewarmFlag"),cm=Symbol("waitingForPrewarm"),hm=S("debugprewarm");function ZC(o,t){if(!o||o[hv]===!0||o[cm]===!0)return;Td.has(t)||Td.set(t,[]),o[cm]=!0,Td.get(t).push(o),hm&&console.debug("register prewarm",o.name)}let I_=null,j_=null;function JC(o){if(!o)return;const t=Td.get(o);if(!(t!=null&&t.length))return;const e=o.mainCamera;if(e){hm&&console.log("prewarm",t.length,"objects",[...t]);const i=o.renderer;if(i.compile){const n=o.scene;i.compile(n,e),I_??(I_=new d.WebGLCubeRenderTarget(64)),j_??(j_=new d.CubeCamera(.001,9999999,I_)),j_.update(i,n);for(const s of t)s[hv]=!0,s[cm]=!1;t.length=0,hm&&console.log("prewarm done")}}}re.registerCallback(he.ContextCreated,o=>{const t=o.context;mv(t),uv(t)});const tu=S("debugcomponents"),B_="eff8ba80-635d-11ec-90d6-0242ac120003";class bt{constructor(t){r(this,"_originalSeed");r(this,"_seed");typeof t=="string"&&(t=bt.hash(t)),this._originalSeed=t,this._seed=t}get seed(){return this._seed}set seed(t){this._seed=t}reset(){this._seed=this._originalSeed}generateUUID(t){if(typeof t=="string")return ae.v5(t,B_);const e=this._seed;return this._seed-=1,ae.v5(e.toString(),B_)}initialize(t){typeof t=="string"?this._seed=bt.hash(t):this._seed=t}static createFromString(t){return new bt(this.hash(t))}static hash(t){let e=0;for(let i=0;i<t.length;i++)e=t.charCodeAt(i)+((e<<5)-e);return e}}var dv=(o=>(o.NewInstanceCreated="new-instance-created",o.InstanceDestroyed="instance-destroyed",o))(dv||{});class e1{constructor(t){r(this,"guid");r(this,"dontSave");this.guid=t}}function oh(o,t,e=!0,i){if(!o)return;const n=o;if(Ri(o,e),!t){console.warn("Can not send destroy: No networking connection provided",o.guid);return}if(!t.isConnected){j()&&console.debug("Can not send destroy: not connected",o.guid);return}let s=o.guid;if(!s&&n.uuid&&(s=n.uuid),!s){console.warn("Can not send destroy: failed to find guid",o);return}gg(s,t,i)}function gg(o,t,e){const i=new e1(o);(e==null?void 0:e.saveInRoom)===!1&&(i.dontSave=!0),t.send("instance-destroyed",i,fn.Queued)}function uv(o){o.connection.beginListen("instance-destroyed",t=>{tu&&console.log("[Remote] Destroyed",o.scene,t);const e=xg(t.guid,o.scene);e&&Ri(e)})}class t1{constructor(t,e,i){r(this,"filename");r(this,"hash");r(this,"size");this.filename=t,this.hash=e,this.size=i}}class fv{constructor(t,e){r(this,"guid");r(this,"originalGuid");r(this,"seed");r(this,"visible");r(this,"hostData");r(this,"dontSave");r(this,"parent");r(this,"position");r(this,"rotation");r(this,"scale");r(this,"preventCreation");r(this,"deleteStateOnDisconnect");this.originalGuid=t,this.guid=e}}function yg(o,t,e,i){var c,h;const n=o;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(t.context||(t.context=X.Current),!t.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const s=t?{...t}:null,{instance:a,seed:l}=i1(n,t);if(a){const u=a;if(u.guid){tu&&console.log("[Local] new instance","gameobject:",a==null?void 0:a.guid);const f=new fv(n.guid,u.guid);f.seed=l,t.deleteOnDisconnect===!0&&(f.deleteStateOnDisconnect=!0),s&&(s.position&&(f.position={x:s.position.x,y:s.position.y,z:s.position.z}),s.rotation&&(f.rotation={x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w}),s.scale&&(f.scale={x:s.scale.x,y:s.scale.y,z:s.scale.z})),f.position||(f.position={x:u.position.x,y:u.position.y,z:u.position.z}),f.rotation||(f.rotation={x:u.quaternion.x,y:u.quaternion.y,z:u.quaternion.z,w:u.quaternion.w}),f.scale||(f.scale={x:u.scale.x,y:u.scale.y,z:u.scale.z}),f.visible=n.visible,s!=null&&s.parent&&(typeof s.parent=="string"?f.parent=s.parent:f.parent=s.parent.guid),f.hostData=e,i===!1&&(f.dontSave=!0),!((c=t==null?void 0:t.context)==null?void 0:c.connection)&&j()&&console.debug("Object will be instantiated but it will not be synced: not connected",n.guid),t.context.connection.isInRoom&&fa.push(new WeakRef(u)),(h=t==null?void 0:t.context)==null||h.connection.send("new-instance-created",f)}else console.warn("Missing guid, can not send new instance event",u)}return a}function pv(){return Math.random()*9999999}const fa=new Array;function mv(o){o.connection.beginListen("new-instance-created",async t=>{const e=await n1(t.originalGuid,o.scene);if(t.preventCreation===!0)return;if(!e){console.warn("could not find object that was instantiated: "+t.guid);return}const i=new xn;t.position&&(i.position=new d.Vector3(t.position.x,t.position.y,t.position.z)),t.rotation&&(i.rotation=new d.Quaternion(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w)),t.scale&&(i.scale=new d.Vector3(t.scale.x,t.scale.y,t.scale.z)),i.parent=t.parent,t.seed&&(i.idProvider=new bt(t.seed)),i.visible=t.visible,i.context=o,tu&&o.alias&&console.log("[Remote] instantiate in: "+o.alias);const n=Er(e,i);fa.push(new WeakRef(n)),n&&(t.parent==="scene"&&o.scene.add(n),tu&&console.log("[Remote] new instance","gameobject:",n==null?void 0:n.guid,e))}),o.connection.beginListen("left-room",()=>{fa.length>0&&console.debug(`Left networking room, cleaning up ${fa.length} instantiated objects`);for(const t of fa){const e=t.deref();e&&e.destroy()}fa.length=0})}function i1(o,t){const e=pv(),i=t??new xn;i.idProvider=new bt(e);const n=Er(o,i);return{seed:e,instance:n}}const gv={};function yv(o,t){gv[o]=t}async function n1(o,t){const e=gv[o];if(e!=null){const i=await e(o);if(i)return i}return _v(o,t)}function _v(o,t){if(t===null||!o)return null;if(t.guid===o)return t;if(t.children)for(const e of t.children){const i=_v(o,e);if(i)return i}return null}const rh=S("gizmos"),dt=S("debugextension"),tp=S("debugtypes");class s1{constructor(){r(this,"_types",new Map);tp&&console.warn("TypeStore: Created",this)}add(t,e){tp&&console.warn("ADD TYPE",t);const i=this._types.get(t);i?tp&&i!==e&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",t):this._types.set(t,e)}get(t){return this._types.get(t)||null}getKey(t){for(const[e,i]of this._types)if(i===t)return e;return null}}const o1=Symbol("BuiltInType"),k=new s1,r1=function(o){k.get(o.name)||k.add(o.name,o)},_g=S("debugresolvedependencies"),a1=["/extensions/","extensions/"],l1=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function bg(o,t){_g&&console.log(o,t);const e=[];dm(l1,o,t,e);const i=await Promise.all(e);return typeof t=="string"&&i.length===1?i[0]:i}function bv(o,t){return!o||!t?!1:o["needle:identifier"]!=null&&t["needle:identifier"]!=null?o["needle:identifier"]===t["needle:identifier"]:!1}function c1(o,t){o["needle:identifier"]=t}function dm(o,t,e,i){if(typeof e=="object"&&e!==void 0&&e!==null)for(const n of Object.keys(e)){const s=e[n];if(typeof s=="string"){const a=F_(t,s);if(a!=null)typeof a.then=="function"?i.push(a.then(l=>e[n]=l)):e[n]=a;else{const l=U_(o,t,s);if(l){i.push(l.then(c=>(e[n]=c,c)));continue}}}else if(Array.isArray(s))for(let a=0;a<s.length;a++){const l=s[a],c=F_(t,l);if(c!==null){typeof c.then=="function"?i.push(c.then(h=>s[a]=h)):s[a]=c;continue}for(const h of o){const u=vv(h.prefix,l);if(u>=0){_g&&console.log(h,u,h.dependencyName),i.push(t.getDependency(h.dependencyName,u).then(f=>s[a]=f));break}}typeof l=="object"&&dm(o,t,l,i)}else typeof s=="object"&&dm(o,t,s,i)}else if(typeof e=="string"){const n=U_(o,t,e);n&&i.push(n)}}function F_(o,t){if(o&&o.plugins&&typeof t=="string"){for(const e of a1)if(t.startsWith(e)){let i=t.substring(e.length);const n=i.indexOf("/");n>=0&&(i=i.substring(0,n));const s=o.plugins[i];if(dt&&console.log(i,s),typeof(s==null?void 0:s.resolve)=="function"){const a=t.substring(e.length+i.length+1);return s.resolve(o,a)}break}}return null}function U_(o,t,e){for(const i of o){const n=vv(i.prefix,e);if(n>=0)return _g&&console.warn("GET DEPENDENCY",i,n,i.dependencyName),t.getDependency(i.dependencyName,n)}return null}function vv(o,t){if(typeof t=="string"&&t.startsWith(o)){const e=t.substring(o.length),i=Number.parseInt(e);if(i>=0)return i}return-1}const ip="NEEDLE_persistent_assets";function h1(o){return(o==null?void 0:o.___persistentAsset)===!0}class d1{constructor(t){r(this,"parser");this.parser=t}get name(){return ip}async afterRoot(t){var n,s;if(!((s=(n=this.parser)==null?void 0:n.json)!=null&&s.extensions))return;const e=this.parser.json.extensions[ip];if(!e)return;dt&&console.log(e);const i=new Array;for(const a of e==null?void 0:e.assets){const l=bg(this.parser,a);l&&i.push(l)}await Promise.all(i)}resolve(t,e){const i=Number.parseInt(e);if(i>=0){dt&&console.log(e);const n=t.json.extensions[ip];if(n){const s=n==null?void 0:n.assets[i];if(s&&typeof s=="object"){s.___persistentAsset=!0;const a=s.__type;a&&k.get(a)}return s}}return null}}const Ln=S("debugserializer");class u1{constructor(){r(this,"typeMap",new Map)}register(t,e){if(this.typeMap.has(t)){const i=this.typeMap.get(t);if(i===e)return;Ln&&console.warn("Type: "+t+" is already registered",e,i)}Ln&&console.log("Register type serializer",e.name,e,t),this.typeMap.set(t,e)}getSerializer(t){if(t)return this.typeMap.get(t)}getSerializerForConstructor(t,e=0){if(e>20)return;if(!t||!t.constructor){Ln&&console.log("invalid type");return}const i=t.name,n=this.getSerializer(t);if(n!==void 0)return Ln&&console.log("FOUND SERIALIZER",n==null?void 0:n.name,t.name,t.constructor.name,"for type: "+i,n,t,this.typeMap),n;const s=Object.getPrototypeOf(t);if(s&&s!==t){const a=this.getSerializerForConstructor(s,++e);if(a){const l=s.constructor||s.prototype;Ln&&console.log("FOUND SERIALIZER(in constructor) "+l.constructor.name,l.name,l,a),this.register(l,a)}return a}Ln&&console.warn("No serializer found for "+i,t,t.name,t.constructor.name)}}const iu=new u1;class Ki{constructor(t,e){r(this,"name");if(this.name=e,Array.isArray(t))for(const i of t)iu.register(i,this);else iu.register(t,this)}}class f1{constructor(){r(this,"isDevMode",Kt());r(this,"cache",{})}registerDefinedKeys(t,e){if(this.isDevMode&&this.cache[t]===void 0){this.cache[t]=Object.keys(e);const i=e;i.$serializedTypes&&Object.keys(i.$serializedTypes)&&this.cache[t].push(...Object.keys(i.$serializedTypes)),Ln&&console.log("registerDefinedKeys for "+t,this.cache[t],e)}}getDefinedKey(t,e){return this.cache[t]===void 0?!1:this.cache[t].includes(e)}}class vg{constructor(t){r(this,"root");r(this,"gltf");r(this,"gltfId");r(this,"object");r(this,"target");r(this,"nodeId");r(this,"nodeToObject");r(this,"objectToNode");r(this,"context");r(this,"path");r(this,"type");r(this,"serializable");r(this,"implementationInformation");this.root=t}}function wv(o,t){const e=o.$serializedTypes;if(e===void 0)return null;const i={};for(const s in e){const a=o[s];if(a!=null&&typeof a=="object"){const l=iu.getSerializerForConstructor(a);if(l){i[s]=l.onSerialize(a,t);continue}}i[s]=a}function n(s){const a=k._types;for(const[l,c]of a)if(c===o.constructor)return l;return s.__name||s.constructor.name}return i.name=n(o),typeof o.guid=="string"&&(i.guid=o.guid),i}const Ad=[];function xv(o,t){if(!o)return t;typeof o.$serializedTypes=="object"&&(t||(t={}),Object.assign(t,o.$serializedTypes));const e=Object.getPrototypeOf(o);return xv(e,t)}function nu(o,t,e){if(!o)return!1;if(e.target=o,o.onBeforeDeserialize!==void 0){const n=o.onBeforeDeserialize(t,e);if(typeof n=="boolean")return n}const i=xv(o);if(t){if(typeof t.guid=="string"&&(o.guid=t.guid),i)for(const n in i){let s=function(c){const u=c.type;return u?um(l,u,e,void 0,o[n]):um(l,c,e,void 0,o[n])};const a=i[n],l=t[n];if(Ln&&console.log(n,l,o,a),!(o[n]!==void 0&&l===void 0)&&(e.type=void 0,e.path=n,e.serializable=a,!(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(n,l,e)===!0))){if(a===null)o[n]=l;else{if(Array.isArray(a))for(let c=0;c<a.length;c++){const h=a[c],u=s(h);if(u!==void 0||c===a.length-1){o[n]=u;break}}else o[n]=s(a);Ad.length=0}o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(n,l,e)}}g1(o,t)}return m1(o,t,e.implementationInformation),o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(t,e),!0}const p1=S("noerrors");function m1(o,t,e){var s,a;if(p1||!t||!Kt()||!o||o.constructor&&o.constructor[o1]===!0)return;const i=(s=o.constructor)==null?void 0:s.name,n=Object.getOwnPropertyNames(t);for(const l of n){if(l==="sourceId")continue;const c=o[l];if(c==null)continue;const h=t[l];if((e==null?void 0:e.getDefinedKey(i,l))===!1){const u=l.charAt(0).toUpperCase()+l.slice(1);e.getDefinedKey(i,u)&&(Fn(Mi.Warn,'<strong>Please rename</strong> "'+u+'" to "'+l+'" in '+i),console.warn('Please use lowercase for field: "'+u+'" in '+i,h,o));continue}if(h!=null){if(typeof h=="object"&&(c===void 0||!c.isObject3D)){if(typeof h.node=="number"||typeof h.guid=="string"){if(h.could_not_resolve)continue;if(!(c!==void 0&&Object.keys(c).length>1)){Fn(Mi.Warn,`<strong>Missing serialization for object reference!</strong>
172
172
 
173
173
  Please change to:
174
174
  @serializable(Object3D)
@@ -183,12 +183,12 @@ Please change to:
183
183
  ${l}? : AssetReference;
184
184
 
185
185
  in script ${i}.ts
186
- <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(i,l,o[l],o);continue}}}}function g1(o,t){for(const e of Object.keys(t)){const i=t[e];if(typeof i=="object"&&i!==null&&i!==void 0){const n=o[e];if(!n){Ln&&console.log(e,"is undefined on",o);continue}for(const s of Object.keys(i))if(n[s]===void 0&&z_(i[s])&&!z_(n)){const l=y1(n,s);if(l&&((l==null?void 0:l.writable)===void 0||(l==null?void 0:l.writable)===!1)&&l.set===void 0){Ln&&console.warn('Property is not writable "'+s+'"',n,l,i[s],n[s]);continue}n[s]=i[s]}}}}function y1(o,t){for(;o;){const e=Object.getOwnPropertyDescriptor(o,t);if(e)return e;o=Object.getPrototypeOf(o)}}function z_(o){switch(typeof o){case"number":case"string":case"boolean":return!0}return!1}function um(o,t,e,i,n){let s=typeof t=="function"&&t.prototype===void 0,a=t;if(s)try{if(a=t==null?void 0:t.call(t,n),s=!1,a==null)return}catch(u){console.error("Error in callback",u,o)}if(e.type=a,!s&&n&&(n instanceof d.Material||n instanceof d.Mesh||n instanceof d.BufferGeometry||n instanceof d.AnimationClip))return n;if(i||(i={serializer:iu.getSerializerForConstructor(a)}),n&&typeof n=="object"&&h1(n)){if(n.__concreteInstance)return n.__concreteInstance;const u=n;if(!u.$serializedTypes&&a.prototype.$serializedTypes&&(u.$serializedTypes=a.prototype.$serializedTypes),u.$serializedTypes&&nu(u,o,e),n&&a!==void 0)try{let f=null;i.serializer&&(f=i.serializer.onDeserialize(o,e)),f||(f=new a,dt&&console.log("Create concrete instance for persistent asset",n,"instance:",f),Ga(f,n)),n.__concreteInstance=f,n=f}catch(f){console.error("Error creating instance or creating values on instance",f,n,a)}return n}if(Array.isArray(o)){const u=[];for(let f=0;f<o.length;f++){const p=o[f],g=um(p,t,e,i,p);u.push(g)}return u}const l=i==null?void 0:i.serializer;if(l)return l.onDeserialize(o,e);if(n instanceof d.Texture)return n;let c;if(o&&(o.isMaterial||o.isTexture||o.isObject3D||o instanceof d.AnimationClip))c=o;else{if(o===void 0)return;if(o===null&&(a===d.Material||a===d.Texture||a===d.Mesh||a===d.AnimationClip))return null;try{c=new a(..._1(o))}catch(u){console.error("Error creating "+e.path,e.target,u);return}}const h=c;return h.$serializedTypes&&nu(h,o,e),c}function _1(o){if(Ad.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(const t of Object.keys(o))Ad.push(o[t]);return Ad}const fm=Symbol("assigned component properties");function Ga(o,t,e,i){var s;if(t==null||o==null)return;o[fm]=!0;const n=((s=o.constructor)==null?void 0:s.name)??"unknown";e==null||e.registerDefinedKeys(n,o);for(const a of Object.keys(t)){const l=b1(o,a);if(typeof(l==null?void 0:l.value)!="function"){if(!l||l.writable===!0){const c=i!=null&&i.onAssign?i.onAssign(t,a,t[a]):t[a];o[a]=c}else if((l==null?void 0:l.set)!==void 0){const c=i!=null&&i.onAssign?i.onAssign(t,a,t[a]):t[a];o[a]=c}}}delete o[fm]}function b1(o,t){let e;do e=Object.getOwnPropertyDescriptor(o,t);while(!e&&(o=Object.getPrototypeOf(o)));return e}const Sv=Symbol("customVisibilityFlag");function xs(o,t){o.layers[Sv]=t}const N_=Symbol("DidPatchLayers");function v1(){const o=d.Layers.prototype;if(o[N_])return;o[N_]=!0;const t=o.test;o.test=function(e){return this[Sv]===!1?!1:t.call(this,e)}}v1();Object.defineProperty(d.PerspectiveCamera.prototype,"fov",{get:function(){return this._fov},set:function(o){const t=o!==this._fov;this._fov=o,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});Object.defineProperty(d.PerspectiveCamera.prototype,"near",{get:function(){return this._near},set:function(o){const t=o!==this._near;this._near=o,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});Object.defineProperty(d.PerspectiveCamera.prototype,"far",{get:function(){return this._far},set:function(o){const t=o!==this._far;this._far=o,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const Cv=new Map;function Pv(o,t){if(!o)return;if(!t){console.warn("No prototype found",o,o.prototype,o.constructor);return}const e=Cv.get(t);e&&e.apply(o)}function Mv(o){const t=w1(o.prototype);Cv.set(o,t)}function w1(o){return new x1(o)}class x1{constructor(t){r(this,"$symbol");r(this,"extensions");r(this,"descriptors");this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(t),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const i=this.extensions[e],n=Object.getOwnPropertyDescriptor(t,i);n&&this.descriptors.push(n)}}apply(t){if(!t[this.$symbol]){t[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const i=this.extensions[e],n=this.descriptors[e];n&&Object.defineProperty(t,i,n)}}}}const S1=S("debuggetcomponent"),$_=()=>S1||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function C1(o){return o==null||o.isObject3D?o:o.object&&o.object.isObject3D?o.object:o}function wg(o,t){if(!o||!o.userData.components)return t;const e=o.userData.components.indexOf(t);return e<0||(sh.dispatchComponentLifecycleEvent("removing-component",t),t.gameObject=null,o.userData.components.splice(e,1)),t}function ah(o,t,e){const i=jr(o,t);return i||Oi(o,t,e)}const Ov=new vt("addComponentIdProvider");function vr(o,t,e=!0){o.userData||(o.userData={}),o.userData.components||(o.userData.components=[]),o.userData.components.push(t),t.gameObject=o,(t.guid===void 0||t.guid==="invalid")&&(t.guid=Ov.generateUUID()),Wu(o),qu(t,t.context);try{e&&t.__internalAwake&&(dc(o),t.activeAndEnabled&&t.__internalAwake()),sh.dispatchComponentLifecycleEvent("component-added",t)}catch(i){console.error(i)}return t}function Oi(o,t,e,i){var n;if(typeof t=="function"){const s=new t;e&&s.__internalNewInstanceCreated(e);let a=!0;return(i==null?void 0:i.callAwake)!=null&&(a=i.callAwake),vr(o,s,a)}if(t.destroyed)return console.warn("Can not move/add a destroyed component",t),t;if(t.gameObject===o)return t;if(t.gameObject&&((n=t.gameObject.userData)!=null&&n.components)){const s=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(s,1)}if(o.userData||(o.userData={}),!o.userData.components)o.userData.components=[];else if(o.userData.components.includes(t))return t;return o.userData.components.push(t),t.gameObject=o,(t.guid===void 0||t.guid==="invalid")&&(t.guid=Ov.generateUUID()),e&&t._internalInit(e),qu(t,t.context),t}function kv(o){if(o.gameObject&&o.gameObject.userData.components){const t=o.gameObject.userData.components.indexOf(o);o.gameObject.userData.components.splice(t,1)}o.__internalDisable&&o.__internalDisable(),ws(o,o.context??X.Current),o.destroy(),o.gameObject=null}let V_=!1;function Rv(o,t,e){var i;if(o==null)return null;if(!o.isObject3D)return console.error("Object is not object3D"),null;if(!((i=o==null?void 0:o.userData)!=null&&i.components)||(typeof t=="string"&&(V_||(V_=!0,console.warn(`Accessing components by name is not supported.
186
+ <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(i,l,o[l],o);continue}}}}function g1(o,t){for(const e of Object.keys(t)){const i=t[e];if(typeof i=="object"&&i!==null&&i!==void 0){const n=o[e];if(!n){Ln&&console.log(e,"is undefined on",o);continue}for(const s of Object.keys(i))if(n[s]===void 0&&z_(i[s])&&!z_(n)){const l=y1(n,s);if(l&&((l==null?void 0:l.writable)===void 0||(l==null?void 0:l.writable)===!1)&&l.set===void 0){Ln&&console.warn('Property is not writable "'+s+'"',n,l,i[s],n[s]);continue}n[s]=i[s]}}}}function y1(o,t){for(;o;){const e=Object.getOwnPropertyDescriptor(o,t);if(e)return e;o=Object.getPrototypeOf(o)}}function z_(o){switch(typeof o){case"number":case"string":case"boolean":return!0}return!1}function um(o,t,e,i,n){let s=typeof t=="function"&&t.prototype===void 0,a=t;if(s)try{if(a=t==null?void 0:t.call(t,n),s=!1,a==null)return}catch(u){console.error("Error in callback",u,o)}if(e.type=a,!s&&n&&(n instanceof d.Material||n instanceof d.Mesh||n instanceof d.BufferGeometry||n instanceof d.AnimationClip))return n;if(i||(i={serializer:iu.getSerializerForConstructor(a)}),n&&typeof n=="object"&&h1(n)){if(n.__concreteInstance)return n.__concreteInstance;const u=n;if(!u.$serializedTypes&&a.prototype.$serializedTypes&&(u.$serializedTypes=a.prototype.$serializedTypes),u.$serializedTypes&&nu(u,o,e),n&&a!==void 0)try{let f=null;i.serializer&&(f=i.serializer.onDeserialize(o,e)),f||(f=new a,dt&&console.log("Create concrete instance for persistent asset",n,"instance:",f),Ga(f,n)),n.__concreteInstance=f,n=f}catch(f){console.error("Error creating instance or creating values on instance",f,n,a)}return n}if(Array.isArray(o)){const u=[];for(let f=0;f<o.length;f++){const p=o[f],g=um(p,t,e,i,p);u.push(g)}return u}const l=i==null?void 0:i.serializer;if(l)return l.onDeserialize(o,e);if(n instanceof d.Texture)return n;let c;if(o&&(o.isMaterial||o.isTexture||o.isObject3D||o instanceof d.AnimationClip))c=o;else{if(o===void 0)return;if(o===null&&(a===d.Material||a===d.Texture||a===d.Mesh||a===d.AnimationClip))return null;try{c=new a(..._1(o))}catch(u){console.error("Error creating "+e.path,e.target,u);return}}const h=c;return h.$serializedTypes&&nu(h,o,e),c}function _1(o){if(Ad.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(const t of Object.keys(o))Ad.push(o[t]);return Ad}const fm=Symbol("assigned component properties");function Ga(o,t,e,i){var s;if(t==null||o==null)return;o[fm]=!0;const n=((s=o.constructor)==null?void 0:s.name)??"unknown";e==null||e.registerDefinedKeys(n,o);for(const a of Object.keys(t)){const l=b1(o,a);if(typeof(l==null?void 0:l.value)!="function"){if(!l||l.writable===!0){const c=i!=null&&i.onAssign?i.onAssign(t,a,t[a]):t[a];o[a]=c}else if((l==null?void 0:l.set)!==void 0){const c=i!=null&&i.onAssign?i.onAssign(t,a,t[a]):t[a];o[a]=c}}}delete o[fm]}function b1(o,t){let e;do e=Object.getOwnPropertyDescriptor(o,t);while(!e&&(o=Object.getPrototypeOf(o)));return e}const Sv=Symbol("customVisibilityFlag");function xs(o,t){o.layers[Sv]=t}const N_=Symbol("DidPatchLayers");function v1(){const o=d.Layers.prototype;if(o[N_])return;o[N_]=!0;const t=o.test;o.test=function(e){return this[Sv]===!1?!1:t.call(this,e)}}v1();Object.defineProperty(d.PerspectiveCamera.prototype,"fov",{get:function(){return this._fov},set:function(o){const t=o!==this._fov;this._fov=o,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});Object.defineProperty(d.PerspectiveCamera.prototype,"near",{get:function(){return this._near},set:function(o){const t=o!==this._near;this._near=o,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});Object.defineProperty(d.PerspectiveCamera.prototype,"far",{get:function(){return this._far},set:function(o){const t=o!==this._far;this._far=o,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const Cv=new Map;function Pv(o,t){if(!o)return;if(!t){console.warn("No prototype found",o,o.prototype,o.constructor);return}const e=Cv.get(t);e&&e.apply(o)}function Mv(o){const t=w1(o.prototype);Cv.set(o,t)}function w1(o){return new x1(o)}class x1{constructor(t){r(this,"$symbol");r(this,"extensions");r(this,"descriptors");this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(t),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const i=this.extensions[e],n=Object.getOwnPropertyDescriptor(t,i);n&&this.descriptors.push(n)}}apply(t){if(!t[this.$symbol]){t[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const i=this.extensions[e],n=this.descriptors[e];n&&Object.defineProperty(t,i,n)}}}}const S1=S("debuggetcomponent"),$_=()=>S1||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function C1(o){return o==null||o.isObject3D?o:o.object&&o.object.isObject3D?o.object:o}function wg(o,t){if(!o||!o.userData.components)return t;const e=o.userData.components.indexOf(t);return e<0||(sh.dispatchComponentLifecycleEvent("removing-component",t),t.gameObject=null,o.userData.components.splice(e,1)),t}function ah(o,t,e){const i=jr(o,t);return i||Oi(o,t,e)}const Ov=new bt("addComponentIdProvider");function vr(o,t,e=!0){o.userData||(o.userData={}),o.userData.components||(o.userData.components=[]),o.userData.components.push(t),t.gameObject=o,(t.guid===void 0||t.guid==="invalid")&&(t.guid=Ov.generateUUID()),Wu(o),qu(t,t.context);try{e&&t.__internalAwake&&(dc(o),t.activeAndEnabled&&t.__internalAwake()),sh.dispatchComponentLifecycleEvent("component-added",t)}catch(i){console.error(i)}return t}function Oi(o,t,e,i){var n;if(typeof t=="function"){const s=new t;e&&s.__internalNewInstanceCreated(e);let a=!0;return(i==null?void 0:i.callAwake)!=null&&(a=i.callAwake),vr(o,s,a)}if(t.destroyed)return console.warn("Can not move/add a destroyed component",t),t;if(t.gameObject===o)return t;if(t.gameObject&&((n=t.gameObject.userData)!=null&&n.components)){const s=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(s,1)}if(o.userData||(o.userData={}),!o.userData.components)o.userData.components=[];else if(o.userData.components.includes(t))return t;return o.userData.components.push(t),t.gameObject=o,(t.guid===void 0||t.guid==="invalid")&&(t.guid=Ov.generateUUID()),e&&t._internalInit(e),qu(t,t.context),t}function kv(o){if(o.gameObject&&o.gameObject.userData.components){const t=o.gameObject.userData.components.indexOf(o);o.gameObject.userData.components.splice(t,1)}o.__internalDisable&&o.__internalDisable(),ws(o,o.context??X.Current),o.destroy(),o.gameObject=null}let V_=!1;function Rv(o,t,e){var i;if(o==null)return null;if(!o.isObject3D)return console.error("Object is not object3D"),null;if(!((i=o==null?void 0:o.userData)!=null&&i.components)||(typeof t=="string"&&(V_||(V_=!0,console.warn(`Accessing components by name is not supported.
187
187
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
188
188
 
189
189
  You can import other modules your main module to get access to types
190
190
  or if you use npmdefs you can make types available globally using globalThis:
191
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,t))),$_()&&console.log("[onGetComponent] FIND",t),t==null))return null;for(let n=0;n<o.userData.components.length;n++){const s=o.userData.components[n];let a=Object.getPrototypeOf(s);for(;a;){if(a===t.prototype)if($_()&&console.log("[onGetComponent] MATCH BY PROTOYPE",a),e)e.push(s);else return s;a=Object.getPrototypeOf(a)}}return e||null}function jr(o,t){const e=Rv(o,t);return e?Array.isArray(e)?e[0]:e:null}function lh(o,t,e,i=!0){return e||(e=[]),i&&(e.length=0),Rv(o,t,e),e}function ch(o,t,e){var n;if(e===!1&&o[Es]===!1)return null;const i=jr(o,t);if(e===!1&&(i==null?void 0:i.enabled)===!1)return null;if(i)return i;for(let s=0;s<((n=o==null?void 0:o.children)==null?void 0:n.length);s++){const a=ch(o.children[s],t);if(a)return a}return null}function sl(o,t,e,i=!0){var n;e||(e=[]),i&&(e.length=0),lh(o,t,e,!1);for(let s=0;s<((n=o==null?void 0:o.children)==null?void 0:n.length);s++)sl(o.children[s],t,e,!1);return e}function Lc(o,t){if(!o)return null;if(Array.isArray(o)){for(let i=0;i<o.length;i++){const n=C1(o[i]),s=Lc(n,t);if(s)return s}return null}const e=jr(o,t);return e||(o.parent?Lc(o.parent,t):null)}function Vu(o,t,e,i=!0){return e||(e=[]),i&&(e.length=0),o?(lh(o,t,e,!1),o.parent?Vu(o.parent,t,e,!1):e):e}function hh(o,t=void 0,e=!0){if(!o)return null;if(!t&&(t=X.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),null;let i=t;if(i.isScene||(i=t==null?void 0:t.scene),!i)return null;const n=ch(i,o,e);return n||null}function Ev(o,t,e=void 0){if(!o)return t??[];if(t||(t=[]),t.length=0,!e&&(e=X.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),t;"scene"in e&&(e=e.scene);const i=e;return i&&sl(i,o,t,!1),t}function Wu(o){o&&o.isObject3D===!0&&Pv(o,d.Object3D)}d.Object3D.prototype.SetActive=function(o){this.visible=o};d.Object3D.prototype.setActive=function(o){this.visible=o};d.Object3D.prototype.destroy=function(){Ri(this)};d.Object3D.prototype.addComponent=function(o,t){return Oi(this,o,t)};d.Object3D.prototype.addNewComponent=function(o,t){return Oi(this,o,t)};d.Object3D.prototype.removeComponent=function(o){return wg(this,o)};d.Object3D.prototype.getOrAddComponent=function(o,t){return ah(this,o,t)};d.Object3D.prototype.getComponent=function(o){return jr(this,o)};d.Object3D.prototype.getComponents=function(o,t){return lh(this,o,t)};d.Object3D.prototype.getComponentInChildren=function(o){return ch(this,o)};d.Object3D.prototype.getComponentsInChildren=function(o,t){return sl(this,o,t)};d.Object3D.prototype.getComponentInParent=function(o){return Lc(this,o)};d.Object3D.prototype.getComponentsInParent=function(o,t){return Vu(this,o,t)};Object.getOwnPropertyDescriptor(d.Object3D.prototype,"activeSelf")||Object.defineProperty(d.Object3D.prototype,"activeSelf",{get:function(){return ol(this)},set:function(o){uc(this,o)}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldPosition")||Object.defineProperty(d.Object3D.prototype,"worldPosition",{get:function(){return this instanceof H.TransformControlsGizmo?Q(this.object):Q(this)},set:function(o){st(this,o)}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldQuaternion")||Object.defineProperty(d.Object3D.prototype,"worldQuaternion",{get:function(){return this instanceof H.TransformControlsGizmo?_e(this.object):_e(this)},set:function(o){Hi(this,o)}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldRotation")||Object.defineProperty(d.Object3D.prototype,"worldRotation",{get:function(){return Bu(this)},set:function(o){P0(this,o)}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldScale")||Object.defineProperty(d.Object3D.prototype,"worldScale",{get:function(){return Ue(this)},set:function(o){Na(this,o)}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldForward")||Object.defineProperty(d.Object3D.prototype,"worldForward",{get:function(){return V().set(0,0,1).applyQuaternion(_e(this))}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldRight")||Object.defineProperty(d.Object3D.prototype,"worldRight",{get:function(){return V().set(1,0,0).applyQuaternion(_e(this))}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldUp")||Object.defineProperty(d.Object3D.prototype,"worldUp",{get:function(){return V().set(0,1,0).applyQuaternion(_e(this))}});Mv(d.Object3D);class ie extends d.Color{constructor(e,i,n,s){super();r(this,"alpha",1);typeof e=="number"&&typeof i=="number"&&typeof n=="number"?(this.set(e,i,n),this.alpha=typeof s=="number"?s:1):e!==void 0&&(this.set(e),this.alpha=1)}get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,i){const n=e;return n.alpha!=null&&(this.alpha=z.lerp(this.alpha,n.alpha,i)),super.lerp(e,i)}lerpColors(e,i,n){const s=e,a=i;return s.alpha!=null&&a.alpha!=null&&(this.alpha=z.lerp(s.alpha,a.alpha,n)),super.lerpColors(e,i,n)}multiply(e){const i=e;return i.alpha!=null&&(this.alpha=this.alpha*i.alpha),super.multiply(e)}fromArray(e,i=0){return this.alpha=e[i+3],super.fromArray(e,i)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new ie(0,0,0,0);if(e.startsWith("#")&&e.length===9){const i=parseInt(e.slice(1,9),16),n=i>>24&255,s=i>>16&255,a=i>>8&255,l=i>>0&255;return new ie(n/255,s/255,a/255,l/255)}else if(e.startsWith("#")){const i=parseInt(e.slice(1),16),n=i>>16&255,s=i>>8&255,a=i>>0&255;return new ie(n/255,s/255,a/255,1)}else if(e.startsWith("rgba")){const i=e.slice(5,-1).split(",").map(Number);return new ie(i[0]/255,i[1]/255,i[2]/255,i[3])}else if(e.startsWith("rgb")){const i=e.slice(4,-1).split(",").map(Number);return new ie(i[0]/255,i[1]/255,i[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new ie(e[0],e[1],e[2],e[3]);if(e.length===3)return new ie(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new ie(e)}}const Ld=S("debuggetcomponent"),wr=S("debuginstantiate");class xn{constructor(){r(this,"idProvider");r(this,"parent");r(this,"keepWorldPosition");r(this,"position");r(this,"rotation");r(this,"scale");r(this,"visible");r(this,"context");r(this,"components")}clone(){var e,i,n;const t=new xn;return t.idProvider=this.idProvider,t.parent=this.parent,t.keepWorldPosition=this.keepWorldPosition,t.position=(e=this.position)==null?void 0:e.clone(),t.rotation=(i=this.rotation)==null?void 0:i.clone(),t.scale=(n=this.scale)==null?void 0:n.clone(),t.visible=this.visible,t.context=this.context,t.components=this.components,t}cloneAssign(t){var e,i,n;this.idProvider=t.idProvider,this.parent=t.parent,this.keepWorldPosition=t.keepWorldPosition,this.position=(e=t.position)==null?void 0:e.clone(),this.rotation=(i=t.rotation)==null?void 0:i.clone(),this.scale=(n=t.scale)==null?void 0:n.clone(),this.visible=t.visible,this.context=t.context,this.components=t.components}}function ol(o){return o.visible}function uc(o,t){return typeof t=="number"&&(t=t>.5),o.visible=t,o.visible}function Tv(o){return o[Es]||Gu(o)}function Av(o,t){o[rv]=t}function Gu(o){return Wi.isUsingInstancing(o)}function xg(o,t){return za(o,t,!0,!0)}const Lv=Symbol("isDestroyed");function kr(o){return o[Lv]}function Dv(o,t){o[Lv]=t}const pm=Symbol("isDontDestroy");function pa(o,t=!0){o[pm]=t}const Dd=[],Id=[];function Ri(o,t=!0,e=!1){Dd.length=0,Id.length=0,mm(o,t,!0);for(const i of Dd)i.gameObject=null,i.context=null;for(const i of Id)Dv(i,!0),e&&Se(i),ov(i);Id.length=0,Dd.length=0}function mm(o,t=!0,e=!0){var a;if(o==null)return;const i=o;if(i.isComponent){if(i[pm])return;Dd.push(i);const l=i.gameObject;i.__internalDisable(),i.__internalDestroy(),i.gameObject=l;return}if(o[pm])return;const n=o;Ld&&console.log(n),Id.push(n);const s=(a=n.userData)==null?void 0:a.components;if(s!=null&&Array.isArray(s)){let l=s.length;for(let c=0;c<s.length;c++){const h=s[c];mm(h,t,!1),s.length<l&&(l=s.length,c--)}}if(t&&n.children)for(const l of n.children)mm(l,t,!1);e&&n.removeFromParent()}function Rr(o,t,e=!0){return Iv(o,t,e)}function*Hu(o,t,e=!1,i=999,n=0){if(o!=null&&o.userData.components&&!(n>i)){for(const s of o.userData.components)t&&(s==null?void 0:s.isComponent)===!0&&s instanceof t?yield s:yield s;if(e===!0)for(const s of o.children)yield*Hu(s,t,!0,i,n+1)}}function Iv(o,t,e,i=0){var n;if(o){if(o.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if((n=o.userData)!=null&&n.components)for(let s=0;s<o.userData.components.length;s++){const a=o.userData.components[s];if((a==null?void 0:a.isComponent)===!0){const l=t(a);if(l!==void 0)return l}}if(e&&o.children){const s=i+1;for(let a=0;a<o.children.length;a++){const l=o.children[a];if(!l)continue;const c=Iv(l,t,e,s);if(c!==void 0)return c}}}}function Er(o,t){if("isAssetReference"in o)return o.instantiate(t??void 0);let e=null;t!=null&&(t.x!==void 0?(e=new xn,e.position=t):e=t);let i=X.Current;e!=null&&e.context&&(i=e.context),Ld&&i.alias&&console.log("context",i.alias),e&&!e.idProvider&&(e.idProvider=new vt(Date.now()));const n=[],s={},a={},l=jv(i,o,e,n,s,a);l&&(M1(s),P1(a,s)),Ld&&(Xd(o,!0),Xd(l,!0));const c={};if((e==null?void 0:e.components)!==!1){for(const h in n){const u=n[h],f=u.guid;e&&e.idProvider&&(u.guid=e.idProvider.generateUUID(),c[f]=u.guid,Ld&&console.log(u.name,u.guid)),qu(u,i),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const h in n){const u=n[h];u.resolveGuids&&u.resolveGuids(c),u.enabled!==!1&&(u.enabled=!0)}eu(i)}return l}function jv(o,t,e,i,n,s){var u;if(!t||t[Si])return null;const a=t.userData;t.userData={};const l=t.children;t.children=[];const c=t.clone(!1);if(Wu(c),t.userData=a,t.children=l,n[t.uuid]={original:t,clone:c},wr&&console.log("ADD",t,c),t.type==="SkinnedMesh"&&(s[t.uuid]={original:t,clone:c}),(e==null?void 0:e.visible)!==void 0&&(c.visible=e.visible),e!=null&&e.idProvider){c.uuid=e.idProvider.generateUUID();const f=c;f&&(f.guid=c.uuid)}t.animations&&t.animations.length>0&&(c.animations=[...t.animations]);const h=t.parent;if(h&&h.add(c),e!=null&&e.position?st(c,e.position):c.position.copy(t.position),e!=null&&e.rotation?Hi(c,e.rotation):c.quaternion.copy(t.quaternion),e!=null&&e.scale?c.scale.copy(e.scale):c.scale.copy(t.scale),e!=null&&e.parent&&e.parent!=="scene"){let f=null;if(typeof e.parent=="string"?f=za(e.parent,o.scene,!0):f=e.parent,f){const p=e.keepWorldPosition===!0?f.attach:f.add;p?p.call(f,c):console.error("Invalid parent object",f,"received when instantiating:",t)}else console.warn("could not find parent:",e.parent)}for(const[f,p]of Object.entries(t.userData))f!=="components"&&(c.userData[f]=p);if((u=t.userData)!=null&&u.components){const f=t.userData.components,p=[];c.userData.components=p;for(let g=0;g<f.length;g++){const y=f[g],b=new y.constructor;Ga(b,y,void 0,{}),y[cc]!==void 0&&(b[cc]=y[cc]),p.push(b),b.gameObject=c,i.push(b),n[y.guid]={original:y,clone:b},sh.dispatchComponentLifecycleEvent("component-added",b)}}e&&(e.position=void 0,e.rotation=void 0,e.scale=void 0,e.parent=void 0,e.visible=void 0);for(const f in t.children){const p=t.children[f],g=jv(o,p,e,i,n,s);g&&(n[g.uuid]={original:p,clone:g},c.add(g))}return c}function P1(o,t){for(const e in o){const i=o[e],n=i.original,s=n.skeleton,a=i.clone;if(!s){console.warn("Skinned mesh has no skeleton?",i);continue}const l=s.bones,c=a.skeleton.clone();a.skeleton=c,a.bindMatrix.clone().copy(n.bindMatrix),a.bindMatrixInverse.copy(n.bindMatrixInverse);const h=[];c.bones=h;for(let u=0;u<l.length;u++){const f=l[u],g=t[f.uuid].clone;h.push(g)}}for(const e in o){const i=o[e].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function M1(o){var t;for(const e in o){const n=o[e].clone;if(n!=null&&n.isObject3D&&((t=n==null?void 0:n.userData)!=null&&t.components))for(let s=0;s<n.userData.components.length;s++){const a=n.userData.components[s],l=Object.entries(a);for(const[c,h]of l)if(Array.isArray(h)){const u=[];a[c]=u;for(let f=0;f<h.length;f++){const p=h[f];if(typeof p!="object"){u.push(p);continue}const g=W_(a,c,p,o);g!==void 0?(wr&&console.log("Found new instance for",c,p,"->",g),u.push(g)):(wr&&console.warn("Could not find new instance for",c,p),u.push(p))}}else if(typeof h=="object"){const u=W_(a,c,h,o);u!==void 0?a[c]=u:wr&&console.warn("Could not find new instance for",c,h)}}}}function W_(o,t,e,i){var n,s;if(e!=null)if(e.isComponent===!0){const a=e.gameObject;if(a){const l=a.uuid,c=(n=i[l])==null?void 0:n.clone;if(!c){wr&&console.log("reference did not change",t,o,e);return}const h=a.userData.components.indexOf(e);if(h>=0&&c.isObject3D)return wr&&console.log(t,l),c.userData.components[h];console.warn("could not find component",t,e)}}else if(e.isObject3D===!0){if(t==="gameObject")return;const a=e;if(a){const l=a.uuid,c=(s=i[l])==null?void 0:s.clone;if(c)return wr&&console.log(t,"old",e,"new",c),c}}else{if(e.isVector4||e.isVector3||e.isVector2||e.isQuaternion||e.isEuler)return e.clone();if(e.isColor===!0)return e.clone();if(e.isEventList===!0)return e.__internalOnInstantiate(i)}}exports.BlobStorage=void 0;(o=>{o.baseUrl="https://networking.needle.tools";function i(u){return ae.md5(new Uint8Array(u))}o.hashMD5=i;function n(u){const f=ae.md5(new Uint8Array(u),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...f))}o.hashMD5_Base64=n;function s(u){const f=new Uint8Array(u);return crypto.subtle.digest("SHA-256",f).then(g=>btoa(String.fromCharCode(...new Uint8Array(g))))}o.hashSha256=s;function a(u){const f=u.filesize/1024/1024;return Yn()?f<50:f<5}o.canUpload=a;async function l(u,f){var x;const p=o.baseUrl;if(p){if(!u.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let g=null;u instanceof File?g=await u.arrayBuffer():g=u.data;const y=g.byteLength,b=y/1024/1024;if(b>50)return(f==null?void 0:f.silent)!==!0&&me(`File (${b.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${b.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Yn()&&b>5)return(f==null?void 0:f.silent)!==!0&&me('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${b.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(y<1)return console.warn(`Your file is too small for uploading (${b.toFixed(1)}MB). Min size is 1 byte`),null;const _=n(g),v={filename:u.name,"Content-Md5":_,"Content-Type":u.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${u.name}"`,"x-amz-server-side-encryption":"AES256"},w=await fetch(p+"/api/needle/blob",{method:"POST",headers:v,signal:f==null?void 0:f.abort}).then(O=>O.json()).catch(O=>(console.error(O),null));if(w==null)return console.warn("Upload failed..."),null;if("error"in w)return console.error(w.error),null;if("upload"in w&&w.upload){let O=function(R){var D;return(D=f==null?void 0:f.onProgress)==null||D.call(null,{progress01:0,state:"inprogress"}),fetch(R,{method:"PUT",headers:v,body:g,signal:f==null?void 0:f.abort}).then(A=>{var T;return(T=f==null?void 0:f.onProgress)==null||T.call(null,{progress01:1,state:"finished"}),A}).catch(A=>A)};console.debug("Uploading file",w.upload);let E=!1,M=null;for(let R=0;R<3;R++)try{if(E)break;if((x=f==null?void 0:f.abort)!=null&&x.aborted)return console.debug("Aborted upload"),null;const F=await O(w.upload);F instanceof Error?(M=F,await Jn(1e3*R)):F.ok&&(console.debug("File uploaded successfully"),E=!0)}catch(F){console.error(F)}if(!E)return console.error((M==null?void 0:M.message)||"Failed to upload file"),null}if("download"in w){const O=p+w.download;return console.debug("File found in blob storage",O),{key:w.key,success:!0,download_url:O}}return null}o.upload=l;function c(u){return`${o.baseUrl}/api/needle/blob/${u}`}o.getBlobUrlForKey=c;async function h(u,f){const p=new d.FileLoader;p.setResponseType("arraybuffer");const g=await p.loadAsync(u,y=>{f&&f.call(null,y)});return g instanceof ArrayBuffer?new Uint8Array(g):(console.error("Download failed, no arraybuffer returned"),null)}o.download=h})(exports.BlobStorage||(exports.BlobStorage={}));const Xs=S("debugaddressables");class Bv{constructor(t){r(this,"_context");r(this,"_assetReferences",{});r(this,"preUpdate",()=>{});this._context=t,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const t=this._context.pre_update_callbacks.indexOf(this.preUpdate);t>=0&&this._context.pre_update_callbacks.splice(t,1);for(const e in this._assetReferences){const i=this._assetReferences[e];i==null||i.unload()}this._assetReferences={}}findAssetReference(t){return this._assetReferences[t]||null}registerAssetReference(t){return t.url&&(this._assetReferences[t.url]?console.warn("Asset reference already registered",t):this._assetReferences[t.url]=t),t}unregisterAssetReference(t){t.url&&delete this._assetReferences[t.url]}}const np=Symbol("assetReference"),ao=class ao{constructor(t,e,i=null){r(this,"_loading");r(this,"_asset");r(this,"_glbRoot");r(this,"_url");r(this,"_urlName");r(this,"_progressListeners",[]);r(this,"_isLoadingRawBinary",!1);r(this,"_rawBinary");this._url=t;const n=t.lastIndexOf("/");if(n>=0){this._urlName=t.substring(n+1);const s=this._urlName.lastIndexOf(".");s>=0&&(this._urlName=this._urlName.substring(0,s))}else this._urlName=t;i!==null&&(this.asset=i),yv(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(t,e){if(!e&&(e=X.Current,!e))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=e.addressables,n=i.findAssetReference(t);if(n)return n;const s=new ao(t,e.hash);return i.registerAssetReference(s),s}static getOrCreate(t,e,i){if(typeof t=="string"){if(!i&&(i=X.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=t.context,t=t.sourceId;const n=Eo(t,e);Xs&&console.log("GetOrCreate Addressable from",t,e,"FinalPath=",n);const s=i.addressables,a=s.findAssetReference(n);if(a)return a;const l=new ao(n,i.hash);return s.registerAssetReference(l),l}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(t){this._asset=t}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}get rawAsset(){return this._asset}async onResolvePrefab(t){return t===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||kr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Xs&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ri(this.asset.scene,!0,!0),Ri(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,X.Current&&X.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Xs&&console.log("Preload",this.url);const t=await exports.BlobStorage.download(this.url,e=>{this.raiseProgressEvent(e)});return this._rawBinary=(t==null?void 0:t.buffer)??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(t){if(Xs&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(t&&this._progressListeners.push(t),this._loading!==void 0)return this._loading.then(n=>this.asset);const e=X.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("Failed loading: Invalid raw binary data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loading=bn().parseSync(e,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else Xs&&console.log("Load async",this.url),this._loading=bn().loadSync(e,this.url,this.url,null,n=>{this.raiseProgressEvent(n)});const i=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i?(i[np]=this,this._glbRoot&&(this._glbRoot[np]=this),this.asset&&(this.asset[np]=this),eu(e),i.scene!==void 0&&(this.asset=i),this.asset):null}instantiate(t){return this.onInstantiate(t,!1)}instantiateSynced(t,e=!0){return this.onInstantiate(t,!0,e)}beginListenDownload(t){this._progressListeners.indexOf(t)<0&&this._progressListeners.push(t)}endListenDownload(t){const e=this._progressListeners.indexOf(t);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(t){for(const e of this._progressListeners)e(this,t)}async onInstantiate(t,e=!1,i){const n=X.Current,s=new xn;if(t instanceof d.Object3D?s.parent=t:t&&(Object.assign(s,t),s.cloneAssign(t)),s.parent===void 0&&(s.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),Xs&&console.log("Instantiate",this.url,"parent:",t),this.asset){Xs&&console.log("Add to scene",this.asset);let a=ao.currentlyInstantiating.get(this.url);if(a!==void 0&&a>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+a+")"),null;try{if(a===void 0&&(a=0),a+=1,ao.currentlyInstantiating.set(this.url,a),e){s.context=n;const l=this.asset;l.guid=this.url;const c=yg(l,s,void 0,i);if(c)return c}else{const l=Er(this.asset,s);if(l)return l}}finally{n.post_render_callbacks.push(()=>{a===void 0||a<0?a=0:a-=1,ao.currentlyInstantiating.set(this.url,a)})}}else Xs&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(t){if(t&&t.scene){const e=t.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};r(ao,"currentlyInstantiating",new Map);let te=ao;class O1 extends Ki{constructor(){super([te],"AssetReferenceSerializer")}onSerialize(t,e){if(t&&t.uri!==void 0&&typeof t.uri=="string")return t.uri}onDeserialize(t,e){if(typeof t=="string")return e.context?e.gltfId?te.getOrCreate(e.gltfId,t,e.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(t instanceof d.Object3D){if(!e.context)return console.error("Missing context"),null;if(!e.gltfId)return console.error("Missing source id"),null;const i=t,n=e.context,s=i.guid??i.uuid,a=n.addressables.findAssetReference(s);if(a)return a;const l=new te(s,void 0,i);return n.addressables.registerAssetReference(l),l}return null}}new O1;const k1=Promise.resolve(null),Ma=class Ma{constructor(t){r(this,"url");r(this,"_bitmap");r(this,"_bitmapObject");r(this,"loader",null);this.url=t}static getOrCreate(t){let e=Ma.imageReferences.get(t);return e||(e=new Ma(t),Ma.imageReferences.set(t,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const t=new Image;return t.src=this.url,t}createTexture(){return this.url?(this.loader||(this.loader=new d.TextureLoader),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(t=>{var e;return t&&!((e=t.name)!=null&&e.length)&&(t.name=this.url.split("/").pop()??this.url),t})):(console.error("Can not load texture without url"),k1)}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((t,e)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,t(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),t(null)}),i.src=this.url}),this._bitmap)}};r(Ma,"imageReferences",new Map);let Dc=Ma;class Fv extends Ki{constructor(){super([Dc],"ImageReferenceSerializer")}onSerialize(t,e){return null}onDeserialize(t,e){if(typeof t=="string"){const i=Eo(e.gltfId,t);return Dc.getOrCreate(i)}}}new Fv;const Oa=class Oa{constructor(t){r(this,"url");r(this,"res");this.url=t}static getOrCreate(t){let e=Oa.cache.get(t);return e||(e=new Oa(t),Oa.cache.set(t,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(t=>t.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(t=>t.text())}};r(Oa,"cache",new Map);let Ic=Oa;class Uv extends Ki{constructor(){super([Ic],"FileReferenceSerializer")}onSerialize(t,e){return null}onDeserialize(t,e){if(typeof t=="string"){const i=Eo(e.gltfId,t);return Ic.getOrCreate(i)}}}new Uv;class R1{constructor(t){r(this,"context");r(this,"mixers",[]);this.context=t}onDestroy(){this.mixers.forEach(t=>t.stopAllAction()),this.mixers.length=0}registerAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(t)||this.mixers.push(t)}unregisterAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const e=this.mixers.indexOf(t);e!==-1&&this.mixers.splice(e,1)}}class Ha{static tryGetActionsFromMixer(t){const e=t._actions;return e||null}static tryGetAnimationClipsFromObjectHierarchy(t,e){if(e||(e=new Array),t)t.animations&&e.push(...t.animations);else return e;if(t.children)for(const i of t.children)this.tryGetAnimationClipsFromObjectHierarchy(i,e);return e}static assignAnimationsFromFile(t,e){if(!t||!t.animations){console.debug("No animations found in file");return}for(let n=0;n<t.animations.length;n++){const s=t.animations[n];if(!s.tracks||s.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in s.tracks){const l=s.tracks[a],c=d.PropertyBinding.parseTrackName(l.name);let h=d.PropertyBinding.findNode(t.scene,c.nodeName);if(!h){const f=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(h=t.scene.getObjectByProperty("uuid",f),!h)continue}let u=i(h);if(!u){if(!(e!=null&&e.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=e.createAnimationComponent(t.scene,s)}u.addClip&&u.addClip(s)}}function i(n){var a;if(!n)return null;const s=(a=n.userData)==null?void 0:a.components;if(s&&s.length>0){for(let l=0;l<s.length;l++)if(s[l].isAnimationComponent===!0)return n}return i(n.parent)}}}function*Sg(o,t=null){const e=t?t.time:X.Current.time,i=e.time;for(;e.time-i<o;)yield}function*E1(o){for(let t=0;t<o;t++)yield}function*zv(o){let t=!0;for(o.then(()=>t=!1),o.catch(()=>t=!1);t;)yield}const G_="NEEDLE_lightmaps",El=S("debuglightmapsextension")||S("debuglightmaps");var Dn=(o=>(o[o.Lightmap=0]="Lightmap",o[o.Skybox=1]="Skybox",o[o.Reflection=2]="Reflection",o))(Dn||{});class T1{constructor(t,e,i){r(this,"parser");r(this,"registry");r(this,"source");this.parser=t,this.registry=e,this.source=i}get name(){return G_}afterRoot(t){const e=this.parser.json.extensions;if(e){const i=e[G_];if(i){const n=i.textures;return n!=null&&n.length?(El&&console.log(i),new Promise(async(s,a)=>{const l=[];for(const h of n)if(h.pointer){El&&console.log(h);let u=null;if(h.pointer.startsWith("/textures/"))El&&console.log("Load texture from gltf",h.pointer),u=bg(this.parser,h.pointer).then(f=>this.resolveTexture(h,f));else if(typeof h.pointer=="string"){El&&console.log("Load texture from path",h.pointer);const f=Eo(this.source,h.pointer);let p;f.endsWith(".exr")?p=new H.EXRLoader(this.parser.options.manager):f.endsWith(".hdr")?p=new H.RGBELoader(this.parser.options.manager):p=new d.TextureLoader(this.parser.options.manager),u=p.loadAsync(f,void 0).then(g=>this.resolveTexture(h,g))}else h.pointer;u&&l.push(u)}const c=await Gm(l);c!=null&&c.anyFailed&&j()&&console.error("Failed to load lightmap extension",c),s()})):null}}return null}resolveTexture(t,e){const i=e;El&&console.log("Lightmap loaded:",i),i!=null&&i.isTexture&&(this.registry?(i.colorSpace=d.LinearSRGBColorSpace,this.registry.registerTexture(this.source,t.type,i,t.index)):console.log(Dn[t.type],t.pointer,i))}}const oa=!!S("debuglightmaps");class A1{constructor(t){r(this,"_context");r(this,"_lightmaps",new Map);this._context=t}clear(){this._lightmaps.clear()}registerTexture(t,e,i,n){oa&&console.log("Registering ",Dn[e]+' "'+t+'"',i),this._lightmaps.has(t)||this._lightmaps.set(t,new Map);const s=this._lightmaps.get(t),a=(s==null?void 0:s.get(e))??[];a.length<n&&(a.length=n+1),a[n]=i,s==null||s.set(e,a)}tryGetLightmap(t,e=0){return this.tryGet(t,Dn.Lightmap,e)}tryGetSkybox(t){return oa&&console.log("[Get Skybox]",t,this._lightmaps),this.tryGet(t,Dn.Skybox,0)}tryGetReflection(t){return oa&&console.log("[Get Reflection]",t,this._lightmaps),this.tryGet(t,Dn.Reflection,0)}tryGet(t,e,i){if(!t)return oa&&console.warn("Missing source id"),null;const n=this._lightmaps.get(t);if(!n)return oa&&console.warn(`[Lighting] No ${Dn[e]} texture entry for`,t),null;const s=n.get(e);return s===void 0?(oa&&console.warn(`[Lighting] No ${Dn[e]} texture for`,t,"index",i),null):!(s!=null&&s.length)||s.length<=i?null:s[i]}}d.ShaderChunk.lights_fragment_maps=d.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
191
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,t))),$_()&&console.log("[onGetComponent] FIND",t),t==null))return null;for(let n=0;n<o.userData.components.length;n++){const s=o.userData.components[n];let a=Object.getPrototypeOf(s);for(;a;){if(a===t.prototype)if($_()&&console.log("[onGetComponent] MATCH BY PROTOYPE",a),e)e.push(s);else return s;a=Object.getPrototypeOf(a)}}return e||null}function jr(o,t){const e=Rv(o,t);return e?Array.isArray(e)?e[0]:e:null}function lh(o,t,e,i=!0){return e||(e=[]),i&&(e.length=0),Rv(o,t,e),e}function ch(o,t,e){var n;if(e===!1&&o[Es]===!1)return null;const i=jr(o,t);if(e===!1&&(i==null?void 0:i.enabled)===!1)return null;if(i)return i;for(let s=0;s<((n=o==null?void 0:o.children)==null?void 0:n.length);s++){const a=ch(o.children[s],t);if(a)return a}return null}function sl(o,t,e,i=!0){var n;e||(e=[]),i&&(e.length=0),lh(o,t,e,!1);for(let s=0;s<((n=o==null?void 0:o.children)==null?void 0:n.length);s++)sl(o.children[s],t,e,!1);return e}function Lc(o,t){if(!o)return null;if(Array.isArray(o)){for(let i=0;i<o.length;i++){const n=C1(o[i]),s=Lc(n,t);if(s)return s}return null}const e=jr(o,t);return e||(o.parent?Lc(o.parent,t):null)}function Vu(o,t,e,i=!0){return e||(e=[]),i&&(e.length=0),o?(lh(o,t,e,!1),o.parent?Vu(o.parent,t,e,!1):e):e}function hh(o,t=void 0,e=!0){if(!o)return null;if(!t&&(t=X.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),null;let i=t;if(i.isScene||(i=t==null?void 0:t.scene),!i)return null;const n=ch(i,o,e);return n||null}function Ev(o,t,e=void 0){if(!o)return t??[];if(t||(t=[]),t.length=0,!e&&(e=X.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),t;"scene"in e&&(e=e.scene);const i=e;return i&&sl(i,o,t,!1),t}function Wu(o){o&&o.isObject3D===!0&&Pv(o,d.Object3D)}d.Object3D.prototype.SetActive=function(o){this.visible=o};d.Object3D.prototype.setActive=function(o){this.visible=o};d.Object3D.prototype.destroy=function(){Ri(this)};d.Object3D.prototype.addComponent=function(o,t){return Oi(this,o,t)};d.Object3D.prototype.addNewComponent=function(o,t){return Oi(this,o,t)};d.Object3D.prototype.removeComponent=function(o){return wg(this,o)};d.Object3D.prototype.getOrAddComponent=function(o,t){return ah(this,o,t)};d.Object3D.prototype.getComponent=function(o){return jr(this,o)};d.Object3D.prototype.getComponents=function(o,t){return lh(this,o,t)};d.Object3D.prototype.getComponentInChildren=function(o){return ch(this,o)};d.Object3D.prototype.getComponentsInChildren=function(o,t){return sl(this,o,t)};d.Object3D.prototype.getComponentInParent=function(o){return Lc(this,o)};d.Object3D.prototype.getComponentsInParent=function(o,t){return Vu(this,o,t)};Object.getOwnPropertyDescriptor(d.Object3D.prototype,"activeSelf")||Object.defineProperty(d.Object3D.prototype,"activeSelf",{get:function(){return ol(this)},set:function(o){uc(this,o)}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldPosition")||Object.defineProperty(d.Object3D.prototype,"worldPosition",{get:function(){return this instanceof H.TransformControlsGizmo?Q(this.object):Q(this)},set:function(o){st(this,o)}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldQuaternion")||Object.defineProperty(d.Object3D.prototype,"worldQuaternion",{get:function(){return this instanceof H.TransformControlsGizmo?_e(this.object):_e(this)},set:function(o){Hi(this,o)}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldRotation")||Object.defineProperty(d.Object3D.prototype,"worldRotation",{get:function(){return Bu(this)},set:function(o){P0(this,o)}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldScale")||Object.defineProperty(d.Object3D.prototype,"worldScale",{get:function(){return Ue(this)},set:function(o){Na(this,o)}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldForward")||Object.defineProperty(d.Object3D.prototype,"worldForward",{get:function(){return V().set(0,0,1).applyQuaternion(_e(this))}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldRight")||Object.defineProperty(d.Object3D.prototype,"worldRight",{get:function(){return V().set(1,0,0).applyQuaternion(_e(this))}});Object.getOwnPropertyDescriptor(d.Object3D.prototype,"worldUp")||Object.defineProperty(d.Object3D.prototype,"worldUp",{get:function(){return V().set(0,1,0).applyQuaternion(_e(this))}});Mv(d.Object3D);class ie extends d.Color{constructor(e,i,n,s){super();r(this,"alpha",1);typeof e=="number"&&typeof i=="number"&&typeof n=="number"?(this.set(e,i,n),this.alpha=typeof s=="number"?s:1):e!==void 0&&(this.set(e),this.alpha=1)}get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,i){const n=e;return n.alpha!=null&&(this.alpha=z.lerp(this.alpha,n.alpha,i)),super.lerp(e,i)}lerpColors(e,i,n){const s=e,a=i;return s.alpha!=null&&a.alpha!=null&&(this.alpha=z.lerp(s.alpha,a.alpha,n)),super.lerpColors(e,i,n)}multiply(e){const i=e;return i.alpha!=null&&(this.alpha=this.alpha*i.alpha),super.multiply(e)}fromArray(e,i=0){return this.alpha=e[i+3],super.fromArray(e,i)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new ie(0,0,0,0);if(e.startsWith("#")&&e.length===9){const i=parseInt(e.slice(1,9),16),n=i>>24&255,s=i>>16&255,a=i>>8&255,l=i>>0&255;return new ie(n/255,s/255,a/255,l/255)}else if(e.startsWith("#")){const i=parseInt(e.slice(1),16),n=i>>16&255,s=i>>8&255,a=i>>0&255;return new ie(n/255,s/255,a/255,1)}else if(e.startsWith("rgba")){const i=e.slice(5,-1).split(",").map(Number);return new ie(i[0]/255,i[1]/255,i[2]/255,i[3])}else if(e.startsWith("rgb")){const i=e.slice(4,-1).split(",").map(Number);return new ie(i[0]/255,i[1]/255,i[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new ie(e[0],e[1],e[2],e[3]);if(e.length===3)return new ie(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new ie(e)}}const Ld=S("debuggetcomponent"),wr=S("debuginstantiate");class xn{constructor(){r(this,"idProvider");r(this,"parent");r(this,"keepWorldPosition");r(this,"position");r(this,"rotation");r(this,"scale");r(this,"visible");r(this,"context");r(this,"components")}clone(){var e,i,n;const t=new xn;return t.idProvider=this.idProvider,t.parent=this.parent,t.keepWorldPosition=this.keepWorldPosition,t.position=(e=this.position)==null?void 0:e.clone(),t.rotation=(i=this.rotation)==null?void 0:i.clone(),t.scale=(n=this.scale)==null?void 0:n.clone(),t.visible=this.visible,t.context=this.context,t.components=this.components,t}cloneAssign(t){var e,i,n;this.idProvider=t.idProvider,this.parent=t.parent,this.keepWorldPosition=t.keepWorldPosition,this.position=(e=t.position)==null?void 0:e.clone(),this.rotation=(i=t.rotation)==null?void 0:i.clone(),this.scale=(n=t.scale)==null?void 0:n.clone(),this.visible=t.visible,this.context=t.context,this.components=t.components}}function ol(o){return o.visible}function uc(o,t){return typeof t=="number"&&(t=t>.5),o.visible=t,o.visible}function Tv(o){return o[Es]||Gu(o)}function Av(o,t){o[rv]=t}function Gu(o){return Wi.isUsingInstancing(o)}function xg(o,t){return za(o,t,!0,!0)}const Lv=Symbol("isDestroyed");function kr(o){return o[Lv]}function Dv(o,t){o[Lv]=t}const pm=Symbol("isDontDestroy");function pa(o,t=!0){o[pm]=t}const Dd=[],Id=[];function Ri(o,t=!0,e=!1){Dd.length=0,Id.length=0,mm(o,t,!0);for(const i of Dd)i.gameObject=null,i.context=null;for(const i of Id)Dv(i,!0),e&&Se(i),ov(i);Id.length=0,Dd.length=0}function mm(o,t=!0,e=!0){var a;if(o==null)return;const i=o;if(i.isComponent){if(i[pm])return;Dd.push(i);const l=i.gameObject;i.__internalDisable(),i.__internalDestroy(),i.gameObject=l;return}if(o[pm])return;const n=o;Ld&&console.log(n),Id.push(n);const s=(a=n.userData)==null?void 0:a.components;if(s!=null&&Array.isArray(s)){let l=s.length;for(let c=0;c<s.length;c++){const h=s[c];mm(h,t,!1),s.length<l&&(l=s.length,c--)}}if(t&&n.children)for(const l of n.children)mm(l,t,!1);e&&n.removeFromParent()}function Rr(o,t,e=!0){return Iv(o,t,e)}function*Hu(o,t,e=!1,i=999,n=0){if(o!=null&&o.userData.components&&!(n>i)){for(const s of o.userData.components)t&&(s==null?void 0:s.isComponent)===!0&&s instanceof t?yield s:yield s;if(e===!0)for(const s of o.children)yield*Hu(s,t,!0,i,n+1)}}function Iv(o,t,e,i=0){var n;if(o){if(o.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if((n=o.userData)!=null&&n.components)for(let s=0;s<o.userData.components.length;s++){const a=o.userData.components[s];if((a==null?void 0:a.isComponent)===!0){const l=t(a);if(l!==void 0)return l}}if(e&&o.children){const s=i+1;for(let a=0;a<o.children.length;a++){const l=o.children[a];if(!l)continue;const c=Iv(l,t,e,s);if(c!==void 0)return c}}}}function Er(o,t){if("isAssetReference"in o)return o.instantiate(t??void 0);let e=null;t!=null&&(t.x!==void 0?(e=new xn,e.position=t):e=t);let i=X.Current;e!=null&&e.context&&(i=e.context),Ld&&i.alias&&console.log("context",i.alias),e&&!e.idProvider&&(e.idProvider=new bt(Date.now()));const n=[],s={},a={},l=jv(i,o,e,n,s,a);l&&(M1(s),P1(a,s)),Ld&&(Xd(o,!0),Xd(l,!0));const c={};if((e==null?void 0:e.components)!==!1){for(const h in n){const u=n[h],f=u.guid;e&&e.idProvider&&(u.guid=e.idProvider.generateUUID(),c[f]=u.guid,Ld&&console.log(u.name,u.guid)),qu(u,i),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const h in n){const u=n[h];u.resolveGuids&&u.resolveGuids(c),u.enabled!==!1&&(u.enabled=!0)}eu(i)}return l}function jv(o,t,e,i,n,s){var u;if(!t||t[Si])return null;const a=t.userData;t.userData={};const l=t.children;t.children=[];const c=t.clone(!1);if(Wu(c),t.userData=a,t.children=l,n[t.uuid]={original:t,clone:c},wr&&console.log("ADD",t,c),t.type==="SkinnedMesh"&&(s[t.uuid]={original:t,clone:c}),(e==null?void 0:e.visible)!==void 0&&(c.visible=e.visible),e!=null&&e.idProvider){c.uuid=e.idProvider.generateUUID();const f=c;f&&(f.guid=c.uuid)}t.animations&&t.animations.length>0&&(c.animations=[...t.animations]);const h=t.parent;if(h&&h.add(c),e!=null&&e.position?st(c,e.position):c.position.copy(t.position),e!=null&&e.rotation?Hi(c,e.rotation):c.quaternion.copy(t.quaternion),e!=null&&e.scale?c.scale.copy(e.scale):c.scale.copy(t.scale),e!=null&&e.parent&&e.parent!=="scene"){let f=null;if(typeof e.parent=="string"?f=za(e.parent,o.scene,!0):f=e.parent,f){const p=e.keepWorldPosition===!0?f.attach:f.add;p?p.call(f,c):console.error("Invalid parent object",f,"received when instantiating:",t)}else console.warn("could not find parent:",e.parent)}for(const[f,p]of Object.entries(t.userData))f!=="components"&&(c.userData[f]=p);if((u=t.userData)!=null&&u.components){const f=t.userData.components,p=[];c.userData.components=p;for(let g=0;g<f.length;g++){const y=f[g],b=new y.constructor;Ga(b,y,void 0,{}),y[cc]!==void 0&&(b[cc]=y[cc]),p.push(b),b.gameObject=c,i.push(b),n[y.guid]={original:y,clone:b},sh.dispatchComponentLifecycleEvent("component-added",b)}}e&&(e.position=void 0,e.rotation=void 0,e.scale=void 0,e.parent=void 0,e.visible=void 0);for(const f in t.children){const p=t.children[f],g=jv(o,p,e,i,n,s);g&&(n[g.uuid]={original:p,clone:g},c.add(g))}return c}function P1(o,t){for(const e in o){const i=o[e],n=i.original,s=n.skeleton,a=i.clone;if(!s){console.warn("Skinned mesh has no skeleton?",i);continue}const l=s.bones,c=a.skeleton.clone();a.skeleton=c,a.bindMatrix.clone().copy(n.bindMatrix),a.bindMatrixInverse.copy(n.bindMatrixInverse);const h=[];c.bones=h;for(let u=0;u<l.length;u++){const f=l[u],g=t[f.uuid].clone;h.push(g)}}for(const e in o){const i=o[e].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function M1(o){var t;for(const e in o){const n=o[e].clone;if(n!=null&&n.isObject3D&&((t=n==null?void 0:n.userData)!=null&&t.components))for(let s=0;s<n.userData.components.length;s++){const a=n.userData.components[s],l=Object.entries(a);for(const[c,h]of l)if(Array.isArray(h)){const u=[];a[c]=u;for(let f=0;f<h.length;f++){const p=h[f];if(typeof p!="object"){u.push(p);continue}const g=W_(a,c,p,o);g!==void 0?(wr&&console.log("Found new instance for",c,p,"->",g),u.push(g)):(wr&&console.warn("Could not find new instance for",c,p),u.push(p))}}else if(typeof h=="object"){const u=W_(a,c,h,o);u!==void 0?a[c]=u:wr&&console.warn("Could not find new instance for",c,h)}}}}function W_(o,t,e,i){var n,s;if(e!=null)if(e.isComponent===!0){const a=e.gameObject;if(a){const l=a.uuid,c=(n=i[l])==null?void 0:n.clone;if(!c){wr&&console.log("reference did not change",t,o,e);return}const h=a.userData.components.indexOf(e);if(h>=0&&c.isObject3D)return wr&&console.log(t,l),c.userData.components[h];console.warn("could not find component",t,e)}}else if(e.isObject3D===!0){if(t==="gameObject")return;const a=e;if(a){const l=a.uuid,c=(s=i[l])==null?void 0:s.clone;if(c)return wr&&console.log(t,"old",e,"new",c),c}}else{if(e.isVector4||e.isVector3||e.isVector2||e.isQuaternion||e.isEuler)return e.clone();if(e.isColor===!0)return e.clone();if(e.isEventList===!0)return e.__internalOnInstantiate(i)}}exports.BlobStorage=void 0;(o=>{o.baseUrl="https://networking.needle.tools";function i(u){return ae.md5(new Uint8Array(u))}o.hashMD5=i;function n(u){const f=ae.md5(new Uint8Array(u),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...f))}o.hashMD5_Base64=n;function s(u){const f=new Uint8Array(u);return crypto.subtle.digest("SHA-256",f).then(g=>btoa(String.fromCharCode(...new Uint8Array(g))))}o.hashSha256=s;function a(u){const f=u.filesize/1024/1024;return Yn()?f<50:f<5}o.canUpload=a;async function l(u,f){var x;const p=o.baseUrl;if(p){if(!u.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let g=null;u instanceof File?g=await u.arrayBuffer():g=u.data;const y=g.byteLength,b=y/1024/1024;if(b>50)return(f==null?void 0:f.silent)!==!0&&me(`File (${b.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${b.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Yn()&&b>5)return(f==null?void 0:f.silent)!==!0&&me('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${b.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(y<1)return console.warn(`Your file is too small for uploading (${b.toFixed(1)}MB). Min size is 1 byte`),null;const _=n(g),v={filename:u.name,"Content-Md5":_,"Content-Type":u.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${u.name}"`,"x-amz-server-side-encryption":"AES256"},w=await fetch(p+"/api/needle/blob",{method:"POST",headers:v,signal:f==null?void 0:f.abort}).then(O=>O.json()).catch(O=>(console.error(O),null));if(w==null)return console.warn("Upload failed..."),null;if("error"in w)return console.error(w.error),null;if("upload"in w&&w.upload){let O=function(R){var D;return(D=f==null?void 0:f.onProgress)==null||D.call(null,{progress01:0,state:"inprogress"}),fetch(R,{method:"PUT",headers:v,body:g,signal:f==null?void 0:f.abort}).then(A=>{var T;return(T=f==null?void 0:f.onProgress)==null||T.call(null,{progress01:1,state:"finished"}),A}).catch(A=>A)};console.debug("Uploading file",w.upload);let E=!1,M=null;for(let R=0;R<3;R++)try{if(E)break;if((x=f==null?void 0:f.abort)!=null&&x.aborted)return console.debug("Aborted upload"),null;const F=await O(w.upload);F instanceof Error?(M=F,await Jn(1e3*R)):F.ok&&(console.debug("File uploaded successfully"),E=!0)}catch(F){console.error(F)}if(!E)return console.error((M==null?void 0:M.message)||"Failed to upload file"),null}if("download"in w){const O=p+w.download;return console.debug("File found in blob storage",O),{key:w.key,success:!0,download_url:O}}return null}o.upload=l;function c(u){return`${o.baseUrl}/api/needle/blob/${u}`}o.getBlobUrlForKey=c;async function h(u,f){const p=new d.FileLoader;p.setResponseType("arraybuffer");const g=await p.loadAsync(u,y=>{f&&f.call(null,y)});return g instanceof ArrayBuffer?new Uint8Array(g):(console.error("Download failed, no arraybuffer returned"),null)}o.download=h})(exports.BlobStorage||(exports.BlobStorage={}));const Xs=S("debugaddressables");class Bv{constructor(t){r(this,"_context");r(this,"_assetReferences",{});r(this,"preUpdate",()=>{});this._context=t,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const t=this._context.pre_update_callbacks.indexOf(this.preUpdate);t>=0&&this._context.pre_update_callbacks.splice(t,1);for(const e in this._assetReferences){const i=this._assetReferences[e];i==null||i.unload()}this._assetReferences={}}findAssetReference(t){return this._assetReferences[t]||null}registerAssetReference(t){return t.url&&(this._assetReferences[t.url]?console.warn("Asset reference already registered",t):this._assetReferences[t.url]=t),t}unregisterAssetReference(t){t.url&&delete this._assetReferences[t.url]}}const np=Symbol("assetReference"),ao=class ao{constructor(t,e,i=null){r(this,"_loading");r(this,"_asset");r(this,"_glbRoot");r(this,"_url");r(this,"_urlName");r(this,"_progressListeners",[]);r(this,"_isLoadingRawBinary",!1);r(this,"_rawBinary");this._url=t;const n=t.lastIndexOf("/");if(n>=0){this._urlName=t.substring(n+1);const s=this._urlName.lastIndexOf(".");s>=0&&(this._urlName=this._urlName.substring(0,s))}else this._urlName=t;i!==null&&(this.asset=i),yv(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(t,e){if(!e&&(e=X.Current,!e))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=e.addressables,n=i.findAssetReference(t);if(n)return n;const s=new ao(t,e.hash);return i.registerAssetReference(s),s}static getOrCreate(t,e,i){if(typeof t=="string"){if(!i&&(i=X.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=t.context,t=t.sourceId;const n=Eo(t,e);Xs&&console.log("GetOrCreate Addressable from",t,e,"FinalPath=",n);const s=i.addressables,a=s.findAssetReference(n);if(a)return a;const l=new ao(n,i.hash);return s.registerAssetReference(l),l}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(t){this._asset=t}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}get rawAsset(){return this._asset}async onResolvePrefab(t){return t===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||kr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Xs&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ri(this.asset.scene,!0,!0),Ri(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,X.Current&&X.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Xs&&console.log("Preload",this.url);const t=await exports.BlobStorage.download(this.url,e=>{this.raiseProgressEvent(e)});return this._rawBinary=(t==null?void 0:t.buffer)??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(t){if(Xs&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(t&&this._progressListeners.push(t),this._loading!==void 0)return this._loading.then(n=>this.asset);const e=X.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("Failed loading: Invalid raw binary data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loading=bn().parseSync(e,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else Xs&&console.log("Load async",this.url),this._loading=bn().loadSync(e,this.url,this.url,null,n=>{this.raiseProgressEvent(n)});const i=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i?(i[np]=this,this._glbRoot&&(this._glbRoot[np]=this),this.asset&&(this.asset[np]=this),eu(e),i.scene!==void 0&&(this.asset=i),this.asset):null}instantiate(t){return this.onInstantiate(t,!1)}instantiateSynced(t,e=!0){return this.onInstantiate(t,!0,e)}beginListenDownload(t){this._progressListeners.indexOf(t)<0&&this._progressListeners.push(t)}endListenDownload(t){const e=this._progressListeners.indexOf(t);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(t){for(const e of this._progressListeners)e(this,t)}async onInstantiate(t,e=!1,i){const n=X.Current,s=new xn;if(t instanceof d.Object3D?s.parent=t:t&&(Object.assign(s,t),s.cloneAssign(t)),s.parent===void 0&&(s.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),Xs&&console.log("Instantiate",this.url,"parent:",t),this.asset){Xs&&console.log("Add to scene",this.asset);let a=ao.currentlyInstantiating.get(this.url);if(a!==void 0&&a>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+a+")"),null;try{if(a===void 0&&(a=0),a+=1,ao.currentlyInstantiating.set(this.url,a),e){s.context=n;const l=this.asset;l.guid=this.url;const c=yg(l,s,void 0,i);if(c)return c}else{const l=Er(this.asset,s);if(l)return l}}finally{n.post_render_callbacks.push(()=>{a===void 0||a<0?a=0:a-=1,ao.currentlyInstantiating.set(this.url,a)})}}else Xs&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(t){if(t&&t.scene){const e=t.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};r(ao,"currentlyInstantiating",new Map);let te=ao;class O1 extends Ki{constructor(){super([te],"AssetReferenceSerializer")}onSerialize(t,e){if(t&&t.uri!==void 0&&typeof t.uri=="string")return t.uri}onDeserialize(t,e){if(typeof t=="string")return e.context?e.gltfId?te.getOrCreate(e.gltfId,t,e.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(t instanceof d.Object3D){if(!e.context)return console.error("Missing context"),null;if(!e.gltfId)return console.error("Missing source id"),null;const i=t,n=e.context,s=i.guid??i.uuid,a=n.addressables.findAssetReference(s);if(a)return a;const l=new te(s,void 0,i);return n.addressables.registerAssetReference(l),l}return null}}new O1;const k1=Promise.resolve(null),Ma=class Ma{constructor(t){r(this,"url");r(this,"_bitmap");r(this,"_bitmapObject");r(this,"loader",null);this.url=t}static getOrCreate(t){let e=Ma.imageReferences.get(t);return e||(e=new Ma(t),Ma.imageReferences.set(t,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const t=new Image;return t.src=this.url,t}createTexture(){return this.url?(this.loader||(this.loader=new d.TextureLoader),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(t=>{var e;return t&&!((e=t.name)!=null&&e.length)&&(t.name=this.url.split("/").pop()??this.url),t})):(console.error("Can not load texture without url"),k1)}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((t,e)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,t(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),t(null)}),i.src=this.url}),this._bitmap)}};r(Ma,"imageReferences",new Map);let Dc=Ma;class Fv extends Ki{constructor(){super([Dc],"ImageReferenceSerializer")}onSerialize(t,e){return null}onDeserialize(t,e){if(typeof t=="string"){const i=Eo(e.gltfId,t);return Dc.getOrCreate(i)}}}new Fv;const Oa=class Oa{constructor(t){r(this,"url");r(this,"res");this.url=t}static getOrCreate(t){let e=Oa.cache.get(t);return e||(e=new Oa(t),Oa.cache.set(t,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(t=>t.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(t=>t.text())}};r(Oa,"cache",new Map);let Ic=Oa;class Uv extends Ki{constructor(){super([Ic],"FileReferenceSerializer")}onSerialize(t,e){return null}onDeserialize(t,e){if(typeof t=="string"){const i=Eo(e.gltfId,t);return Ic.getOrCreate(i)}}}new Uv;class R1{constructor(t){r(this,"context");r(this,"mixers",[]);this.context=t}onDestroy(){this.mixers.forEach(t=>t.stopAllAction()),this.mixers.length=0}registerAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(t)||this.mixers.push(t)}unregisterAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const e=this.mixers.indexOf(t);e!==-1&&this.mixers.splice(e,1)}}class Ha{static tryGetActionsFromMixer(t){const e=t._actions;return e||null}static tryGetAnimationClipsFromObjectHierarchy(t,e){if(e||(e=new Array),t)t.animations&&e.push(...t.animations);else return e;if(t.children)for(const i of t.children)this.tryGetAnimationClipsFromObjectHierarchy(i,e);return e}static assignAnimationsFromFile(t,e){if(!t||!t.animations){console.debug("No animations found in file");return}for(let n=0;n<t.animations.length;n++){const s=t.animations[n];if(!s.tracks||s.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in s.tracks){const l=s.tracks[a],c=d.PropertyBinding.parseTrackName(l.name);let h=d.PropertyBinding.findNode(t.scene,c.nodeName);if(!h){const f=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(h=t.scene.getObjectByProperty("uuid",f),!h)continue}let u=i(h);if(!u){if(!(e!=null&&e.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=e.createAnimationComponent(t.scene,s)}u.addClip&&u.addClip(s)}}function i(n){var a;if(!n)return null;const s=(a=n.userData)==null?void 0:a.components;if(s&&s.length>0){for(let l=0;l<s.length;l++)if(s[l].isAnimationComponent===!0)return n}return i(n.parent)}}}function*Sg(o,t=null){const e=t?t.time:X.Current.time,i=e.time;for(;e.time-i<o;)yield}function*E1(o){for(let t=0;t<o;t++)yield}function*zv(o){let t=!0;for(o.then(()=>t=!1),o.catch(()=>t=!1);t;)yield}const G_="NEEDLE_lightmaps",El=S("debuglightmapsextension")||S("debuglightmaps");var Dn=(o=>(o[o.Lightmap=0]="Lightmap",o[o.Skybox=1]="Skybox",o[o.Reflection=2]="Reflection",o))(Dn||{});class T1{constructor(t,e,i){r(this,"parser");r(this,"registry");r(this,"source");this.parser=t,this.registry=e,this.source=i}get name(){return G_}afterRoot(t){const e=this.parser.json.extensions;if(e){const i=e[G_];if(i){const n=i.textures;return n!=null&&n.length?(El&&console.log(i),new Promise(async(s,a)=>{const l=[];for(const h of n)if(h.pointer){El&&console.log(h);let u=null;if(h.pointer.startsWith("/textures/"))El&&console.log("Load texture from gltf",h.pointer),u=bg(this.parser,h.pointer).then(f=>this.resolveTexture(h,f));else if(typeof h.pointer=="string"){El&&console.log("Load texture from path",h.pointer);const f=Eo(this.source,h.pointer);let p;f.endsWith(".exr")?p=new H.EXRLoader(this.parser.options.manager):f.endsWith(".hdr")?p=new H.RGBELoader(this.parser.options.manager):p=new d.TextureLoader(this.parser.options.manager),u=p.loadAsync(f,void 0).then(g=>this.resolveTexture(h,g))}else h.pointer;u&&l.push(u)}const c=await Gm(l);c!=null&&c.anyFailed&&j()&&console.error("Failed to load lightmap extension",c),s()})):null}}return null}resolveTexture(t,e){const i=e;El&&console.log("Lightmap loaded:",i),i!=null&&i.isTexture&&(this.registry?(i.colorSpace=d.LinearSRGBColorSpace,this.registry.registerTexture(this.source,t.type,i,t.index)):console.log(Dn[t.type],t.pointer,i))}}const oa=!!S("debuglightmaps");class A1{constructor(t){r(this,"_context");r(this,"_lightmaps",new Map);this._context=t}clear(){this._lightmaps.clear()}registerTexture(t,e,i,n){oa&&console.log("Registering ",Dn[e]+' "'+t+'"',i),this._lightmaps.has(t)||this._lightmaps.set(t,new Map);const s=this._lightmaps.get(t),a=(s==null?void 0:s.get(e))??[];a.length<n&&(a.length=n+1),a[n]=i,s==null||s.set(e,a)}tryGetLightmap(t,e=0){return this.tryGet(t,Dn.Lightmap,e)}tryGetSkybox(t){return oa&&console.log("[Get Skybox]",t,this._lightmaps),this.tryGet(t,Dn.Skybox,0)}tryGetReflection(t){return oa&&console.log("[Get Reflection]",t,this._lightmaps),this.tryGet(t,Dn.Reflection,0)}tryGet(t,e,i){if(!t)return oa&&console.warn("Missing source id"),null;const n=this._lightmaps.get(t);if(!n)return oa&&console.warn(`[Lighting] No ${Dn[e]} texture entry for`,t),null;const s=n.get(e);return s===void 0?(oa&&console.warn(`[Lighting] No ${Dn[e]} texture for`,t,"index",i),null):!(s!=null&&s.length)||s.length<=i?null:s[i]}}d.ShaderChunk.lights_fragment_maps=d.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
192
192
  vec2 lUv = vLightMapUv.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
193
193
  vec4 lightMapTexel = texture2D( lightMap, lUv);
194
194
  // The range of RGBM lightmaps goes from 0 to 34.49 (5^2.2) in linear space, and from 0 to 5 in gamma space.
@@ -349,7 +349,7 @@ vec3 AgXToneMapping( vec3 color ) {
349
349
  color = _agxLook(color); // Optional
350
350
  color = _agxEotf(color);
351
351
  return color;
352
- `,t="vec3 AgXToneMapping( vec3 color ) {",e="return color;",i=d.ShaderChunk.tonemapping_pars_fragment.indexOf(t),n=d.ShaderChunk.tonemapping_pars_fragment.indexOf(e,i);if(i>=0&&n>=0){const s=d.ShaderChunk.tonemapping_pars_fragment.substring(i,n+e.length);d.ShaderChunk.tonemapping_pars_fragment=d.ShaderChunk.tonemapping_pars_fragment.replace(s,o)}else j()&&console.error("Couldn't find AgXToneMapping in ShaderChunk.tonemapping_pars_fragment")}function qv(o){if(typeof o=="string")switch(o=o.toLowerCase(),o){case"none":return d.NoToneMapping;case"neutral":return d.NeutralToneMapping;case"aces":return d.ACESFilmicToneMapping;case"agx":return d.AgXToneMapping;case"khronos_neutral":return d.NeutralToneMapping;default:console.warn("[PostProcessing] Unknown tone mapping mode",o);return}}function bt(o){const t=document.createElement("span");return t.style.maxWidth="48px",t.style.maxHeight="48px",t.style.overflow="hidden",t.classList.add("material-symbols-outlined","notranslate"),t.setAttribute("translate","no"),t.innerText=o,t}function Xv(o){var e;return((e=o.classList)==null?void 0:e.contains("material-symbols-outlined"))||!1}const rd=new Map;async function ym(o){const t="Material Symbols Outlined";if(document.fonts.check(`1em '${t}'`)||(console.log("Font not loaded yet"),await document.fonts.ready),rd.has(o))return rd.get(o);const e=document.createElement("canvas"),i=48;e.width=i,e.height=i;const n=e.getContext("2d");if(n){n.font=`${i}px '${t}'`,n.fillStyle="black",n.fillText(o,0,i);const s=e.toDataURL(),a=new d.Texture;return a.name=o+" icon",a.image=new Image,a.image.src=s,a.needsUpdate=!0,rd.set(o,a),a}return rd.set(o,null),null}const Sc=class Sc{constructor(){r(this,"_fullscreenButton");r(this,"_muteButton");r(this,"_qrButton");r(this,"_customQRButtonUrl")}static get instance(){return this.getOrCreate()}static getOrCreate(){return this._instance||(this._instance=new Sc),this._instance}static create(){return new Sc}get fullscreenButton(){return this._fullscreenButton}createFullscreenButton(t){if(this._fullscreenButton)return this._fullscreenButton;if(!document.fullscreenEnabled)return j()&&console.warn("NeedleMenu: Fullscreen button could not be created, device doesn't support the Fullscreen API"),null;const e=document.createElement("button");this._fullscreenButton=e,e.classList.add("fullscreen-button"),e.title="Click to enter fullscreen mode";const i=bt("fullscreen"),n=bt("fullscreen_exit");return e.appendChild(i),e.onclick=()=>{document.fullscreenElement?document.exitFullscreen():"webkitRequestFullscreen"in t.domElement&&typeof t.domElement.webkitRequestFullscreen=="function"?t.domElement.webkitRequestFullscreen():"requestFullscreen"in t.domElement&&t.domElement.requestFullscreen()},document.addEventListener("fullscreenchange",()=>{document.fullscreenElement?(i.remove(),e.appendChild(n),e.title="Click to enter fullscreen mode"):(n.remove(),e.appendChild(i),e.title="Click to exit fullscreen mode")}),globalThis.addEventListener("needle-xrsession-start",()=>{e.style.display="none"}),globalThis.addEventListener("needle-xrsession-end",()=>{e.style.display=""}),e}get muteButton(){return this._muteButton}createMuteButton(t){if(this._muteButton)return this._muteButton;const e=document.createElement("button");this._muteButton=e,e.classList.add("mute-button"),e.title="Click to mute/unmute";const i=bt("volume_off"),n=bt("volume_up");return t.application.muted?e.appendChild(i):e.appendChild(n),e.onclick=()=>{t.application.muted?(i.remove(),e.appendChild(n),t.application.muted=!1):(n.remove(),e.appendChild(i),t.application.muted=!0)},e}get qrButton(){return this._qrButton}set qrButtonUrl(t){try{new URL(t),this._customQRButtonUrl=t}catch{console.warn(`[Needle] QR code button URL is not a valid URL '${t}'`)}}get qrButtonUrl(){return this._customQRButtonUrl||window.location.href}createQRCode(){if(this._qrButton)return this._qrButton;const t=this,e=document.createElement("button");this._qrButton=e,e.innerText="QR Code",e.prepend(bt("qr_code")),e.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(e);const i=document.createElement("div");i.style.cssText=`
352
+ `,t="vec3 AgXToneMapping( vec3 color ) {",e="return color;",i=d.ShaderChunk.tonemapping_pars_fragment.indexOf(t),n=d.ShaderChunk.tonemapping_pars_fragment.indexOf(e,i);if(i>=0&&n>=0){const s=d.ShaderChunk.tonemapping_pars_fragment.substring(i,n+e.length);d.ShaderChunk.tonemapping_pars_fragment=d.ShaderChunk.tonemapping_pars_fragment.replace(s,o)}else j()&&console.error("Couldn't find AgXToneMapping in ShaderChunk.tonemapping_pars_fragment")}function qv(o){if(typeof o=="string")switch(o=o.toLowerCase(),o){case"none":return d.NoToneMapping;case"neutral":return d.NeutralToneMapping;case"aces":return d.ACESFilmicToneMapping;case"agx":return d.AgXToneMapping;case"khronos_neutral":return d.NeutralToneMapping;default:console.warn("[PostProcessing] Unknown tone mapping mode",o);return}}function _t(o){const t=document.createElement("span");return t.style.maxWidth="48px",t.style.maxHeight="48px",t.style.overflow="hidden",t.classList.add("material-symbols-outlined","notranslate"),t.setAttribute("translate","no"),t.innerText=o,t}function Xv(o){var e;return((e=o.classList)==null?void 0:e.contains("material-symbols-outlined"))||!1}const rd=new Map;async function ym(o){const t="Material Symbols Outlined";if(document.fonts.check(`1em '${t}'`)||(console.log("Font not loaded yet"),await document.fonts.ready),rd.has(o))return rd.get(o);const e=document.createElement("canvas"),i=48;e.width=i,e.height=i;const n=e.getContext("2d");if(n){n.font=`${i}px '${t}'`,n.fillStyle="black",n.fillText(o,0,i);const s=e.toDataURL(),a=new d.Texture;return a.name=o+" icon",a.image=new Image,a.image.src=s,a.needsUpdate=!0,rd.set(o,a),a}return rd.set(o,null),null}const Sc=class Sc{constructor(){r(this,"_fullscreenButton");r(this,"_muteButton");r(this,"_qrButton");r(this,"_customQRButtonUrl")}static get instance(){return this.getOrCreate()}static getOrCreate(){return this._instance||(this._instance=new Sc),this._instance}static create(){return new Sc}get fullscreenButton(){return this._fullscreenButton}createFullscreenButton(t){if(this._fullscreenButton)return this._fullscreenButton;if(!document.fullscreenEnabled)return j()&&console.warn("NeedleMenu: Fullscreen button could not be created, device doesn't support the Fullscreen API"),null;const e=document.createElement("button");this._fullscreenButton=e,e.classList.add("fullscreen-button"),e.title="Click to enter fullscreen mode";const i=_t("fullscreen"),n=_t("fullscreen_exit");return e.appendChild(i),e.onclick=()=>{document.fullscreenElement?document.exitFullscreen():"webkitRequestFullscreen"in t.domElement&&typeof t.domElement.webkitRequestFullscreen=="function"?t.domElement.webkitRequestFullscreen():"requestFullscreen"in t.domElement&&t.domElement.requestFullscreen()},document.addEventListener("fullscreenchange",()=>{document.fullscreenElement?(i.remove(),e.appendChild(n),e.title="Click to enter fullscreen mode"):(n.remove(),e.appendChild(i),e.title="Click to exit fullscreen mode")}),globalThis.addEventListener("needle-xrsession-start",()=>{e.style.display="none"}),globalThis.addEventListener("needle-xrsession-end",()=>{e.style.display=""}),e}get muteButton(){return this._muteButton}createMuteButton(t){if(this._muteButton)return this._muteButton;const e=document.createElement("button");this._muteButton=e,e.classList.add("mute-button"),e.title="Click to mute/unmute";const i=_t("volume_off"),n=_t("volume_up");return t.application.muted?e.appendChild(i):e.appendChild(n),e.onclick=()=>{t.application.muted?(i.remove(),e.appendChild(n),t.application.muted=!1):(n.remove(),e.appendChild(i),t.application.muted=!0)},e}get qrButton(){return this._qrButton}set qrButtonUrl(t){try{new URL(t),this._customQRButtonUrl=t}catch{console.warn(`[Needle] QR code button URL is not a valid URL '${t}'`)}}get qrButtonUrl(){return this._customQRButtonUrl||window.location.href}createQRCode(){if(this._qrButton)return this._qrButton;const t=this,e=document.createElement("button");this._qrButton=e,e.innerText="QR Code",e.prepend(_t("qr_code")),e.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(e);const i=document.createElement("div");i.style.cssText=`
353
353
  position: fixed;
354
354
  display: inline-block;
355
355
  padding: 0.5rem;
@@ -389,7 +389,7 @@ vec3 AgXToneMapping( vec3 color ) {
389
389
  <div class="wrapper">
390
390
  <img class="logo" src=${iS} />
391
391
  </div>
392
- `,this._root.appendChild(e.content.cloneNode(!0)),this.wrapper=this._root.querySelector(".wrapper"),this._root.appendChild(this.wrapper),this.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")}),this.wrapper.setAttribute("title","Made with Needle Engine")}static get elementName(){return au}static create(){return document.createElement(au)}setLogoVisible(e){this.logoElement.style.display=e?"block":"none"}}customElements.get(au)||customElements.define(au,Yv);const rp=S("debugspatialmenu");class V1{constructor(t,e){r(this,"_context");r(this,"needleMenu");r(this,"htmlButtonsMap",new Map);r(this,"enabled",!0);r(this,"userRequestedMenu",!1);r(this,"uiisDirty",!1);r(this,"_showNeedleLogo");r(this,"_wasInXR",!1);r(this,"preRender",()=>{var e;if(!this.enabled){(e=this.menu)==null||e.removeFromParent();return}rp&&exports.DeviceUtilities.isDesktop()&&this.updateMenu();const t=this._context.xr;if(!(t!=null&&t.running)){this._wasInXR&&(this._wasInXR=!1,this.onExitXR());return}this._wasInXR||(this._wasInXR=!0,this.onEnterXR()),this.updateMenu()});r(this,"_menuTarget",new d.Object3D);r(this,"positionFilter",new qm(90,.5));r(this,"familyName","Needle Spatial Menu");r(this,"menu");r(this,"_poweredByNeedleElement");var n;this._context=t,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=e;const i=(n=this.needleMenu.shadowRoot)==null?void 0:n.querySelector(".options");i?new MutationObserver(a=>{if(this.enabled&&!(this._context.isInXR==!1&&!rp))for(const l of a)l.type==="childList"&&(l.addedNodes.forEach(c=>{this.createButtonFromHTMLNode(c)}),l.removedNodes.forEach(c=>{const h=c,u=this.htmlButtonsMap.get(h);u&&(this.htmlButtonsMap.delete(h),u.remove(),ne.__webpack_exports__default.update())}))}).observe(i,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(t){var e;this.enabled=t,t||(e=this.menu)==null||e.removeFromParent()}setDisplay(t){return this.enabled?(this.userRequestedMenu=t,!0):!1}onDestroy(){const t=this._context.pre_render_callbacks.indexOf(this.preRender);t>-1&&this._context.pre_render_callbacks.splice(t,1)}markDirty(){this.uiisDirty=!0}showNeedleLogo(t){this._showNeedleLogo=t}onEnterXR(){var e;const t=(e=this.needleMenu.shadowRoot)==null?void 0:e.querySelector(".options");t&&t.childNodes.forEach(i=>{this.createButtonFromHTMLNode(i)})}onExitXR(){var t;(t=this.menu)==null||t.removeFromParent()}createButtonFromHTMLNode(t){const e=this.getMenu(),i=this.htmlButtonsMap.get(t);if(i){i.add();return}if(t instanceof HTMLButtonElement){const n=this.createButton(e,t);this.htmlButtonsMap.set(t,n),n.add()}else t instanceof HTMLSlotElement&&t.assignedNodes().forEach(n=>{this.createButtonFromHTMLNode(n)})}updateMenu(){var s,a;const t=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(t);const e=this._context.mainCamera,i=this._context.xr,n=(i==null?void 0:i.rigScale)||1;if(e){const l=e.worldPosition,c=e.worldForward.multiplyScalar(-1),h=c.y>.6,u=c.y>.4,f=(t.visible?u:h)||this.userRequestedMenu,p=!t.visible&&f;t.visible=f||exports.DeviceUtilities.isDesktop()&&rp,c.multiplyScalar(3*n),l.add(c),(p||!1)&&(t.position.copy(this._menuTarget.position),t.position.y+=.25,this._menuTarget.position.copy(t.position),this.positionFilter.reset(t.position),t.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const y=this._menuTarget.position.distanceTo(l);(p||y>1.5*n)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(l),this._context.scene.add(this._menuTarget),th(this._menuTarget,this._context.mainCamera,!0,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,t.position,this._context.time.time),(s=this.menu)==null||s.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*5),(a=this.menu)==null||a.scale.setScalar(n)}this.uiisDirty&&(this.uiisDirty=!1,ne.__webpack_exports__default.update())}ensureRenderOnTop(t,e=0){t instanceof d.Mesh&&(t.material.depthTest=!1,t.material.depthWrite=!1),t.renderOrder=1e3+e*2;for(const i of t.children)this.ensureRenderOnTop(i,e+1)}get isVisible(){var t;return(t=this.menu)==null?void 0:t.visible}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new ne.__webpack_exports__default.Block({boxSizing:"border-box",fontFamily:this.familyName,height:"auto",fontSize:.1,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:.55,borderRadius:1,whiteSpace:"pre-wrap",flexDirection:"row",alignItems:"center",padding:new d.Vector4(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const t=k.get("ObjectRaycaster");return t&&vr(this.menu,new t),this.menu}handleNeedleWatermark(){var t;if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new ne.__webpack_exports__default.Block({width:"auto",height:"auto",fontSize:.05,whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",margin:.02,borderRadius:.02,padding:.02,backgroundColor:16777215,backgroundOpacity:1}),this._poweredByNeedleElement["needle:use_eventsystem"]=!0;const e=new Y_(this._context,()=>globalThis.open("https://needle.tools","_self"));vr(this._poweredByNeedleElement,e);const i=new ne.__webpack_exports__default.Text({textContent:"Powered by",width:"auto",height:"auto"}),n=new ne.__webpack_exports__default.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new d.Vector4(0,0,0,.02)});this._poweredByNeedleElement.add(i),this._poweredByNeedleElement.add(n),(t=this.menu)==null||t.add(this._poweredByNeedleElement),this.markDirty(),new d.TextureLoader().load("./include/needle/poweredbyneedle.webp",a=>{var c;e.allowModifyUI=!1,i.removeFromParent(),n.removeFromParent();const l=a.image.width/a.image.height;(c=this._poweredByNeedleElement)==null||c.set({backgroundImage:a,backgroundOpacity:1,width:.1*l,height:.1}),this.markDirty()})}if(this.menu){const e=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&Qn())e>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const i=this.menu.children.indexOf(this._poweredByNeedleElement);e!==i&&this.markDirty()}}}ensureFont(){let t=ne.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);if(!t){t=ne.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName);const e=t.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");e==null||e.addEventListener("ready",()=>{this.markDirty()})}}createButton(t,e){const i=new ne.__webpack_exports__default.Block({width:"auto",height:"auto",whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",backgroundColor:16777215,backgroundOpacity:0,padding:.02,margin:.01,borderRadius:.02,cursor:"pointer",fontSize:.05}),n=new ne.__webpack_exports__default.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});i.add(n),i["needle:use_eventsystem"]=!0;const s=new Y_(this._context,()=>e.click());return vr(i,s),new W1(this,t,e,i,n)}}class W1{constructor(t,e,i,n,s){r(this,"menu");r(this,"root");r(this,"htmlbutton");r(this,"spatialContainer");r(this,"spatialText");r(this,"spatialIcon");r(this,"_lastText","");r(this,"_lastTexture");this.menu=t,this.root=e,this.htmlbutton=i,this.spatialContainer=n,this.spatialText=s,new MutationObserver(l=>{for(const c of l)c.type==="attributes"?c.attributeName==="style"&&this.updateVisible():c.type==="childList"&&this.updateText()}).observe(i,{attributes:!0,childList:!0}),this.updateText()}add(){this.spatialContainer.parent!=this.root&&(this.root.add(this.spatialContainer),this.menu.markDirty(),this.updateVisible(),this.updateText())}remove(){this.spatialContainer.parent&&(this.spatialContainer.removeFromParent(),this.menu.markDirty())}updateVisible(){const t=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",t!==this.spatialContainer.visible&&this.menu.markDirty()}updateText(){let t="",e="";this.htmlbutton.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?t+=i.textContent:i instanceof HTMLElement&&Xv(i)&&i.textContent&&(e=i.textContent)}),this._lastText!==t&&(this._lastText=t,this.spatialText.name=t,this.spatialText.set({textContent:t}),this.menu.markDirty()),t.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),e&&this.createIcon(e)}async createIcon(t){var i;if(!this.spatialIcon){const n=await ym(t);if(n&&!this.spatialIcon){const a=new ne.__webpack_exports__default.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:n,backgroundOpacity:1,margin:new d.Vector4(0,.005,0,0)});this.spatialIcon=a,this.spatialContainer.add(a),this.menu.markDirty()}}if(t!=this._lastTexture){this._lastTexture=t;const n=await ym(t);n&&((i=this.spatialIcon)==null||i.set({backgroundImage:n}),this.menu.markDirty())}const e=this.spatialContainer.children.indexOf(this.spatialIcon);e>0&&(this.spatialContainer.children.splice(e,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class Y_{constructor(t,e){r(this,"isComponent",!0);r(this,"enabled",!0);r(this,"gameObject");r(this,"allowModifyUI",!0);r(this,"context");r(this,"onclick");this.context=t,this.onclick=e}get activeAndEnabled(){return!0}__internalAwake(){}__internalEnable(){}__internalDisable(){}__internalStart(){}onEnable(){}onDisable(){}get element(){return this.gameObject}onPointerEnter(){this.context.input.setCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:1}),ne.__webpack_exports__default.update())}onPointerExit(){this.context.input.unsetCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),ne.__webpack_exports__default.update())}onPointerDown(t){t.use()}onPointerUp(t){t.use()}onPointerClick(t){t.use(),this.onclick()}}const tr="needle-menu",fc=S("debugmenu"),K_=S("debugnoncommercial");let G1=class{constructor(t){r(this,"_context");r(this,"_menu");r(this,"_spatialMenu");r(this,"onPostMessage",t=>{if(t.origin===globalThis.location.origin&&typeof t.data=="object"){const e=t.data,i=e.type;if(i==="needle:menu"){const n=e.button;if(n){if(!n.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!n.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const s=document.createElement("button");if(s.textContent=n.label,n.icon){const a=bt(n.icon);s.prepend(a)}n.priority&&s.setAttribute("priority",n.priority.toString()),s.onclick=()=>{if(n.onclick){const a=n.onclick.startsWith("http")||n.onclick.startsWith("www."),l=n.target||"_blank";a?globalThis.open(n.onclick,l):console.error("NeedleMenu: onclick is not a valid link",n.onclick)}},this._menu.appendChild(s)}else fc&&console.error("NeedleMenu: unknown postMessage event",e)}else fc&&console.warn("NeedleMenu: unknown postMessage type",i,e)}});r(this,"onStartXR",t=>{t.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),t.session.session.addEventListener("end",this.onExitXR),this._menu.closeFoldout())});r(this,"onExitXR",()=>{this._menu.previousParent&&(this._menu.previousParent.appendChild(this._menu),delete this._menu.previousParent)});r(this,"_muteButton");r(this,"_fullscreenButton");this._menu=lu.getOrCreate(t.domElement,t),this._context=t,this._spatialMenu=new V1(t,this._menu),window.addEventListener("message",this.onPostMessage),zu(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}setPosition(t){this._menu.setPosition(t)}setVisible(t){this._menu.setVisible(t)}showNeedleLogo(t){var e;this._menu.showNeedleLogo(t),(e=this._spatialMenu)==null||e.showNeedleLogo(t)}get logoIsVisible(){return this._menu.logoIsVisible}showSpatialMenu(t){this._spatialMenu.setEnabled(t)}setSpatialMenuVisible(t){this._spatialMenu.setDisplay(t)}get spatialMenuIsVisible(){return this._spatialMenu.isVisible}showQRCodeButton(t){if(t==="desktop-only"&&(t=!exports.DeviceUtilities.isMobileDevice()),t){const e=zn.getOrCreate().createQRCode();return e.style.display="",this._menu.appendChild(e),e}else{const e=zn.getOrCreate().qrButton;return e&&(e.style.display="none"),e??null}}showAudioPlaybackOption(t){var e;if(!t){(e=this._muteButton)==null||e.remove();return}this._muteButton=zn.getOrCreate().createMuteButton(this._context),this._muteButton.setAttribute("priority","100"),this._menu.appendChild(this._muteButton)}showFullscreenOption(t){var e;if(!t){(e=this._fullscreenButton)==null||e.remove();return}this._fullscreenButton=zn.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&(this._fullscreenButton.setAttribute("priority","150"),this._menu.appendChild(this._fullscreenButton))}appendChild(t){return this._menu.appendChild(t)}};var Yc;const e_=class e_ extends HTMLElement{constructor(){var f,p,g,y,b,_;super();r(this,"_domElement",null);r(this,"_context",null);r(this,"_sizeChangeInterval");on(this,Yc,e=>{if(!e.defaultPrevented&&e.target==this._domElement&&e instanceof PointerEvent&&e.button===0&&this.root.classList.contains("open")){const i=this.foldout.getBoundingClientRect(),n=e;n.clientX>i.left&&n.clientX<i.right&&n.clientY>i.top&&n.clientY<i.bottom||this.root.classList.toggle("open",!1)}});r(this,"_userRequestedLogoVisible");r(this,"_userRequestedMenuVisible");r(this,"root");r(this,"wrapper");r(this,"options");r(this,"logoContainer");r(this,"compactMenuButton");r(this,"foldout");r(this,"_isHandlingChange",!1);r(this,"_didSort",new Map);r(this,"_lastAvailableWidthChange",0);r(this,"_timeoutHandle",0);r(this,"handleSizeChange",(e,i)=>{if(!this._domElement)return;const n=this._domElement.clientWidth;if(n<100){clearTimeout(this._timeoutHandle),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const a=n-40;if(!i&&Math.abs(a-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=a,clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{const h=c();h<0?(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")):h>0&&(this.root.classList.remove("compact"),this.foldout.classList.remove("floating-panel-style"),c()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")))},5);const l=()=>this.options.clientWidth+this.logoContainer.clientWidth,c=()=>a-l()});const e=document.createElement("template");e.innerHTML=`<style>
392
+ `,this._root.appendChild(e.content.cloneNode(!0)),this.wrapper=this._root.querySelector(".wrapper"),this._root.appendChild(this.wrapper),this.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")}),this.wrapper.setAttribute("title","Made with Needle Engine")}static get elementName(){return au}static create(){return document.createElement(au)}setLogoVisible(e){this.logoElement.style.display=e?"block":"none"}}customElements.get(au)||customElements.define(au,Yv);const rp=S("debugspatialmenu");class V1{constructor(t,e){r(this,"_context");r(this,"needleMenu");r(this,"htmlButtonsMap",new Map);r(this,"enabled",!0);r(this,"userRequestedMenu",!1);r(this,"uiisDirty",!1);r(this,"_showNeedleLogo");r(this,"_wasInXR",!1);r(this,"preRender",()=>{var e;if(!this.enabled){(e=this.menu)==null||e.removeFromParent();return}rp&&exports.DeviceUtilities.isDesktop()&&this.updateMenu();const t=this._context.xr;if(!(t!=null&&t.running)){this._wasInXR&&(this._wasInXR=!1,this.onExitXR());return}this._wasInXR||(this._wasInXR=!0,this.onEnterXR()),this.updateMenu()});r(this,"_menuTarget",new d.Object3D);r(this,"positionFilter",new qm(90,.5));r(this,"familyName","Needle Spatial Menu");r(this,"menu");r(this,"_poweredByNeedleElement");var n;this._context=t,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=e;const i=(n=this.needleMenu.shadowRoot)==null?void 0:n.querySelector(".options");i?new MutationObserver(a=>{if(this.enabled&&!(this._context.isInXR==!1&&!rp))for(const l of a)l.type==="childList"&&(l.addedNodes.forEach(c=>{this.createButtonFromHTMLNode(c)}),l.removedNodes.forEach(c=>{const h=c,u=this.htmlButtonsMap.get(h);u&&(this.htmlButtonsMap.delete(h),u.remove(),ne.__webpack_exports__default.update())}))}).observe(i,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(t){var e;this.enabled=t,t||(e=this.menu)==null||e.removeFromParent()}setDisplay(t){return this.enabled?(this.userRequestedMenu=t,!0):!1}onDestroy(){const t=this._context.pre_render_callbacks.indexOf(this.preRender);t>-1&&this._context.pre_render_callbacks.splice(t,1)}markDirty(){this.uiisDirty=!0}showNeedleLogo(t){this._showNeedleLogo=t}onEnterXR(){var e;const t=(e=this.needleMenu.shadowRoot)==null?void 0:e.querySelector(".options");t&&t.childNodes.forEach(i=>{this.createButtonFromHTMLNode(i)})}onExitXR(){var t;(t=this.menu)==null||t.removeFromParent()}createButtonFromHTMLNode(t){const e=this.getMenu(),i=this.htmlButtonsMap.get(t);if(i){i.add();return}if(t instanceof HTMLButtonElement){const n=this.createButton(e,t);this.htmlButtonsMap.set(t,n),n.add()}else t instanceof HTMLSlotElement&&t.assignedNodes().forEach(n=>{this.createButtonFromHTMLNode(n)})}updateMenu(){var s,a;const t=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(t);const e=this._context.mainCamera,i=this._context.xr,n=(i==null?void 0:i.rigScale)||1;if(e){const l=e.worldPosition,c=e.worldForward.multiplyScalar(-1),h=c.y>.6,u=c.y>.4,f=(t.visible?u:h)||this.userRequestedMenu,p=!t.visible&&f;t.visible=f||exports.DeviceUtilities.isDesktop()&&rp,c.multiplyScalar(3*n),l.add(c),(p||!1)&&(t.position.copy(this._menuTarget.position),t.position.y+=.25,this._menuTarget.position.copy(t.position),this.positionFilter.reset(t.position),t.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const y=this._menuTarget.position.distanceTo(l);(p||y>1.5*n)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(l),this._context.scene.add(this._menuTarget),th(this._menuTarget,this._context.mainCamera,!0,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,t.position,this._context.time.time),(s=this.menu)==null||s.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*5),(a=this.menu)==null||a.scale.setScalar(n)}this.uiisDirty&&(this.uiisDirty=!1,ne.__webpack_exports__default.update())}ensureRenderOnTop(t,e=0){t instanceof d.Mesh&&(t.material.depthTest=!1,t.material.depthWrite=!1),t.renderOrder=1e3+e*2;for(const i of t.children)this.ensureRenderOnTop(i,e+1)}get isVisible(){var t;return(t=this.menu)==null?void 0:t.visible}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new ne.__webpack_exports__default.Block({boxSizing:"border-box",fontFamily:this.familyName,height:"auto",fontSize:.1,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:.55,borderRadius:1,whiteSpace:"pre-wrap",flexDirection:"row",alignItems:"center",padding:new d.Vector4(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const t=k.get("ObjectRaycaster");return t&&vr(this.menu,new t),this.menu}handleNeedleWatermark(){var t;if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new ne.__webpack_exports__default.Block({width:"auto",height:"auto",fontSize:.05,whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",margin:.02,borderRadius:.02,padding:.02,backgroundColor:16777215,backgroundOpacity:1}),this._poweredByNeedleElement["needle:use_eventsystem"]=!0;const e=new Y_(this._context,()=>globalThis.open("https://needle.tools","_self"));vr(this._poweredByNeedleElement,e);const i=new ne.__webpack_exports__default.Text({textContent:"Powered by",width:"auto",height:"auto"}),n=new ne.__webpack_exports__default.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new d.Vector4(0,0,0,.02)});this._poweredByNeedleElement.add(i),this._poweredByNeedleElement.add(n),(t=this.menu)==null||t.add(this._poweredByNeedleElement),this.markDirty(),new d.TextureLoader().load("./include/needle/poweredbyneedle.webp",a=>{var c;e.allowModifyUI=!1,i.removeFromParent(),n.removeFromParent();const l=a.image.width/a.image.height;(c=this._poweredByNeedleElement)==null||c.set({backgroundImage:a,backgroundOpacity:1,width:.1*l,height:.1}),this.markDirty()})}if(this.menu){const e=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&Qn())e>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const i=this.menu.children.indexOf(this._poweredByNeedleElement);e!==i&&this.markDirty()}}}ensureFont(){let t=ne.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);if(!t){t=ne.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName);const e=t.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");e==null||e.addEventListener("ready",()=>{this.markDirty()})}}createButton(t,e){const i=new ne.__webpack_exports__default.Block({width:"auto",height:"auto",whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",backgroundColor:16777215,backgroundOpacity:0,padding:.02,margin:.01,borderRadius:.02,cursor:"pointer",fontSize:.05}),n=new ne.__webpack_exports__default.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});i.add(n),i["needle:use_eventsystem"]=!0;const s=new Y_(this._context,()=>e.click());return vr(i,s),new W1(this,t,e,i,n)}}class W1{constructor(t,e,i,n,s){r(this,"menu");r(this,"root");r(this,"htmlbutton");r(this,"spatialContainer");r(this,"spatialText");r(this,"spatialIcon");r(this,"_lastText","");r(this,"_lastTexture");this.menu=t,this.root=e,this.htmlbutton=i,this.spatialContainer=n,this.spatialText=s,new MutationObserver(l=>{for(const c of l)c.type==="attributes"?c.attributeName==="style"&&this.updateVisible():c.type==="childList"&&this.updateText()}).observe(i,{attributes:!0,childList:!0}),this.updateText()}add(){this.spatialContainer.parent!=this.root&&(this.root.add(this.spatialContainer),this.menu.markDirty(),this.updateVisible(),this.updateText())}remove(){this.spatialContainer.parent&&(this.spatialContainer.removeFromParent(),this.menu.markDirty())}updateVisible(){const t=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",t!==this.spatialContainer.visible&&this.menu.markDirty()}updateText(){let t="",e="";this.htmlbutton.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?t+=i.textContent:i instanceof HTMLElement&&Xv(i)&&i.textContent&&(e=i.textContent)}),this._lastText!==t&&(this._lastText=t,this.spatialText.name=t,this.spatialText.set({textContent:t}),this.menu.markDirty()),t.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),e&&this.createIcon(e)}async createIcon(t){var i;if(!this.spatialIcon){const n=await ym(t);if(n&&!this.spatialIcon){const a=new ne.__webpack_exports__default.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:n,backgroundOpacity:1,margin:new d.Vector4(0,.005,0,0)});this.spatialIcon=a,this.spatialContainer.add(a),this.menu.markDirty()}}if(t!=this._lastTexture){this._lastTexture=t;const n=await ym(t);n&&((i=this.spatialIcon)==null||i.set({backgroundImage:n}),this.menu.markDirty())}const e=this.spatialContainer.children.indexOf(this.spatialIcon);e>0&&(this.spatialContainer.children.splice(e,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class Y_{constructor(t,e){r(this,"isComponent",!0);r(this,"enabled",!0);r(this,"gameObject");r(this,"allowModifyUI",!0);r(this,"context");r(this,"onclick");this.context=t,this.onclick=e}get activeAndEnabled(){return!0}__internalAwake(){}__internalEnable(){}__internalDisable(){}__internalStart(){}onEnable(){}onDisable(){}get element(){return this.gameObject}onPointerEnter(){this.context.input.setCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:1}),ne.__webpack_exports__default.update())}onPointerExit(){this.context.input.unsetCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),ne.__webpack_exports__default.update())}onPointerDown(t){t.use()}onPointerUp(t){t.use()}onPointerClick(t){t.use(),this.onclick()}}const tr="needle-menu",fc=S("debugmenu"),K_=S("debugnoncommercial");let G1=class{constructor(t){r(this,"_context");r(this,"_menu");r(this,"_spatialMenu");r(this,"onPostMessage",t=>{if(t.origin===globalThis.location.origin&&typeof t.data=="object"){const e=t.data,i=e.type;if(i==="needle:menu"){const n=e.button;if(n){if(!n.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!n.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const s=document.createElement("button");if(s.textContent=n.label,n.icon){const a=_t(n.icon);s.prepend(a)}n.priority&&s.setAttribute("priority",n.priority.toString()),s.onclick=()=>{if(n.onclick){const a=n.onclick.startsWith("http")||n.onclick.startsWith("www."),l=n.target||"_blank";a?globalThis.open(n.onclick,l):console.error("NeedleMenu: onclick is not a valid link",n.onclick)}},this._menu.appendChild(s)}else fc&&console.error("NeedleMenu: unknown postMessage event",e)}else fc&&console.warn("NeedleMenu: unknown postMessage type",i,e)}});r(this,"onStartXR",t=>{t.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),t.session.session.addEventListener("end",this.onExitXR),this._menu.closeFoldout())});r(this,"onExitXR",()=>{this._menu.previousParent&&(this._menu.previousParent.appendChild(this._menu),delete this._menu.previousParent)});r(this,"_muteButton");r(this,"_fullscreenButton");this._menu=lu.getOrCreate(t.domElement,t),this._context=t,this._spatialMenu=new V1(t,this._menu),window.addEventListener("message",this.onPostMessage),zu(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}setPosition(t){this._menu.setPosition(t)}setVisible(t){this._menu.setVisible(t)}showNeedleLogo(t){var e;this._menu.showNeedleLogo(t),(e=this._spatialMenu)==null||e.showNeedleLogo(t)}get logoIsVisible(){return this._menu.logoIsVisible}showSpatialMenu(t){this._spatialMenu.setEnabled(t)}setSpatialMenuVisible(t){this._spatialMenu.setDisplay(t)}get spatialMenuIsVisible(){return this._spatialMenu.isVisible}showQRCodeButton(t){if(t==="desktop-only"&&(t=!exports.DeviceUtilities.isMobileDevice()),t){const e=zn.getOrCreate().createQRCode();return e.style.display="",this._menu.appendChild(e),e}else{const e=zn.getOrCreate().qrButton;return e&&(e.style.display="none"),e??null}}showAudioPlaybackOption(t){var e;if(!t){(e=this._muteButton)==null||e.remove();return}this._muteButton=zn.getOrCreate().createMuteButton(this._context),this._muteButton.setAttribute("priority","100"),this._menu.appendChild(this._muteButton)}showFullscreenOption(t){var e;if(!t){(e=this._fullscreenButton)==null||e.remove();return}this._fullscreenButton=zn.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&(this._fullscreenButton.setAttribute("priority","150"),this._menu.appendChild(this._fullscreenButton))}appendChild(t){return this._menu.appendChild(t)}};var Yc;const e_=class e_ extends HTMLElement{constructor(){var f,p,g,y,b,_;super();r(this,"_domElement",null);r(this,"_context",null);r(this,"_sizeChangeInterval");on(this,Yc,e=>{if(!e.defaultPrevented&&e.target==this._domElement&&e instanceof PointerEvent&&e.button===0&&this.root.classList.contains("open")){const i=this.foldout.getBoundingClientRect(),n=e;n.clientX>i.left&&n.clientX<i.right&&n.clientY>i.top&&n.clientY<i.bottom||this.root.classList.toggle("open",!1)}});r(this,"_userRequestedLogoVisible");r(this,"_userRequestedMenuVisible");r(this,"root");r(this,"wrapper");r(this,"options");r(this,"logoContainer");r(this,"compactMenuButton");r(this,"foldout");r(this,"_isHandlingChange",!1);r(this,"_didSort",new Map);r(this,"_lastAvailableWidthChange",0);r(this,"_timeoutHandle",0);r(this,"handleSizeChange",(e,i)=>{if(!this._domElement)return;const n=this._domElement.clientWidth;if(n<100){clearTimeout(this._timeoutHandle),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const a=n-40;if(!i&&Math.abs(a-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=a,clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{const h=c();h<0?(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")):h>0&&(this.root.classList.remove("compact"),this.foldout.classList.remove("floating-panel-style"),c()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")))},5);const l=()=>this.options.clientWidth+this.logoContainer.clientWidth,c=()=>a-l()});const e=document.createElement("template");e.innerHTML=`<style>
393
393
 
394
394
  #root {
395
395
  position: absolute;
@@ -766,7 +766,7 @@ vec3 AgXToneMapping( vec3 color ) {
766
766
  <div class="expanded-click-area"></div>
767
767
  </button>
768
768
  </div>
769
- `;const i=this.attachShadow({mode:"open"});Qv(),ru(_m,{loadedCallback:()=>{this.handleSizeChange()}}),ru(_m,{element:i});const n=e.content.cloneNode(!0);i==null||i.appendChild(n),this.root=i.querySelector("#root"),this.wrapper=(f=this.root)==null?void 0:f.querySelector(".wrapper"),this.options=(p=this.root)==null?void 0:p.querySelector(".options"),this.logoContainer=(g=this.root)==null?void 0:g.querySelector(".logo"),this.compactMenuButton=(y=this.root)==null?void 0:y.querySelector(".compact-menu-button"),this.compactMenuButton.append(bt("more_vert")),this.foldout=(b=this.root)==null?void 0:b.querySelector(".foldout"),(_=this.root)==null||_.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const s=Yv.create();s.style.minHeight="1rem",this.logoContainer.append(s),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>Z1(v=>{if(v==!0&&Yn()&&!K_){let w=this._userRequestedLogoVisible;w===void 0&&(w=!1),this.___onSetLogoVisible(w)}else this.___onSetLogoVisible(!0)}))}catch(v){console.error("[Needle Menu] License check failed.",v)}this.compactMenuButton.addEventListener("click",v=>{v.preventDefault(),this.root.classList.toggle("open")});let a=this._context;setTimeout(()=>a=this._context);let l=0;const c=(v,w)=>{var x,O,E;fc&&console.log("Set menu visible",w),a!=null&&a.isInAR&&a.arOverlayElement?v!=a.arOverlayElement&&a.arOverlayElement.appendChild(this):this.parentNode!=((x=this._domElement)==null?void 0:x.shadowRoot)&&((E=(O=this._domElement)==null?void 0:O.shadowRoot)==null||E.appendChild(this)),this.style.display=w?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let h=!1;new MutationObserver(v=>{var w;if(!h)try{h=!0,this.onChangeDetected(v);const x=this==null?void 0:this.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||x!=((w=this._domElement)==null?void 0:w.shadowRoot))&&!Yn()){const O=l++;Kt()&&this._userRequestedMenuVisible===!1?(O===0&&c(x,this._userRequestedMenuVisible),O===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu → The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):O===0?c(x,!0):setTimeout(()=>c(x,!0),5)}}finally{h=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),fc&&this.___insertDebugOptions()}static create(){return document.createElement(tr,{is:tr})}static getOrCreate(e,i){let n=e.querySelector(tr);return!n&&e.shadowRoot&&(n=e.shadowRoot.querySelector(tr)),n||(n=window.document.body.querySelector(tr)),n||(n=e_.create(),e.shadowRoot?e.shadowRoot.appendChild(n):e.appendChild(n)),n._domElement=e,n._context=i,n}connectedCallback(){window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!0),5e3),setTimeout(()=>{var e,i;(e=this._domElement)==null||e.addEventListener("resize",this.handleSizeChange),(i=this._domElement)==null||i.addEventListener("click",ce(this,Yc))},1)}disconnectedCallback(){var e,i;window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),(e=this._domElement)==null||e.removeEventListener("resize",this.handleSizeChange),(i=this._context)==null||i.domElement.removeEventListener("click",ce(this,Yc))}showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!Yn()||K_)&&(console.warn("[Needle Engine] You need a PRO license to hide the Needle Engine logo in production."),!Kt()))&&this.___onSetLogoVisible(e)}get logoIsVisible(){return!this.root.classList.contains("logo-hidden")}___onSetLogoVisible(e){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",e?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))}setPosition(e){if(e!=="top"&&e!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",e);this.root.classList.remove("top","bottom"),this.root.classList.add(e)}setVisible(e){this._userRequestedMenuVisible=e,this.style.display=e?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}append(...e){for(const i of e)if(typeof i=="string"){const n=document.createTextNode(i);this.options.appendChild(n)}else this.options.appendChild(i)}appendChild(e){var n;if(!(e instanceof Node)){const s=document.createElement("button");if(s.textContent=e.label,s.onclick=e.onClick,s.setAttribute("priority",((n=e.priority)==null?void 0:n.toString())??"0"),e.title&&(s.title=e.title),e.icon){const a=bt(e.icon);e.iconSide==="right"?s.appendChild(a):s.prepend(a)}e.class&&s.classList.add(e.class),e=s}return this.options.appendChild(e)}prepend(...e){for(const i of e)if(typeof i=="string"){const n=document.createTextNode(i);this.options.prepend(n)}else this.options.prepend(i)}onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const i of e)i.target==this.options&&this.onOptionsChildrenChanged(i)}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type==="childList"&&e.addedNodes.length>0){const i=Array.from(this.options.children);i.sort((s,a)=>{const l=parseInt(s.getAttribute("priority")||"0"),c=parseInt(a.getAttribute("priority")||"0");return l-c});let n=!1;for(let s=0;s<i.length;s++){const a=this.options.children[s],l=i[s];if(a!==l){n=!0;break}}if(n)for(const s of i)this.options.appendChild(s)}}handleMenuVisible(){fc&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions)}get hasAnyContent(){return!!(this.logoContainer.style.display!="none"||this.hasAnyVisibleOptions)}get hasAnyVisibleOptions(){for(let e=0;e<this.options.children.length;e++){const i=this.options.children[e];if(i.tagName==="SLOT"){const s=i.assignedNodes();for(const a of s)if(a instanceof HTMLElement&&a.style.display!="none")return!0}else if(i.style.display!="none")return!0}return!1}___insertDebugOptions(){window.addEventListener("keydown",n=>{n.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const n=new Array(this.options.children.length);for(let s=0;s<this.options.children.length;s++)n[s]=this.options.children[s];for(const s of n)this.options.removeChild(s);setTimeout(()=>{for(const s of n)this.options.appendChild(s)},1e3)},this.appendChild(e);const i=document.createElement("button");i.textContent="Toggle Logo",i.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(i)}};Yc=new WeakMap;let lu=e_;customElements.get(tr)||customElements.define(tr,lu);const Xe=S("debugcontext"),H1=S("stats"),q1=S("debugactive"),X1=S("debugframerate"),Q1=S("debugcoroutine"),Y1={};class K1{constructor(){r(this,"name");r(this,"alias");r(this,"hash");r(this,"runInBackground");r(this,"domElement");r(this,"renderer");r(this,"camera");r(this,"scene")}}var we=(o=>(o[o.Start=-1]="Start",o[o.EarlyUpdate=0]="EarlyUpdate",o[o.Update=1]="Update",o[o.LateUpdate=2]="LateUpdate",o[o.OnBeforeRender=3]="OnBeforeRender",o[o.OnAfterRender=4]="OnAfterRender",o[o.PrePhysicsStep=9]="PrePhysicsStep",o[o.PostPhysicsStep=10]="PostPhysicsStep",o[o.Undefined=-1]="Undefined",o))(we||{});function qu(o,t){if(!o)return;if(!o.isComponent){(j()||Xe)&&console.error(`Registered script is not a Needle Engine component.
769
+ `;const i=this.attachShadow({mode:"open"});Qv(),ru(_m,{loadedCallback:()=>{this.handleSizeChange()}}),ru(_m,{element:i});const n=e.content.cloneNode(!0);i==null||i.appendChild(n),this.root=i.querySelector("#root"),this.wrapper=(f=this.root)==null?void 0:f.querySelector(".wrapper"),this.options=(p=this.root)==null?void 0:p.querySelector(".options"),this.logoContainer=(g=this.root)==null?void 0:g.querySelector(".logo"),this.compactMenuButton=(y=this.root)==null?void 0:y.querySelector(".compact-menu-button"),this.compactMenuButton.append(_t("more_vert")),this.foldout=(b=this.root)==null?void 0:b.querySelector(".foldout"),(_=this.root)==null||_.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const s=Yv.create();s.style.minHeight="1rem",this.logoContainer.append(s),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>Z1(v=>{if(v==!0&&Yn()&&!K_){let w=this._userRequestedLogoVisible;w===void 0&&(w=!1),this.___onSetLogoVisible(w)}else this.___onSetLogoVisible(!0)}))}catch(v){console.error("[Needle Menu] License check failed.",v)}this.compactMenuButton.addEventListener("click",v=>{v.preventDefault(),this.root.classList.toggle("open")});let a=this._context;setTimeout(()=>a=this._context);let l=0;const c=(v,w)=>{var x,O,E;fc&&console.log("Set menu visible",w),a!=null&&a.isInAR&&a.arOverlayElement?v!=a.arOverlayElement&&a.arOverlayElement.appendChild(this):this.parentNode!=((x=this._domElement)==null?void 0:x.shadowRoot)&&((E=(O=this._domElement)==null?void 0:O.shadowRoot)==null||E.appendChild(this)),this.style.display=w?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let h=!1;new MutationObserver(v=>{var w;if(!h)try{h=!0,this.onChangeDetected(v);const x=this==null?void 0:this.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||x!=((w=this._domElement)==null?void 0:w.shadowRoot))&&!Yn()){const O=l++;Kt()&&this._userRequestedMenuVisible===!1?(O===0&&c(x,this._userRequestedMenuVisible),O===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu → The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):O===0?c(x,!0):setTimeout(()=>c(x,!0),5)}}finally{h=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),fc&&this.___insertDebugOptions()}static create(){return document.createElement(tr,{is:tr})}static getOrCreate(e,i){let n=e.querySelector(tr);return!n&&e.shadowRoot&&(n=e.shadowRoot.querySelector(tr)),n||(n=window.document.body.querySelector(tr)),n||(n=e_.create(),e.shadowRoot?e.shadowRoot.appendChild(n):e.appendChild(n)),n._domElement=e,n._context=i,n}connectedCallback(){window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!0),5e3),setTimeout(()=>{var e,i;(e=this._domElement)==null||e.addEventListener("resize",this.handleSizeChange),(i=this._domElement)==null||i.addEventListener("click",ce(this,Yc))},1)}disconnectedCallback(){var e,i;window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),(e=this._domElement)==null||e.removeEventListener("resize",this.handleSizeChange),(i=this._context)==null||i.domElement.removeEventListener("click",ce(this,Yc))}showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!Yn()||K_)&&(console.warn("[Needle Engine] You need a PRO license to hide the Needle Engine logo in production."),!Kt()))&&this.___onSetLogoVisible(e)}get logoIsVisible(){return!this.root.classList.contains("logo-hidden")}___onSetLogoVisible(e){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",e?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))}setPosition(e){if(e!=="top"&&e!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",e);this.root.classList.remove("top","bottom"),this.root.classList.add(e)}setVisible(e){this._userRequestedMenuVisible=e,this.style.display=e?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}append(...e){for(const i of e)if(typeof i=="string"){const n=document.createTextNode(i);this.options.appendChild(n)}else this.options.appendChild(i)}appendChild(e){var n;if(!(e instanceof Node)){const s=document.createElement("button");if(s.textContent=e.label,s.onclick=e.onClick,s.setAttribute("priority",((n=e.priority)==null?void 0:n.toString())??"0"),e.title&&(s.title=e.title),e.icon){const a=_t(e.icon);e.iconSide==="right"?s.appendChild(a):s.prepend(a)}e.class&&s.classList.add(e.class),e=s}return this.options.appendChild(e)}prepend(...e){for(const i of e)if(typeof i=="string"){const n=document.createTextNode(i);this.options.prepend(n)}else this.options.prepend(i)}onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const i of e)i.target==this.options&&this.onOptionsChildrenChanged(i)}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type==="childList"&&e.addedNodes.length>0){const i=Array.from(this.options.children);i.sort((s,a)=>{const l=parseInt(s.getAttribute("priority")||"0"),c=parseInt(a.getAttribute("priority")||"0");return l-c});let n=!1;for(let s=0;s<i.length;s++){const a=this.options.children[s],l=i[s];if(a!==l){n=!0;break}}if(n)for(const s of i)this.options.appendChild(s)}}handleMenuVisible(){fc&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions)}get hasAnyContent(){return!!(this.logoContainer.style.display!="none"||this.hasAnyVisibleOptions)}get hasAnyVisibleOptions(){for(let e=0;e<this.options.children.length;e++){const i=this.options.children[e];if(i.tagName==="SLOT"){const s=i.assignedNodes();for(const a of s)if(a instanceof HTMLElement&&a.style.display!="none")return!0}else if(i.style.display!="none")return!0}return!1}___insertDebugOptions(){window.addEventListener("keydown",n=>{n.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const n=new Array(this.options.children.length);for(let s=0;s<this.options.children.length;s++)n[s]=this.options.children[s];for(const s of n)this.options.removeChild(s);setTimeout(()=>{for(const s of n)this.options.appendChild(s)},1e3)},this.appendChild(e);const i=document.createElement("button");i.textContent="Toggle Logo",i.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(i)}};Yc=new WeakMap;let lu=e_;customElements.get(tr)||customElements.define(tr,lu);const Xe=S("debugcontext"),H1=S("stats"),q1=S("debugactive"),X1=S("debugframerate"),Q1=S("debugcoroutine"),Y1={};class K1{constructor(){r(this,"name");r(this,"alias");r(this,"hash");r(this,"runInBackground");r(this,"domElement");r(this,"renderer");r(this,"camera");r(this,"scene")}}var we=(o=>(o[o.Start=-1]="Start",o[o.EarlyUpdate=0]="EarlyUpdate",o[o.Update=1]="Update",o[o.LateUpdate=2]="LateUpdate",o[o.OnBeforeRender=3]="OnBeforeRender",o[o.OnAfterRender=4]="OnAfterRender",o[o.PrePhysicsStep=9]="PrePhysicsStep",o[o.PostPhysicsStep=10]="PostPhysicsStep",o[o.Undefined=-1]="Undefined",o))(we||{});function qu(o,t){if(!o)return;if(!o.isComponent){(j()||Xe)&&console.error(`Registered script is not a Needle Engine component.
770
770
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
771
771
  `,o);return}t||(t=X.Current,Xe&&console.warn("> Registering component without context"));const e=t==null?void 0:t.new_scripts;e.includes(o)||e.push(o)}const ve=class ve{constructor(t){r(this,"name");r(this,"alias");r(this,"isManagedExternally",!1);r(this,"isPaused",!1);r(this,"runInBackground",!1);r(this,"targetFrameRate");r(this,"physicsSteps",1);r(this,"hash");r(this,"domElement");r(this,"_resolutionScaleFactor",1);r(this,"_boundingClientRectFrame",-1);r(this,"_boundingClientRect",null);r(this,"_domX");r(this,"_domY");r(this,"xr",null);r(this,"_xrFrame",null);r(this,"_currentFrameEvent",-1);r(this,"scene");r(this,"renderer");r(this,"composer",null);r(this,"scripts",[]);r(this,"scripts_pausedChanged",[]);r(this,"scripts_earlyUpdate",[]);r(this,"scripts_update",[]);r(this,"scripts_lateUpdate",[]);r(this,"scripts_onBeforeRender",[]);r(this,"scripts_onAfterRender",[]);r(this,"scripts_WithCorroutines",[]);r(this,"scripts_immersive_vr",[]);r(this,"scripts_immersive_ar",[]);r(this,"coroutines",{});r(this,"post_setup_callbacks",[]);r(this,"pre_update_callbacks",[]);r(this,"pre_render_callbacks",[]);r(this,"post_render_callbacks",[]);r(this,"pre_update_oneshot_callbacks",[]);r(this,"new_scripts",[]);r(this,"new_script_start",[]);r(this,"new_scripts_pre_setup_callbacks",[]);r(this,"new_scripts_post_setup_callbacks",[]);r(this,"new_scripts_xr",[]);r(this,"mainCameraComponent");r(this,"_mainCamera",null);r(this,"_fallbackCamera",null);r(this,"application");r(this,"animations");r(this,"time");r(this,"input");r(this,"physics");r(this,"connection");r(this,"assets");r(this,"mainLight",null);r(this,"sceneLighting");r(this,"addressables");r(this,"lightmaps");r(this,"players");r(this,"lodsManager");r(this,"menu");r(this,"_needsUpdateSize",!1);r(this,"_isCreated",!1);r(this,"_isCreating",!1);r(this,"_isVisible",!1);r(this,"_stats",H1?new H.Stats:null);r(this,"_intersectionObserver",null);r(this,"_disposeCallbacks",[]);r(this,"maxRenderResolution");r(this,"_devicePixelRatio","auto");r(this,"_originalCreationArgs");r(this,"onUnhandledRejection",t=>{this.onError(t.reason)});r(this,"_cameraStack",[]);r(this,"_onBeforeRenderListeners",new Map);r(this,"_onAfterRenderListeners",new Map);r(this,"_requireDepthTexture",!1);r(this,"_requireColorTexture",!1);r(this,"_renderTarget");r(this,"_isRendering",!1);r(this,"_createId",0);r(this,"_renderlooperrors",0);r(this,"_lastTimestamp",0);r(this,"_accumulatedTime",0);r(this,"_dispatchReadyAfterFrame",!1);r(this,"_tempClearColor",new d.Color);r(this,"_tempClearColor2",new d.Color);r(this,"_contextRestoreTries",0);r(this,"_wasPaused",!1);this.name=(t==null?void 0:t.name)||"",this.alias=t==null?void 0:t.alias,this.domElement=(t==null?void 0:t.domElement)||document.body,this.hash=t==null?void 0:t.hash,t!=null&&t.renderer&&(this.renderer=t.renderer,this.isManagedExternally=!0),(t==null?void 0:t.runInBackground)!==void 0&&(this.runInBackground=t.runInBackground),t!=null&&t.scene?this.scene=t.scene:this.scene=new d.Scene,t!=null&&t.camera&&(this._mainCamera=t.camera),this.application=new vn(this),this.time=new Gv,this.input=new $0(this),this.physics=new Ec(this),this.connection=new Y0(this),this.assets=new ev,this.sceneLighting=new Vv(this),this.addressables=new Bv(this),this.lightmaps=new A1(this),this.players=new $v(this),this.menu=new G1(this),this.lodsManager=new L1(this),this.animations=new R1(this);const e=()=>this._needsUpdateSize=!0;window.addEventListener("resize",e),this._disposeCallbacks.push(()=>window.removeEventListener("resize",e));const i=new ResizeObserver(n=>this._needsUpdateSize=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>{var n;return(n=this._intersectionObserver)==null?void 0:n.disconnect()}),re.register(this)}static get DefaultTargetFrameRate(){return ve._defaultTargetFramerate.value}static set DefaultTargetFrameRate(t){ve._defaultTargetFramerate.value=t}static get DefaultWebGLRendererParameters(){return ve._defaultWebglRendererParameters}get version(){return _n}static get Current(){return re.Current}static set Current(t){re.Current=t}static get All(){return re.All}appendHTMLElement(t){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(t):this.domElement.appendChild(t)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(t){if(t!==this._resolutionScaleFactor&&typeof t=="number"){if(t<=0){console.error("Invalid resolution scale factor",t);return}this._resolutionScaleFactor=t,this.updateSize()}}calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var t,e;return((e=(t=this.renderer)==null?void 0:t.xr)==null?void 0:e.isPresenting)||!1}get xrSessionMode(){var t;return(t=this.xr)==null?void 0:t.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){var t,e;return(e=(t=this.renderer)==null?void 0:t.xr)==null?void 0:e.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var t,e;return this.renderer.xr.isPresenting?(e=(t=this.renderer)==null?void 0:t.xr)==null?void 0:e.getCamera():void 0}get arOverlayElement(){const t=this.domElement;return typeof t.getAROverlayContainer=="function"?t.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const t=this.mainCameraComponent;return t.threeCamera||t.buildCamera(),t.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new d.PerspectiveCamera(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(t){this._mainCamera=t}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(t){var e,i,n;if((e=this.renderer)==null||e.dispose(),t={...ve.DefaultWebGLRendererParameters,...t},!t.canvas){const s=(n=(i=this.domElement)==null?void 0:i.shadowRoot)==null?void 0:n.querySelector("canvas");s&&(t.canvas=s,Xe&&console.log("Using canvas from shadow root",s))}return Xe&&console.log("Using Renderer Parameters:",t,this.domElement),this.renderer=new d.WebGLRenderer(t),this.renderer.debug.checkShaderErrors=j()||S("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=d.NoToneMapping,this.renderer.setClearColor(new d.Color("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=d.PCFSoftShadowMap$1,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=d.SRGBColorSpace,this.renderer.nodes={library:new d.BasicNodeLibrary,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents(),this.renderer}internalOnUpdateVisible(){var t,e;(t=this._intersectionObserver)==null||t.disconnect(),(e=this._intersectionObserver)==null||e.observe(this.domElement)}requestSizeUpdate(){this._needsUpdateSize=!0}get devicePixelRatio(){return this._devicePixelRatio}set devicePixelRatio(t){t!==this._devicePixelRatio&&(this._devicePixelRatio=t,this._needsUpdateSize=!0)}updateSize(t=!1){var e,i,n;if(t||!this.isManagedExternally&&((e=this.renderer.xr)==null?void 0:e.isPresenting)===!1){this._needsUpdateSize=!1;const s=this.resolutionScaleFactor;let a=this.domWidth*s,l=this.domHeight*s;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),a=Math.min(this.maxRenderResolution.x,a),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),l=Math.min(this.maxRenderResolution.y,l));const c=this.mainCamera;this.updateAspect(c),this.renderer.setSize(a,l,!0),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%";const h=typeof this.devicePixelRatio=="number"?this.devicePixelRatio:this.devicePixelRatio==="auto"?window.devicePixelRatio:void 0;h!==void 0&&this.renderer.setPixelRatio(h),this.composer&&((i=this.composer.setSize)==null||i.call(this.composer,a,l),h!==void 0&&"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((n=this.composer.setPixelRatio)==null||n.call(this.composer,window.devicePixelRatio)))}}updateAspect(t,e,i){if(!t)return;e===void 0&&(e=this.domWidth),i===void 0&&(i=this.domHeight);const n=e/i;if(t.isPerspectiveCamera){const s=t,a=s.aspect;s.aspect=n,a!==s.aspect&&t.updateProjectionMatrix()}else if(t.isOrthographicCamera){const s=t,a=s.top-s.bottom,c=a*n/2,h=a/2;(s.left!=-c||s.top!=h)&&(s.left=-c,s.right=c,s.top=h,s.bottom=-h,t.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(t){return this.create(t)}async create(t){try{this._isCreating=!0,t!==this._originalCreationArgs&&(this._originalCreationArgs=Jc(t)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const e=await this.internalOnCreate(t);return this._isCreated=e,e}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onError(t){this.domElement.dispatchEvent(new CustomEvent("error",{detail:t}))}clear(){var t,e,i,n;re.dispatchCallback(he.ContextClearing,this),Rn(this,he.ContextClearing),Ri(this.scene,!0,!0),this.scene=new d.Scene,(t=this.addressables)==null||t.dispose(),(e=this.lightmaps)==null||e.clear(),(n=(i=this.physics)==null?void 0:i.engine)==null||n.clearCaches(),this.lodsManager.disable(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),re.dispatchCallback(he.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var t,e;ve.Current=this,re.dispatchCallback(he.ContextDestroying,this),Rn(this,he.ContextDestroying),this.clear(),(t=this.renderer)==null||t.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(Xe&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const i of this._disposeCallbacks)try{i()}catch(n){console.error("Error in on dispose callback:",n,i)}(e=this.domElement)!=null&&e.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,re.dispatchCallback(he.ContextDestroyed,this),Rn(this,he.ContextDestroyed),re.unregister(this),ve.Current===this&&(ve.Current=null)}registerCoroutineUpdate(t,e,i){return typeof(e==null?void 0:e.next)!="function"?(console.error("Registered invalid coroutine function from "+t.name+`
772
772
  Coroutine functions must be generators: "*myCoroutine() {...}"
@@ -853,10 +853,10 @@ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this.
853
853
  padding-left: 25px;
854
854
  border-radius: .5em;
855
855
  border: 2px solid rgba(160,160,160,.3);
856
- `,n=`Needle Engine — No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${_n}`;(s=X.Current)!=null&&s.xr?console.log(n):console.log("%c "+n,e)}async function nP(o){var e,i;if(window.crossOriginIsolated)return;if(Xn==="pro"){const n=(e=o==null?void 0:o.domElement)==null?void 0:e.getAttribute("no-telemetry");if(n===""||n==="true"||n==="1"){Ci&&console.debug("Telemetry is disabled");return}Ci&&console.debug("Telemetry attribute: "+n)}try{const n="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(n){const s=window.location.href.split("?")[0];let a="api/v2/new/request";n.endsWith("/")||(a="/"+a);const l=Xn,c=`${n}${a}`;Ci&&console.debug("Sending beacon");const h={license:l,url:s,hostname:window.location.hostname,pathname:window.location.pathname,version:_n,generator:Fu,build_time:tg,public_key:ba},u=(i=navigator.sendBeacon)==null?void 0:i.call(navigator,c,JSON.stringify(h));Ci&&console.debug("Sent beacon: "+u)}}catch(n){Ci&&console.log("Failed to send non-commercial usage message to analytics backend",n)}}function Jv(o,t){return Ls(o,he.ContextCreated,t),()=>Ao(o,he.ContextCreated)}function sP(o,t){return Ls(o,he.ContextClearing,t),()=>Ao(o,he.ContextClearing)}function oP(o,t){return Ls(o,he.ContextDestroying,t),()=>Ao(o,he.ContextDestroying)}function Mg(o,t){return Ls(o,we.Start,t),()=>Ao(o,we.Start)}function ew(o,t){return Ls(o,we.Update,t),()=>Ao(o,we.Update)}function rP(o,t){return Ls(o,we.OnBeforeRender,t),()=>Ao(o,we.OnBeforeRender)}function aP(o,t){return Ls(o,we.OnAfterRender,t),()=>Ao(o,we.OnAfterRender)}const lP=S("debugdecoders");let lp=null;function tw(){if(!lp){const o=le.createLoaders(null);lp={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return lp}function J_(o){o!==void 0&&typeof o=="string"&&le.setDracoDecoderLocation(o)}function eb(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const t=tw();lP&&console.log("Setting draco decoder type to",o),t.dracoLoader.setDecoderConfig({type:o})}}function tb(o){o!==void 0&&typeof o=="string"&&le.setKTX2TranscoderLocation(o)}function Og(o,t){const e=tw();return t.renderer?e.ktx2Loader.detectSupport(t.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),le.addDracoAndKTX2Loaders(o),o.dracoLoader||o.setDRACOLoader(e.dracoLoader),o.ktx2Loader||o.setKTX2Loader(e.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(e.meshoptDecoder),le.configureLoader(o,{progressive:!0}),o}const Br=function(o){return m(o)},m=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=ib(o);else for(let t=0;t<o.length;t++){const e=o[t];o[t]=ib(e)}return function(t,e){if(!t){console.error("Found @serializable decorator without a target");return}typeof e!="string"&&(e=e.name),Object.getOwnPropertyDescriptor(t,"$serializedTypes")||(t.$serializedTypes={});const i=t.$serializedTypes=t.$serializedTypes||{};i[e]=o}};function ib(o){var t,e;switch((e=(t=o==null?void 0:o.prototype)==null?void 0:t.constructor)==null?void 0:e.name){case"Number":case"String":case"Boolean":return null}return o}const So=S("debughotreload");let jc=!1;const pc=new Map;function cP(){return jc}function wm(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function iw(o){var i;if(jc){So&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",o);return}So&&console.log("[Needle Engine] Registering hot reload instance",o);const e=o.constructor.name;pc.has(e)?(i=pc.get(e))==null||i.push(o):pc.set(e,[o])}function nw(o){if(jc){So&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",o);return}So&&console.log("[Needle Engine] Unregistering hot reload instance",o);const e=o.constructor.name,i=pc.get(e);if(!i)return;const n=i.indexOf(o);n!==-1&&i.splice(n,1)}let nb=!1;function hP(){if(So||nb)return;nb=!0;const o=console.error;console.error=(...t)=>{if(t.length){const e=t[0];if(typeof e=="string"&&e.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}o.apply(console,t)}}function dP(o){So&&console.log("[HMR] Apply changes",o,Object.keys(o)),hP();for(const t of Object.keys(o))try{jc=!0;const e=k.get(t);if(!e){So&&console.log("[HMR] Type not found: "+t);continue}const i=o[t],n=pc.get(i.name);let s="[Needle Engine] Updating type: "+t;const a=(n==null?void 0:n.length)??-1;a>0?s+=" x"+a:s+=" (No instances registered)",console.log(s);const l=Object.getOwnPropertyNames(e.prototype),c=Object.getOwnPropertyDescriptors(i.prototype);for(const h in c)c[h].writable&&(e.prototype[h]=o[t].prototype[h]);for(const h of l)c[h]||delete e.prototype[h];if(n){const h=new i,u=Object.getOwnPropertyDescriptors(h);for(const f of n){const p=f,g=p.isComponent===!0,y=g?p.activeAndEnabled:!0,b=g?p.context:void 0;try{if(g&&b&&ws(p,b),g&&y&&(p.enabled=!1),f.onBeforeHotReloadFields&&f.onBeforeHotReloadFields()===!1)continue;for(const _ in u)if(u[_].writable){if(f[_]===void 0)f[_]=h[_];else if(typeof f[_]=="function"&&!f[_].prototype){const w=f[_],x=w.name,O="bound ";if(x===O)continue;const E=w.name.substring(O.length),M=i.prototype[E];M&&(f[_]=M.bind(f))}}f.onAfterHotReloadFields&&f.onAfterHotReloadFields()}finally{g&&b&&mg(p,b),g&&y&&(p.enabled=!0)}}}}catch(e){if(So)console.error(e);else return!1}finally{jc=!1,Fn(Mi.Log,"Script changes applied (HMR)")}return!0}class C extends d.Object3D{constructor(){super(...arguments);r(this,"guid")}static isDestroyed(e){return kr(e)}static setActive(e,i,n=!0){e&&(uc(e,i),Ed(e),i&&n&&lv(X.Current,e))}static isActiveSelf(e){return ol(e)}static isActiveInHierarchy(e){return Tv(e)}static markAsInstancedRendered(e,i){Av(e,i)}static isUsingInstancing(e){return Gu(e)}static foreachComponent(e,i,n=!0){return Rr(e,i,n)}static instantiateSynced(e,i){return e?yg(e,i):null}static instantiate(e,i=null){return"isAssetReference"in e,Er(e,i)}static destroySynced(e,i,n=!0){if(!e)return;const s=e;i=i??X.Current,oh(s,i.connection,n)}static destroy(e,i=!0){return Ri(e,i)}static add(e,i,n){if(!(!e||!i)){if(e===i){console.warn("Can not add object to self",e);return}n||(n=X.Current),i.add(e),uc(e,!0),Ed(e),n?C.foreachComponent(e,s=>{mg(s,n),!s.__internalDidAwakeAndStart&&n.new_script_start.includes(s)===!1&&n.new_script_start.push(s)},!0):console.warn("Missing context")}}static remove(e){var i;e&&((i=e.parent)==null||i.remove(e),uc(e,!1),Ed(e),C.foreachComponent(e,n=>{YC(n)},!0))}static invokeOnChildren(e,i,...n){this.invoke(e,i,!0,n)}static invoke(e,i,n=!1,...s){e&&this.foreachComponent(e,a=>{const l=a[i];l&&typeof l=="function"&&(l==null||l.call(a,...s))},n)}static addNewComponent(e,i,n,s=!0){return Oi(e,i,n,{callAwake:s})}static addComponent(e,i,n,s){return Oi(e,i,n,s)}static moveComponent(e,i){return Oi(e,i)}static removeComponent(e){return wg(e.gameObject,e),e}static getOrAddComponent(e,i){return ah(e,i)}static getComponent(e,i){return e===null?null:jr(e,i)}static getComponents(e,i,n=null){return e===null?n??[]:lh(e,i,n)}static findByGuid(e,i){return xg(e,i)}static findObjectOfType(e,i,n=!0){return hh(e,i??X.Current,n)}static findObjectsOfType(e,i){const n=[];return Ev(e,n,i),n}static getComponentInChildren(e,i){return ch(e,i)}static getComponentsInChildren(e,i,n=null){return sl(e,i,n??void 0)}static getComponentInParent(e,i){return Lc(e,i)}static getComponentsInParent(e,i,n=null){return Vu(e,i,n)}static getAllComponents(e){var s;const i=(s=e.userData)==null?void 0:s.components;return i?[...i]:[]}static*iterateComponents(e){var n;const i=(n=e==null?void 0:e.userData)==null?void 0:n.components;if(i&&Array.isArray(i))for(let s=0;s<i.length;s++)yield i[s]}}const lo=class lo{constructor(t){r(this,"__context");r(this,"__name");r(this,"gameObject");r(this,"guid","invalid");r(this,"sourceId");r(this,"__didAwake",!1);r(this,"__didStart",!1);r(this,"__didEnable",!1);r(this,"__isEnabled");r(this,"__destroyed",!1);r(this,"_eventListeners",new Map);this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(t),wm()&&iw(this)}get isComponent(){return!0}get context(){return this.__context??X.Current}set context(t){this.__context=t}get scene(){return this.context.scene}get layer(){var t,e;return(e=(t=this.gameObject)==null?void 0:t.userData)==null?void 0:e.layer}get name(){var t,e;return(t=this.gameObject)!=null&&t.name?this.gameObject.name:(e=this.gameObject)==null?void 0:e.userData.name}set name(t){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=t,this.__name=t):this.__name=t}get tag(){var t;return(t=this.gameObject)==null?void 0:t.userData.tag}set tag(t){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=t)}get static(){var t;return(t=this.gameObject)==null?void 0:t.userData.static}set static(t){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=t)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const t=this.gameObject[Es];return t===void 0?!0:t}set __isActiveInHierarchy(t){this.gameObject&&(this.gameObject[Es]=t)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(t,e=we.Update){return this.context.registerCoroutineUpdate(this,t,e)}stopCoroutine(t,e=we.Update){this.context.unregisterCoroutineUpdate(t,e)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(t){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(t),this}_internalInit(t){if(typeof t=="object")for(const e of Object.keys(t)){const i=t[e];typeof i!="function"&&(this[e]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(t){return this.__destroyed?(j()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(t!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(t){if(this.__didAwake){if(!this.__didEnable){t!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var t;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((t=this.onDestroy)==null||t.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),kv(this),wm()&&nw(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(t){if(this.__destroyed){j()&&console.warn(`[Needle Engine Dev] Trying to ${t?"enable":"disable"} destroyed component`);return}if(typeof t=="number"&&(t>=.5?t=!0:t=!1),!this.__didAwake){this.__isEnabled=t;return}t?this.__internalEnable():this.__internalDisable()}get worldPosition(){return Q(this.gameObject)}set worldPosition(t){st(this.gameObject,t)}setWorldPosition(t,e,i){Pr(this.gameObject,t,e,i)}get worldQuaternion(){return _e(this.gameObject)}set worldQuaternion(t){Hi(this.gameObject,t)}setWorldQuaternion(t,e,i,n){Qm(this.gameObject,t,e,i,n)}get worldEuler(){return Ym(this.gameObject)}set worldEuler(t){Km(this.gameObject,t)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(t){this.setWorldRotation(t.x,t.y,t.z,!0)}setWorldRotation(t,e,i,n=!0){ih(this.gameObject,t,e,i,n)}get forward(){return lo._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return lo._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return lo._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(t,e){this._eventListeners[t]=this._eventListeners[t]||[],this._eventListeners[t].push(e)}removeEventListener(t,e){if(!this._eventListeners[t])return;const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}dispatchEvent(t){if(!t||!this._eventListeners[t.type])return!1;const e=this._eventListeners[t.type];for(let i=0;i<e.length;i++)e[i](t);return!1}};r(lo,"_forward",new d.Vector3),r(lo,"_right",new d.Vector3),r(lo,"_up",new d.Vector3);let I=lo;const uP=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:I,Component:I,GameObject:C},Symbol.toStringTag,{value:"Module"}));var fP=Object.defineProperty,sw=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&fP(t,e,n),n};class fh extends I{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"width",0);r(this,"centered",!0);r(this,"_centerPos")}awake(){this._centerPos=new d.Vector3}update(){if(!this.from||!this.to)return;const e=Q(this.from).clone(),i=Q(this.to).clone(),n=e.distanceTo(i);this._centerPos.copy(e),this._centerPos.add(i),this._centerPos.multiplyScalar(.5),st(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(Q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}}sw([m(C)],fh.prototype,"from");sw([m(C)],fh.prototype,"to");var pP=Object.defineProperty,mP=Object.getOwnPropertyDescriptor,Fr=(o,t,e,i)=>{for(var n=i>1?void 0:i?mP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&pP(t,e,n),n};const Qs=S("debuganimation");let ow=class{constructor(){r(this,"x");r(this,"y")}};class Tt extends I{constructor(){super(...arguments);r(this,"playAutomatically",!0);r(this,"randomStartTime",!0);r(this,"minMaxSpeed");r(this,"minMaxOffsetNormalized");r(this,"loop",!0);r(this,"clampWhenFinished",!1);r(this,"_tempAnimationClipBeforeGameObjectExisted",null);r(this,"_tempAnimationsArray");r(this,"mixer");r(this,"_actions");r(this,"_handles")}get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.push(e)}get time(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.time}return 0}set time(e){if(this.actions)for(const i of this.actions)i.time=e}get clip(){var e;return(e=this.animations)!=null&&e.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){Qs&&console.warn("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}set animations(e){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get actions(){return this._actions}set actions(e){this._actions=e}awake(){this.mixer=void 0,Qs&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){var e;if(this.playAutomatically&&((e=this.animations)==null?void 0:e.length)>0){const i=Math.floor(Math.random()*this.animations.length),n=this.animations[i];this.play(i,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*n.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(e=>e.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){var i;return((i=this.actions)==null?void 0:i.find(n=>n.getClip().name===e))||null}get isPlaying(){if(this.actions){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0}return!1}stopAll(e){if(this.actions)for(const i of this.actions)e!=null&&e.fadeDuration?i.fadeOut(e.fadeDuration):i.stop()}stop(e,i){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){Qs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(s=>s.name===e));if(!e){console.error("Could not find clip",e);return}const n=this.actions.find(s=>s.getClip()===e);if(!n){console.error("Could not find action",e);return}i!=null&&i.fadeDuration?n.fadeOut(i.fadeDuration):n.stop()}pause(e,i=!1){if(e===void 0){for(const s of this.actions)s.paused=!i;return}else if(typeof e=="number"){if(e>=this.animations.length){Qs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(s=>s.name===e));if(!e){console.error("Could not find clip",e);return}const n=this.actions.find(s=>s.getClip()===e);if(!n){console.error("Could not find action",e);return}n.paused=!i}resume(){for(const e of this.actions)e.paused=!1}play(e=0,i){if(Qs&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Qs&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let n=e;if(typeof e=="number"){if(e>=this.animations.length){Qs&&console.log("No animation at index",e);return}n=this.animations[e]}else typeof e=="string"&&(n=this.animations.find(a=>a.name===e));if(!n){console.error("Could not find clip",e);return}i||(i={});for(const a of this.actions)if(a.getClip()===n)return this.internalOnPlay(a,i);if(!n.tracks){console.warn("Clip is no AnimationClip",n);return}const s=this.mixer.clipAction(n);return this.actions.push(s),this.internalOnPlay(s,i)}internalOnPlay(e,i){var n=this.actions.find(l=>l===e);if(n===e&&n.isRunning()&&n.time<n.getClip().duration){const l=this.tryFindHandle(e);if(n.paused&&(n.paused=!1),l)return l.waitForFinish()}if(i.loop===void 0&&(i.loop=this.loop),i.clampWhenFinished===void 0&&(i.clampWhenFinished=this.clampWhenFinished),i.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(i.minMaxOffsetNormalized=this.minMaxOffsetNormalized),i.minMaxSpeed===void 0&&(i.minMaxSpeed=this.minMaxSpeed),(i==null?void 0:i.exclusive)??!0)for(const l of this.actions)l!=n&&(i.fadeDuration?l.fadeOut(i.fadeDuration):l.stop());if(i!=null&&i.fadeDuration&&e.fadeIn(i.fadeDuration),e.enabled=!0,(i==null?void 0:i.startTime)!=null)e.time=i.startTime;else if(i!=null&&i.minMaxOffsetNormalized&&i.minMaxOffsetNormalized.x!=0&&i.minMaxOffsetNormalized.y!=0){const l=e.getClip();e.time=z.lerp(i.minMaxOffsetNormalized.x,i.minMaxOffsetNormalized.y,Math.random())*l.duration}else e.time>=e.getClip().duration&&(e.time=0);i!=null&&i.minMaxSpeed?e.timeScale=z.lerp(i.minMaxSpeed.x,i.minMaxSpeed.y,Math.random()):e.timeScale=(i==null?void 0:i.speed)??1,(i==null?void 0:i.loop)!=null?e.loop=i.loop?d.LoopRepeat:d.LoopOnce:e.loop=d.LoopOnce,i!=null&&i.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),Qs&&console.log("PLAY",e.getClip().name,e);const a=new gP(e,this.mixer,i,l=>{this._handles.splice(this._handles.indexOf(a),1)});return this._handles.push(a),a.waitForFinish()}tryFindHandle(e){for(const i of this._handles)if(i.action===e)return i}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new d.AnimationMixer(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Fr([m()],Tt.prototype,"playAutomatically",2);Fr([m()],Tt.prototype,"randomStartTime",2);Fr([m(ow)],Tt.prototype,"minMaxSpeed",2);Fr([m(ow)],Tt.prototype,"minMaxOffsetNormalized",2);Fr([m()],Tt.prototype,"loop",2);Fr([m()],Tt.prototype,"clampWhenFinished",2);Fr([m(d.AnimationClip)],Tt.prototype,"clips",1);class gP{constructor(t,e,i,n){r(this,"mixer");r(this,"action");r(this,"promise",null);r(this,"_options");r(this,"_resolveCallback",null);r(this,"_resolvedOrRejectedCallback");r(this,"onFinished",t=>{t.action===this.action&&this.onResolve()});this.action=t,this.mixer=e,this._resolvedOrRejectedCallback=n,this._options=i}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(t=>{this._resolveCallback=t}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var t,e;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(e=this._resolveCallback)==null||e.call(this,this.action)}dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const jd=Symbol("objectIsAnimatedData");function sb(o,t,e){if(!o)return;if(o[jd]===void 0){if(!e)return;o[jd]=new Set}const i=o[jd];e?i.add(t):i.has(t)&&i.delete(t)}function yP(o){if(!o)return!1;const t=o[jd];return t!==void 0&&t.size>0}class _P{constructor(){r(this,"_context")}get context(){return this._context??X.Current}get isStateMachineBehaviour(){return!0}}class Jl{constructor(t,e,i,n){r(this,"name");r(this,"nameHash");r(this,"normalizedTime");r(this,"length");r(this,"speed");r(this,"action");r(this,"hasTransitions");var s;this.name=t.name,this.nameHash=t.hash,this.normalizedTime=e,this.length=i,this.speed=n,this.action=t.motion.action||null,this.hasTransitions=((s=t.transitions)==null?void 0:s.length)>0||!1}}function rw(o,t){return{name:"Empty",isLooping:!1,guid:(t==null?void 0:t.generateUUID())??d.MathUtils.generateUUID(),index:-1,clip:new d.AnimationClip(o,0,[])}}var oo=(o=>(o[o.If=1]="If",o[o.IfNot=2]="IfNot",o[o.Greater=3]="Greater",o[o.Less=4]="Less",o[o.Equals=6]="Equals",o[o.NotEqual=7]="NotEqual",o))(oo||{}),kg=(o=>(o[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",o))(kg||{});const Je=S("debuganimatorcontroller"),ld=S("debugrootmotion");class Gi{constructor(t){r(this,"_speed",1);r(this,"normalizedStartOffset",0);r(this,"animator");r(this,"model");r(this,"_mixer");r(this,"_activeState");r(this,"_activeStates",[]);r(this,"_heldActions",[]);r(this,"rootMotionHandler");this.model=t,Je&&console.log(this)}static createFromClips(t,e={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let a=0;a<t.length;a++){const l=t[a],c=[];if(e.autoTransition!==!1){const u=e.transitionDuration??0,f=u/l.duration;let p=a;(e.autoTransition===void 0||e.autoTransition===!0)&&(p=(a+1)%t.length),c.push({exitTime:1-f,offset:0,duration:u,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:l.name,hash:a,motion:{name:l.name,clip:l,isLooping:(e==null?void 0:e.looping)??!1},transitions:c,behaviours:[]};i.push(h)}const n={name:"AnimatorController",guid:new vt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new Gi(n)}play(t,e=-1,i=Number.NEGATIVE_INFINITY,n=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const a=this.model.layers[e].stateMachine;for(const l of a.states)if(l.name===t||l.hash===t){Je&&console.log("transition to ",l),this.transitionTo(l,n,i);return}console.warn("Could not find "+t+" to play")}reset(){this.setStartTransition()}setBool(t,e){var n,s;const i=typeof t=="string"?"name":"hash";return(s=(n=this.model)==null?void 0:n.parameters)==null?void 0:s.filter(a=>a[i]===t).forEach(a=>a.value=e)}getBool(t){var i,n,s;const e=typeof t=="string"?"name":"hash";return((s=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(a=>a[e]===t))==null?void 0:s.value)??!1}setFloat(t,e){var s,a;const i=typeof t=="string"?"name":"hash",n=(a=(s=this.model)==null?void 0:s.parameters)==null?void 0:a.filter(l=>l[i]===t);return n.forEach(l=>l.value=e),(n==null?void 0:n.length)>0}getFloat(t){var i,n,s;const e=typeof t=="string"?"name":"hash";return((s=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(a=>a[e]===t))==null?void 0:s.value)??0}setInteger(t,e){var n,s;const i=typeof t=="string"?"name":"hash";return(s=(n=this.model)==null?void 0:n.parameters)==null?void 0:s.filter(a=>a[i]===t).forEach(a=>a.value=e)}getInteger(t){var i,n,s;const e=typeof t=="string"?"name":"hash";return((s=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(a=>a[e]===t))==null?void 0:s.value)??0}setTrigger(t){var i,n;Je&&console.log("SET TRIGGER",t);const e=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(s=>s[e]===t).forEach(s=>s.value=!0)}resetTrigger(t){var i,n;const e=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(s=>s[e]===t).forEach(s=>s.value=!1)}getTrigger(t){var i,n,s;const e=typeof t=="string"?"name":"hash";return((s=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(a=>a[e]===t))==null?void 0:s.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(t){this._speed=t}FindState(t){return this.findState(t)}findState(t){if(!t)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const i of e.stateMachine.states)if(i.name===t||i.hash==t)return i}return null}getCurrentStateInfo(){if(!this._activeState)return null;const t=this._activeState.motion.action;if(!t)return null;const e=this._activeState.motion.clip.duration,i=e<=0?0:Math.abs(t.time/e);return new Jl(this._activeState,i,e,this._speed)}get currentAction(){if(!this._activeState)return null;const t=this._activeState.motion.action;return t||null}get context(){var t;return(t=this.animator)==null?void 0:t.context}get mixer(){return this._mixer}dispose(){var t;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)}bind(t){var e,i;t?this.animator!==t&&(this._mixer&&(this._mixer.stopAllAction(),(e=this.context)==null||e.animations.unregisterAnimationMixer(this._mixer)),this.animator=t,this._mixer=new d.AnimationMixer(this.animator.gameObject),(i=this.context)==null||i.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;Je&&console.warn("AnimatorController clone()",this.model);const t=Jc(this.model,(i,n,s)=>s==null?!0:!(s.type==="Object3D"||s.isObject3D===!0||M0(s)||s.tracks!==void 0||s instanceof Gi));return console.assert(t!==this.model),new Gi(t)}update(t){var i,n;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(t);const e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onBeforeUpdate(t)),this._mixer.update(e),this.animator.applyRootMotion&&((n=this.rootMotionHandler)==null||n.onAfterUpdate(t))}get activeState(){return this._activeState}updateActiveStates(t){for(let e=0;e<this._activeStates.length;e++){const i=this._activeStates[e],n=i.motion;if(!n.action)this._activeStates.splice(e,1),e--;else{const s=n.action;s.weight=t,s.getEffectiveWeight()<=0&&!s.isRunning()&&(Je&&console.debug("REMOVE",i.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){var t;this.model.layers.length>1&&(Je||j())&&console.warn("Multiple layers are not supported yet "+((t=this.animator)==null?void 0:t.name));for(const e of this.model.layers){const i=e.stateMachine;i.defaultState===void 0&&(Je&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),i.defaultState=0);const n=i.states[i.defaultState];this.transitionTo(n,0,this.normalizedStartOffset);break}}evaluateTransitions(){var s;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const e=this._activeState,i=e.motion.action;for(const a of e.transitions){if(!a.hasExitTime&&a.conditions.length<=0)continue;let l=!0;for(const c of a.conditions)if(!this.evaluateCondition(c)){l=!1;break}if(l)if(i){const c=e.motion.clip.duration,h=c<=0?1:Math.abs(i.time/c);let u=a.exitTime;i.timeScale<0&&(u=1-u);let f=!1;if(a.hasExitTime?i.timeScale>0?f=h>=a.exitTime:i.timeScale<0&&(f=1-h>=a.exitTime):f=!0,f){for(const p of a.conditions){const g=this.model.parameters.find(y=>y.name===p.parameter);(g==null?void 0:g.type)===kg.Trigger&&g.value&&(g.value=!1)}if(i.clampWhenFinished=!0,Je){const p=this.getState(a.destinationState,0);console.log(`Transition to ${a.destinationState} / ${p==null?void 0:p.name}`,a,`
856
+ `,n=`Needle Engine — No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${_n}`;(s=X.Current)!=null&&s.xr?console.log(n):console.log("%c "+n,e)}async function nP(o){var e,i;if(window.crossOriginIsolated)return;if(Xn==="pro"){const n=(e=o==null?void 0:o.domElement)==null?void 0:e.getAttribute("no-telemetry");if(n===""||n==="true"||n==="1"){Ci&&console.debug("Telemetry is disabled");return}Ci&&console.debug("Telemetry attribute: "+n)}try{const n="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(n){const s=window.location.href.split("?")[0];let a="api/v2/new/request";n.endsWith("/")||(a="/"+a);const l=Xn,c=`${n}${a}`;Ci&&console.debug("Sending beacon");const h={license:l,url:s,hostname:window.location.hostname,pathname:window.location.pathname,version:_n,generator:Fu,build_time:tg,public_key:ba},u=(i=navigator.sendBeacon)==null?void 0:i.call(navigator,c,JSON.stringify(h));Ci&&console.debug("Sent beacon: "+u)}}catch(n){Ci&&console.log("Failed to send non-commercial usage message to analytics backend",n)}}function Jv(o,t){return Ls(o,he.ContextCreated,t),()=>Ao(o,he.ContextCreated)}function sP(o,t){return Ls(o,he.ContextClearing,t),()=>Ao(o,he.ContextClearing)}function oP(o,t){return Ls(o,he.ContextDestroying,t),()=>Ao(o,he.ContextDestroying)}function Mg(o,t){return Ls(o,we.Start,t),()=>Ao(o,we.Start)}function ew(o,t){return Ls(o,we.Update,t),()=>Ao(o,we.Update)}function rP(o,t){return Ls(o,we.OnBeforeRender,t),()=>Ao(o,we.OnBeforeRender)}function aP(o,t){return Ls(o,we.OnAfterRender,t),()=>Ao(o,we.OnAfterRender)}const lP=S("debugdecoders");let lp=null;function tw(){if(!lp){const o=le.createLoaders(null);lp={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return lp}function J_(o){o!==void 0&&typeof o=="string"&&le.setDracoDecoderLocation(o)}function eb(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const t=tw();lP&&console.log("Setting draco decoder type to",o),t.dracoLoader.setDecoderConfig({type:o})}}function tb(o){o!==void 0&&typeof o=="string"&&le.setKTX2TranscoderLocation(o)}function Og(o,t){const e=tw();return t.renderer?e.ktx2Loader.detectSupport(t.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),le.addDracoAndKTX2Loaders(o),o.dracoLoader||o.setDRACOLoader(e.dracoLoader),o.ktx2Loader||o.setKTX2Loader(e.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(e.meshoptDecoder),le.configureLoader(o,{progressive:!0}),o}const Br=function(o){return m(o)},m=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=ib(o);else for(let t=0;t<o.length;t++){const e=o[t];o[t]=ib(e)}return function(t,e){if(!t){console.error("Found @serializable decorator without a target");return}typeof e!="string"&&(e=e.name),Object.getOwnPropertyDescriptor(t,"$serializedTypes")||(t.$serializedTypes={});const i=t.$serializedTypes=t.$serializedTypes||{};i[e]=o}};function ib(o){var t,e;switch((e=(t=o==null?void 0:o.prototype)==null?void 0:t.constructor)==null?void 0:e.name){case"Number":case"String":case"Boolean":return null}return o}const So=S("debughotreload");let jc=!1;const pc=new Map;function cP(){return jc}function wm(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function iw(o){var i;if(jc){So&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",o);return}So&&console.log("[Needle Engine] Registering hot reload instance",o);const e=o.constructor.name;pc.has(e)?(i=pc.get(e))==null||i.push(o):pc.set(e,[o])}function nw(o){if(jc){So&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",o);return}So&&console.log("[Needle Engine] Unregistering hot reload instance",o);const e=o.constructor.name,i=pc.get(e);if(!i)return;const n=i.indexOf(o);n!==-1&&i.splice(n,1)}let nb=!1;function hP(){if(So||nb)return;nb=!0;const o=console.error;console.error=(...t)=>{if(t.length){const e=t[0];if(typeof e=="string"&&e.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}o.apply(console,t)}}function dP(o){So&&console.log("[HMR] Apply changes",o,Object.keys(o)),hP();for(const t of Object.keys(o))try{jc=!0;const e=k.get(t);if(!e){So&&console.log("[HMR] Type not found: "+t);continue}const i=o[t],n=pc.get(i.name);let s="[Needle Engine] Updating type: "+t;const a=(n==null?void 0:n.length)??-1;a>0?s+=" x"+a:s+=" (No instances registered)",console.log(s);const l=Object.getOwnPropertyNames(e.prototype),c=Object.getOwnPropertyDescriptors(i.prototype);for(const h in c)c[h].writable&&(e.prototype[h]=o[t].prototype[h]);for(const h of l)c[h]||delete e.prototype[h];if(n){const h=new i,u=Object.getOwnPropertyDescriptors(h);for(const f of n){const p=f,g=p.isComponent===!0,y=g?p.activeAndEnabled:!0,b=g?p.context:void 0;try{if(g&&b&&ws(p,b),g&&y&&(p.enabled=!1),f.onBeforeHotReloadFields&&f.onBeforeHotReloadFields()===!1)continue;for(const _ in u)if(u[_].writable){if(f[_]===void 0)f[_]=h[_];else if(typeof f[_]=="function"&&!f[_].prototype){const w=f[_],x=w.name,O="bound ";if(x===O)continue;const E=w.name.substring(O.length),M=i.prototype[E];M&&(f[_]=M.bind(f))}}f.onAfterHotReloadFields&&f.onAfterHotReloadFields()}finally{g&&b&&mg(p,b),g&&y&&(p.enabled=!0)}}}}catch(e){if(So)console.error(e);else return!1}finally{jc=!1,Fn(Mi.Log,"Script changes applied (HMR)")}return!0}class C extends d.Object3D{constructor(){super(...arguments);r(this,"guid")}static isDestroyed(e){return kr(e)}static setActive(e,i,n=!0){e&&(uc(e,i),Ed(e),i&&n&&lv(X.Current,e))}static isActiveSelf(e){return ol(e)}static isActiveInHierarchy(e){return Tv(e)}static markAsInstancedRendered(e,i){Av(e,i)}static isUsingInstancing(e){return Gu(e)}static foreachComponent(e,i,n=!0){return Rr(e,i,n)}static instantiateSynced(e,i){return e?yg(e,i):null}static instantiate(e,i=null){return"isAssetReference"in e,Er(e,i)}static destroySynced(e,i,n=!0){if(!e)return;const s=e;i=i??X.Current,oh(s,i.connection,n)}static destroy(e,i=!0){return Ri(e,i)}static add(e,i,n){if(!(!e||!i)){if(e===i){console.warn("Can not add object to self",e);return}n||(n=X.Current),i.add(e),uc(e,!0),Ed(e),n?C.foreachComponent(e,s=>{mg(s,n),!s.__internalDidAwakeAndStart&&n.new_script_start.includes(s)===!1&&n.new_script_start.push(s)},!0):console.warn("Missing context")}}static remove(e){var i;e&&((i=e.parent)==null||i.remove(e),uc(e,!1),Ed(e),C.foreachComponent(e,n=>{YC(n)},!0))}static invokeOnChildren(e,i,...n){this.invoke(e,i,!0,n)}static invoke(e,i,n=!1,...s){e&&this.foreachComponent(e,a=>{const l=a[i];l&&typeof l=="function"&&(l==null||l.call(a,...s))},n)}static addNewComponent(e,i,n,s=!0){return Oi(e,i,n,{callAwake:s})}static addComponent(e,i,n,s){return Oi(e,i,n,s)}static moveComponent(e,i){return Oi(e,i)}static removeComponent(e){return wg(e.gameObject,e),e}static getOrAddComponent(e,i){return ah(e,i)}static getComponent(e,i){return e===null?null:jr(e,i)}static getComponents(e,i,n=null){return e===null?n??[]:lh(e,i,n)}static findByGuid(e,i){return xg(e,i)}static findObjectOfType(e,i,n=!0){return hh(e,i??X.Current,n)}static findObjectsOfType(e,i){const n=[];return Ev(e,n,i),n}static getComponentInChildren(e,i){return ch(e,i)}static getComponentsInChildren(e,i,n=null){return sl(e,i,n??void 0)}static getComponentInParent(e,i){return Lc(e,i)}static getComponentsInParent(e,i,n=null){return Vu(e,i,n)}static getAllComponents(e){var s;const i=(s=e.userData)==null?void 0:s.components;return i?[...i]:[]}static*iterateComponents(e){var n;const i=(n=e==null?void 0:e.userData)==null?void 0:n.components;if(i&&Array.isArray(i))for(let s=0;s<i.length;s++)yield i[s]}}const lo=class lo{constructor(t){r(this,"__context");r(this,"__name");r(this,"gameObject");r(this,"guid","invalid");r(this,"sourceId");r(this,"__didAwake",!1);r(this,"__didStart",!1);r(this,"__didEnable",!1);r(this,"__isEnabled");r(this,"__destroyed",!1);r(this,"_eventListeners",new Map);this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(t),wm()&&iw(this)}get isComponent(){return!0}get context(){return this.__context??X.Current}set context(t){this.__context=t}get scene(){return this.context.scene}get layer(){var t,e;return(e=(t=this.gameObject)==null?void 0:t.userData)==null?void 0:e.layer}get name(){var t,e;return(t=this.gameObject)!=null&&t.name?this.gameObject.name:(e=this.gameObject)==null?void 0:e.userData.name}set name(t){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=t,this.__name=t):this.__name=t}get tag(){var t;return(t=this.gameObject)==null?void 0:t.userData.tag}set tag(t){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=t)}get static(){var t;return(t=this.gameObject)==null?void 0:t.userData.static}set static(t){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=t)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const t=this.gameObject[Es];return t===void 0?!0:t}set __isActiveInHierarchy(t){this.gameObject&&(this.gameObject[Es]=t)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(t,e=we.Update){return this.context.registerCoroutineUpdate(this,t,e)}stopCoroutine(t,e=we.Update){this.context.unregisterCoroutineUpdate(t,e)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(t){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(t),this}_internalInit(t){if(typeof t=="object")for(const e of Object.keys(t)){const i=t[e];typeof i!="function"&&(this[e]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(t){return this.__destroyed?(j()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(t!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(t){if(this.__didAwake){if(!this.__didEnable){t!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var t;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((t=this.onDestroy)==null||t.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),kv(this),wm()&&nw(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(t){if(this.__destroyed){j()&&console.warn(`[Needle Engine Dev] Trying to ${t?"enable":"disable"} destroyed component`);return}if(typeof t=="number"&&(t>=.5?t=!0:t=!1),!this.__didAwake){this.__isEnabled=t;return}t?this.__internalEnable():this.__internalDisable()}get worldPosition(){return Q(this.gameObject)}set worldPosition(t){st(this.gameObject,t)}setWorldPosition(t,e,i){Pr(this.gameObject,t,e,i)}get worldQuaternion(){return _e(this.gameObject)}set worldQuaternion(t){Hi(this.gameObject,t)}setWorldQuaternion(t,e,i,n){Qm(this.gameObject,t,e,i,n)}get worldEuler(){return Ym(this.gameObject)}set worldEuler(t){Km(this.gameObject,t)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(t){this.setWorldRotation(t.x,t.y,t.z,!0)}setWorldRotation(t,e,i,n=!0){ih(this.gameObject,t,e,i,n)}get forward(){return lo._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return lo._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return lo._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(t,e){this._eventListeners[t]=this._eventListeners[t]||[],this._eventListeners[t].push(e)}removeEventListener(t,e){if(!this._eventListeners[t])return;const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}dispatchEvent(t){if(!t||!this._eventListeners[t.type])return!1;const e=this._eventListeners[t.type];for(let i=0;i<e.length;i++)e[i](t);return!1}};r(lo,"_forward",new d.Vector3),r(lo,"_right",new d.Vector3),r(lo,"_up",new d.Vector3);let I=lo;const uP=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:I,Component:I,GameObject:C},Symbol.toStringTag,{value:"Module"}));var fP=Object.defineProperty,sw=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&fP(t,e,n),n};class fh extends I{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"width",0);r(this,"centered",!0);r(this,"_centerPos")}awake(){this._centerPos=new d.Vector3}update(){if(!this.from||!this.to)return;const e=Q(this.from).clone(),i=Q(this.to).clone(),n=e.distanceTo(i);this._centerPos.copy(e),this._centerPos.add(i),this._centerPos.multiplyScalar(.5),st(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(Q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}}sw([m(C)],fh.prototype,"from");sw([m(C)],fh.prototype,"to");var pP=Object.defineProperty,mP=Object.getOwnPropertyDescriptor,Fr=(o,t,e,i)=>{for(var n=i>1?void 0:i?mP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&pP(t,e,n),n};const Qs=S("debuganimation");let ow=class{constructor(){r(this,"x");r(this,"y")}};class Tt extends I{constructor(){super(...arguments);r(this,"playAutomatically",!0);r(this,"randomStartTime",!0);r(this,"minMaxSpeed");r(this,"minMaxOffsetNormalized");r(this,"loop",!0);r(this,"clampWhenFinished",!1);r(this,"_tempAnimationClipBeforeGameObjectExisted",null);r(this,"_tempAnimationsArray");r(this,"mixer");r(this,"_actions");r(this,"_handles")}get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.push(e)}get time(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.time}return 0}set time(e){if(this.actions)for(const i of this.actions)i.time=e}get clip(){var e;return(e=this.animations)!=null&&e.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){Qs&&console.warn("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}set animations(e){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get actions(){return this._actions}set actions(e){this._actions=e}awake(){this.mixer=void 0,Qs&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){var e;if(this.playAutomatically&&((e=this.animations)==null?void 0:e.length)>0){const i=Math.floor(Math.random()*this.animations.length),n=this.animations[i];this.play(i,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*n.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(e=>e.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){var i;return((i=this.actions)==null?void 0:i.find(n=>n.getClip().name===e))||null}get isPlaying(){if(this.actions){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0}return!1}stopAll(e){if(this.actions)for(const i of this.actions)e!=null&&e.fadeDuration?i.fadeOut(e.fadeDuration):i.stop()}stop(e,i){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){Qs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(s=>s.name===e));if(!e){console.error("Could not find clip",e);return}const n=this.actions.find(s=>s.getClip()===e);if(!n){console.error("Could not find action",e);return}i!=null&&i.fadeDuration?n.fadeOut(i.fadeDuration):n.stop()}pause(e,i=!1){if(e===void 0){for(const s of this.actions)s.paused=!i;return}else if(typeof e=="number"){if(e>=this.animations.length){Qs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(s=>s.name===e));if(!e){console.error("Could not find clip",e);return}const n=this.actions.find(s=>s.getClip()===e);if(!n){console.error("Could not find action",e);return}n.paused=!i}resume(){for(const e of this.actions)e.paused=!1}play(e=0,i){if(Qs&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Qs&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let n=e;if(typeof e=="number"){if(e>=this.animations.length){Qs&&console.log("No animation at index",e);return}n=this.animations[e]}else typeof e=="string"&&(n=this.animations.find(a=>a.name===e));if(!n){console.error("Could not find clip",e);return}i||(i={});for(const a of this.actions)if(a.getClip()===n)return this.internalOnPlay(a,i);if(!n.tracks){console.warn("Clip is no AnimationClip",n);return}const s=this.mixer.clipAction(n);return this.actions.push(s),this.internalOnPlay(s,i)}internalOnPlay(e,i){var n=this.actions.find(l=>l===e);if(n===e&&n.isRunning()&&n.time<n.getClip().duration){const l=this.tryFindHandle(e);if(n.paused&&(n.paused=!1),l)return l.waitForFinish()}if(i.loop===void 0&&(i.loop=this.loop),i.clampWhenFinished===void 0&&(i.clampWhenFinished=this.clampWhenFinished),i.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(i.minMaxOffsetNormalized=this.minMaxOffsetNormalized),i.minMaxSpeed===void 0&&(i.minMaxSpeed=this.minMaxSpeed),(i==null?void 0:i.exclusive)??!0)for(const l of this.actions)l!=n&&(i.fadeDuration?l.fadeOut(i.fadeDuration):l.stop());if(i!=null&&i.fadeDuration&&e.fadeIn(i.fadeDuration),e.enabled=!0,(i==null?void 0:i.startTime)!=null)e.time=i.startTime;else if(i!=null&&i.minMaxOffsetNormalized&&i.minMaxOffsetNormalized.x!=0&&i.minMaxOffsetNormalized.y!=0){const l=e.getClip();e.time=z.lerp(i.minMaxOffsetNormalized.x,i.minMaxOffsetNormalized.y,Math.random())*l.duration}else e.time>=e.getClip().duration&&(e.time=0);i!=null&&i.minMaxSpeed?e.timeScale=z.lerp(i.minMaxSpeed.x,i.minMaxSpeed.y,Math.random()):e.timeScale=(i==null?void 0:i.speed)??1,(i==null?void 0:i.loop)!=null?e.loop=i.loop?d.LoopRepeat:d.LoopOnce:e.loop=d.LoopOnce,i!=null&&i.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),Qs&&console.log("PLAY",e.getClip().name,e);const a=new gP(e,this.mixer,i,l=>{this._handles.splice(this._handles.indexOf(a),1)});return this._handles.push(a),a.waitForFinish()}tryFindHandle(e){for(const i of this._handles)if(i.action===e)return i}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new d.AnimationMixer(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Fr([m()],Tt.prototype,"playAutomatically",2);Fr([m()],Tt.prototype,"randomStartTime",2);Fr([m(ow)],Tt.prototype,"minMaxSpeed",2);Fr([m(ow)],Tt.prototype,"minMaxOffsetNormalized",2);Fr([m()],Tt.prototype,"loop",2);Fr([m()],Tt.prototype,"clampWhenFinished",2);Fr([m(d.AnimationClip)],Tt.prototype,"clips",1);class gP{constructor(t,e,i,n){r(this,"mixer");r(this,"action");r(this,"promise",null);r(this,"_options");r(this,"_resolveCallback",null);r(this,"_resolvedOrRejectedCallback");r(this,"onFinished",t=>{t.action===this.action&&this.onResolve()});this.action=t,this.mixer=e,this._resolvedOrRejectedCallback=n,this._options=i}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(t=>{this._resolveCallback=t}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var t,e;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(e=this._resolveCallback)==null||e.call(this,this.action)}dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const jd=Symbol("objectIsAnimatedData");function sb(o,t,e){if(!o)return;if(o[jd]===void 0){if(!e)return;o[jd]=new Set}const i=o[jd];e?i.add(t):i.has(t)&&i.delete(t)}function yP(o){if(!o)return!1;const t=o[jd];return t!==void 0&&t.size>0}class _P{constructor(){r(this,"_context")}get context(){return this._context??X.Current}get isStateMachineBehaviour(){return!0}}class Jl{constructor(t,e,i,n){r(this,"name");r(this,"nameHash");r(this,"normalizedTime");r(this,"length");r(this,"speed");r(this,"action");r(this,"hasTransitions");var s;this.name=t.name,this.nameHash=t.hash,this.normalizedTime=e,this.length=i,this.speed=n,this.action=t.motion.action||null,this.hasTransitions=((s=t.transitions)==null?void 0:s.length)>0||!1}}function rw(o,t){return{name:"Empty",isLooping:!1,guid:(t==null?void 0:t.generateUUID())??d.MathUtils.generateUUID(),index:-1,clip:new d.AnimationClip(o,0,[])}}var oo=(o=>(o[o.If=1]="If",o[o.IfNot=2]="IfNot",o[o.Greater=3]="Greater",o[o.Less=4]="Less",o[o.Equals=6]="Equals",o[o.NotEqual=7]="NotEqual",o))(oo||{}),kg=(o=>(o[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",o))(kg||{});const Je=S("debuganimatorcontroller"),ld=S("debugrootmotion");class Gi{constructor(t){r(this,"_speed",1);r(this,"normalizedStartOffset",0);r(this,"animator");r(this,"model");r(this,"_mixer");r(this,"_activeState");r(this,"_activeStates",[]);r(this,"_heldActions",[]);r(this,"rootMotionHandler");this.model=t,Je&&console.log(this)}static createFromClips(t,e={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let a=0;a<t.length;a++){const l=t[a],c=[];if(e.autoTransition!==!1){const u=e.transitionDuration??0,f=u/l.duration;let p=a;(e.autoTransition===void 0||e.autoTransition===!0)&&(p=(a+1)%t.length),c.push({exitTime:1-f,offset:0,duration:u,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:l.name,hash:a,motion:{name:l.name,clip:l,isLooping:(e==null?void 0:e.looping)??!1},transitions:c,behaviours:[]};i.push(h)}const n={name:"AnimatorController",guid:new bt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new Gi(n)}play(t,e=-1,i=Number.NEGATIVE_INFINITY,n=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const a=this.model.layers[e].stateMachine;for(const l of a.states)if(l.name===t||l.hash===t){Je&&console.log("transition to ",l),this.transitionTo(l,n,i);return}console.warn("Could not find "+t+" to play")}reset(){this.setStartTransition()}setBool(t,e){var n,s;const i=typeof t=="string"?"name":"hash";return(s=(n=this.model)==null?void 0:n.parameters)==null?void 0:s.filter(a=>a[i]===t).forEach(a=>a.value=e)}getBool(t){var i,n,s;const e=typeof t=="string"?"name":"hash";return((s=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(a=>a[e]===t))==null?void 0:s.value)??!1}setFloat(t,e){var s,a;const i=typeof t=="string"?"name":"hash",n=(a=(s=this.model)==null?void 0:s.parameters)==null?void 0:a.filter(l=>l[i]===t);return n.forEach(l=>l.value=e),(n==null?void 0:n.length)>0}getFloat(t){var i,n,s;const e=typeof t=="string"?"name":"hash";return((s=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(a=>a[e]===t))==null?void 0:s.value)??0}setInteger(t,e){var n,s;const i=typeof t=="string"?"name":"hash";return(s=(n=this.model)==null?void 0:n.parameters)==null?void 0:s.filter(a=>a[i]===t).forEach(a=>a.value=e)}getInteger(t){var i,n,s;const e=typeof t=="string"?"name":"hash";return((s=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(a=>a[e]===t))==null?void 0:s.value)??0}setTrigger(t){var i,n;Je&&console.log("SET TRIGGER",t);const e=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(s=>s[e]===t).forEach(s=>s.value=!0)}resetTrigger(t){var i,n;const e=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(s=>s[e]===t).forEach(s=>s.value=!1)}getTrigger(t){var i,n,s;const e=typeof t=="string"?"name":"hash";return((s=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(a=>a[e]===t))==null?void 0:s.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(t){this._speed=t}FindState(t){return this.findState(t)}findState(t){if(!t)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const i of e.stateMachine.states)if(i.name===t||i.hash==t)return i}return null}getCurrentStateInfo(){if(!this._activeState)return null;const t=this._activeState.motion.action;if(!t)return null;const e=this._activeState.motion.clip.duration,i=e<=0?0:Math.abs(t.time/e);return new Jl(this._activeState,i,e,this._speed)}get currentAction(){if(!this._activeState)return null;const t=this._activeState.motion.action;return t||null}get context(){var t;return(t=this.animator)==null?void 0:t.context}get mixer(){return this._mixer}dispose(){var t;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)}bind(t){var e,i;t?this.animator!==t&&(this._mixer&&(this._mixer.stopAllAction(),(e=this.context)==null||e.animations.unregisterAnimationMixer(this._mixer)),this.animator=t,this._mixer=new d.AnimationMixer(this.animator.gameObject),(i=this.context)==null||i.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;Je&&console.warn("AnimatorController clone()",this.model);const t=Jc(this.model,(i,n,s)=>s==null?!0:!(s.type==="Object3D"||s.isObject3D===!0||M0(s)||s.tracks!==void 0||s instanceof Gi));return console.assert(t!==this.model),new Gi(t)}update(t){var i,n;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(t);const e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onBeforeUpdate(t)),this._mixer.update(e),this.animator.applyRootMotion&&((n=this.rootMotionHandler)==null||n.onAfterUpdate(t))}get activeState(){return this._activeState}updateActiveStates(t){for(let e=0;e<this._activeStates.length;e++){const i=this._activeStates[e],n=i.motion;if(!n.action)this._activeStates.splice(e,1),e--;else{const s=n.action;s.weight=t,s.getEffectiveWeight()<=0&&!s.isRunning()&&(Je&&console.debug("REMOVE",i.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){var t;this.model.layers.length>1&&(Je||j())&&console.warn("Multiple layers are not supported yet "+((t=this.animator)==null?void 0:t.name));for(const e of this.model.layers){const i=e.stateMachine;i.defaultState===void 0&&(Je&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),i.defaultState=0);const n=i.states[i.defaultState];this.transitionTo(n,0,this.normalizedStartOffset);break}}evaluateTransitions(){var s;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const e=this._activeState,i=e.motion.action;for(const a of e.transitions){if(!a.hasExitTime&&a.conditions.length<=0)continue;let l=!0;for(const c of a.conditions)if(!this.evaluateCondition(c)){l=!1;break}if(l)if(i){const c=e.motion.clip.duration,h=c<=0?1:Math.abs(i.time/c);let u=a.exitTime;i.timeScale<0&&(u=1-u);let f=!1;if(a.hasExitTime?i.timeScale>0?f=h>=a.exitTime:i.timeScale<0&&(f=1-h>=a.exitTime):f=!0,f){for(const p of a.conditions){const g=this.model.parameters.find(y=>y.name===p.parameter);(g==null?void 0:g.type)===kg.Trigger&&g.value&&(g.value=!1)}if(i.clampWhenFinished=!0,Je){const p=this.getState(a.destinationState,0);console.log(`Transition to ${a.destinationState} / ${p==null?void 0:p.name}`,a,`
857
857
  Timescale: `+i.timeScale,`
858
858
  Normalized time: `+h.toFixed(3),`
859
- Exit Time: `+u,a.hasExitTime)}this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}}i&&this.setTimescale(i,e);let n=!1;if(e.motion.isLooping&&i&&(i.time>=i.getClip().duration?(n=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(n=!0,i.reset(),i.time=i.getClip().duration,i.play())),!n&&e&&!t&&i&&this.animator&&e.behaviours){const a=i==null?void 0:i.getClip().duration,l=i.time/a,c=new Jl(this._activeState,l,a,this._speed);for(const h of e.behaviours)h.instance&&((s=h.instance.onStateUpdate)==null||s.call(h.instance,this.animator,c,0))}}setTimescale(t,e){let i=e.speed??1;e.speedParameter&&(i*=this.getFloat(e.speedParameter)),i!==void 0&&(t.timeScale=i*this._speed)}getState(t,e){return typeof t=="number"&&(t==-1&&(t=this.model.layers[e].stateMachine.defaultState,t===void 0&&(Je&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+e),t=0)),t=this.model.layers[e].stateMachine.states[t]),t}releaseHeldActions(t){for(const e of this._heldActions)e.fadeOut(t);this._heldActions.length=0}transitionTo(t,e,i){var u,f,p,g,y,b,_,v;if(!this.animator)return;const n=0;if(t=this.getState(t,n),!(t!=null&&t.motion)||!t.motion.clip||!(t.motion.clip instanceof d.AnimationClip))return;const s=this._activeState===t;if(s){const w=t.motion;if(!w.action_loopback&&w.clip){const x=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(w.clip,this.animator.gameObject),x&&x.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),w.action_loopback=this.createAction(w.clip)}}if((u=this._activeState)!=null&&u.behaviours&&this._activeState.motion.action){const w=(f=this._activeState)==null?void 0:f.motion.clip.duration,x=this._activeState.motion.action.time/w,O=new Jl(this._activeState,x,w,this._speed);for(const E of this._activeState.behaviours)(g=(p=E.instance)==null?void 0:p.onStateExit)==null||g.call(E.instance,this.animator,O,n)}const a=(y=this._activeState)==null?void 0:y.motion.action;s&&(t.motion.action=t.motion.action_loopback,t.motion.action_loopback=a);const l=this._activeState;this._activeState=t;const c=(b=t.motion)==null?void 0:b.action,h=t.motion.clip;if((h==null?void 0:h.duration)<=0&&h.tracks.length<=0?a&&this._heldActions.push(a):a&&(a.fadeOut(e),this.releaseHeldActions(e)),c){if(i=Math.max(0,Math.min(1,i)),t.cycleOffsetParameter){let x=this.getFloat(t.cycleOffsetParameter);typeof x=="number"?(x<0&&(x+=1),i+=x,i%=1):Je&&console.warn("AnimatorController cycle offset parameter is not a number",t.cycleOffsetParameter)}else typeof t.cycleOffset=="number"&&(i+=t.cycleOffset,i%=1);c.isRunning()&&c.stop(),c.reset(),c.enabled=!0,this.setTimescale(c,t);const w=t.motion.clip.duration;if(c.time=s?0:i*w,c.timeScale<0&&(c.time=w-c.time),c.clampWhenFinished=!0,c.setLoop(d.LoopOnce,0),e>0?c.fadeIn(e):c.weight=1,c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(t)||this._activeStates.push(t),this._activeState.behaviours){const x=new Jl(t,i,w,this._speed);for(const O of this._activeState.behaviours)(v=(_=O.instance)==null?void 0:_.onStateEnter)==null||v.call(O.instance,this.animator,x,n)}}else Je&&(t.__warned_no_motion||(t.__warned_no_motion=!0,console.warn("No action",t.motion,this)));Je&&console.log("TRANSITION FROM "+(l==null?void 0:l.name)+" TO "+t.name,e,a,c,c==null?void 0:c.getEffectiveTimeScale(),c==null?void 0:c.getEffectiveWeight(),c==null?void 0:c.isRunning(),c==null?void 0:c.isScheduled(),c==null?void 0:c.paused)}createAction(t){var i,n;if(this._mixer.existingAction(t)&&this._mixer.uncacheAction(t,(i=this.animator)==null?void 0:i.gameObject),(n=this.animator)!=null&&n.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new bP(this));const s=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,s,t)}else return this._mixer.clipAction(t)}evaluateCondition(t){const e=this.model.parameters.find(i=>i.name===t.parameter);if(!e)return!1;switch(t.mode){case oo.If:return e.value===!0;case oo.IfNot:return e.value===!1;case oo.Greater:return e.value>t.threshold;case oo.Less:return e.value<t.threshold;case oo.Equals:return e.value===t.threshold;case oo.NotEqual:return e.value!==t.threshold}return!1}createActions(t){var e,i,n,s;Je&&console.log("AnimatorController createActions",this.model);for(const a of this.model.layers){const l=a.stateMachine;for(let c=0;c<l.states.length;c++){const h=l.states[c];h.transitions||(h.transitions=[]);for(const u of h.transitions)u.conditions||(u.conditions=[]);if(h.motion||(Je&&console.warn("No motion",h),h.motion=rw(h.name)),this.animator&&h.motion.clips){const u=(e=h.motion.clips)==null?void 0:e.find(f=>{var p,g;return f.node.name===((g=(p=this.animator)==null?void 0:p.gameObject)==null?void 0:g.name)});u?h.motion.clip=u.clip:(Je||j())&&console.warn('Could not find clip for animator "'+((n=(i=this.animator)==null?void 0:i.gameObject)==null?void 0:n.name)+'"',h.motion.clips.map(f=>f.node.name))}if(!h.motion.clip){Je&&console.warn("No clip assigned to state",h);const u=new d.AnimationClip(void 0,void 0,[]);h.motion.clip=u}if((s=h.motion)!=null&&s.clip){const u=h.motion.clip;if(u instanceof d.AnimationClip){const f=this.createAction(u);h.motion.action=f}else(Je||j())&&console.warn("No valid animationclip assigned",h)}if(h.behaviours&&Array.isArray(h.behaviours))for(const u of h.behaviours){if(!(u!=null&&u.typeName))continue;const f=k.get(u.typeName);if(f){const p=new f;p.isStateMachineBehaviour&&(p._context=this.context??void 0,Ga(p,u.properties),u.instance=p),Je&&console.log("Created animator controller behaviour",h.name,u.typeName,u.properties,p)}else(Je||j())&&console.warn("Could not find AnimatorBehaviour type: "+u.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const t of this.model.layers){const e=t.stateMachine;for(let i=0;i<e.states.length;i++){const n=e.states[i];n!=null&&n.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}}class ob{constructor(t,e){r(this,"track");r(this,"createdInterpolant");r(this,"originalEvaluate");r(this,"customEvaluate");this.track=t;const i=t,n=i.createInterpolant.bind(t);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;const a=this.originalEvaluate(s);return e(s,a)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const xe=class xe{constructor(t,e,i,n,s){r(this,"_action");r(this,"root");r(this,"clip");r(this,"positionWrapper",null);r(this,"rotationWrapper",null);r(this,"context");r(this,"positionChange",new d.Vector3);r(this,"rotationChange",new d.Quaternion);r(this,"_prevTime",0);if(this.context=t,this.root=e,this.clip=i,xe.firstKeyframeRotation[this.cacheId]||(xe.firstKeyframeRotation[this.cacheId]=new d.Quaternion),s){const a=s.values;xe.firstKeyframeRotation[this.cacheId].set(a[0],a[1],a[2],a[3])}xe.spaceRotation[this.cacheId]||(xe.spaceRotation[this.cacheId]=new d.Quaternion),xe.effectiveSpaceRotation[this.cacheId]||(xe.effectiveSpaceRotation[this.cacheId]=new d.Quaternion),xe.clipOffsetRotation[this.cacheId]=new d.Quaternion,s&&xe.clipOffsetRotation[this.cacheId].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,s)}set action(t){this._action=t}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(t){if(t.getClip()!==this.clip)return;xe.lastObjRotation[this.cacheId]||(xe.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const e=xe.lastObjRotation[this.cacheId];if(xe.spaceRotation[this.cacheId].copy(e),ld){const i=new d.Euler().setFromQuaternion(e);console.log("START",this.clip.name,z.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return xe.clipOffsetRotation[this.cacheId]}handlePosition(t,e){if(e){const i=this.root;ld&&i.add(new d.AxesHelper),xe.lastObjPosition[this.cacheId]||(xe.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new d.Vector3,s=new d.Vector3;this.positionWrapper=new ob(e,(a,l)=>{const c=this.action.getEffectiveWeight();return ld&&i.position.length()>8&&i.position.set(0,i.position.y,0),a>this._prevTime&&(n.set(l[0],l[1],l[2]),n.sub(s),n.multiplyScalar(c),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),s.fromArray(l),this._prevTime=a,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(t,e){if(e){if(ld){const a=e.values,l=new d.Euler().setFromQuaternion(new d.Quaternion(a[0],a[1],a[2],a[3]));console.log(t.name,e.name,"FIRST ROTATION IN TRACK",z.toDegrees(l.y));const c=e.values.length-4,h=new d.Quaternion().set(a[c],a[c+1],a[c+2],a[c+3]),u=new d.Euler().setFromQuaternion(h);console.log(t.name,e.name,"LAST ROTATION IN TRACK",z.toDegrees(u.y))}let i=0;const n=new d.Quaternion,s=new d.Quaternion;this.rotationWrapper=new ob(e,(a,l)=>(a>i&&(s.set(l[0],l[1],l[2],l[3]),n.invert(),s.multiply(n),this.rotationChange.copy(s)),n.fromArray(l),i=a,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(t){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(t){return!this.action||(t*=this.action.getEffectiveWeight(),t<=0)?!1:(this.positionChange.multiplyScalar(t),this.rotationChange.slerp(xe.identityQuaternion,1-t),!0)}};r(xe,"lastObjPosition",{}),r(xe,"lastObjRotation",{}),r(xe,"firstKeyframeRotation",{}),r(xe,"spaceRotation",{}),r(xe,"effectiveSpaceRotation",{}),r(xe,"clipOffsetRotation",{}),r(xe,"identityQuaternion",new d.Quaternion);let xm=xe;class bP{constructor(t){r(this,"controller");r(this,"handler",[]);r(this,"root");r(this,"basePosition",new d.Vector3);r(this,"baseQuaternion",new d.Quaternion);r(this,"baseRotation",new d.Euler);r(this,"summedPosition",new d.Vector3);r(this,"summedRotation",new d.Quaternion);this.controller=t}createClip(t,e,i){this.root=e,e&&"name"in e&&e.name;const n=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),a=new xm(this.controller.context,e,i,n,s);this.handler.push(a);const l=t.clipAction(i);return a.action=l,l}onStart(t){for(const e of this.handler)e.onStart(t)}onBeforeUpdate(t){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const e of this.handler)e.onBeforeUpdate(t)}onAfterUpdate(t){if(!(t<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const e of this.handler)e.onAfterUpdate(t)&&(this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(t,e){const i=t.tracks;if(!i)return null;for(const n of i)if(n.name.endsWith(e))return n;return null}}class vP extends Ki{onSerialize(t,e){}onDeserialize(t,e){if(e.type===Gi&&(t==null?void 0:t.__type)==="AnimatorController")return new Gi(t)}}new vP(Gi);var wP=Object.defineProperty,xP=Object.getOwnPropertyDescriptor,Xu=(o,t,e,i)=>{for(var n=i>1?void 0:i?xP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&wP(t,e,n),n};const Fi=S("debuganimator");class St extends I{constructor(){super(...arguments);r(this,"applyRootMotion",!1);r(this,"hasRootMotion",!1);r(this,"keepAnimatorControllerStateOnDisable",!1);r(this,"_parametersAreDirty",!1);r(this,"_isDirty",!1);r(this,"_speed",1);r(this,"_normalizedStartOffset",0);r(this,"_animatorController",null);r(this,"_initializeWithRuntimeAnimatorController")}get isAnimationComponent(){return!0}set runtimeAnimatorController(e){var i;this._animatorController&&this._animatorController.model===e||(e?e instanceof Gi?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(i=e.model)==null?void 0:i.name),e.model||console.error("AnimatorController has no model"),e=new Gi(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Fi&&console.log("Assign animator controller",e,this),this._animatorController=new Gi(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var e;return(e=this.runtimeAnimatorController)==null?void 0:e.getCurrentStateInfo()}get currentAction(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(e,i=-1,n=Number.NEGATIVE_INFINITY,s=0){this.play(e,i,n,s)}play(e,i=-1,n=Number.NEGATIVE_INFINITY,s=0){var a;(a=this.runtimeAnimatorController)==null||a.play(e,i,n,s),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,i){this.setBool(e,i)}setBool(e,i){var n,s;Fi&&console.log("setBool",e,i),((n=this.runtimeAnimatorController)==null?void 0:n.getBool(e))!==i&&(this._parametersAreDirty=!0),(s=this.runtimeAnimatorController)==null||s.setBool(e,i)}GetBool(e){return this.getBool(e)}getBool(e){var n;const i=((n=this.runtimeAnimatorController)==null?void 0:n.getBool(e))??!1;return Fi&&console.log("getBool",e,i),i}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,i){this.setFloat(e,i)}setFloat(e,i){var n,s;((n=this.runtimeAnimatorController)==null?void 0:n.getFloat(e))!==i&&(this._parametersAreDirty=!0),Fi&&console.log("setFloat",e,i),(s=this.runtimeAnimatorController)==null||s.setFloat(e,i)}GetFloat(e){return this.getFloat(e)}getFloat(e){var n;const i=((n=this.runtimeAnimatorController)==null?void 0:n.getFloat(e))??-1;return Fi&&console.log("getFloat",e,i),i}SetInteger(e,i){this.setInteger(e,i)}setInteger(e,i){var n,s;((n=this.runtimeAnimatorController)==null?void 0:n.getInteger(e))!==i&&(this._parametersAreDirty=!0),Fi&&console.log("setInteger",e,i),(s=this.runtimeAnimatorController)==null||s.setInteger(e,i)}GetInteger(e){return this.getInteger(e)}getInteger(e){var n;const i=((n=this.runtimeAnimatorController)==null?void 0:n.getInteger(e))??-1;return Fi&&console.log("getInteger",e,i),i}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var i;this._parametersAreDirty=!0,Fi&&console.log("setTrigger",e),(i=this.runtimeAnimatorController)==null||i.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var i;this._parametersAreDirty=!0,Fi&&console.log("resetTrigger",e),(i=this.runtimeAnimatorController)==null||i.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var n;const i=(n=this.runtimeAnimatorController)==null?void 0:n.getTrigger(e);return Fi&&console.log("getTrigger",e,i),i}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var i;e!==this._speed&&(Fi&&console.log("setSpeed",e),this._speed=e,((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){var i;this._speed=z.lerp(e.x,e.y,Math.random()),((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){var i;this._normalizedStartOffset=z.lerp(e.x,e.y,Math.random()),((i=this.runtimeAnimatorController)==null?void 0:i.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){Fi&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const i=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&i){const n=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=n,n?(console.assert(this.runtimeAnimatorController!==n),this.runtimeAnimatorController=n,console.assert(this.runtimeAnimatorController===n),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!yP(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Xu([m()],St.prototype,"applyRootMotion",2);Xu([m()],St.prototype,"hasRootMotion",2);Xu([m()],St.prototype,"keepAnimatorControllerStateOnDisable",2);Xu([m()],St.prototype,"runtimeAnimatorController",1);const rb=Symbol("previous-visibility"),sr=class sr extends d.WebGLRenderTarget{render(t,e,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof d.WebGLRenderer){this.onBeforeRender();const s=i.getRenderTarget(),a=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(t,e),i.setRenderTarget(s),i.xr.enabled=a,this.onAfterRender()}}onBeforeRender(){sr._userSet.clear();const t=pg(this.texture,!0,null,sr._userSet);for(const e of t)e instanceof d.Mesh&&(e[rb]=e.visible,e.visible=!1)}onAfterRender(){for(const t of sr._userSet)t instanceof d.Mesh&&(t.visible=t[rb]);sr._userSet.clear()}};r(sr,"_userSet",new Set);let xr=sr;var SP=Object.defineProperty,CP=Object.getOwnPropertyDescriptor,ph=(o,t,e,i)=>{for(var n=i>1?void 0:i?CP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&SP(t,e,n),n};const cd=S("debuggroundprojection");class ss extends I{constructor(){super(...arguments);r(this,"applyOnAwake",!1);r(this,"autoFit",!0);r(this,"_radius",50);r(this,"_height",3);r(this,"_arblending",0);r(this,"_lastBackground");r(this,"_lastRadius");r(this,"_lastHeight");r(this,"_projection");r(this,"_watcher");r(this,"_needsTextureUpdate",!1);r(this,"_blurrynessShader",null);r(this,"_lastBlurriness",-1)}set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new Rs(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{cd&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){var e,i;(e=this._watcher)==null||e.revoke(),(i=this._projection)==null||i.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await eh(1),this.updateProjection())}onBeforeRender(){this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this.context.scene.backgroundBlurriness!==void 0&&this._lastBlurriness!=this.context.scene.backgroundBlurriness&&this.context.scene.backgroundBlurriness>.001?this.updateProjection():this._needsTextureUpdate&&this.context.scene.background instanceof d.Texture&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){var e;this.updateProjection(),(e=this._watcher)==null||e.apply()}updateProjection(){var a,l,c,h,u,f;if(!this.context.scene.background){(a=this._projection)==null||a.removeFromParent();return}const e=this.context.scene.background;if(!(e instanceof d.Texture)){(l=this._projection)==null||l.removeFromParent();return}if(((c=this.context.xr)!=null&&c.isPassThrough||(h=this.context.xr)!=null&&h.isAR)&&this.arBlending===0){(u=this._projection)==null||u.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let i=!0;const n=0,s=e!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||s){cd&&console.log("Create/Update Ground Projection",e.name),(f=this._projection)==null||f.removeFromParent();try{this._projection=new H.GroundedSkybox(e,this._height,this._radius,64)}catch(p){console.error("Error creating three GroundProjection",p);return}this._projection.position.y=this._height-n,this._projection.name="GroundProjection",Zm(this._projection,!1)}else i=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&i){this._projection.updateWorldMatrix(!0,!0);const p=ci(this.context.scene.children,[this._projection]),g=p.min.y;if(g<1/0){const y=V();y.x=p.min.x+(p.max.x-p.min.x)*.5;const b=Ue(this.gameObject).x;y.y=g+this._height*b-n,y.z=p.min.z+(p.max.z-p.min.z)*.5,st(this._projection,y)}cd&&$.DrawWireBox3(p,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(e,this.context.scene.backgroundBlurriness),this._lastBackground=e,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}updateBlurriness(e,i){var s;if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,cd&&console.log("Update Blurriness",i),this._blurrynessShader??(this._blurrynessShader=new d.ShaderMaterial({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:i},blending:{value:0},alphaFactor:{value:1}},vertexShader:PP,fragmentShader:MP})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=i,this._lastBlurriness=i,e.needsUpdate=!0;const n=this._projection.material.transparent;this._projection.material.transparent=(((s=this.context.xr)==null?void 0:s.isAR)===!0&&this.arBlending>1e-6)??!1,this._projection.material.transparent?this._blurrynessShader.uniforms.blending.value=this.arBlending:this._blurrynessShader.uniforms.blending.value=0,this.context.isInPassThrough?this._blurrynessShader.uniforms.alphaFactor.value=.95:this._blurrynessShader.uniforms.alphaFactor.value=1,n!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=Mr.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}ph([m()],ss.prototype,"applyOnAwake",2);ph([m()],ss.prototype,"autoFit",2);ph([m()],ss.prototype,"radius",1);ph([m()],ss.prototype,"height",1);ph([m()],ss.prototype,"arBlending",1);const PP=`
859
+ Exit Time: `+u,a.hasExitTime)}this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}}i&&this.setTimescale(i,e);let n=!1;if(e.motion.isLooping&&i&&(i.time>=i.getClip().duration?(n=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(n=!0,i.reset(),i.time=i.getClip().duration,i.play())),!n&&e&&!t&&i&&this.animator&&e.behaviours){const a=i==null?void 0:i.getClip().duration,l=i.time/a,c=new Jl(this._activeState,l,a,this._speed);for(const h of e.behaviours)h.instance&&((s=h.instance.onStateUpdate)==null||s.call(h.instance,this.animator,c,0))}}setTimescale(t,e){let i=e.speed??1;e.speedParameter&&(i*=this.getFloat(e.speedParameter)),i!==void 0&&(t.timeScale=i*this._speed)}getState(t,e){return typeof t=="number"&&(t==-1&&(t=this.model.layers[e].stateMachine.defaultState,t===void 0&&(Je&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+e),t=0)),t=this.model.layers[e].stateMachine.states[t]),t}releaseHeldActions(t){for(const e of this._heldActions)e.fadeOut(t);this._heldActions.length=0}transitionTo(t,e,i){var u,f,p,g,y,b,_,v;if(!this.animator)return;const n=0;if(t=this.getState(t,n),!(t!=null&&t.motion)||!t.motion.clip||!(t.motion.clip instanceof d.AnimationClip))return;const s=this._activeState===t;if(s){const w=t.motion;if(!w.action_loopback&&w.clip){const x=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(w.clip,this.animator.gameObject),x&&x.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),w.action_loopback=this.createAction(w.clip)}}if((u=this._activeState)!=null&&u.behaviours&&this._activeState.motion.action){const w=(f=this._activeState)==null?void 0:f.motion.clip.duration,x=this._activeState.motion.action.time/w,O=new Jl(this._activeState,x,w,this._speed);for(const E of this._activeState.behaviours)(g=(p=E.instance)==null?void 0:p.onStateExit)==null||g.call(E.instance,this.animator,O,n)}const a=(y=this._activeState)==null?void 0:y.motion.action;s&&(t.motion.action=t.motion.action_loopback,t.motion.action_loopback=a);const l=this._activeState;this._activeState=t;const c=(b=t.motion)==null?void 0:b.action,h=t.motion.clip;if((h==null?void 0:h.duration)<=0&&h.tracks.length<=0?a&&this._heldActions.push(a):a&&(a.fadeOut(e),this.releaseHeldActions(e)),c){if(i=Math.max(0,Math.min(1,i)),t.cycleOffsetParameter){let x=this.getFloat(t.cycleOffsetParameter);typeof x=="number"?(x<0&&(x+=1),i+=x,i%=1):Je&&console.warn("AnimatorController cycle offset parameter is not a number",t.cycleOffsetParameter)}else typeof t.cycleOffset=="number"&&(i+=t.cycleOffset,i%=1);c.isRunning()&&c.stop(),c.reset(),c.enabled=!0,this.setTimescale(c,t);const w=t.motion.clip.duration;if(c.time=s?0:i*w,c.timeScale<0&&(c.time=w-c.time),c.clampWhenFinished=!0,c.setLoop(d.LoopOnce,0),e>0?c.fadeIn(e):c.weight=1,c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(t)||this._activeStates.push(t),this._activeState.behaviours){const x=new Jl(t,i,w,this._speed);for(const O of this._activeState.behaviours)(v=(_=O.instance)==null?void 0:_.onStateEnter)==null||v.call(O.instance,this.animator,x,n)}}else Je&&(t.__warned_no_motion||(t.__warned_no_motion=!0,console.warn("No action",t.motion,this)));Je&&console.log("TRANSITION FROM "+(l==null?void 0:l.name)+" TO "+t.name,e,a,c,c==null?void 0:c.getEffectiveTimeScale(),c==null?void 0:c.getEffectiveWeight(),c==null?void 0:c.isRunning(),c==null?void 0:c.isScheduled(),c==null?void 0:c.paused)}createAction(t){var i,n;if(this._mixer.existingAction(t)&&this._mixer.uncacheAction(t,(i=this.animator)==null?void 0:i.gameObject),(n=this.animator)!=null&&n.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new bP(this));const s=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,s,t)}else return this._mixer.clipAction(t)}evaluateCondition(t){const e=this.model.parameters.find(i=>i.name===t.parameter);if(!e)return!1;switch(t.mode){case oo.If:return e.value===!0;case oo.IfNot:return e.value===!1;case oo.Greater:return e.value>t.threshold;case oo.Less:return e.value<t.threshold;case oo.Equals:return e.value===t.threshold;case oo.NotEqual:return e.value!==t.threshold}return!1}createActions(t){var e,i,n,s;Je&&console.log("AnimatorController createActions",this.model);for(const a of this.model.layers){const l=a.stateMachine;for(let c=0;c<l.states.length;c++){const h=l.states[c];h.transitions||(h.transitions=[]);for(const u of h.transitions)u.conditions||(u.conditions=[]);if(h.motion||(Je&&console.warn("No motion",h),h.motion=rw(h.name)),this.animator&&h.motion.clips){const u=(e=h.motion.clips)==null?void 0:e.find(f=>{var p,g;return f.node.name===((g=(p=this.animator)==null?void 0:p.gameObject)==null?void 0:g.name)});u?h.motion.clip=u.clip:(Je||j())&&console.warn('Could not find clip for animator "'+((n=(i=this.animator)==null?void 0:i.gameObject)==null?void 0:n.name)+'"',h.motion.clips.map(f=>f.node.name))}if(!h.motion.clip){Je&&console.warn("No clip assigned to state",h);const u=new d.AnimationClip(void 0,void 0,[]);h.motion.clip=u}if((s=h.motion)!=null&&s.clip){const u=h.motion.clip;if(u instanceof d.AnimationClip){const f=this.createAction(u);h.motion.action=f}else(Je||j())&&console.warn("No valid animationclip assigned",h)}if(h.behaviours&&Array.isArray(h.behaviours))for(const u of h.behaviours){if(!(u!=null&&u.typeName))continue;const f=k.get(u.typeName);if(f){const p=new f;p.isStateMachineBehaviour&&(p._context=this.context??void 0,Ga(p,u.properties),u.instance=p),Je&&console.log("Created animator controller behaviour",h.name,u.typeName,u.properties,p)}else(Je||j())&&console.warn("Could not find AnimatorBehaviour type: "+u.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const t of this.model.layers){const e=t.stateMachine;for(let i=0;i<e.states.length;i++){const n=e.states[i];n!=null&&n.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}}class ob{constructor(t,e){r(this,"track");r(this,"createdInterpolant");r(this,"originalEvaluate");r(this,"customEvaluate");this.track=t;const i=t,n=i.createInterpolant.bind(t);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;const a=this.originalEvaluate(s);return e(s,a)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const xe=class xe{constructor(t,e,i,n,s){r(this,"_action");r(this,"root");r(this,"clip");r(this,"positionWrapper",null);r(this,"rotationWrapper",null);r(this,"context");r(this,"positionChange",new d.Vector3);r(this,"rotationChange",new d.Quaternion);r(this,"_prevTime",0);if(this.context=t,this.root=e,this.clip=i,xe.firstKeyframeRotation[this.cacheId]||(xe.firstKeyframeRotation[this.cacheId]=new d.Quaternion),s){const a=s.values;xe.firstKeyframeRotation[this.cacheId].set(a[0],a[1],a[2],a[3])}xe.spaceRotation[this.cacheId]||(xe.spaceRotation[this.cacheId]=new d.Quaternion),xe.effectiveSpaceRotation[this.cacheId]||(xe.effectiveSpaceRotation[this.cacheId]=new d.Quaternion),xe.clipOffsetRotation[this.cacheId]=new d.Quaternion,s&&xe.clipOffsetRotation[this.cacheId].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,s)}set action(t){this._action=t}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(t){if(t.getClip()!==this.clip)return;xe.lastObjRotation[this.cacheId]||(xe.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const e=xe.lastObjRotation[this.cacheId];if(xe.spaceRotation[this.cacheId].copy(e),ld){const i=new d.Euler().setFromQuaternion(e);console.log("START",this.clip.name,z.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return xe.clipOffsetRotation[this.cacheId]}handlePosition(t,e){if(e){const i=this.root;ld&&i.add(new d.AxesHelper),xe.lastObjPosition[this.cacheId]||(xe.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new d.Vector3,s=new d.Vector3;this.positionWrapper=new ob(e,(a,l)=>{const c=this.action.getEffectiveWeight();return ld&&i.position.length()>8&&i.position.set(0,i.position.y,0),a>this._prevTime&&(n.set(l[0],l[1],l[2]),n.sub(s),n.multiplyScalar(c),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),s.fromArray(l),this._prevTime=a,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(t,e){if(e){if(ld){const a=e.values,l=new d.Euler().setFromQuaternion(new d.Quaternion(a[0],a[1],a[2],a[3]));console.log(t.name,e.name,"FIRST ROTATION IN TRACK",z.toDegrees(l.y));const c=e.values.length-4,h=new d.Quaternion().set(a[c],a[c+1],a[c+2],a[c+3]),u=new d.Euler().setFromQuaternion(h);console.log(t.name,e.name,"LAST ROTATION IN TRACK",z.toDegrees(u.y))}let i=0;const n=new d.Quaternion,s=new d.Quaternion;this.rotationWrapper=new ob(e,(a,l)=>(a>i&&(s.set(l[0],l[1],l[2],l[3]),n.invert(),s.multiply(n),this.rotationChange.copy(s)),n.fromArray(l),i=a,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(t){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(t){return!this.action||(t*=this.action.getEffectiveWeight(),t<=0)?!1:(this.positionChange.multiplyScalar(t),this.rotationChange.slerp(xe.identityQuaternion,1-t),!0)}};r(xe,"lastObjPosition",{}),r(xe,"lastObjRotation",{}),r(xe,"firstKeyframeRotation",{}),r(xe,"spaceRotation",{}),r(xe,"effectiveSpaceRotation",{}),r(xe,"clipOffsetRotation",{}),r(xe,"identityQuaternion",new d.Quaternion);let xm=xe;class bP{constructor(t){r(this,"controller");r(this,"handler",[]);r(this,"root");r(this,"basePosition",new d.Vector3);r(this,"baseQuaternion",new d.Quaternion);r(this,"baseRotation",new d.Euler);r(this,"summedPosition",new d.Vector3);r(this,"summedRotation",new d.Quaternion);this.controller=t}createClip(t,e,i){this.root=e,e&&"name"in e&&e.name;const n=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),a=new xm(this.controller.context,e,i,n,s);this.handler.push(a);const l=t.clipAction(i);return a.action=l,l}onStart(t){for(const e of this.handler)e.onStart(t)}onBeforeUpdate(t){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const e of this.handler)e.onBeforeUpdate(t)}onAfterUpdate(t){if(!(t<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const e of this.handler)e.onAfterUpdate(t)&&(this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(t,e){const i=t.tracks;if(!i)return null;for(const n of i)if(n.name.endsWith(e))return n;return null}}class vP extends Ki{onSerialize(t,e){}onDeserialize(t,e){if(e.type===Gi&&(t==null?void 0:t.__type)==="AnimatorController")return new Gi(t)}}new vP(Gi);var wP=Object.defineProperty,xP=Object.getOwnPropertyDescriptor,Xu=(o,t,e,i)=>{for(var n=i>1?void 0:i?xP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&wP(t,e,n),n};const Fi=S("debuganimator");class xt extends I{constructor(){super(...arguments);r(this,"applyRootMotion",!1);r(this,"hasRootMotion",!1);r(this,"keepAnimatorControllerStateOnDisable",!1);r(this,"_parametersAreDirty",!1);r(this,"_isDirty",!1);r(this,"_speed",1);r(this,"_normalizedStartOffset",0);r(this,"_animatorController",null);r(this,"_initializeWithRuntimeAnimatorController")}get isAnimationComponent(){return!0}set runtimeAnimatorController(e){var i;this._animatorController&&this._animatorController.model===e||(e?e instanceof Gi?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(i=e.model)==null?void 0:i.name),e.model||console.error("AnimatorController has no model"),e=new Gi(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Fi&&console.log("Assign animator controller",e,this),this._animatorController=new Gi(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var e;return(e=this.runtimeAnimatorController)==null?void 0:e.getCurrentStateInfo()}get currentAction(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(e,i=-1,n=Number.NEGATIVE_INFINITY,s=0){this.play(e,i,n,s)}play(e,i=-1,n=Number.NEGATIVE_INFINITY,s=0){var a;(a=this.runtimeAnimatorController)==null||a.play(e,i,n,s),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,i){this.setBool(e,i)}setBool(e,i){var n,s;Fi&&console.log("setBool",e,i),((n=this.runtimeAnimatorController)==null?void 0:n.getBool(e))!==i&&(this._parametersAreDirty=!0),(s=this.runtimeAnimatorController)==null||s.setBool(e,i)}GetBool(e){return this.getBool(e)}getBool(e){var n;const i=((n=this.runtimeAnimatorController)==null?void 0:n.getBool(e))??!1;return Fi&&console.log("getBool",e,i),i}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,i){this.setFloat(e,i)}setFloat(e,i){var n,s;((n=this.runtimeAnimatorController)==null?void 0:n.getFloat(e))!==i&&(this._parametersAreDirty=!0),Fi&&console.log("setFloat",e,i),(s=this.runtimeAnimatorController)==null||s.setFloat(e,i)}GetFloat(e){return this.getFloat(e)}getFloat(e){var n;const i=((n=this.runtimeAnimatorController)==null?void 0:n.getFloat(e))??-1;return Fi&&console.log("getFloat",e,i),i}SetInteger(e,i){this.setInteger(e,i)}setInteger(e,i){var n,s;((n=this.runtimeAnimatorController)==null?void 0:n.getInteger(e))!==i&&(this._parametersAreDirty=!0),Fi&&console.log("setInteger",e,i),(s=this.runtimeAnimatorController)==null||s.setInteger(e,i)}GetInteger(e){return this.getInteger(e)}getInteger(e){var n;const i=((n=this.runtimeAnimatorController)==null?void 0:n.getInteger(e))??-1;return Fi&&console.log("getInteger",e,i),i}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var i;this._parametersAreDirty=!0,Fi&&console.log("setTrigger",e),(i=this.runtimeAnimatorController)==null||i.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var i;this._parametersAreDirty=!0,Fi&&console.log("resetTrigger",e),(i=this.runtimeAnimatorController)==null||i.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var n;const i=(n=this.runtimeAnimatorController)==null?void 0:n.getTrigger(e);return Fi&&console.log("getTrigger",e,i),i}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var i;e!==this._speed&&(Fi&&console.log("setSpeed",e),this._speed=e,((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){var i;this._speed=z.lerp(e.x,e.y,Math.random()),((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){var i;this._normalizedStartOffset=z.lerp(e.x,e.y,Math.random()),((i=this.runtimeAnimatorController)==null?void 0:i.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){Fi&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const i=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&i){const n=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=n,n?(console.assert(this.runtimeAnimatorController!==n),this.runtimeAnimatorController=n,console.assert(this.runtimeAnimatorController===n),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!yP(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Xu([m()],xt.prototype,"applyRootMotion",2);Xu([m()],xt.prototype,"hasRootMotion",2);Xu([m()],xt.prototype,"keepAnimatorControllerStateOnDisable",2);Xu([m()],xt.prototype,"runtimeAnimatorController",1);const rb=Symbol("previous-visibility"),sr=class sr extends d.WebGLRenderTarget{render(t,e,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof d.WebGLRenderer){this.onBeforeRender();const s=i.getRenderTarget(),a=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(t,e),i.setRenderTarget(s),i.xr.enabled=a,this.onAfterRender()}}onBeforeRender(){sr._userSet.clear();const t=pg(this.texture,!0,null,sr._userSet);for(const e of t)e instanceof d.Mesh&&(e[rb]=e.visible,e.visible=!1)}onAfterRender(){for(const t of sr._userSet)t instanceof d.Mesh&&(t.visible=t[rb]);sr._userSet.clear()}};r(sr,"_userSet",new Set);let xr=sr;var SP=Object.defineProperty,CP=Object.getOwnPropertyDescriptor,ph=(o,t,e,i)=>{for(var n=i>1?void 0:i?CP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&SP(t,e,n),n};const cd=S("debuggroundprojection");class ss extends I{constructor(){super(...arguments);r(this,"applyOnAwake",!1);r(this,"autoFit",!0);r(this,"_radius",50);r(this,"_height",3);r(this,"_arblending",0);r(this,"_lastBackground");r(this,"_lastRadius");r(this,"_lastHeight");r(this,"_projection");r(this,"_watcher");r(this,"_needsTextureUpdate",!1);r(this,"_blurrynessShader",null);r(this,"_lastBlurriness",-1)}set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new Rs(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{cd&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){var e,i;(e=this._watcher)==null||e.revoke(),(i=this._projection)==null||i.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await eh(1),this.updateProjection())}onBeforeRender(){this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this.context.scene.backgroundBlurriness!==void 0&&this._lastBlurriness!=this.context.scene.backgroundBlurriness&&this.context.scene.backgroundBlurriness>.001?this.updateProjection():this._needsTextureUpdate&&this.context.scene.background instanceof d.Texture&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){var e;this.updateProjection(),(e=this._watcher)==null||e.apply()}updateProjection(){var a,l,c,h,u,f;if(!this.context.scene.background){(a=this._projection)==null||a.removeFromParent();return}const e=this.context.scene.background;if(!(e instanceof d.Texture)){(l=this._projection)==null||l.removeFromParent();return}if(((c=this.context.xr)!=null&&c.isPassThrough||(h=this.context.xr)!=null&&h.isAR)&&this.arBlending===0){(u=this._projection)==null||u.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let i=!0;const n=0,s=e!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||s){cd&&console.log("Create/Update Ground Projection",e.name),(f=this._projection)==null||f.removeFromParent();try{this._projection=new H.GroundedSkybox(e,this._height,this._radius,64)}catch(p){console.error("Error creating three GroundProjection",p);return}this._projection.position.y=this._height-n,this._projection.name="GroundProjection",Zm(this._projection,!1)}else i=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&i){this._projection.updateWorldMatrix(!0,!0);const p=ci(this.context.scene.children,[this._projection]),g=p.min.y;if(g<1/0){const y=V();y.x=p.min.x+(p.max.x-p.min.x)*.5;const b=Ue(this.gameObject).x;y.y=g+this._height*b-n,y.z=p.min.z+(p.max.z-p.min.z)*.5,st(this._projection,y)}cd&&$.DrawWireBox3(p,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(e,this.context.scene.backgroundBlurriness),this._lastBackground=e,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}updateBlurriness(e,i){var s;if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,cd&&console.log("Update Blurriness",i),this._blurrynessShader??(this._blurrynessShader=new d.ShaderMaterial({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:i},blending:{value:0},alphaFactor:{value:1}},vertexShader:PP,fragmentShader:MP})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=i,this._lastBlurriness=i,e.needsUpdate=!0;const n=this._projection.material.transparent;this._projection.material.transparent=(((s=this.context.xr)==null?void 0:s.isAR)===!0&&this.arBlending>1e-6)??!1,this._projection.material.transparent?this._blurrynessShader.uniforms.blending.value=this.arBlending:this._blurrynessShader.uniforms.blending.value=0,this.context.isInPassThrough?this._blurrynessShader.uniforms.alphaFactor.value=.95:this._blurrynessShader.uniforms.alphaFactor.value=1,n!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=Mr.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}ph([m()],ss.prototype,"applyOnAwake",2);ph([m()],ss.prototype,"autoFit",2);ph([m()],ss.prototype,"radius",1);ph([m()],ss.prototype,"height",1);ph([m()],ss.prototype,"arBlending",1);const PP=`
860
860
  varying vec2 vUv;
861
861
 
862
862
  void main() {
@@ -925,7 +925,7 @@ Exit Time: `+u,a.hasExitTime)}this.transitionTo(a.destinationState,a.duration,a.
925
925
  // Uncomment to visualize blur amount
926
926
  // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
927
927
  }
928
- `;var OP=Object.defineProperty,Rg=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&OP(t,e,n),n};class Ur extends I{constructor(){super(...arguments);r(this,"constraintActive",!0);r(this,"locked",!1);r(this,"sources",[])}}Rg([m()],Ur.prototype,"constraintActive");Rg([m()],Ur.prototype,"locked");Rg([m(d.Object3D)],Ur.prototype,"sources");let Sr=class{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(t,e){return this.bb_pos=t,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(t,e,i,n){return t.prep(4,12),t.writeFloat32(n),t.writeFloat32(i),t.writeFloat32(e),t.offset()}};class aw{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(t,e){return this.bb_pos=t,this.bb=e,this}position(t){return(t||new Sr).__init(this.bb_pos,this.bb)}rotation(t){return(t||new Sr).__init(this.bb_pos+12,this.bb)}scale(t){return(t||new Sr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(t,e,i,n,s,a,l,c,h,u){return t.prep(4,36),t.prep(4,12),t.writeFloat32(u),t.writeFloat32(h),t.writeFloat32(c),t.prep(4,12),t.writeFloat32(l),t.writeFloat32(a),t.writeFloat32(s),t.prep(4,12),t.writeFloat32(n),t.writeFloat32(i),t.writeFloat32(e),t.offset()}}class Ss{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSyncedTransformModel(t,e){return(e||new Ss).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedTransformModel(t,e){return t.setPosition(t.position()+ae.SIZE_PREFIX_LENGTH),(e||new Ss).__init(t.readInt32(t.position())+t.position(),t)}guid(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}fast(){const t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}transform(t){const e=this.bb.__offset(this.bb_pos,8);return e?(t||new aw).__init(this.bb_pos+e,this.bb):null}dontSave(){const t=this.bb.__offset(this.bb_pos,10);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startSyncedTransformModel(t){t.startObject(4)}static addGuid(t,e){t.addFieldOffset(0,e,0)}static addFast(t,e){t.addFieldInt8(1,+e,0)}static addTransform(t,e){t.addFieldStruct(2,e,0)}static addDontSave(t,e){t.addFieldInt8(3,+e,0)}static endSyncedTransformModel(t){return t.endObject()}static finishSyncedTransformModelBuffer(t,e){t.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(t,e){t.finish(e,void 0,!0)}}exports.MODULES=void 0;(o=>{(t=>{t.MAYBEMODULE=null;const e=[];function i(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(s=>{e.push(s)})}t.ready=i;async function n(){if(t.MODULE)return t.MODULE;const s=await Promise.resolve().then(()=>require("./rapier-CUe6_xwE.umd.cjs"));return t.MODULE=s,t.MAYBEMODULE=s,e.forEach(a=>a(s)),e.length=0,s}t.load=n})(o.RAPIER_PHYSICS||(o.RAPIER_PHYSICS={})),(t=>{t.MAYBEMODULE=null;const e=[];function i(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(s=>{e.push(s)})}t.ready=i;async function n(){if(t.MODULE)return t.MODULE;const s=await Promise.resolve().then(()=>require("./postprocessing-CNCT892s.umd.cjs")).then(a=>a.index);return t.MODULE=s,t.MAYBEMODULE=s,e.forEach(a=>a(s)),e.length=0,s}t.load=n})(o.POSTPROCESSING||(o.POSTPROCESSING={})),(t=>{t.MAYBEMODULE=null;const e=[];function i(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(s=>{e.push(s)})}t.ready=i;async function n(){if(t.MODULE)return t.MODULE;const s=await Promise.resolve().then(()=>require("./postprocessing-CNCT892s.umd.cjs")).then(a=>a.N8AO);return t.MODULE=s,t.MAYBEMODULE=s,e.forEach(a=>a(s)),e.length=0,s}t.load=n})(o.POSTPROCESSING_AO||(o.POSTPROCESSING_AO={}))})(exports.MODULES||(exports.MODULES={}));var ht=(o=>(o[o.Average=0]="Average",o[o.Multiply=1]="Multiply",o[o.Minimum=2]="Minimum",o[o.Maximum=3]="Maximum",o))(ht||{}),Qu=(o=>(o[o.Discrete=0]="Discrete",o[o.Continuous=1]="Continuous",o))(Qu||{}),Ne=(o=>(o[o.None=0]="None",o[o.FreezePositionX=2]="FreezePositionX",o[o.FreezePositionY=4]="FreezePositionY",o[o.FreezePositionZ=8]="FreezePositionZ",o[o.FreezePosition=14]="FreezePosition",o[o.FreezeRotationX=16]="FreezeRotationX",o[o.FreezeRotationY=32]="FreezeRotationY",o[o.FreezeRotationZ=64]="FreezeRotationZ",o[o.FreezeRotation=112]="FreezeRotation",o[o.FreezeAll=126]="FreezeAll",o))(Ne||{}),xa=(o=>(o[o.None=0]="None",o[o.X=2]="X",o[o.Y=4]="Y",o[o.Z=8]="Z",o[o.All=-1]="All",o))(xa||{});const Ct=function(o,t){return function(e,i,n){kP(e,i,n,o,t)}};function kP(o,t,e,i,n){if(!n&&!i&&!o.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,t,e),Ee("Invalid usage of validate decorator. Only fields can be validated. Property: "+t,Mi.Error);return}let s="";if(typeof t=="string"?s=t:s=t.name,o.__internalAwake){const a=Symbol(s),l=o.__internalAwake;o.__internalAwake=function(){var c;if(!this.onValidate){j()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((c=o.constructor)==null?void 0:c.name)+'"');return}if(this[a]===void 0){this[a]=this[s];const h=this[s];if(h instanceof d.Vector2||h instanceof d.Vector3||h instanceof d.Vector4||h instanceof d.Quaternion){const u=this[s];ju(u,()=>{this.onValidate(s)})}Object.defineProperty(this,s,{set:function(u){var f;if(this[fm]===!0)this[a]=u;else{i==null||i.call(this,u);const p=this[a];this[a]=u,(f=this.onValidate)==null||f.call(this,s,p)}},get:function(){return n==null||n.call(this),this[a]}})}l.call(this)}}}const RP=function(o){return function(t,e,i){let n="";typeof e=="string"?n=e:n=e.name;const s=o.prototype,a=Object.getOwnPropertyDescriptor(s,n);if(!(a!=null&&a.value)){console.warn("Can not apply prefix: type does not have method named",e,o);return}const l=a.value,c=t[n];Object.defineProperty(s,n,{value:function(...h){const u=c==null?void 0:c.call(this,...h);if(u instanceof Promise){u.then(f=>{if(f!==!1)return l.call(this,...h)});return}if(u!==!1)return l.call(this,...h)}})}};var EP=Object.defineProperty,TP=Object.getOwnPropertyDescriptor,Li=(o,t,e,i)=>{for(var n=i>1?void 0:i?TP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&EP(t,e,n),n};class AP{constructor(t,e){r(this,"positionChanged",!1);r(this,"rotationChanged",!1);r(this,"position");r(this,"quaternion");r(this,"_positionKeys",["x","y","z"]);r(this,"_quaternionKeys",["_x","_y","_z","_w"]);r(this,"mute",!1);r(this,"context");r(this,"obj");r(this,"_positionWatch");r(this,"_rotationWatch");this.context=e,this.obj=t}get isDirty(){return this.positionChanged||this.rotationChanged}reset(t=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,t){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const t of this._positionKeys)this.position[t]=this.obj.position[t];for(const t of this._quaternionKeys)this.quaternion[t]=this.obj.quaternion[t]}applyValues(){if(this.positionChanged&&this.position)for(const t of this._positionKeys){const e=this.position[t];e!==void 0&&(this.obj.position[t]=e)}if(this.rotationChanged&&this.quaternion)for(const t of this._quaternionKeys){const e=this.quaternion[t];e!==void 0&&(this.obj.quaternion[t]=e)}}start(t,e){this.reset(),t&&(this._positionWatch||(this._positionWatch=new Rs(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((s,a)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const l=this.position[a];Math.abs(l-s)<1e-5||(this.position[a]=s,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new Rs(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((s,a)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const l=this.quaternion[a];Math.abs(l-s)<1e-5||(this.quaternion[a]=s,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new d.Matrix4;this.obj.matrixWorld.multiplyMatrices=(s,a)=>{var l;return(l=this.context.physics.engine)!=null&&l.isUpdating||this.mute||n.equals(s)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(s)),i(s,a)}}stop(){var t,e;(t=this._positionWatch)==null||t.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var Os;const hi=(Os=class extends I{constructor(){super(...arguments);r(this,"autoMass",!0);r(this,"_mass",0);r(this,"useGravity",!0);r(this,"centerOfMass",new d.Vector3(0,0,0));r(this,"constraints",Ne.None);r(this,"isKinematic",!1);r(this,"drag",0);r(this,"angularDrag",1);r(this,"detectCollisions",!0);r(this,"sleepThreshold",.01);r(this,"collisionDetectionMode",Qu.Discrete);r(this,"_gravityScale",1);r(this,"dominanceGroup",0);r(this,"_propertiesChanged",!1);r(this,"_currentVelocity",new d.Vector3);r(this,"_smoothedVelocity",new d.Vector3);r(this,"_smoothedVelocityGetter",new d.Vector3);r(this,"_lastPosition",new d.Vector3);r(this,"_watch")}get isRigidbody(){return!0}set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var e,i;return this.autoMass?((i=(e=this.context.physics.engine)==null?void 0:e.getBody(this))==null?void 0:i.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Ne.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Ne.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Ne.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Ne.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Ne.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Ne.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Ne.FreezePositionX:this.constraints&=~Ne.FreezePositionX}set lockPositionY(e){e?this.constraints|=Ne.FreezePositionY:this.constraints&=~Ne.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Ne.FreezePositionZ:this.constraints&=~Ne.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Ne.FreezeRotationX:this.constraints&=~Ne.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Ne.FreezeRotationY:this.constraints&=~Ne.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Ne.FreezeRotationZ:this.constraints&=~Ne.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new AP(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),we.LateUpdate),j()&&(globalThis.NEEDLE_USE_RAPIER?exports.MODULES.RAPIER_PHYSICS.ready().then(async()=>{var e;await eh(3),(e=this.context.physics.engine)!=null&&e.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){var e,i;(e=this._watch)==null||e.stop(),(i=this.context.physics.engine)==null||i.removeBody(this)}onDestroy(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var e,i,n,s;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(e=this.context.physics.engine)==null||e.updateProperties(this)),(i=this._watch)!=null&&i.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(n=this.context.physics.engine)==null||n.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(e,i=!0){var n;(n=this._watch)==null||n.reset(!0),i?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){var i;(i=this.context.physics.engine)==null||i.resetForces(this,e)}resetTorques(e=!0){var i;(i=this.context.physics.engine)==null||i.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var e;(e=this.context.physics.engine)==null||e.wakeup(this)}get isSleeping(){var e;return(e=this.context.physics.engine)==null?void 0:e.isSleeping(this)}updateProperties(){var e;return this._propertiesChanged=!1,(e=this.context.physics.engine)==null?void 0:e.updateProperties(this)}applyForce(e,i,n=!0){var s;this._propertiesChanged&&this.updateProperties(),(s=this.context.physics.engine)==null||s.addForce(this,e,n)}applyImpulse(e,i=!0){var n;this._propertiesChanged&&this.updateProperties(),(n=this.context.physics.engine)==null||n.applyImpulse(this,e,i)}setForce(e,i,n,s=!0){var a,l,c;(a=this.context.physics.engine)==null||a.resetForces(this,s),typeof e=="number"?(i??(i=0),n??(n=0),(l=this.context.physics.engine)==null||l.addForce(this,{x:e,y:i,z:n},s)):(c=this.context.physics.engine)==null||c.addForce(this,e,s)}getVelocity(){var i;const e=(i=this.context.physics.engine)==null?void 0:i.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,i,n,s=!0){var a,l;if(e instanceof d.Vector3){const c=e;(a=this.context.physics.engine)==null||a.setLinearVelocity(this,c,s);return}i===void 0||n===void 0||(l=this.context.physics.engine)==null||l.setLinearVelocity(this,{x:e,y:i,z:n},s)}getAngularVelocity(){var i;const e=(i=this.context.physics.engine)==null?void 0:i.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,i,n,s=!0){var a,l;if(typeof e=="object"){const c=e;(a=this.context.physics.engine)==null||a.setAngularVelocity(this,c,s);return}if(i===void 0||n===void 0||typeof i=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(l=this.context.physics.engine)==null||l.setAngularVelocity(this,{x:e,y:i,z:n},s)}setTorque(e,i,n){typeof e=="number"?this.setAngularVelocity(e,i,n):this.setAngularVelocity(e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=this.gameObject.matrixWorld;Os.tempPosition.setFromMatrixPosition(e);const i=Os.tempPosition.sub(this._lastPosition);this._lastPosition.copy(Os.tempPosition),this._smoothedVelocity.lerp(i,this.context.time.deltaTime/.1)}},r(Os,"tempPosition",new d.Vector3),Os);Li([Ct()],hi.prototype,"autoMass",2);Li([m()],hi.prototype,"mass",1);Li([Ct(),m()],hi.prototype,"useGravity",2);Li([m(d.Vector3)],hi.prototype,"centerOfMass",2);Li([Ct(),m()],hi.prototype,"constraints",2);Li([Ct(),m()],hi.prototype,"isKinematic",2);Li([Ct(),m()],hi.prototype,"drag",2);Li([Ct(),m()],hi.prototype,"angularDrag",2);Li([Ct(),m()],hi.prototype,"detectCollisions",2);Li([Ct(),m()],hi.prototype,"sleepThreshold",2);Li([Ct(),m()],hi.prototype,"collisionDetectionMode",2);Li([Ct()],hi.prototype,"_gravityScale",2);Li([Ct()],hi.prototype,"dominanceGroup",2);let ot=hi;new d.Vector3;new d.Vector3;const to=S("debugsync"),Bc="STRS";ag(Bc,Ss.getRootAsSyncedTransformModel);const En=new ae.Builder;function lw(o,t,e=!0){En.clear();const i=En.createString(o);Ss.startSyncedTransformModel(En),Ss.addGuid(En,i),Ss.addFast(En,e);const n=t.worldPosition,s=t.worldEuler,a=t.gameObject.scale;Ss.addTransform(En,aw.createTransform(En,n.x,n.y,n.z,s.x,s.y,s.z,a.x,a.y,a.z));const l=Ss.endSyncedTransformModel(En);return En.finish(l,Bc),En.asUint8Array()}let Sm=0,mc=0;ew(o=>{var i;const e=((i=o.connection.currentServerUrl)==null?void 0:i.includes("glitch"))?10:40;mc=Math.floor(Sm/e),Sm=0,to&&mc>0&&console.log("Sync Transform Fast Interval",mc)});class es extends I{constructor(){super(...arguments);r(this,"overridePhysics",!0);r(this,"interpolatePosition",!0);r(this,"interpolateRotation",!0);r(this,"fastMode",!1);r(this,"syncDestroy",!1);r(this,"_model",null);r(this,"_needsUpdate",!0);r(this,"rb",null);r(this,"_wasKinematic",!1);r(this,"_receivedDataBefore",!1);r(this,"_targetPosition");r(this,"_targetRotation");r(this,"_receivedFastUpdate",!1);r(this,"_shouldRequestOwnership",!1);r(this,"joinedRoomCallback",null);r(this,"receivedDataCallback",null);r(this,"tempEuler",new d.Euler);r(this,"receivedUpdate",!1);r(this,"lastPosition");r(this,"lastRotation");r(this,"lastScale")}requestOwnership(){to&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){var e;(e=this._model)==null||e.freeOwnership()}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){to&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new d.Vector3,this._targetRotation=new d.Quaternion,this.lastPosition=new d.Vector3,this.lastRotation=new d.Quaternion,this.lastScale=new d.Vector3,this.rb=C.getComponentInChildren(this.gameObject,ot),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new cg(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ee.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Bc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&gg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ee.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Bc,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var i;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){to&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const n=e.transform();if(n){Wi.markDirty(this.gameObject,!0);const s=n.position();s&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(s.x(),s.y(),s.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(s.x(),s.y(),s.z()));const a=n.rotation();a&&(this.tempEuler.set(a.x(),a.y(),a.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Km(this.gameObject,this.tempEuler));const l=n.scale();l&&this.gameObject.scale.set(l.x(),l.y(),l.z())}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.scale),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){to&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,i=this.worldQuaternion,n=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const l=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>l||i.angleTo(this.lastRotation)>l||n.distanceTo(this.lastScale)>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(to&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,i.copy(this.lastRotation),this.gameObject.scale.copy(this.lastScale),Wi.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const l=this._receivedFastUpdate||this.fastMode?.5:.3;let c=!1;if(this.interpolatePosition&&this._targetPosition){const h=this.worldPosition;h.lerp(this._targetPosition,l),this.worldPosition=h,c=!0}if(this.interpolateRotation&&this._targetRotation){const h=this.worldQuaternion;h.slerp(this._targetRotation,l),this.worldQuaternion=h,c=!0}c&&Wi.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(i),this.lastScale.copy(n),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(to&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const s=10,a=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%s===0||a)){if(Sm++,a&&mc>0&&this.context.time.frameCount%mc!==0)return;to&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const l=lw(this.guid,this,!!a);this.context.connection.sendBinary(l)}}}class mh{constructor(t,e){r(this,"event");r(this,"button");r(this,"buttonName");r(this,"_used",!1);r(this,"_propagationStopped",!1);r(this,"z__pointer_ctured",!1);r(this,"z__pointer_cture_rleased",!1);r(this,"inputSource");r(this,"object");r(this,"point");r(this,"normal");r(this,"face");r(this,"distance");r(this,"instanceId");r(this,"intersection");r(this,"isDown");r(this,"isUp");r(this,"isPressed");r(this,"isClick");r(this,"isDoubleClick");r(this,"input");this.event=e,this.input=t,this.button=e.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.event.use())}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const t=new mh(this.input,this.event);return Object.assign(t,this),t}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function cu(o,t){return C.foreachComponent(o,i=>{if(!i.enabled)return;const n=i;if(t)switch(t){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}const ds=new Array;class Cs{constructor(t,e,i,n){r(this,"enabled",!0);r(this,"target");r(this,"methodName");r(this,"arguments");this.target=t,this.methodName=e||null,this.arguments=i,n!=null&&(this.enabled=n)}get canClone(){return this.target instanceof Object}invoke(...t){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(ds.length=0,t!==void 0&&t.length>0&&ds.push(...t),ds.push(...this.arguments),this.target(...this.arguments),ds.length=0):this.target(...t);else if(this.methodName!=null){const e=this.target[this.methodName];typeof e=="function"?this.arguments?(ds.length=0,t!==void 0&&t.length>0&&ds.push(...t),ds.push(...this.arguments),e.call(this.target,...ds),ds.length=0):e.call(this.target,...t):this.arguments?this.target[this.methodName]=this.arguments[0]||t[0]:this.target[this.methodName]=t[0]}}}}const LP=o=>/^[A-Z]*$/.test(o);class Yu extends Event{constructor(){super(...arguments);r(this,"args")}}class ye{constructor(t){r(this,"isEventList",!0);r(this,"target");r(this,"key");r(this,"_isInvoking",!1);r(this,"methods",[]);r(this,"_methodsCopy",[]);if(this.methods=[],Array.isArray(t))for(const e of t)e instanceof Cs?this.methods.push(e):typeof e=="function"&&this.methods.push(new Cs(e));else typeof t=="function"&&this.methods.push(new Cs(t))}__internalOnInstantiate(t){var n;const e=new Array;for(let s=0;s<this.methods.length;s++){const a=this.methods[s];if(!(a.target instanceof Function)){const l=a.target;let c=l==null?void 0:l.uuid;if(l&&(c=l.guid),c){const h=t[c];if(h){const u=(n=a.arguments)==null?void 0:n.map(f=>f instanceof Object&&f.uuid?t[f.uuid]:f!=null&&f.isComponent?t[f.guid]:f);e.push(new Cs(h.clone,a.methodName,u,a.enabled))}else j()&&console.warn("Could not find target for event listener")}}}return new ye(e)}setEventTarget(t,e){if(this.key=t,this.target=e,this.key!==void 0){let i="",n=!1;for(const s of this.key)n&&LP(s)&&(i+="-"),n=!0,i+=s.toLowerCase();this.key=i}}get listenerCount(){var t;return((t=this.methods)==null?void 0:t.length)??0}get isInvoking(){return this._isInvoking}static from(...t){return new ye(t)}invoke(...t){var e;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((e=this.methods)==null?void 0:e.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const i of this._methodsCopy)i.invoke(...t);if(typeof this.target=="object"&&typeof this.key=="string"){const i=this.target.dispatchEvent;if(typeof i=="function"){const n=new Yu(this.key);n.args=t,i.call(this.target,n)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(t){return this.methods.push(new Cs(t)),t}removeEventListener(t){if(t)for(let e=this.methods.length-1;e>=0;e--)this.methods[e].target===t&&(this.methods[e].enabled=!1,this.methods.splice(e,1))}removeAllEventListeners(){this.methods.length=0}}class DP extends Ki{constructor(){super([d.Color,ie],"ColorSerializer")}onDeserialize(t){if(t!=null)return t.a!==void 0?new ie(t.r,t.g,t.b,t.a):t.alpha!==void 0?new ie(t.r,t.g,t.b,t.alpha):new d.Color(t.r,t.g,t.b)}onSerialize(t){if(t!=null)return t.a!==void 0?{r:t.r,g:t.g,b:t.b,a:t.a}:{r:t.r,g:t.g,b:t.b}}}const IP=new DP;class jP extends Ki{constructor(){super([d.Euler],"EulerSerializer")}onDeserialize(t,e){if(t!=null){if(t.order)return new d.Euler(t.x,t.y,t.z,t.order);if(t.x!=null)return new d.Euler(t.x,t.y,t.z)}}onSerialize(t,e){return{x:t.x,y:t.y,z:t.z,order:t.order}}}const BP=new jP;class FP extends Ki{constructor(){super(d.Object3D,"ObjectSerializer")}onSerialize(t,e){if(e.objectToNode!==void 0&&t.uuid){const i=e.objectToNode[t.uuid];return dt&&console.log(i,t.name,t.uuid),{node:i}}}onDeserialize(t,e){var i,n,s;if(typeof t=="string"){if(t.endsWith(".glb")||t.endsWith(".gltf")){if(e.serializable instanceof Array&&e.serializable.includes(te))return;j()&&me("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const a=(n=(i=e.target)==null?void 0:i.constructor)==null?void 0:n.name;console.warn(`Wrong usage of @serializable detected in your script "${a}"
928
+ `;var OP=Object.defineProperty,Rg=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&OP(t,e,n),n};class Ur extends I{constructor(){super(...arguments);r(this,"constraintActive",!0);r(this,"locked",!1);r(this,"sources",[])}}Rg([m()],Ur.prototype,"constraintActive");Rg([m()],Ur.prototype,"locked");Rg([m(d.Object3D)],Ur.prototype,"sources");let Sr=class{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(t,e){return this.bb_pos=t,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(t,e,i,n){return t.prep(4,12),t.writeFloat32(n),t.writeFloat32(i),t.writeFloat32(e),t.offset()}};class aw{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(t,e){return this.bb_pos=t,this.bb=e,this}position(t){return(t||new Sr).__init(this.bb_pos,this.bb)}rotation(t){return(t||new Sr).__init(this.bb_pos+12,this.bb)}scale(t){return(t||new Sr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(t,e,i,n,s,a,l,c,h,u){return t.prep(4,36),t.prep(4,12),t.writeFloat32(u),t.writeFloat32(h),t.writeFloat32(c),t.prep(4,12),t.writeFloat32(l),t.writeFloat32(a),t.writeFloat32(s),t.prep(4,12),t.writeFloat32(n),t.writeFloat32(i),t.writeFloat32(e),t.offset()}}class Ss{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSyncedTransformModel(t,e){return(e||new Ss).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedTransformModel(t,e){return t.setPosition(t.position()+ae.SIZE_PREFIX_LENGTH),(e||new Ss).__init(t.readInt32(t.position())+t.position(),t)}guid(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}fast(){const t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}transform(t){const e=this.bb.__offset(this.bb_pos,8);return e?(t||new aw).__init(this.bb_pos+e,this.bb):null}dontSave(){const t=this.bb.__offset(this.bb_pos,10);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startSyncedTransformModel(t){t.startObject(4)}static addGuid(t,e){t.addFieldOffset(0,e,0)}static addFast(t,e){t.addFieldInt8(1,+e,0)}static addTransform(t,e){t.addFieldStruct(2,e,0)}static addDontSave(t,e){t.addFieldInt8(3,+e,0)}static endSyncedTransformModel(t){return t.endObject()}static finishSyncedTransformModelBuffer(t,e){t.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(t,e){t.finish(e,void 0,!0)}}exports.MODULES=void 0;(o=>{(t=>{t.MAYBEMODULE=null;const e=[];function i(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(s=>{e.push(s)})}t.ready=i;async function n(){if(t.MODULE)return t.MODULE;const s=await Promise.resolve().then(()=>require("./rapier-CUe6_xwE.umd.cjs"));return t.MODULE=s,t.MAYBEMODULE=s,e.forEach(a=>a(s)),e.length=0,s}t.load=n})(o.RAPIER_PHYSICS||(o.RAPIER_PHYSICS={})),(t=>{t.MAYBEMODULE=null;const e=[];function i(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(s=>{e.push(s)})}t.ready=i;async function n(){if(t.MODULE)return t.MODULE;const s=await Promise.resolve().then(()=>require("./postprocessing-Dw2OCMp4.umd.cjs")).then(a=>a.index);return t.MODULE=s,t.MAYBEMODULE=s,e.forEach(a=>a(s)),e.length=0,s}t.load=n})(o.POSTPROCESSING||(o.POSTPROCESSING={})),(t=>{t.MAYBEMODULE=null;const e=[];function i(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(s=>{e.push(s)})}t.ready=i;async function n(){if(t.MODULE)return t.MODULE;const s=await Promise.resolve().then(()=>require("./postprocessing-Dw2OCMp4.umd.cjs")).then(a=>a.N8AO);return t.MODULE=s,t.MAYBEMODULE=s,e.forEach(a=>a(s)),e.length=0,s}t.load=n})(o.POSTPROCESSING_AO||(o.POSTPROCESSING_AO={}))})(exports.MODULES||(exports.MODULES={}));var ht=(o=>(o[o.Average=0]="Average",o[o.Multiply=1]="Multiply",o[o.Minimum=2]="Minimum",o[o.Maximum=3]="Maximum",o))(ht||{}),Qu=(o=>(o[o.Discrete=0]="Discrete",o[o.Continuous=1]="Continuous",o))(Qu||{}),Ne=(o=>(o[o.None=0]="None",o[o.FreezePositionX=2]="FreezePositionX",o[o.FreezePositionY=4]="FreezePositionY",o[o.FreezePositionZ=8]="FreezePositionZ",o[o.FreezePosition=14]="FreezePosition",o[o.FreezeRotationX=16]="FreezeRotationX",o[o.FreezeRotationY=32]="FreezeRotationY",o[o.FreezeRotationZ=64]="FreezeRotationZ",o[o.FreezeRotation=112]="FreezeRotation",o[o.FreezeAll=126]="FreezeAll",o))(Ne||{}),xa=(o=>(o[o.None=0]="None",o[o.X=2]="X",o[o.Y=4]="Y",o[o.Z=8]="Z",o[o.All=-1]="All",o))(xa||{});const St=function(o,t){return function(e,i,n){kP(e,i,n,o,t)}};function kP(o,t,e,i,n){if(!n&&!i&&!o.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,t,e),Ee("Invalid usage of validate decorator. Only fields can be validated. Property: "+t,Mi.Error);return}let s="";if(typeof t=="string"?s=t:s=t.name,o.__internalAwake){const a=Symbol(s),l=o.__internalAwake;o.__internalAwake=function(){var c;if(!this.onValidate){j()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((c=o.constructor)==null?void 0:c.name)+'"');return}if(this[a]===void 0){this[a]=this[s];const h=this[s];if(h instanceof d.Vector2||h instanceof d.Vector3||h instanceof d.Vector4||h instanceof d.Quaternion){const u=this[s];ju(u,()=>{this.onValidate(s)})}Object.defineProperty(this,s,{set:function(u){var f;if(this[fm]===!0)this[a]=u;else{i==null||i.call(this,u);const p=this[a];this[a]=u,(f=this.onValidate)==null||f.call(this,s,p)}},get:function(){return n==null||n.call(this),this[a]}})}l.call(this)}}}const RP=function(o){return function(t,e,i){let n="";typeof e=="string"?n=e:n=e.name;const s=o.prototype,a=Object.getOwnPropertyDescriptor(s,n);if(!(a!=null&&a.value)){console.warn("Can not apply prefix: type does not have method named",e,o);return}const l=a.value,c=t[n];Object.defineProperty(s,n,{value:function(...h){const u=c==null?void 0:c.call(this,...h);if(u instanceof Promise){u.then(f=>{if(f!==!1)return l.call(this,...h)});return}if(u!==!1)return l.call(this,...h)}})}};var EP=Object.defineProperty,TP=Object.getOwnPropertyDescriptor,Li=(o,t,e,i)=>{for(var n=i>1?void 0:i?TP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&EP(t,e,n),n};class AP{constructor(t,e){r(this,"positionChanged",!1);r(this,"rotationChanged",!1);r(this,"position");r(this,"quaternion");r(this,"_positionKeys",["x","y","z"]);r(this,"_quaternionKeys",["_x","_y","_z","_w"]);r(this,"mute",!1);r(this,"context");r(this,"obj");r(this,"_positionWatch");r(this,"_rotationWatch");this.context=e,this.obj=t}get isDirty(){return this.positionChanged||this.rotationChanged}reset(t=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,t){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const t of this._positionKeys)this.position[t]=this.obj.position[t];for(const t of this._quaternionKeys)this.quaternion[t]=this.obj.quaternion[t]}applyValues(){if(this.positionChanged&&this.position)for(const t of this._positionKeys){const e=this.position[t];e!==void 0&&(this.obj.position[t]=e)}if(this.rotationChanged&&this.quaternion)for(const t of this._quaternionKeys){const e=this.quaternion[t];e!==void 0&&(this.obj.quaternion[t]=e)}}start(t,e){this.reset(),t&&(this._positionWatch||(this._positionWatch=new Rs(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((s,a)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const l=this.position[a];Math.abs(l-s)<1e-5||(this.position[a]=s,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new Rs(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((s,a)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const l=this.quaternion[a];Math.abs(l-s)<1e-5||(this.quaternion[a]=s,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new d.Matrix4;this.obj.matrixWorld.multiplyMatrices=(s,a)=>{var l;return(l=this.context.physics.engine)!=null&&l.isUpdating||this.mute||n.equals(s)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(s)),i(s,a)}}stop(){var t,e;(t=this._positionWatch)==null||t.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var Os;const hi=(Os=class extends I{constructor(){super(...arguments);r(this,"autoMass",!0);r(this,"_mass",0);r(this,"useGravity",!0);r(this,"centerOfMass",new d.Vector3(0,0,0));r(this,"constraints",Ne.None);r(this,"isKinematic",!1);r(this,"drag",0);r(this,"angularDrag",1);r(this,"detectCollisions",!0);r(this,"sleepThreshold",.01);r(this,"collisionDetectionMode",Qu.Discrete);r(this,"_gravityScale",1);r(this,"dominanceGroup",0);r(this,"_propertiesChanged",!1);r(this,"_currentVelocity",new d.Vector3);r(this,"_smoothedVelocity",new d.Vector3);r(this,"_smoothedVelocityGetter",new d.Vector3);r(this,"_lastPosition",new d.Vector3);r(this,"_watch")}get isRigidbody(){return!0}set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var e,i;return this.autoMass?((i=(e=this.context.physics.engine)==null?void 0:e.getBody(this))==null?void 0:i.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Ne.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Ne.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Ne.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Ne.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Ne.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Ne.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Ne.FreezePositionX:this.constraints&=~Ne.FreezePositionX}set lockPositionY(e){e?this.constraints|=Ne.FreezePositionY:this.constraints&=~Ne.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Ne.FreezePositionZ:this.constraints&=~Ne.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Ne.FreezeRotationX:this.constraints&=~Ne.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Ne.FreezeRotationY:this.constraints&=~Ne.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Ne.FreezeRotationZ:this.constraints&=~Ne.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new AP(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),we.LateUpdate),j()&&(globalThis.NEEDLE_USE_RAPIER?exports.MODULES.RAPIER_PHYSICS.ready().then(async()=>{var e;await eh(3),(e=this.context.physics.engine)!=null&&e.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){var e,i;(e=this._watch)==null||e.stop(),(i=this.context.physics.engine)==null||i.removeBody(this)}onDestroy(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var e,i,n,s;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(e=this.context.physics.engine)==null||e.updateProperties(this)),(i=this._watch)!=null&&i.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(n=this.context.physics.engine)==null||n.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(e,i=!0){var n;(n=this._watch)==null||n.reset(!0),i?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){var i;(i=this.context.physics.engine)==null||i.resetForces(this,e)}resetTorques(e=!0){var i;(i=this.context.physics.engine)==null||i.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var e;(e=this.context.physics.engine)==null||e.wakeup(this)}get isSleeping(){var e;return(e=this.context.physics.engine)==null?void 0:e.isSleeping(this)}updateProperties(){var e;return this._propertiesChanged=!1,(e=this.context.physics.engine)==null?void 0:e.updateProperties(this)}applyForce(e,i,n=!0){var s;this._propertiesChanged&&this.updateProperties(),(s=this.context.physics.engine)==null||s.addForce(this,e,n)}applyImpulse(e,i=!0){var n;this._propertiesChanged&&this.updateProperties(),(n=this.context.physics.engine)==null||n.applyImpulse(this,e,i)}setForce(e,i,n,s=!0){var a,l,c;(a=this.context.physics.engine)==null||a.resetForces(this,s),typeof e=="number"?(i??(i=0),n??(n=0),(l=this.context.physics.engine)==null||l.addForce(this,{x:e,y:i,z:n},s)):(c=this.context.physics.engine)==null||c.addForce(this,e,s)}getVelocity(){var i;const e=(i=this.context.physics.engine)==null?void 0:i.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,i,n,s=!0){var a,l;if(e instanceof d.Vector3){const c=e;(a=this.context.physics.engine)==null||a.setLinearVelocity(this,c,s);return}i===void 0||n===void 0||(l=this.context.physics.engine)==null||l.setLinearVelocity(this,{x:e,y:i,z:n},s)}getAngularVelocity(){var i;const e=(i=this.context.physics.engine)==null?void 0:i.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,i,n,s=!0){var a,l;if(typeof e=="object"){const c=e;(a=this.context.physics.engine)==null||a.setAngularVelocity(this,c,s);return}if(i===void 0||n===void 0||typeof i=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(l=this.context.physics.engine)==null||l.setAngularVelocity(this,{x:e,y:i,z:n},s)}setTorque(e,i,n){typeof e=="number"?this.setAngularVelocity(e,i,n):this.setAngularVelocity(e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=this.gameObject.matrixWorld;Os.tempPosition.setFromMatrixPosition(e);const i=Os.tempPosition.sub(this._lastPosition);this._lastPosition.copy(Os.tempPosition),this._smoothedVelocity.lerp(i,this.context.time.deltaTime/.1)}},r(Os,"tempPosition",new d.Vector3),Os);Li([St()],hi.prototype,"autoMass",2);Li([m()],hi.prototype,"mass",1);Li([St(),m()],hi.prototype,"useGravity",2);Li([m(d.Vector3)],hi.prototype,"centerOfMass",2);Li([St(),m()],hi.prototype,"constraints",2);Li([St(),m()],hi.prototype,"isKinematic",2);Li([St(),m()],hi.prototype,"drag",2);Li([St(),m()],hi.prototype,"angularDrag",2);Li([St(),m()],hi.prototype,"detectCollisions",2);Li([St(),m()],hi.prototype,"sleepThreshold",2);Li([St(),m()],hi.prototype,"collisionDetectionMode",2);Li([St()],hi.prototype,"_gravityScale",2);Li([St()],hi.prototype,"dominanceGroup",2);let ot=hi;new d.Vector3;new d.Vector3;const to=S("debugsync"),Bc="STRS";ag(Bc,Ss.getRootAsSyncedTransformModel);const En=new ae.Builder;function lw(o,t,e=!0){En.clear();const i=En.createString(o);Ss.startSyncedTransformModel(En),Ss.addGuid(En,i),Ss.addFast(En,e);const n=t.worldPosition,s=t.worldEuler,a=t.gameObject.scale;Ss.addTransform(En,aw.createTransform(En,n.x,n.y,n.z,s.x,s.y,s.z,a.x,a.y,a.z));const l=Ss.endSyncedTransformModel(En);return En.finish(l,Bc),En.asUint8Array()}let Sm=0,mc=0;ew(o=>{var i;const e=((i=o.connection.currentServerUrl)==null?void 0:i.includes("glitch"))?10:40;mc=Math.floor(Sm/e),Sm=0,to&&mc>0&&console.log("Sync Transform Fast Interval",mc)});class es extends I{constructor(){super(...arguments);r(this,"overridePhysics",!0);r(this,"interpolatePosition",!0);r(this,"interpolateRotation",!0);r(this,"fastMode",!1);r(this,"syncDestroy",!1);r(this,"_model",null);r(this,"_needsUpdate",!0);r(this,"rb",null);r(this,"_wasKinematic",!1);r(this,"_receivedDataBefore",!1);r(this,"_targetPosition");r(this,"_targetRotation");r(this,"_receivedFastUpdate",!1);r(this,"_shouldRequestOwnership",!1);r(this,"joinedRoomCallback",null);r(this,"receivedDataCallback",null);r(this,"tempEuler",new d.Euler);r(this,"receivedUpdate",!1);r(this,"lastPosition");r(this,"lastRotation");r(this,"lastScale")}requestOwnership(){to&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){var e;(e=this._model)==null||e.freeOwnership()}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){to&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new d.Vector3,this._targetRotation=new d.Quaternion,this.lastPosition=new d.Vector3,this.lastRotation=new d.Quaternion,this.lastScale=new d.Vector3,this.rb=C.getComponentInChildren(this.gameObject,ot),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new cg(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ee.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Bc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&gg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ee.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Bc,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var i;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){to&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const n=e.transform();if(n){Wi.markDirty(this.gameObject,!0);const s=n.position();s&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(s.x(),s.y(),s.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(s.x(),s.y(),s.z()));const a=n.rotation();a&&(this.tempEuler.set(a.x(),a.y(),a.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Km(this.gameObject,this.tempEuler));const l=n.scale();l&&this.gameObject.scale.set(l.x(),l.y(),l.z())}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.scale),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){to&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,i=this.worldQuaternion,n=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const l=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>l||i.angleTo(this.lastRotation)>l||n.distanceTo(this.lastScale)>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(to&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,i.copy(this.lastRotation),this.gameObject.scale.copy(this.lastScale),Wi.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const l=this._receivedFastUpdate||this.fastMode?.5:.3;let c=!1;if(this.interpolatePosition&&this._targetPosition){const h=this.worldPosition;h.lerp(this._targetPosition,l),this.worldPosition=h,c=!0}if(this.interpolateRotation&&this._targetRotation){const h=this.worldQuaternion;h.slerp(this._targetRotation,l),this.worldQuaternion=h,c=!0}c&&Wi.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(i),this.lastScale.copy(n),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(to&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const s=10,a=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%s===0||a)){if(Sm++,a&&mc>0&&this.context.time.frameCount%mc!==0)return;to&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const l=lw(this.guid,this,!!a);this.context.connection.sendBinary(l)}}}class mh{constructor(t,e){r(this,"event");r(this,"button");r(this,"buttonName");r(this,"_used",!1);r(this,"_propagationStopped",!1);r(this,"z__pointer_ctured",!1);r(this,"z__pointer_cture_rleased",!1);r(this,"inputSource");r(this,"object");r(this,"point");r(this,"normal");r(this,"face");r(this,"distance");r(this,"instanceId");r(this,"intersection");r(this,"isDown");r(this,"isUp");r(this,"isPressed");r(this,"isClick");r(this,"isDoubleClick");r(this,"input");this.event=e,this.input=t,this.button=e.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.event.use())}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const t=new mh(this.input,this.event);return Object.assign(t,this),t}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function cu(o,t){return C.foreachComponent(o,i=>{if(!i.enabled)return;const n=i;if(t)switch(t){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}const ds=new Array;class Cs{constructor(t,e,i,n){r(this,"enabled",!0);r(this,"target");r(this,"methodName");r(this,"arguments");this.target=t,this.methodName=e||null,this.arguments=i,n!=null&&(this.enabled=n)}get canClone(){return this.target instanceof Object}invoke(...t){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(ds.length=0,t!==void 0&&t.length>0&&ds.push(...t),ds.push(...this.arguments),this.target(...this.arguments),ds.length=0):this.target(...t);else if(this.methodName!=null){const e=this.target[this.methodName];typeof e=="function"?this.arguments?(ds.length=0,t!==void 0&&t.length>0&&ds.push(...t),ds.push(...this.arguments),e.call(this.target,...ds),ds.length=0):e.call(this.target,...t):this.arguments?this.target[this.methodName]=this.arguments[0]||t[0]:this.target[this.methodName]=t[0]}}}}const LP=o=>/^[A-Z]*$/.test(o);class Yu extends Event{constructor(){super(...arguments);r(this,"args")}}class ye{constructor(t){r(this,"isEventList",!0);r(this,"target");r(this,"key");r(this,"_isInvoking",!1);r(this,"methods",[]);r(this,"_methodsCopy",[]);if(this.methods=[],Array.isArray(t))for(const e of t)e instanceof Cs?this.methods.push(e):typeof e=="function"&&this.methods.push(new Cs(e));else typeof t=="function"&&this.methods.push(new Cs(t))}__internalOnInstantiate(t){var n;const e=new Array;for(let s=0;s<this.methods.length;s++){const a=this.methods[s];if(!(a.target instanceof Function)){const l=a.target;let c=l==null?void 0:l.uuid;if(l&&(c=l.guid),c){const h=t[c];if(h){const u=(n=a.arguments)==null?void 0:n.map(f=>f instanceof Object&&f.uuid?t[f.uuid]:f!=null&&f.isComponent?t[f.guid]:f);e.push(new Cs(h.clone,a.methodName,u,a.enabled))}else j()&&console.warn("Could not find target for event listener")}}}return new ye(e)}setEventTarget(t,e){if(this.key=t,this.target=e,this.key!==void 0){let i="",n=!1;for(const s of this.key)n&&LP(s)&&(i+="-"),n=!0,i+=s.toLowerCase();this.key=i}}get listenerCount(){var t;return((t=this.methods)==null?void 0:t.length)??0}get isInvoking(){return this._isInvoking}static from(...t){return new ye(t)}invoke(...t){var e;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((e=this.methods)==null?void 0:e.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const i of this._methodsCopy)i.invoke(...t);if(typeof this.target=="object"&&typeof this.key=="string"){const i=this.target.dispatchEvent;if(typeof i=="function"){const n=new Yu(this.key);n.args=t,i.call(this.target,n)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(t){return this.methods.push(new Cs(t)),t}removeEventListener(t){if(t)for(let e=this.methods.length-1;e>=0;e--)this.methods[e].target===t&&(this.methods[e].enabled=!1,this.methods.splice(e,1))}removeAllEventListeners(){this.methods.length=0}}class DP extends Ki{constructor(){super([d.Color,ie],"ColorSerializer")}onDeserialize(t){if(t!=null)return t.a!==void 0?new ie(t.r,t.g,t.b,t.a):t.alpha!==void 0?new ie(t.r,t.g,t.b,t.alpha):new d.Color(t.r,t.g,t.b)}onSerialize(t){if(t!=null)return t.a!==void 0?{r:t.r,g:t.g,b:t.b,a:t.a}:{r:t.r,g:t.g,b:t.b}}}const IP=new DP;class jP extends Ki{constructor(){super([d.Euler],"EulerSerializer")}onDeserialize(t,e){if(t!=null){if(t.order)return new d.Euler(t.x,t.y,t.z,t.order);if(t.x!=null)return new d.Euler(t.x,t.y,t.z)}}onSerialize(t,e){return{x:t.x,y:t.y,z:t.z,order:t.order}}}const BP=new jP;class FP extends Ki{constructor(){super(d.Object3D,"ObjectSerializer")}onSerialize(t,e){if(e.objectToNode!==void 0&&t.uuid){const i=e.objectToNode[t.uuid];return dt&&console.log(i,t.name,t.uuid),{node:i}}}onDeserialize(t,e){var i,n,s;if(typeof t=="string"){if(t.endsWith(".glb")||t.endsWith(".gltf")){if(e.serializable instanceof Array&&e.serializable.includes(te))return;j()&&me("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const a=(n=(i=e.target)==null?void 0:i.constructor)==null?void 0:n.name;console.warn(`Wrong usage of @serializable detected in your script "${a}"
929
929
 
930
930
  It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
931
931
 
@@ -937,12 +937,12 @@ ${e.path}! : AssetReference;
937
937
  Could not find method ${h.method} on object ${f.name}. Please rename ${h.method} to ${b}?
938
938
  `,f[b],`
939
939
  in script: `,f),me("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
940
- Could not find method ${h.method} on object ${f.name}`,f,typeof f[h.method])};if(typeof f[h.method]!="function"){let b=!1,_=f;for(;_;){const v=Object.getOwnPropertyDescriptor(_,h.method);if(v&&(v.writable===!0||v.set)){b=!0;break}_=Object.getPrototypeOf(_)}!b&&(j()||dt)&&g()}}if(f){let g=h.argument;if(g!==void 0?g=u(g):h.arguments!==void 0&&(g=h.arguments.map(u)),!f[h.method])console.warn(`EventList method not found: "${h.method}" on ${f==null?void 0:f.name}`);else{g!==void 0&&!Array.isArray(g)&&(g=[g]);const b=new Cs(f,h.method,g,h.enabled);a.push(b)}}else j()&&console.warn("[Debug] EventList: Could not find event listener in scene",h,e.object,t)}const l=new ye(a);dt&&console.log(l);const c=e.target;return c!==void 0&&e.path!==void 0&&l.setEventTarget(e.path,c),l}}}const NP=new zP,hu=new WeakMap,$P=d.Texture.prototype.clone;d.Texture.prototype.clone=function(){const o=$P.call(this);return hu.has(o)||hu.set(o,this),o};class hw extends Ki{constructor(){super([xr,d.WebGLRenderTarget])}onSerialize(t,e){}onDeserialize(t,e){if(t instanceof d.Texture&&e.type===xr){let i=t;hu.has(i)&&(i=hu.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof d.CompressedTexture&&(i.isCompressedTexture=!1,i.format=d.RGBAFormat);const n=new xr(i.image.width,i.image.height,{colorSpace:d.LinearSRGBColorSpace});return n.texture=i,n}}}new hw;class dw extends Ki{constructor(){super([URL])}onSerialize(t,e){return null}onDeserialize(t,e){if(typeof t=="string"&&t.length>0)return Eo(e.gltfId,t)}}new dw;var VP=Object.defineProperty,WP=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&VP(t,e,n),n};class qa extends I{awake(){Yt.createIfNoneExists(this.context)}onEnable(){var t;(t=Yt.get(this.context))==null||t.register(this)}onDisable(){var t;(t=Yt.get(this.context))==null||t.unregister(this)}}class Ei extends qa{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[]);r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Ds),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const i=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=s=>s instanceof d.SkinnedMesh?"continue in children":i?i(s):!0);const n=this.context.physics.raycast(e);return e.testObject=i,n}}WP([m()],Ei.prototype,"ignoreSkinnedMeshes");class Ku extends Ei{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Eu=class Eu extends qa{performRaycast(t){if(!J.active||!Eu.allow||!(t!=null&&t.ray))return null;const e=t.ray.origin;return this.context.physics.sphereOverlap(e,.015,!1,!0)}};r(Eu,"allow",!0);let Tr=Eu;class Eg{static getObject(t){const e=t[Si];return e&&(e.isComponent===!0?t=e.gameObject:t=e),t}static isInteractable(t,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),t==null||!t.visible||(t=this.getObject(t),!t.visible))return!1;const i=this.tryFindCanvasGroup(t);if((i==null?void 0:i.isCanvasGroup)===!0&&(e&&(e.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=Rr(t,s=>{if(s.isGraphic===!0)return s},!1);return e&&(n==null?void 0:n.isGraphic)===!0&&(e.graphic=n),!((n==null?void 0:n.raycastTarget)===!1||(n==null?void 0:n.layer)===2)}static tryFindCanvasGroup(t){if(!t)return null;const e=Rr(t,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return e!==void 0?e:this.tryFindCanvasGroup(t.parent)}}function Tg(o){const t=o[Si];return t||(o.parent?Tg(o.parent):null)}function GP(o){return o.isUI===!0||typeof o[Si]=="object"}function du(o,t){if(!o)return;const e=o.material;if((e==null?void 0:e.isMaterial)===!0){const i=o.parent;i&&i.isText,e.side=t.doubleSided??!0?d.DoubleSide:d.FrontSide,e.shadowSide=t.doubleSided?d.DoubleSide:d.FrontSide,o.castShadow=t.castShadows?t.castShadows:!1,o.receiveShadow=t.receiveShadows?t.receiveShadows:!1}for(const i of o.children)du(i,t)}function ma(o,t,e){o[t]===void 0&&console.warn("Field",t,"is undefined on",o);const i=Proxy.revocable(o[t],{set(a,l,c,h){const u=a[l],f=Reflect.set(a,l,c,h);return e(c,u),f}}),n=i.revoke,s=o[t];return i.revoke=()=>{o[t]=s,n()},o[t]=i.proxy,i}const ab=Symbol("Scheduled action");function HP(o,t,e=we.OnBeforeRender){let i=o[ab];i||(i=o[ab]={});const n=t.name;i[e]||(i[e]={});const s=i[e];if(s[n])return;function*l(){t==null||t.call(o),s[n]=null}const c=o.startCoroutine(l(),e);s[n]=c}const io=S("debugeventsystem");var Cm=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(Cm||{});Jv(o=>{Yt.createIfNoneExists(o)});class Yt extends I{constructor(){super(...arguments);r(this,"raycaster",[]);r(this,"pressedByID",new Map);r(this,"hoveredByID",new Map);r(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const i=new mh(this.context.input,e);this._currentPointerEventName=e.type,i.inputSource=this.context.input,i.isClick=e.isClick,i.isDoubleClick=e.isDoubleClick,i.isDown=e.type==Re.PointerDown,i.isUp=e.type==Re.PointerUp,i.isPressed=this.context.input.getPointerPressed(e.pointerId);const n=new Ds;e.hasRay?n.ray=e.ray:n.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),n.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const s=this.performRaycast(n);if(io&&(i.isDown?console.log("DOWN",{id:i.pointerId,hits:s.length}):i.isUp&&console.log("UP",{id:i.pointerId,hits:s.length}),i.isClick&&console.log("CLICK",{id:i.pointerId,hits:s.length})),s){for(const l of s)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:s})}io&&i.isClick&&Ee("EventSystem: "+i.pointerId+" - "+this.context.time.frame+" - Up:"+i.isUp+", Down:"+i.isDown);const a={sender:this,args:i,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:a})),this.handleIntersections(s,i),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:a}))});r(this,"_sortedHits",[]);r(this,"_testObjectsCache",new Map);r(this,"_currentlyActiveRaycaster",null);r(this,"_currentPointerEventName",null);r(this,"shouldRaycastObject",e=>{var a;const i=e&&"getComponent"in e?e.getComponent(qa):null;if(i&&i!=this._currentlyActiveRaycaster)return!1;let n=null;if(GP(e)&&(n=(a=e[Si])==null?void 0:a.gameObject),this._testObjectsCache.has(e)||n&&this._testObjectsCache.has(n))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let l=cu(e,this._currentPointerEventName);if(!l&&n&&(l=cu(n,this._currentPointerEventName)),l){this._testObjectsCache.set(e,!0);for(const c of e.children)this.shouldRaycastObject_AddToYesCache(c);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}});r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"out",{});r(this,"_capturedPointer",{});r(this,"pointerEnterSymbol",Symbol("pointerEnter"));r(this,"pointerExitSymbol",Symbol("pointerExit"));r(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,i,n=!1){po.update(e,i,n)}static markUIDirty(e){po.markDirty()}static createIfNoneExists(e){e.scene.getComponent(Yt)||e.scene.addComponent(Yt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(Yt)}static get instance(){return this.get(X.Current)}register(e){var i;e&&this.raycaster&&!this.raycaster.includes(e)&&((i=this.raycaster)==null||i.push(e))}unregister(e){var n,s;const i=(n=this.raycaster)==null?void 0:n.indexOf(e);i!==void 0&&i!==-1&&((s=this.raycaster)==null||s.splice(i,1))}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(qa)||this.context.scene.addComponent(Ei)}onEnable(){this.context.input.addEventListener(Re.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Re.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Re.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Re.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Re.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Re.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const i of e.children)this.shouldRaycastObject_AddToYesCache(i)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const i of this.raycaster){if(!i.activeAndEnabled)continue;this._currentlyActiveRaycaster=i;const n=i.performRaycast(e);this._currentlyActiveRaycaster=null,n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((i,n)=>i.distance-n.distance),this._sortedHits}assignHitInformation(e,i){i?(e.intersection=i,e.point=i.point,e.normal=i.normal,e.face=i.face,e.distance=i.distance,e.instanceId=i.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,i){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const a of e){if(i.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(i,a),this.handleEventOnObject(a.object,i))return!0}}this.assignHitInformation(i,e==null?void 0:e[0]),this.invokePointerCapture(i);const n=this.hoveredByID.get(i.pointerId);return n&&this.propagatePointerExit(n.obj,n.data,null),this.hoveredByID.delete(i.pointerId),i.isUp&&((s=this.pressedByID.get(i.pointerId))==null||s.handlers.forEach(a=>this.invokeOnPointerUp(i,a)),this.pressedByID.delete(i.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let i=0;i<e.length;i++){const n=e[i],s=n.object;if(s.material&&s.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(const i of this._sortingBuffer)this._noDepthTestingResults.push(i);return this._noDepthTestingResults}handleEventOnObject(e,i){if(!this.testIsVisible(e))return i.isClick&&io&&console.log("not allowed",e),!1;if(i.pointerId===void 0)return io&&console.error("Event without pointer can't be handled",i),!1;i.object=e;const n=e.parent,s=i.isClick??!1;let a=null;if(n&&n.isUI){const f=(i.isPressed||i.isClick)??!1;if(n[Si]){const p=n[Si].gameObject;if(p){if(!Eg.isInteractable(p,this.out))return!1;a=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,f),e=p}}}s&&io&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(i.pointerId),c=l==null?void 0:l.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const u=this.hoveredByID.get(i.pointerId);if(u?(u.obj=e,u.data=i):this.hoveredByID.set(i.pointerId,{obj:e,data:i}),i.isDown){const f=this.pressedByID.get(i.pointerId);f?(f.obj=e,f.data=i):this.pressedByID.set(i.pointerId,{obj:e,data:i,handlers:new Set})}return(a===null||a.interactable)&&this.handleMainInteraction(e,i,c??null),!0}propagate(e,i){for(;e;)C.foreachComponent(e,n=>{i(n)},!1),e=e.parent}handleMainInteraction(e,i,n){const s=this.pressedByID.get(i.pointerId),a=n!==e;let l=!0;switch(i.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(i.pointerId),h=this.context.input.getPointerPosition(i.pointerId);l=c&&!z.approximately(c,h);break}this.propagate(e,c=>{var u;const h=c;h.interactable!==!1&&(!h.activeAndEnabled||!h.enabled||(h.onPointerEnter&&a&&this.handlePointerEnter(h,i),i.isDown&&h.onPointerDown&&(h.onPointerDown(i),s==null||s.handlers.add(h),this.handlePointerCapture(i,h)),h.onPointerMove&&(l&&h.onPointerMove(i),this.handlePointerCapture(i,h)),i.isUp&&(h.onPointerUp&&(this.invokeOnPointerUp(i,h),s==null||s.handlers.delete(h)),h.onPointerExit&&((u=i.event)==null?void 0:u.pointerType)===Nu.Touch&&(this.handlePointerExit(h,i),this.hoveredByID.delete(i.pointerId))),i.isClick&&h.onPointerClick&&h.onPointerClick(i)))}),i.isUp&&(s==null||s.handlers.forEach(c=>{this.invokeOnPointerUp(i,c)}),this.pressedByID.delete(i.pointerId))}propagatePointerExit(e,i,n){this.propagate(e,s=>{if(!s.gameObject||s.destroyed)return;const a=s;if(a.onPointerExit||a.onPointerEnter){if(n&&this.isChild(n,s.gameObject))return;this.handlePointerExit(a,i)}})}invokeOnPointerUp(e,i){var n;(n=i.onPointerUp)==null||n.call(i,e),this.releasePointerCapture(e,i)}handlePointerEnter(e,i){e.onPointerEnter&&this.updatePointerState(e,i.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(i),this.updatePointerState(e,i.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,i){e.onPointerExit&&this.updatePointerState(e,i.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(i),this.updatePointerState(e,i.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,i,n,s){let a=e[n];if(s)return a&&a.includes(i)?!1:(a=a||[],a.push(i),e[n]=a,!0);{if(!a||!a.includes(i))return!1;const l=a.indexOf(i);return l!==-1&&a.splice(l,1),!0}}handlePointerCapture(e,i){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const n=e.pointerId;if(i.onPointerMove){const s=this._capturedPointer[n]||[];s.push(i),this._capturedPointer[n]=s}else j()&&!i.z__warned_no_pointermove&&(i.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,i))}releasePointerCapture(e,i){const n=e.pointerId;if(this._capturedPointer[n]){const s=this._capturedPointer[n].indexOf(i);s!==-1&&(this._capturedPointer[n].splice(s,1),io&&console.log("released pointer capture",n,i,this._capturedPointer))}}invokePointerCapture(e){var i;if(e.event.type===Re.PointerMove){const n=e.pointerId,s=this._capturedPointer[n];if(s){io&&console.log("Captured",n,s);for(let a=0;a<s.length;a++){const l=s[a];if(l.destroyed){s.splice(a,1),a--;continue}(i=l.onPointerMove)==null||i.call(l,e)}}}}isChild(e,i){return!e||!i?!1:e===i?!0:e.parent?this.isChild(e.parent,i):!1}handleMeshUiObjectWithoutShadowDom(e,i){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,i)}handleMeshUIIntersection(e,i){const n=po.updateState(e,i);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&po.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const i=this.currentActiveMeshUIComponents[e];po.resetState(i)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?C.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class po{static markDirty(){this.needsUpdate=!0}static update(t,e,i=!1){if(i){t.update();return}const n=e.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===e){if(n===s.frame)return;s.frame=n;let a=this.needsUpdate||n<1;s.nextUpdate<=n&&(a=!0),a&&(io&&console.log("Update threemeshui"),this.needsUpdate=!1,s.nextUpdate=n+60,t.update());return}this.lastUpdateFrame=[{context:e,frame:n,nextUpdate:n+60}],t.update(),this.needsUpdate=!1}static updateState(t,e){let i=null;if(t&&(i=this.findBlockOrTextInParent(t),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const t=this.lastSelected;t&&(this.lastSelected=null,this.resetState(t))}static resetState(t){t&&(this.needsUpdate=!0)}static findBlockOrTextInParent(t){return t?t.isBlock||t.isText?t:this.findBlockOrTextInParent(t.parent):null}}r(po,"lastSelected",null),r(po,"lastUpdateFrame",[]),r(po,"needsUpdate",!1);var qP=Object.defineProperty,Te=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&qP(t,e,n),n};const Ui=S("debugorbit"),cp=S("freecam"),Tl=S("debugcamerafit"),hd=S("smoothcam"),XP={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let hp;class Fc extends CustomEvent{constructor(t,e){super("target-reached",{detail:{controls:t,type:e}})}}class ge extends I{constructor(){super(...arguments);r(this,"autoTarget",!0);r(this,"autoFit",!1);r(this,"enableRotate",!0);r(this,"autoRotate",!1);r(this,"autoRotateSpeed",1);r(this,"minAzimuthAngle",1/0);r(this,"maxAzimuthAngle",1/0);r(this,"minPolarAngle",0);r(this,"maxPolarAngle",Math.PI);r(this,"enableKeys",!1);r(this,"enableDamping",!0);r(this,"dampingFactor",.1);r(this,"enableZoom",!0);r(this,"minZoom",0);r(this,"maxZoom",1/0);r(this,"zoomSpeed",1);r(this,"zoomToCursor",!1);r(this,"enablePan",!0);r(this,"lookAtConstraint",null);r(this,"lookAtConstraint01",1);r(this,"allowInterrupt",!0);r(this,"middleClickToFocus",!0);r(this,"doubleClickToFocus",!0);r(this,"clickBackgroundToFitScene",2);r(this,"debugLog",!1);r(this,"targetLerpDuration",1);r(this,"_controls",null);r(this,"_cameraObject",null);r(this,"_lookTargetLerpActive",!1);r(this,"_lookTargetStartPosition",new d.Vector3);r(this,"_lookTargetEndPosition",new d.Vector3);r(this,"_lookTargetLerp01",0);r(this,"_lookTargetLerpDuration",0);r(this,"_cameraLerpActive",!1);r(this,"_cameraStartPosition",new d.Vector3);r(this,"_cameraEndPosition",new d.Vector3);r(this,"_cameraLerp01",0);r(this,"_cameraLerpDuration",0);r(this,"_fovLerpActive",!1);r(this,"_fovLerpStartValue",0);r(this,"_fovLerpEndValue",0);r(this,"_fovLerp01",0);r(this,"_fovLerpDuration",0);r(this,"_inputs",0);r(this,"_enableTime",0);r(this,"_startedListeningToKeyEvents",!1);r(this,"_eventSystem");r(this,"_afterHandleInputFn");r(this,"_camera",null);r(this,"_syncedTransform");r(this,"_didSetTarget",0);r(this,"targetElement",null);r(this,"_activePointerEvents");r(this,"_lastTimeClickOnBackground",-1);r(this,"_clickOnBackgroundCount",0);r(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)});r(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)});r(this,"_onPointerUp",e=>{for(let i=this._activePointerEvents.length-1;i>=0;i--){const n=this._activePointerEvents[i];if(n.pointerId===e.pointerId&&n.button===e.button){this._activePointerEvents.splice(i,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const i=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||i<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}Ui&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}});r(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()});r(this,"_orbitStartAngle",0);r(this,"_zoomStartDistance",0);r(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()});r(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const i=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(i)<.01?(Ui&&console.debug("OrbitControls: Update target",{deltaAngle:i}),this.updateTargetNow({allowSlowRaycastFallback:!1})):Ui&&console.debug("OrbitControls: No target update",{deltaAngle:i})}});r(this,"_shouldDisable",!1);r(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))});r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var i;(i=this.controls)==null||i.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}rotateLeft(e){var i;(i=this._controls)==null||i._rotateLeft(e)}pan(e,i){var n;(n=this._controls)==null||n._pan(e,i)}zoomIn(e){var i,n;e>0?(i=this._controls)==null||i._dollyIn(1-e):e<0&&((n=this._controls)==null||n._dollyOut(1+e))}awake(){Ui&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Yt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Cm.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,i;(e=this._controls)==null||e.dispose(),(i=this._eventSystem)==null||i.removeEventListener(Cm.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=C.getComponent(this.gameObject,ai);this._camera=e;let i=e==null?void 0:e.threeCamera;if(!i&&this.gameObject instanceof d.PerspectiveCamera&&(i=this.gameObject),i&&Zp(i,this,!0),!this._controls&&i instanceof d.Object3D){this._cameraObject=i;const n=this.targetElement??this.context.renderer.domElement,s=i==null?void 0:i.quaternion.clone();this._controls=new H.OrbitControls(i,n),i==null||i.quaternion.copy(s),hp===void 0&&(hp={...this._controls.keys});const a=Q(i),l=this.gameObject.worldForward,h=a.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(h)}if(this._controls)if(cp&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=C.getComponent(this.gameObject,es)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ri.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ri.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ri.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ri.Late})}onDisable(){var e;if((e=this._camera)!=null&&e.threeCamera&&Zp(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}updateTargetNow(e){var a,l,c;const i=new d.Ray((a=this._cameraObject)==null?void 0:a.worldPosition,(l=this._cameraObject)==null?void 0:l.worldForward.multiplyScalar(-1)),n=this.context.physics.raycastFromRay(i,e),s=n.length>0?n[0]:void 0;s&&s.distance>this.minZoom&&s.distance<this.maxZoom&&(Ui&&$.DrawWireSphere(s.point,.1,16711680,2),(c=this._controls)==null||c.target.copy(n[0].point))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var i,n,s,a;if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&((i=this.context.input.getPointerPositionDelta(0))!=null&&i.length()))&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const l=C.getComponent(this.gameObject,ai);if(l&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const c=Q(l.threeCamera),h=Math.max(.01,c.length()),u=new d.Vector3(0,0,-h).applyMatrix4(l.threeCamera.matrixWorld);Ui&&$.DrawLine(c,u,5592575,10),this.setLookTargetPosition(u,!0)}if(!this.setLookTargetFromConstraint()){const c=new Ds;c.screenPoint=new d.Vector2(0,0),c.lineThreshold=.1;const h=this.context.physics.raycast(c);h.length>0&&this.setLookTargetPosition(h[0].point,!0),Tl&&console.log("OrbitControls hits",...h)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Fc(this,"camera"));else{const l=z.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,l)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Fc(this,"lookat"));else{const l=z.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,l)}if(this._fovLerpActive&&this._cameraObject){const l=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)l.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const c=z.easeInOutCubic(this._fovLerp01);l.fov=z.lerp(this._fovLerpStartValue,this._fovLerpEndValue,c)}l.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(l=>l.used),this._controls.keys=this.enableKeys?hp:XP,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,cp||(((s=(n=this._camera)==null?void 0:n.threeCamera)==null?void 0:s.type)==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof hd=="number"||hd===!0){this._controls.enableDamping=!0;const l=typeof hd=="number"?hd:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,l))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!cp&&((a=this.lookAtConstraint)!=null&&a.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),Ui&&$.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(e,i=!1){if(!e)return(j()||Ui)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof d.Object3D)&&!(e instanceof ai))return(j()||Ui)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof ai&&(e=e.gameObject);const n=e.worldPosition,s=e.worldForward;e instanceof d.Camera&&(Ui&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),s.multiplyScalar(-1));const a=new d.Ray(n,s);return Ui&&$.DrawRay(a.origin,a.direction,16711680,10),this.setTargetFromRaycast(a,i)||this.setLookTargetPosition(a.at(2,V()),i),this.setCameraTargetPosition(n,i),!0}setCameraTargetPosition(e,i=!1){var n;e&&(e instanceof d.Object3D&&(e=Q(e)),this._cameraEndPosition||(this._cameraEndPosition=new d.Vector3),this._cameraEndPosition.copy(e),i===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((n=this._cameraObject)==null?void 0:n.position),typeof i=="number"?this._cameraLerpDuration=i:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,i=!1){var s;if(!this._controls||typeof e!="number")return;const n=(s=this._camera)==null?void 0:s.threeCamera;n&&(i===!0?n.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=n.fov,this._fovLerpEndValue=e,typeof i=="number"?this._fovLerpDuration=i:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,i=!1){this._controls&&e&&(e instanceof d.Object3D&&(e=Q(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,Ui&&(console.warn("OrbitControls: setLookTargetPosition",e,i),$.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),i===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof i=="number"?this._lookTargetLerpDuration=i:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,i=1){var s,a;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const n=(a=this.lookAtConstraint)==null?void 0:a.sources;if(n&&n.length>0){const l=n[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,i),!0}return!1}lerpTarget(e,i){return this.lerpLookTarget(e,i)}lerpLookTarget(e,i){this._controls&&(i>=1?this._controls.target.copy(e):this._controls.target.lerp(e,i))}setTargetFromRaycast(e,i=!1){if(!this.controls)return!1;const n=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const s of n)if(s.distance>0&&C.isActiveInHierarchy(s.object)){const a=Tg(s.object);if(a){const l=a.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(s.point,i),!0}return!1}fitCamera(e,i){var G,B;if(this.context.isInXR)return;let n;if(Array.isArray(e)?n=e:e&&"type"in e?n=e.children:e&&typeof e=="object"&&!(e instanceof d.Object3D)&&!Array.isArray(e)&&(i=e,n=i.objects),n&&!Array.isArray(n)&&(n=n.children),(!Array.isArray(n)||n&&n.length<=0)&&(n=this.context.scene.children),!Array.isArray(n)||n.length<=0){console.warn("No objects to fit camera to...");return}const s=this._cameraObject,a=this._controls;if(!s||!a){console.warn("No camera or controls found to fit camera to objects...");return}i||(i={});const{immediate:l=!1,centerCamera:c="y",cameraNearFar:h="auto",fitOffset:u=1.1,fov:f=s==null?void 0:s.fov}=i,p=new d.Vector3,g=new d.Vector3,y=ci(n,void 0,(B=(G=this._camera)==null?void 0:G.threeCamera)==null?void 0:B.layers),b=y.clone();s.updateMatrixWorld(),s.updateProjectionMatrix(),y.getCenter(g);const _=new d.Vector3;if(y.getSize(_),y.applyMatrix4(s.matrixWorldInverse),y.getSize(p),y.setFromCenterAndSize(g,p),Number.isNaN(p.x)||Number.isNaN(p.y)||Number.isNaN(p.z)){console.warn("Camera fit size resultet in NaN",s,y,[...n]);return}if(p.length()<=1e-10){Tl&&console.warn("Camera fit size is zero",y,[...n]);return}const v=i.fov||s.fov,w=2*Math.atan(Math.tan(v*Math.PI/360/2)*s.aspect)/Math.PI*360,x=p.y/(2*Math.atan(Math.PI*v/360)),O=p.x/(2*Math.atan(Math.PI*w/360)),E=u*Math.max(x,O)+p.z/2;Tl&&console.log("Fit camera to objects",{fitHeightDistance:x,fitWidthDistance:O,distance:E,verticalFov:v,horizontalFov:w}),this.maxZoom=E*10,this.minZoom=E*.01;const M=.05,R=g.clone();if(R.y-=p.y*M,this.setLookTargetPosition(R,l),this.setFieldOfView(i.fov,l),h==null||h=="auto"){const L=C.findObjectOfType(ss),N=L?L.radius:0,Y=Math.max(_.x,_.y,_.z,N);s.near=E/100,s.far=Y+E*10,L&&(this.maxZoom=Math.max(Math.min(this.maxZoom,N*.5),E))}const F=a.getDistance();F<this.minZoom&&(this.minZoom=F*.9),F>this.maxZoom&&(this.maxZoom=F*1.1),s.updateMatrixWorld(),s.updateProjectionMatrix();const D=Q(s),A=g.clone();A.sub(D),c==="y"&&(A.y=0),A.normalize(),A.multiplyScalar(E),c==="y"&&(A.y+=-M*4*E);let T=g.clone().sub(A);s.parent&&(T=s.parent.worldToLocal(T)),this.setCameraTargetPosition(T,l),(Tl||i.debug)&&($.DrawWireBox3(y,16777011,10),$.DrawWireBox3(b,65280,10),!this._haveAttachedKeyboardEvents&&Tl&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",L=>{if(L.code==="KeyF"){let N;this._cameraObject instanceof d.PerspectiveCamera&&(N=Math.random()*Math.random()*170+10),this.fitCamera({objects:n,fitOffset:u,immediate:!1,fov:N})}L.code==="KeyV"&&this._cameraObject instanceof d.PerspectiveCamera&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}Te([m()],ge.prototype,"autoTarget");Te([m()],ge.prototype,"autoFit");Te([m()],ge.prototype,"enableRotate");Te([m()],ge.prototype,"autoRotate");Te([m()],ge.prototype,"autoRotateSpeed");Te([m()],ge.prototype,"minAzimuthAngle");Te([m()],ge.prototype,"maxAzimuthAngle");Te([m()],ge.prototype,"minPolarAngle");Te([m()],ge.prototype,"maxPolarAngle");Te([m()],ge.prototype,"enableKeys");Te([m()],ge.prototype,"enableDamping");Te([m()],ge.prototype,"dampingFactor");Te([m()],ge.prototype,"enableZoom");Te([m()],ge.prototype,"minZoom");Te([m()],ge.prototype,"maxZoom");Te([m()],ge.prototype,"zoomSpeed");Te([m()],ge.prototype,"enablePan");Te([m(Ur)],ge.prototype,"lookAtConstraint");Te([m()],ge.prototype,"lookAtConstraint01");Te([m()],ge.prototype,"allowInterrupt");Te([m()],ge.prototype,"middleClickToFocus");Te([m()],ge.prototype,"doubleClickToFocus");Te([m()],ge.prototype,"clickBackgroundToFitScene");Te([m()],ge.prototype,"targetLerpDuration");var QP=Object.defineProperty,YP=Object.getOwnPropertyDescriptor,Zt=(o,t,e,i)=>{for(var n=i>1?void 0:i?YP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QP(t,e,n),n},Cr=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))(Cr||{});const no=S("debugcam"),lb=S("debugscreenpointtoray");var pn;const Lt=(pn=class extends I{constructor(){super(...arguments);r(this,"_nearClipPlane",.1);r(this,"_farClipPlane",1e3);r(this,"orthographic",!1);r(this,"orthographicSize",5);r(this,"ARBackgroundAlpha",0);r(this,"_cullingMask",4294967295);r(this,"_backgroundBlurriness");r(this,"_backgroundIntensity");r(this,"_backgroundRotation");r(this,"_environmentIntensity");r(this,"_targetTexture",null);r(this,"_backgroundColor");r(this,"_fov");r(this,"_cam",null);r(this,"_clearFlags",2);r(this,"_skybox");r(this,"_frustum");r(this,"_projScreenMatrix",new d.Matrix4)}get isCamera(){return!0}get aspect(){return this._cam instanceof d.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof d.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof d.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const i=this.fieldOfView!=e;if(this._fov=e,i&&this._cam&&this._cam instanceof d.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const i=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(i||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const i=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(i||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new ie(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(e,i,n){const s=this.threeCamera,a=pn._origin;a.set(e,i,-1),this.context.input.convertScreenspaceToRaycastSpace(a),lb&&console.log("screenPointToRay",e.toFixed(2),i.toFixed(2),"now:",a.x.toFixed(2),a.y.toFixed(2),"isInXR:"+this.context.isInXR),a.z=-1,a.unproject(s);const l=pn._direction.set(a.x,a.y,a.z),c=Q(s);return l.sub(c),l.normalize(),n?(n.set(c,l),n):new d.Ray(c.clone(),l.clone())}getFrustum(){return this._frustum||(this._frustum=new d.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new d.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,i){return i&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}awake(){lb&&window.addEventListener("pointerdown",e=>{const i=e.clientX,n=e.clientY;console.log("touch",i.toFixed(2),n.toFixed(2));const s=this.screenPointToRay(i,n),a="#"+Math.floor(Math.random()*16777215).toString(16);$.DrawRay(s.origin,s.direction,a,10)})}onEnable(){no&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Cr[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),ZP(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const i=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),i==null||i.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let i=null;if(e?(i=this.gameObject,i==null||i.layers.enableAll(),i instanceof d.PerspectiveCamera&&(this._fov=i.fov)):i=this.gameObject.children[0],i&&i.isCamera)i instanceof d.PerspectiveCamera&&(this._fov&&(i.fov=this._fov),i.near=this._nearClipPlane,i.far=this._farClipPlane,i.updateProjectionMatrix());else if(!this.orthographic)i=new d.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(i.fov=this.fieldOfView),this.gameObject.add(i);else{const n=this.orthographicSize*100;i=new d.OrthographicCamera(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane),this.gameObject.add(i)}this._cam=i,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){var n;if(!this._cam){no&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,no){const s=`[Camera] Apply ClearFlags: ${Cr[this._clearFlags]} - "${this.name}"`;console.debug(s)}const i=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(pn.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||(e==null?void 0:e.applySkybox)===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:no&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:no&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!i){let s=this._backgroundColor.alpha;pn.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(n=this.context.xr)!=null&&n.isVR?this.context.renderer.setClearColor(S0(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||no&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:i||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new KP(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){var a,l,c,h;const i=(a=e.renderer.xr)==null?void 0:a.getSession();if(!i)return!1;if(typeof i._transparent=="boolean")return i._transparent;const n=i.environmentBlendMode;no&&Ee("Environment blend mode: "+n+" on "+navigator.userAgent);let s=n==="additive"||n==="alpha-blend";return e.isInAR&&n==="opaque"&&((l=navigator.userAgent)!=null&&l.includes("OculusBrowser")||(c=navigator.userAgent)!=null&&c.includes("Mozilla")&&((h=navigator.userAgent)!=null&&h.includes("Mobile WebXRViewer/v2")))&&(s=!0),i._transparent=s,s}},r(pn,"_origin",new d.Vector3),r(pn,"_direction",new d.Vector3),pn);Zt([m()],Lt.prototype,"aspect",1);Zt([m()],Lt.prototype,"fieldOfView",1);Zt([m()],Lt.prototype,"nearClipPlane",1);Zt([m()],Lt.prototype,"farClipPlane",1);Zt([m()],Lt.prototype,"clearFlags",1);Zt([m()],Lt.prototype,"orthographic",2);Zt([m()],Lt.prototype,"orthographicSize",2);Zt([m()],Lt.prototype,"ARBackgroundAlpha",2);Zt([m()],Lt.prototype,"cullingMask",1);Zt([m()],Lt.prototype,"backgroundBlurriness",1);Zt([m()],Lt.prototype,"backgroundIntensity",1);Zt([m(d.Euler)],Lt.prototype,"backgroundRotation",1);Zt([m()],Lt.prototype,"environmentIntensity",1);Zt([m(ie)],Lt.prototype,"backgroundColor",1);Zt([m(xr)],Lt.prototype,"targetTexture",1);let ai=Lt;class KP{constructor(t){r(this,"_camera");r(this,"_skybox");this._camera=t}get context(){var t;return(t=this._camera)==null?void 0:t.context}apply(){var t;if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");no&&console.debug(`[Camera] Apply Skybox ${(t=this._skybox)==null?void 0:t.name} ${e} - "${this._camera.name}"`),e!=null&&e.length||(this._skybox.mapping=d.EquirectangularReflectionMapping,this.context.scene.background=this._skybox)}}}function ZP(o){S("freecam")&&o.context.mainCameraComponent===o&&C.getOrAddComponent(o.gameObject,ge)}class Ms extends I{constructor(){super(...arguments);r(this,"_listener",null);r(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new d.AudioListener),this._listener}onEnable(){vn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){vn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const i=this.context.mainCameraComponent||C.getComponentInParent(this.gameObject,ai);i!=null&&i.threeCamera?i.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var JP=Object.defineProperty,eM=Object.getOwnPropertyDescriptor,Sn=(o,t,e,i)=>{for(var n=i>1?void 0:i?eM(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&JP(t,e,n),n};const gt=S("debugaudio"),Zi=class so extends I{constructor(){super(...arguments);r(this,"clip","");r(this,"playOnAwake",!1);r(this,"preload",!0);r(this,"playInBackground",!0);r(this,"_spatialBlend",0);r(this,"_minDistance",1);r(this,"_maxDistance",100);r(this,"_volume",1);r(this,"rollOffMode",0);r(this,"_loop",!1);r(this,"sound",null);r(this,"helper",null);r(this,"wasPlaying",!1);r(this,"audioLoader",null);r(this,"shouldPlay",!1);r(this,"_lastClipStartedLoading",null);r(this,"_audioElement",null);r(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":gt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,so.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&so.userInteractionRegistered&&this.wasPlaying&&this.play();break}});r(this,"onApplicationMuteChanged",()=>{var e,i;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(i=this.sound)==null||i.setVolume(this.volume)});r(this,"createAudio",e=>{if(this.destroyed){gt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}gt&&console.log("AudioBuffer finished loading",e);const i=this.Sound;if(!i){gt&&console.warn("Failed getting sound?",this.name);return}i.isPlaying&&i.stop(),e&&i.setBuffer(e),i.loop=this._loop,this.context.application.muted?i.setVolume(0):i.setVolume(this.volume),i.autoplay=this.shouldPlay&&so.userInteractionRegistered,this.applySpatialDistanceSettings(),i.isPlaying&&i.stop(),so.registerWaitForAllowAudio(this.__onAllowAudioCallback)});r(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()});r(this,"_lastContextTime",0);r(this,"_hasEnded",!0);r(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return vn.userInteractionRegistered}static registerWaitForAllowAudio(e){vn.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,i;return(i=(e=this.sound)==null?void 0:e.buffer)==null?void 0:i.duration}get time01(){var i;const e=this.duration;return e&&this.sound?((i=this.sound)==null?void 0:i.context.currentTime)/e:0}set time01(e){const i=this.duration;i&&this.sound&&(this.time=e*i)}get time(){var e,i;return(e=this.sound)!=null&&e.source?((i=this.sound.source)==null?void 0:i.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const i=this.isPlaying;this.stop(),this.sound.offset=e,i&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(gt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var e;if(!this.sound&&so.userInteractionRegistered){let i=this.gameObject.getComponent(Ms)??this.context.mainCamera.getComponent(Ms)??hh(Ms,this.context,!1);!i&&this.context.mainCamera&&(i=this.context.mainCamera.addComponent(Ms)),i!=null&&i.listener?(this.sound=new d.PositionalAudio(i.listener),(e=this.gameObject)==null||e.add(this.sound)):gt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){gt&&console.log("[AudioSource]",this),this.audioLoader=new d.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),so.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():so.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(nm.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(nm.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const i=z.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(gt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+i),e.setRefDistance(i),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?gt&&!this.helper&&(this.helper=new H.PositionalAudioHelper(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(gt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new d.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){gt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,gt&&console.log("load audio",e);const i=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),i&&this.createAudio(i)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var n,s,a;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(j()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
940
+ Could not find method ${h.method} on object ${f.name}`,f,typeof f[h.method])};if(typeof f[h.method]!="function"){let b=!1,_=f;for(;_;){const v=Object.getOwnPropertyDescriptor(_,h.method);if(v&&(v.writable===!0||v.set)){b=!0;break}_=Object.getPrototypeOf(_)}!b&&(j()||dt)&&g()}}if(f){let g=h.argument;if(g!==void 0?g=u(g):h.arguments!==void 0&&(g=h.arguments.map(u)),!f[h.method])console.warn(`EventList method not found: "${h.method}" on ${f==null?void 0:f.name}`);else{g!==void 0&&!Array.isArray(g)&&(g=[g]);const b=new Cs(f,h.method,g,h.enabled);a.push(b)}}else j()&&console.warn("[Debug] EventList: Could not find event listener in scene",h,e.object,t)}const l=new ye(a);dt&&console.log(l);const c=e.target;return c!==void 0&&e.path!==void 0&&l.setEventTarget(e.path,c),l}}}const NP=new zP,hu=new WeakMap,$P=d.Texture.prototype.clone;d.Texture.prototype.clone=function(){const o=$P.call(this);return hu.has(o)||hu.set(o,this),o};class hw extends Ki{constructor(){super([xr,d.WebGLRenderTarget])}onSerialize(t,e){}onDeserialize(t,e){if(t instanceof d.Texture&&e.type===xr){let i=t;hu.has(i)&&(i=hu.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof d.CompressedTexture&&(i.isCompressedTexture=!1,i.format=d.RGBAFormat);const n=new xr(i.image.width,i.image.height,{colorSpace:d.LinearSRGBColorSpace});return n.texture=i,n}}}new hw;class dw extends Ki{constructor(){super([URL])}onSerialize(t,e){return null}onDeserialize(t,e){if(typeof t=="string"&&t.length>0)return Eo(e.gltfId,t)}}new dw;var VP=Object.defineProperty,WP=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&VP(t,e,n),n};class qa extends I{awake(){Yt.createIfNoneExists(this.context)}onEnable(){var t;(t=Yt.get(this.context))==null||t.register(this)}onDisable(){var t;(t=Yt.get(this.context))==null||t.unregister(this)}}class Ei extends qa{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[]);r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Ds),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const i=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=s=>s instanceof d.SkinnedMesh?"continue in children":i?i(s):!0);const n=this.context.physics.raycast(e);return e.testObject=i,n}}WP([m()],Ei.prototype,"ignoreSkinnedMeshes");class Ku extends Ei{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Eu=class Eu extends qa{performRaycast(t){if(!J.active||!Eu.allow||!(t!=null&&t.ray))return null;const e=t.ray.origin;return this.context.physics.sphereOverlap(e,.015,!1,!0)}};r(Eu,"allow",!0);let Tr=Eu;class Eg{static getObject(t){const e=t[Si];return e&&(e.isComponent===!0?t=e.gameObject:t=e),t}static isInteractable(t,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),t==null||!t.visible||(t=this.getObject(t),!t.visible))return!1;const i=this.tryFindCanvasGroup(t);if((i==null?void 0:i.isCanvasGroup)===!0&&(e&&(e.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=Rr(t,s=>{if(s.isGraphic===!0)return s},!1);return e&&(n==null?void 0:n.isGraphic)===!0&&(e.graphic=n),!((n==null?void 0:n.raycastTarget)===!1||(n==null?void 0:n.layer)===2)}static tryFindCanvasGroup(t){if(!t)return null;const e=Rr(t,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return e!==void 0?e:this.tryFindCanvasGroup(t.parent)}}function Tg(o){const t=o[Si];return t||(o.parent?Tg(o.parent):null)}function GP(o){return o.isUI===!0||typeof o[Si]=="object"}function du(o,t){if(!o)return;const e=o.material;if((e==null?void 0:e.isMaterial)===!0){const i=o.parent;i&&i.isText,e.side=t.doubleSided??!0?d.DoubleSide:d.FrontSide,e.shadowSide=t.doubleSided?d.DoubleSide:d.FrontSide,o.castShadow=t.castShadows?t.castShadows:!1,o.receiveShadow=t.receiveShadows?t.receiveShadows:!1}for(const i of o.children)du(i,t)}function ma(o,t,e){o[t]===void 0&&console.warn("Field",t,"is undefined on",o);const i=Proxy.revocable(o[t],{set(a,l,c,h){const u=a[l],f=Reflect.set(a,l,c,h);return e(c,u),f}}),n=i.revoke,s=o[t];return i.revoke=()=>{o[t]=s,n()},o[t]=i.proxy,i}const ab=Symbol("Scheduled action");function HP(o,t,e=we.OnBeforeRender){let i=o[ab];i||(i=o[ab]={});const n=t.name;i[e]||(i[e]={});const s=i[e];if(s[n])return;function*l(){t==null||t.call(o),s[n]=null}const c=o.startCoroutine(l(),e);s[n]=c}const io=S("debugeventsystem");var Cm=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(Cm||{});Jv(o=>{Yt.createIfNoneExists(o)});class Yt extends I{constructor(){super(...arguments);r(this,"raycaster",[]);r(this,"pressedByID",new Map);r(this,"hoveredByID",new Map);r(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const i=new mh(this.context.input,e);this._currentPointerEventName=e.type,i.inputSource=this.context.input,i.isClick=e.isClick,i.isDoubleClick=e.isDoubleClick,i.isDown=e.type==Re.PointerDown,i.isUp=e.type==Re.PointerUp,i.isPressed=this.context.input.getPointerPressed(e.pointerId);const n=new Ds;e.hasRay?n.ray=e.ray:n.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),n.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const s=this.performRaycast(n);if(io&&(i.isDown?console.log("DOWN",{id:i.pointerId,hits:s.length}):i.isUp&&console.log("UP",{id:i.pointerId,hits:s.length}),i.isClick&&console.log("CLICK",{id:i.pointerId,hits:s.length})),s){for(const l of s)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:s})}io&&i.isClick&&Ee("EventSystem: "+i.pointerId+" - "+this.context.time.frame+" - Up:"+i.isUp+", Down:"+i.isDown);const a={sender:this,args:i,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:a})),this.handleIntersections(s,i),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:a}))});r(this,"_sortedHits",[]);r(this,"_testObjectsCache",new Map);r(this,"_currentlyActiveRaycaster",null);r(this,"_currentPointerEventName",null);r(this,"shouldRaycastObject",e=>{var a;const i=e&&"getComponent"in e?e.getComponent(qa):null;if(i&&i!=this._currentlyActiveRaycaster)return!1;let n=null;if(GP(e)&&(n=(a=e[Si])==null?void 0:a.gameObject),this._testObjectsCache.has(e)||n&&this._testObjectsCache.has(n))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let l=cu(e,this._currentPointerEventName);if(!l&&n&&(l=cu(n,this._currentPointerEventName)),l){this._testObjectsCache.set(e,!0);for(const c of e.children)this.shouldRaycastObject_AddToYesCache(c);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}});r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"out",{});r(this,"_capturedPointer",{});r(this,"pointerEnterSymbol",Symbol("pointerEnter"));r(this,"pointerExitSymbol",Symbol("pointerExit"));r(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,i,n=!1){po.update(e,i,n)}static markUIDirty(e){po.markDirty()}static createIfNoneExists(e){e.scene.getComponent(Yt)||e.scene.addComponent(Yt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(Yt)}static get instance(){return this.get(X.Current)}register(e){var i;e&&this.raycaster&&!this.raycaster.includes(e)&&((i=this.raycaster)==null||i.push(e))}unregister(e){var n,s;const i=(n=this.raycaster)==null?void 0:n.indexOf(e);i!==void 0&&i!==-1&&((s=this.raycaster)==null||s.splice(i,1))}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(qa)||this.context.scene.addComponent(Ei)}onEnable(){this.context.input.addEventListener(Re.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Re.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Re.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Re.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Re.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Re.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const i of e.children)this.shouldRaycastObject_AddToYesCache(i)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const i of this.raycaster){if(!i.activeAndEnabled)continue;this._currentlyActiveRaycaster=i;const n=i.performRaycast(e);this._currentlyActiveRaycaster=null,n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((i,n)=>i.distance-n.distance),this._sortedHits}assignHitInformation(e,i){i?(e.intersection=i,e.point=i.point,e.normal=i.normal,e.face=i.face,e.distance=i.distance,e.instanceId=i.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,i){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const a of e){if(i.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(i,a),this.handleEventOnObject(a.object,i))return!0}}this.assignHitInformation(i,e==null?void 0:e[0]),this.invokePointerCapture(i);const n=this.hoveredByID.get(i.pointerId);return n&&this.propagatePointerExit(n.obj,n.data,null),this.hoveredByID.delete(i.pointerId),i.isUp&&((s=this.pressedByID.get(i.pointerId))==null||s.handlers.forEach(a=>this.invokeOnPointerUp(i,a)),this.pressedByID.delete(i.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let i=0;i<e.length;i++){const n=e[i],s=n.object;if(s.material&&s.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(const i of this._sortingBuffer)this._noDepthTestingResults.push(i);return this._noDepthTestingResults}handleEventOnObject(e,i){if(!this.testIsVisible(e))return i.isClick&&io&&console.log("not allowed",e),!1;if(i.pointerId===void 0)return io&&console.error("Event without pointer can't be handled",i),!1;i.object=e;const n=e.parent,s=i.isClick??!1;let a=null;if(n&&n.isUI){const f=(i.isPressed||i.isClick)??!1;if(n[Si]){const p=n[Si].gameObject;if(p){if(!Eg.isInteractable(p,this.out))return!1;a=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,f),e=p}}}s&&io&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(i.pointerId),c=l==null?void 0:l.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const u=this.hoveredByID.get(i.pointerId);if(u?(u.obj=e,u.data=i):this.hoveredByID.set(i.pointerId,{obj:e,data:i}),i.isDown){const f=this.pressedByID.get(i.pointerId);f?(f.obj=e,f.data=i):this.pressedByID.set(i.pointerId,{obj:e,data:i,handlers:new Set})}return(a===null||a.interactable)&&this.handleMainInteraction(e,i,c??null),!0}propagate(e,i){for(;e;)C.foreachComponent(e,n=>{i(n)},!1),e=e.parent}handleMainInteraction(e,i,n){const s=this.pressedByID.get(i.pointerId),a=n!==e;let l=!0;switch(i.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(i.pointerId),h=this.context.input.getPointerPosition(i.pointerId);l=c&&!z.approximately(c,h);break}this.propagate(e,c=>{var u;const h=c;h.interactable!==!1&&(!h.activeAndEnabled||!h.enabled||(h.onPointerEnter&&a&&this.handlePointerEnter(h,i),i.isDown&&h.onPointerDown&&(h.onPointerDown(i),s==null||s.handlers.add(h),this.handlePointerCapture(i,h)),h.onPointerMove&&(l&&h.onPointerMove(i),this.handlePointerCapture(i,h)),i.isUp&&(h.onPointerUp&&(this.invokeOnPointerUp(i,h),s==null||s.handlers.delete(h)),h.onPointerExit&&((u=i.event)==null?void 0:u.pointerType)===Nu.Touch&&(this.handlePointerExit(h,i),this.hoveredByID.delete(i.pointerId))),i.isClick&&h.onPointerClick&&h.onPointerClick(i)))}),i.isUp&&(s==null||s.handlers.forEach(c=>{this.invokeOnPointerUp(i,c)}),this.pressedByID.delete(i.pointerId))}propagatePointerExit(e,i,n){this.propagate(e,s=>{if(!s.gameObject||s.destroyed)return;const a=s;if(a.onPointerExit||a.onPointerEnter){if(n&&this.isChild(n,s.gameObject))return;this.handlePointerExit(a,i)}})}invokeOnPointerUp(e,i){var n;(n=i.onPointerUp)==null||n.call(i,e),this.releasePointerCapture(e,i)}handlePointerEnter(e,i){e.onPointerEnter&&this.updatePointerState(e,i.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(i),this.updatePointerState(e,i.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,i){e.onPointerExit&&this.updatePointerState(e,i.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(i),this.updatePointerState(e,i.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,i,n,s){let a=e[n];if(s)return a&&a.includes(i)?!1:(a=a||[],a.push(i),e[n]=a,!0);{if(!a||!a.includes(i))return!1;const l=a.indexOf(i);return l!==-1&&a.splice(l,1),!0}}handlePointerCapture(e,i){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const n=e.pointerId;if(i.onPointerMove){const s=this._capturedPointer[n]||[];s.push(i),this._capturedPointer[n]=s}else j()&&!i.z__warned_no_pointermove&&(i.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,i))}releasePointerCapture(e,i){const n=e.pointerId;if(this._capturedPointer[n]){const s=this._capturedPointer[n].indexOf(i);s!==-1&&(this._capturedPointer[n].splice(s,1),io&&console.log("released pointer capture",n,i,this._capturedPointer))}}invokePointerCapture(e){var i;if(e.event.type===Re.PointerMove){const n=e.pointerId,s=this._capturedPointer[n];if(s){io&&console.log("Captured",n,s);for(let a=0;a<s.length;a++){const l=s[a];if(l.destroyed){s.splice(a,1),a--;continue}(i=l.onPointerMove)==null||i.call(l,e)}}}}isChild(e,i){return!e||!i?!1:e===i?!0:e.parent?this.isChild(e.parent,i):!1}handleMeshUiObjectWithoutShadowDom(e,i){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,i)}handleMeshUIIntersection(e,i){const n=po.updateState(e,i);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&po.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const i=this.currentActiveMeshUIComponents[e];po.resetState(i)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?C.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class po{static markDirty(){this.needsUpdate=!0}static update(t,e,i=!1){if(i){t.update();return}const n=e.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===e){if(n===s.frame)return;s.frame=n;let a=this.needsUpdate||n<1;s.nextUpdate<=n&&(a=!0),a&&(io&&console.log("Update threemeshui"),this.needsUpdate=!1,s.nextUpdate=n+60,t.update());return}this.lastUpdateFrame=[{context:e,frame:n,nextUpdate:n+60}],t.update(),this.needsUpdate=!1}static updateState(t,e){let i=null;if(t&&(i=this.findBlockOrTextInParent(t),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const t=this.lastSelected;t&&(this.lastSelected=null,this.resetState(t))}static resetState(t){t&&(this.needsUpdate=!0)}static findBlockOrTextInParent(t){return t?t.isBlock||t.isText?t:this.findBlockOrTextInParent(t.parent):null}}r(po,"lastSelected",null),r(po,"lastUpdateFrame",[]),r(po,"needsUpdate",!1);var qP=Object.defineProperty,Te=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&qP(t,e,n),n};const Ui=S("debugorbit"),cp=S("freecam"),Tl=S("debugcamerafit"),hd=S("smoothcam"),XP={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let hp;class Fc extends CustomEvent{constructor(t,e){super("target-reached",{detail:{controls:t,type:e}})}}class ge extends I{constructor(){super(...arguments);r(this,"autoTarget",!0);r(this,"autoFit",!1);r(this,"enableRotate",!0);r(this,"autoRotate",!1);r(this,"autoRotateSpeed",1);r(this,"minAzimuthAngle",1/0);r(this,"maxAzimuthAngle",1/0);r(this,"minPolarAngle",0);r(this,"maxPolarAngle",Math.PI);r(this,"enableKeys",!1);r(this,"enableDamping",!0);r(this,"dampingFactor",.1);r(this,"enableZoom",!0);r(this,"minZoom",0);r(this,"maxZoom",1/0);r(this,"zoomSpeed",1);r(this,"zoomToCursor",!1);r(this,"enablePan",!0);r(this,"lookAtConstraint",null);r(this,"lookAtConstraint01",1);r(this,"allowInterrupt",!0);r(this,"middleClickToFocus",!0);r(this,"doubleClickToFocus",!0);r(this,"clickBackgroundToFitScene",2);r(this,"debugLog",!1);r(this,"targetLerpDuration",1);r(this,"_controls",null);r(this,"_cameraObject",null);r(this,"_lookTargetLerpActive",!1);r(this,"_lookTargetStartPosition",new d.Vector3);r(this,"_lookTargetEndPosition",new d.Vector3);r(this,"_lookTargetLerp01",0);r(this,"_lookTargetLerpDuration",0);r(this,"_cameraLerpActive",!1);r(this,"_cameraStartPosition",new d.Vector3);r(this,"_cameraEndPosition",new d.Vector3);r(this,"_cameraLerp01",0);r(this,"_cameraLerpDuration",0);r(this,"_fovLerpActive",!1);r(this,"_fovLerpStartValue",0);r(this,"_fovLerpEndValue",0);r(this,"_fovLerp01",0);r(this,"_fovLerpDuration",0);r(this,"_inputs",0);r(this,"_enableTime",0);r(this,"_startedListeningToKeyEvents",!1);r(this,"_eventSystem");r(this,"_afterHandleInputFn");r(this,"_camera",null);r(this,"_syncedTransform");r(this,"_didSetTarget",0);r(this,"targetElement",null);r(this,"_activePointerEvents");r(this,"_lastTimeClickOnBackground",-1);r(this,"_clickOnBackgroundCount",0);r(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)});r(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)});r(this,"_onPointerUp",e=>{for(let i=this._activePointerEvents.length-1;i>=0;i--){const n=this._activePointerEvents[i];if(n.pointerId===e.pointerId&&n.button===e.button){this._activePointerEvents.splice(i,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const i=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||i<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}Ui&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}});r(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()});r(this,"_orbitStartAngle",0);r(this,"_zoomStartDistance",0);r(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()});r(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const i=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(i)<.01?(Ui&&console.debug("OrbitControls: Update target",{deltaAngle:i}),this.updateTargetNow({allowSlowRaycastFallback:!1})):Ui&&console.debug("OrbitControls: No target update",{deltaAngle:i})}});r(this,"_shouldDisable",!1);r(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))});r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var i;(i=this.controls)==null||i.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}rotateLeft(e){var i;(i=this._controls)==null||i._rotateLeft(e)}rotateUp(e){var i;(i=this._controls)==null||i._rotateUp(e)}pan(e,i){var n;(n=this._controls)==null||n._pan(e,i)}zoomIn(e){var i,n;e>0?(i=this._controls)==null||i._dollyIn(1-e):e<0&&((n=this._controls)==null||n._dollyOut(1+e))}awake(){Ui&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Yt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Cm.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,i;(e=this._controls)==null||e.dispose(),(i=this._eventSystem)==null||i.removeEventListener(Cm.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=C.getComponent(this.gameObject,ai);this._camera=e;let i=e==null?void 0:e.threeCamera;if(!i&&this.gameObject instanceof d.PerspectiveCamera&&(i=this.gameObject),i&&Zp(i,this,!0),!this._controls&&i instanceof d.Object3D){this._cameraObject=i;const n=this.targetElement??this.context.renderer.domElement,s=i==null?void 0:i.quaternion.clone();this._controls=new H.OrbitControls(i,n),i==null||i.quaternion.copy(s),hp===void 0&&(hp={...this._controls.keys});const a=Q(i),l=this.gameObject.worldForward,h=a.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(h)}if(this._controls)if(cp&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=C.getComponent(this.gameObject,es)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ri.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ri.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ri.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ri.Late})}onDisable(){var e;if((e=this._camera)!=null&&e.threeCamera&&Zp(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}updateTargetNow(e){var a,l,c;const i=new d.Ray((a=this._cameraObject)==null?void 0:a.worldPosition,(l=this._cameraObject)==null?void 0:l.worldForward.multiplyScalar(-1)),n=this.context.physics.raycastFromRay(i,e),s=n.length>0?n[0]:void 0;s&&s.distance>this.minZoom&&s.distance<this.maxZoom&&(Ui&&$.DrawWireSphere(s.point,.1,16711680,2),(c=this._controls)==null||c.target.copy(n[0].point))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var i,n,s,a;if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&((i=this.context.input.getPointerPositionDelta(0))!=null&&i.length()))&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const l=C.getComponent(this.gameObject,ai);if(l&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const c=Q(l.threeCamera),h=Math.max(.01,c.length()),u=new d.Vector3(0,0,-h).applyMatrix4(l.threeCamera.matrixWorld);Ui&&$.DrawLine(c,u,5592575,10),this.setLookTargetPosition(u,!0)}if(!this.setLookTargetFromConstraint()){const c=new Ds;c.screenPoint=new d.Vector2(0,0),c.lineThreshold=.1;const h=this.context.physics.raycast(c);h.length>0&&this.setLookTargetPosition(h[0].point,!0),Tl&&console.log("OrbitControls hits",...h)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Fc(this,"camera"));else{const l=z.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,l)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Fc(this,"lookat"));else{const l=z.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,l)}if(this._fovLerpActive&&this._cameraObject){const l=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)l.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const c=z.easeInOutCubic(this._fovLerp01);l.fov=z.lerp(this._fovLerpStartValue,this._fovLerpEndValue,c)}l.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(l=>l.used),this._controls.keys=this.enableKeys?hp:XP,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,cp||(((s=(n=this._camera)==null?void 0:n.threeCamera)==null?void 0:s.type)==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof hd=="number"||hd===!0){this._controls.enableDamping=!0;const l=typeof hd=="number"?hd:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,l))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!cp&&((a=this.lookAtConstraint)!=null&&a.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),Ui&&$.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(e,i=!1){if(!e)return(j()||Ui)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof d.Object3D)&&!(e instanceof ai))return(j()||Ui)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof ai&&(e=e.gameObject);const n=e.worldPosition,s=e.worldForward;e instanceof d.Camera&&(Ui&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),s.multiplyScalar(-1));const a=new d.Ray(n,s);return Ui&&$.DrawRay(a.origin,a.direction,16711680,10),this.setTargetFromRaycast(a,i)||this.setLookTargetPosition(a.at(2,V()),i),this.setCameraTargetPosition(n,i),!0}setCameraTargetPosition(e,i=!1){var n;e&&(e instanceof d.Object3D&&(e=Q(e)),this._cameraEndPosition||(this._cameraEndPosition=new d.Vector3),this._cameraEndPosition.copy(e),i===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((n=this._cameraObject)==null?void 0:n.position),typeof i=="number"?this._cameraLerpDuration=i:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,i=!1){var s;if(!this._controls||typeof e!="number")return;const n=(s=this._camera)==null?void 0:s.threeCamera;n&&(i===!0?n.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=n.fov,this._fovLerpEndValue=e,typeof i=="number"?this._fovLerpDuration=i:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,i=!1){this._controls&&e&&(e instanceof d.Object3D&&(e=Q(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,Ui&&(console.warn("OrbitControls: setLookTargetPosition",e,i),$.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),i===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof i=="number"?this._lookTargetLerpDuration=i:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,i=1){var s,a;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const n=(a=this.lookAtConstraint)==null?void 0:a.sources;if(n&&n.length>0){const l=n[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,i),!0}return!1}lerpTarget(e,i){return this.lerpLookTarget(e,i)}lerpLookTarget(e,i){this._controls&&(i>=1?this._controls.target.copy(e):this._controls.target.lerp(e,i))}setTargetFromRaycast(e,i=!1){if(!this.controls)return!1;const n=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const s of n)if(s.distance>0&&C.isActiveInHierarchy(s.object)){const a=Tg(s.object);if(a){const l=a.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(s.point,i),!0}return!1}fitCamera(e,i){var G,B;if(this.context.isInXR)return;let n;if(Array.isArray(e)?n=e:e&&"type"in e?n=e.children:e&&typeof e=="object"&&!(e instanceof d.Object3D)&&!Array.isArray(e)&&(i=e,n=i.objects),n&&!Array.isArray(n)&&(n=n.children),(!Array.isArray(n)||n&&n.length<=0)&&(n=this.context.scene.children),!Array.isArray(n)||n.length<=0){console.warn("No objects to fit camera to...");return}const s=this._cameraObject,a=this._controls;if(!s||!a){console.warn("No camera or controls found to fit camera to objects...");return}i||(i={});const{immediate:l=!1,centerCamera:c="y",cameraNearFar:h="auto",fitOffset:u=1.1,fov:f=s==null?void 0:s.fov}=i,p=new d.Vector3,g=new d.Vector3,y=ci(n,void 0,(B=(G=this._camera)==null?void 0:G.threeCamera)==null?void 0:B.layers),b=y.clone();s.updateMatrixWorld(),s.updateProjectionMatrix(),y.getCenter(g);const _=new d.Vector3;if(y.getSize(_),y.applyMatrix4(s.matrixWorldInverse),y.getSize(p),y.setFromCenterAndSize(g,p),Number.isNaN(p.x)||Number.isNaN(p.y)||Number.isNaN(p.z)){console.warn("Camera fit size resultet in NaN",s,y,[...n]);return}if(p.length()<=1e-10){Tl&&console.warn("Camera fit size is zero",y,[...n]);return}const v=i.fov||s.fov,w=2*Math.atan(Math.tan(v*Math.PI/360/2)*s.aspect)/Math.PI*360,x=p.y/(2*Math.atan(Math.PI*v/360)),O=p.x/(2*Math.atan(Math.PI*w/360)),E=u*Math.max(x,O)+p.z/2;Tl&&console.log("Fit camera to objects",{fitHeightDistance:x,fitWidthDistance:O,distance:E,verticalFov:v,horizontalFov:w}),this.maxZoom=E*10,this.minZoom=E*.01;const M=.05,R=g.clone();if(R.y-=p.y*M,this.setLookTargetPosition(R,l),this.setFieldOfView(i.fov,l),h==null||h=="auto"){const L=C.findObjectOfType(ss),N=L?L.radius:0,Y=Math.max(_.x,_.y,_.z,N);s.near=E/100,s.far=Y+E*10,L&&(this.maxZoom=Math.max(Math.min(this.maxZoom,N*.5),E))}const F=a.getDistance();F<this.minZoom&&(this.minZoom=F*.9),F>this.maxZoom&&(this.maxZoom=F*1.1),s.updateMatrixWorld(),s.updateProjectionMatrix();const D=Q(s),A=g.clone();A.sub(D),c==="y"&&(A.y=0),A.normalize(),A.multiplyScalar(E),c==="y"&&(A.y+=-M*4*E);let T=g.clone().sub(A);s.parent&&(T=s.parent.worldToLocal(T)),this.setCameraTargetPosition(T,l),(Tl||i.debug)&&($.DrawWireBox3(y,16777011,10),$.DrawWireBox3(b,65280,10),!this._haveAttachedKeyboardEvents&&Tl&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",L=>{if(L.code==="KeyF"){let N;this._cameraObject instanceof d.PerspectiveCamera&&(N=Math.random()*Math.random()*170+10),this.fitCamera({objects:n,fitOffset:u,immediate:!1,fov:N})}L.code==="KeyV"&&this._cameraObject instanceof d.PerspectiveCamera&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}Te([m()],ge.prototype,"autoTarget");Te([m()],ge.prototype,"autoFit");Te([m()],ge.prototype,"enableRotate");Te([m()],ge.prototype,"autoRotate");Te([m()],ge.prototype,"autoRotateSpeed");Te([m()],ge.prototype,"minAzimuthAngle");Te([m()],ge.prototype,"maxAzimuthAngle");Te([m()],ge.prototype,"minPolarAngle");Te([m()],ge.prototype,"maxPolarAngle");Te([m()],ge.prototype,"enableKeys");Te([m()],ge.prototype,"enableDamping");Te([m()],ge.prototype,"dampingFactor");Te([m()],ge.prototype,"enableZoom");Te([m()],ge.prototype,"minZoom");Te([m()],ge.prototype,"maxZoom");Te([m()],ge.prototype,"zoomSpeed");Te([m()],ge.prototype,"enablePan");Te([m(Ur)],ge.prototype,"lookAtConstraint");Te([m()],ge.prototype,"lookAtConstraint01");Te([m()],ge.prototype,"allowInterrupt");Te([m()],ge.prototype,"middleClickToFocus");Te([m()],ge.prototype,"doubleClickToFocus");Te([m()],ge.prototype,"clickBackgroundToFitScene");Te([m()],ge.prototype,"targetLerpDuration");var QP=Object.defineProperty,YP=Object.getOwnPropertyDescriptor,Zt=(o,t,e,i)=>{for(var n=i>1?void 0:i?YP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QP(t,e,n),n},Cr=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))(Cr||{});const no=S("debugcam"),lb=S("debugscreenpointtoray");var pn;const Lt=(pn=class extends I{constructor(){super(...arguments);r(this,"_nearClipPlane",.1);r(this,"_farClipPlane",1e3);r(this,"orthographic",!1);r(this,"orthographicSize",5);r(this,"ARBackgroundAlpha",0);r(this,"_cullingMask",4294967295);r(this,"_backgroundBlurriness");r(this,"_backgroundIntensity");r(this,"_backgroundRotation");r(this,"_environmentIntensity");r(this,"_targetTexture",null);r(this,"_backgroundColor");r(this,"_fov");r(this,"_cam",null);r(this,"_clearFlags",2);r(this,"_skybox");r(this,"_frustum");r(this,"_projScreenMatrix",new d.Matrix4)}get isCamera(){return!0}get aspect(){return this._cam instanceof d.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof d.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof d.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const i=this.fieldOfView!=e;if(this._fov=e,i&&this._cam&&this._cam instanceof d.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const i=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(i||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const i=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(i||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new ie(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(e,i,n){const s=this.threeCamera,a=pn._origin;a.set(e,i,-1),this.context.input.convertScreenspaceToRaycastSpace(a),lb&&console.log("screenPointToRay",e.toFixed(2),i.toFixed(2),"now:",a.x.toFixed(2),a.y.toFixed(2),"isInXR:"+this.context.isInXR),a.z=-1,a.unproject(s);const l=pn._direction.set(a.x,a.y,a.z),c=Q(s);return l.sub(c),l.normalize(),n?(n.set(c,l),n):new d.Ray(c.clone(),l.clone())}getFrustum(){return this._frustum||(this._frustum=new d.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new d.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,i){return i&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}awake(){lb&&window.addEventListener("pointerdown",e=>{const i=e.clientX,n=e.clientY;console.log("touch",i.toFixed(2),n.toFixed(2));const s=this.screenPointToRay(i,n),a="#"+Math.floor(Math.random()*16777215).toString(16);$.DrawRay(s.origin,s.direction,a,10)})}onEnable(){no&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Cr[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),ZP(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const i=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),i==null||i.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let i=null;if(e?(i=this.gameObject,i==null||i.layers.enableAll(),i instanceof d.PerspectiveCamera&&(this._fov=i.fov)):i=this.gameObject.children[0],i&&i.isCamera)i instanceof d.PerspectiveCamera&&(this._fov&&(i.fov=this._fov),i.near=this._nearClipPlane,i.far=this._farClipPlane,i.updateProjectionMatrix());else if(!this.orthographic)i=new d.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(i.fov=this.fieldOfView),this.gameObject.add(i);else{const n=this.orthographicSize*100;i=new d.OrthographicCamera(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane),this.gameObject.add(i)}this._cam=i,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){var n;if(!this._cam){no&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,no){const s=`[Camera] Apply ClearFlags: ${Cr[this._clearFlags]} - "${this.name}"`;console.debug(s)}const i=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(pn.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||(e==null?void 0:e.applySkybox)===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:no&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:no&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!i){let s=this._backgroundColor.alpha;pn.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(n=this.context.xr)!=null&&n.isVR?this.context.renderer.setClearColor(S0(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||no&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:i||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new KP(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){var a,l,c,h;const i=(a=e.renderer.xr)==null?void 0:a.getSession();if(!i)return!1;if(typeof i._transparent=="boolean")return i._transparent;const n=i.environmentBlendMode;no&&Ee("Environment blend mode: "+n+" on "+navigator.userAgent);let s=n==="additive"||n==="alpha-blend";return e.isInAR&&n==="opaque"&&((l=navigator.userAgent)!=null&&l.includes("OculusBrowser")||(c=navigator.userAgent)!=null&&c.includes("Mozilla")&&((h=navigator.userAgent)!=null&&h.includes("Mobile WebXRViewer/v2")))&&(s=!0),i._transparent=s,s}},r(pn,"_origin",new d.Vector3),r(pn,"_direction",new d.Vector3),pn);Zt([m()],Lt.prototype,"aspect",1);Zt([m()],Lt.prototype,"fieldOfView",1);Zt([m()],Lt.prototype,"nearClipPlane",1);Zt([m()],Lt.prototype,"farClipPlane",1);Zt([m()],Lt.prototype,"clearFlags",1);Zt([m()],Lt.prototype,"orthographic",2);Zt([m()],Lt.prototype,"orthographicSize",2);Zt([m()],Lt.prototype,"ARBackgroundAlpha",2);Zt([m()],Lt.prototype,"cullingMask",1);Zt([m()],Lt.prototype,"backgroundBlurriness",1);Zt([m()],Lt.prototype,"backgroundIntensity",1);Zt([m(d.Euler)],Lt.prototype,"backgroundRotation",1);Zt([m()],Lt.prototype,"environmentIntensity",1);Zt([m(ie)],Lt.prototype,"backgroundColor",1);Zt([m(xr)],Lt.prototype,"targetTexture",1);let ai=Lt;class KP{constructor(t){r(this,"_camera");r(this,"_skybox");this._camera=t}get context(){var t;return(t=this._camera)==null?void 0:t.context}apply(){var t;if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");no&&console.debug(`[Camera] Apply Skybox ${(t=this._skybox)==null?void 0:t.name} ${e} - "${this._camera.name}"`),e!=null&&e.length||(this._skybox.mapping=d.EquirectangularReflectionMapping,this.context.scene.background=this._skybox)}}}function ZP(o){S("freecam")&&o.context.mainCameraComponent===o&&C.getOrAddComponent(o.gameObject,ge)}class Ms extends I{constructor(){super(...arguments);r(this,"_listener",null);r(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new d.AudioListener),this._listener}onEnable(){vn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){vn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const i=this.context.mainCameraComponent||C.getComponentInParent(this.gameObject,ai);i!=null&&i.threeCamera?i.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var JP=Object.defineProperty,eM=Object.getOwnPropertyDescriptor,Sn=(o,t,e,i)=>{for(var n=i>1?void 0:i?eM(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&JP(t,e,n),n};const gt=S("debugaudio"),Zi=class so extends I{constructor(){super(...arguments);r(this,"clip","");r(this,"playOnAwake",!1);r(this,"preload",!0);r(this,"playInBackground",!0);r(this,"_spatialBlend",0);r(this,"_minDistance",1);r(this,"_maxDistance",100);r(this,"_volume",1);r(this,"rollOffMode",0);r(this,"_loop",!1);r(this,"sound",null);r(this,"helper",null);r(this,"wasPlaying",!1);r(this,"audioLoader",null);r(this,"shouldPlay",!1);r(this,"_lastClipStartedLoading",null);r(this,"_audioElement",null);r(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":gt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,so.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&so.userInteractionRegistered&&this.wasPlaying&&this.play();break}});r(this,"onApplicationMuteChanged",()=>{var e,i;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(i=this.sound)==null||i.setVolume(this.volume)});r(this,"createAudio",e=>{if(this.destroyed){gt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}gt&&console.log("AudioBuffer finished loading",e);const i=this.Sound;if(!i){gt&&console.warn("Failed getting sound?",this.name);return}i.isPlaying&&i.stop(),e&&i.setBuffer(e),i.loop=this._loop,this.context.application.muted?i.setVolume(0):i.setVolume(this.volume),i.autoplay=this.shouldPlay&&so.userInteractionRegistered,this.applySpatialDistanceSettings(),i.isPlaying&&i.stop(),so.registerWaitForAllowAudio(this.__onAllowAudioCallback)});r(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()});r(this,"_lastContextTime",0);r(this,"_hasEnded",!0);r(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return vn.userInteractionRegistered}static registerWaitForAllowAudio(e){vn.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,i;return(i=(e=this.sound)==null?void 0:e.buffer)==null?void 0:i.duration}get time01(){var i;const e=this.duration;return e&&this.sound?((i=this.sound)==null?void 0:i.context.currentTime)/e:0}set time01(e){const i=this.duration;i&&this.sound&&(this.time=e*i)}get time(){var e,i;return(e=this.sound)!=null&&e.source?((i=this.sound.source)==null?void 0:i.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const i=this.isPlaying;this.stop(),this.sound.offset=e,i&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(gt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var e;if(!this.sound&&so.userInteractionRegistered){let i=this.gameObject.getComponent(Ms)??this.context.mainCamera.getComponent(Ms)??hh(Ms,this.context,!1);!i&&this.context.mainCamera&&(i=this.context.mainCamera.addComponent(Ms)),i!=null&&i.listener?(this.sound=new d.PositionalAudio(i.listener),(e=this.gameObject)==null||e.add(this.sound)):gt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){gt&&console.log("[AudioSource]",this),this.audioLoader=new d.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),so.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():so.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(nm.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(nm.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const i=z.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(gt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+i),e.setRefDistance(i),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?gt&&!this.helper&&(this.helper=new H.PositionalAudioHelper(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(gt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new d.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){gt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,gt&&console.log("load audio",e);const i=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),i&&this.createAudio(i)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var n,s,a;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(j()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
941
941
  Using the assigned clip instead:`,this.clip),e=this.clip);let i=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(i=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),i){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,gt&&console.log("play",(n=this.sound)==null?void 0:n.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const l=this.context.application.muted;l&&this.sound.setVolume(0),(s=this.gameObject)==null||s.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(a=this.context.domElement.shadowRoot)==null||a.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(l?.1:0))}}pause(){var e,i;gt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,this.sound.pause()),(i=this._audioElement)==null||i.remove()}stop(){var e,i;gt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,gt&&console.log(this._lastContextTime),this.sound.stop()),(i=this._audioElement)==null||i.remove()}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,gt&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};Sn([m(URL)],Zi.prototype,"clip",2);Sn([m()],Zi.prototype,"playOnAwake",2);Sn([m()],Zi.prototype,"preload",2);Sn([m()],Zi.prototype,"playInBackground",2);Sn([m()],Zi.prototype,"loop",1);Sn([m()],Zi.prototype,"spatialBlend",1);Sn([m()],Zi.prototype,"minDistance",1);Sn([m()],Zi.prototype,"maxDistance",1);Sn([m()],Zi.prototype,"volume",1);Sn([m()],Zi.prototype,"pitch",1);Sn([m()],Zi.prototype,"rollOffMode",2);let qi=Zi;const tM=S("debugavatar"),si=class si extends I{constructor(){super(...arguments);r(this,"connectionId");r(this,"avatar")}static getAvatar(e){return e>=0&&e<si.instances.length?si.instances[e]:null}static onAvatarMarkerCreated(e){return si._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return si._onAvatarMarkerDestroyed.push(e),e}awake(){si.instances.push(this),tM&&console.log(this);for(const e of si._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){si.instances.splice(si.instances.indexOf(this),1);for(const e of si._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};r(si,"instances",[]),r(si,"_onNewAvatarMarkerAdded",[]),r(si,"_onAvatarMarkerDestroyed",[]);let At=si;class Ts{static Add(t,e,i=null){if(e){for(const n of this.Pois)if(n.obj===e)return;this.Pois.push({obj:e,avatar:i}),this.LastChangeTime=t.time.time}}static Remove(t,e){var i;if(e){for(const n of this.Pois)if(n.obj===e){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=(t==null?void 0:t.time.time)??((i=X.Current)==null?void 0:i.time.time);return}}}}r(Ts,"Pois",[]),r(Ts,"LastChangeTime",0);class iM{constructor(){r(this,"guid");r(this,"position",new d.Vector3)}}class Uc extends I{constructor(){super(...arguments);r(this,"target",null);r(this,"avatar",null);r(this,"_model",null);r(this,"_targetModel",new iM);r(this,"_currentTargetObject",null);r(this,"_lastUpdateTime",0);r(this,"_lookDuration",0);r(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const i=k.get("MoveRandom");if(i&&this.target){const n=C.getComponent(this.target,i);n&&n.destroy()}}awake(){if(this.avatar=C.getComponentInParent(this.gameObject,At),this.avatar){const e=C.getComponentInParent(this.gameObject,At);this._model=new cg(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var i;this.target&&e&&e.guid===((i=this.avatar)==null?void 0:i.guid)&&st(this.target,e.position)})}update(){var i;if((!this.context.connection.isConnected||(i=this._model)!=null&&i.hasOwnership)&&(Ts.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Ts.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const n=Q(this._currentTargetObject);st(this.target,n),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(n))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const i=Ts.Pois;if(i.length>0){const n=i[Math.floor(Math.random()*i.length)];if(n&&n.obj){if(n.avatar&&n.avatar===this.avatar)return;this._currentTargetObject=n.obj}}}}}function uw(o){const t=o;return!!(t.parser&&t.parser.json)}var Zu=(o=>(o[o.None=0]="None",o[o.DontExport=1]="DontExport",o))(Zu||{});function fw(o){return o&&o.isComponent}const nM=Symbol("object"),dp=new ki(()=>new d.Vector3,20);class pw{constructor(t,e,i,n,s,a){r(this,"_point");r(this,"_normal");r(this,"_tangentVelocity");r(this,"distance");r(this,"impulse");r(this,"friction");this._point=t,this.distance=e,this._normal=i,this.impulse=n,this.friction=s,this._tangentVelocity=a}get point(){return dp.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return dp.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return dp.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}}class mw{constructor(t,e,i){r(this,"contacts");r(this,"me");r(this,"_collider");r(this,"_gameObject");this.me=t,this._collider=e,this._gameObject=e.gameObject,this.contacts=i}get collider(){return this._collider}get gameObject(){return this._gameObject}get rigidBody(){var t;return(t=this.collider)==null?void 0:t.attachedRigidbody}}class gw{constructor(t,e){r(this,"object");r(this,"collider");this.object=t,this.collider=e}}const Ve=S("debugnetworkingstreams");var Nn=(o=>(o.Connected="peer-user-connected",o.StreamReceived="receive-stream",o.StreamEnded="call-ended",o.Disconnected="peer-user-disconnected",o.UserJoined="user-joined",o))(Nn||{});class Ag{constructor(t,e){r(this,"type","call-ended");r(this,"userId");r(this,"direction");this.userId=t,this.direction=e}}class yw{constructor(t,e,i){r(this,"type","receive-stream");r(this,"userId");r(this,"stream");r(this,"target");this.userId=t,this.stream=e,this.target=i}}class sM{constructor(t,e){r(this,"guid");r(this,"peerId");r(this,"dontSave",!0);this.guid=t.id,this.peerId=e}}var _w=(o=>(o.Incoming="incoming",o.Outgoing="outgoing",o))(_w||{});class oM extends d.EventDispatcher{constructor(e,i,n,s=null){super();r(this,"peerId");r(this,"userId");r(this,"direction");r(this,"call");r(this,"_stream",null);r(this,"_isDisposed",!1);this.peerId=i.peer,this.userId=e,this.call=i,this.direction=n,this._stream=s,i.on("stream",a=>{if(Ve&&console.log("Receive stream",`
942
942
  Audio:`,a.getAudioTracks(),`
943
943
  Video:`,a.getVideoTracks()),this._stream=a,n==="incoming"){const l=new yw(e,a,this);this.dispatchEvent(l)}}),i.on("close",()=>{this.dispatchEvent(new Ag(e,n))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),$n(this._stream))}get isOpen(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connected"}get isOpening(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}}function cb(o){return o=o.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),o}const or=class or extends d.EventDispatcher{constructor(e,i){super();r(this,"updateCalls",()=>{var e;for(let i=this._incomingCalls.length-1;i>=0;i--){const n=this._incomingCalls[i];n.isClosed&&!n.isOpening&&this._incomingCalls.splice(i,1)}for(let i=this._outgoingCalls.length-1;i>=0;i--){const n=this._outgoingCalls[i];let s=!1;n.isClosed&&!n.isOpening&&((e=n.stream)!=null&&e.active?Ve&&console.warn("!!! Stream is still active, don't remove call",n.userId,"Your id: "+this.context.connection.connectionId):(Ve&&console.warn("!!! Remove closed call",n.userId),s=!0)),this.context.connection.userIsInRoom(n.userId)===!1&&(Ve&&console.warn("!!! User is not in room anymore, remove call",n.userId),s=!0),s&&(n.close(),this._outgoingCalls.splice(i,1))}});r(this,"id");r(this,"context");r(this,"_incomingCalls",[]);r(this,"_outgoingCalls",[]);r(this,"_peer");r(this,"_enabled",!1);r(this,"_enabledPeer",!1);r(this,"onConnectRoomFn",this.onConnectRoom.bind(this));r(this,"onPeerConnect",e=>{if(Ve&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new sM(this,e))});r(this,"onPeerClose",()=>{Ve&&console.log("PEER closed"),this.updateCalls()});r(this,"onPeerDisconnected",()=>{Ve&&console.log("PEER disconnected"),this.updateCalls()});r(this,"onPeerError",e=>{Ve&&console.error("PEER error",e)});r(this,"onPeerReceivingCall",e=>{e.answer(void 0,{sdpTransform:i=>cb(i)}),this.registerCall(e,"incoming",null)});this.context=e,this.id=i,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(e,i){if(or.instances.has(i))return or.instances.get(i);const n=new or(e,i);return or.instances.set(i,n),n}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,i){var a;if(!(i!=null&&i.id)){Ve?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const n={metadata:{userId:this.context.connection.connectionId,streamId:i.id},sdpTransform:l=>cb(l)},s=(a=this._peer)==null?void 0:a.call(e,i,n);if(s){const l=this.registerCall(s,"outgoing",i);return Ve&&console.warn(`📞 CALL ${e}`,`
944
944
  Outgoing:`,this._outgoingCalls,`
945
- Incoming:`,this._incomingCalls),l}else Ve&&console.error("Failed to make call",e,i,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(ee.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(ee.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=H0(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}registerCall(e,i,n){const s=e.metadata;(!s||!s.userId)&&console.error("Missing call metadata",e);const a=s.userId;i==="incoming"&&Ve?console.warn("← Receive call from",e.metadata,e.connectionId):Ve&&console.warn("→ Make call to",e.metadata);const l=i==="incoming"?this._incomingCalls:this._outgoingCalls,c=new oM(a,e,i,n);return l.push(c),e.on("error",h=>{console.error("Call error",h)}),e.on("close",()=>{Ve&&console.log("Call ended",e.metadata);const h=l.indexOf(c);h!==-1&&l.splice(h,1),c.close(),this.dispatchEvent(new Ag(a,i))}),c.addEventListener("call-ended",h=>{this.dispatchEvent(h)}),i==="incoming"&&(c.addEventListener("receive-stream",h=>{this.dispatchEvent(h)}),e.on("stream",()=>{Ve&&console.log("Received stream for call",e.metadata);let h=0;const u=setInterval(()=>{const f=h===0;!c.isOpen&&f&&(Ve&&console.warn("Close call because stream is not active",e.metadata),h+=1,clearInterval(u),c.close())},2e3)})),c}};r(or,"instances",new Map);let ja=or;class gh extends d.EventDispatcher{constructor(e,i){super();r(this,"context");r(this,"peer");r(this,"_sendingStreams",new Map);r(this,"debug",!1);r(this,"_enabled",!1);r(this,"_tickIntervalId");r(this,"tick",()=>{this.updateSendingCalls()});r(this,"onJoinedRoom",e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e!=null&&e.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())});r(this,"onLeftRoom",e=>{this.debug&&console.warn(`${(e==null?void 0:e.userId)||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()});r(this,"onCallStreamReceived",e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()});r(this,"onCallEnded",e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()});r(this,"onUserConnected",e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const i=this._sendingStreams.keys().next().value;this.peer.makeCall(e.peerId,i)}else Ve&&console.log("Unknown user connected",e.guid,e.peerId)});r(this,"onUserLeft",e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()});if(fw(e)){const n=e;e=n.context,i=ja.getOrCreate(n.context,n.guid)}else typeof i=="string"&&(i=ja.getOrCreate(e,i));if(e){if(!(e instanceof X))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!i)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=i,Ve&&(this.debug=!0)}static create(e,i){const n=ja.getOrCreate(e.context,i||e.context.connection.connectionId||e.guid);return new gh(e.context,n)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const i=this._sendingStreams.get(e);if(i){for(const n of i)n.close();i.length=0}this._sendingStreams.delete(e),i&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ee.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ee.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(ee.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ee.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ee.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(ee.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}updateSendingCalls(){const e=this.context.connection.connectionId;for(const i of this._sendingStreams.keys()){const n=this._sendingStreams.get(i)||[];for(const s of this.context.connection.usersInRoom()){if(s===e)continue;const a=this.peer.getPeerIdFromUserId(s);if(n.find(c=>{var h;return c.peerId===a&&c.direction==="outgoing"&&!c.isClosed&&((h=c.stream)==null?void 0:h.active)}))Ve&&console.debug("Already have a call with user "+s+" / peer "+a);else{const c=this.peer.makeCall(a,i);c&&n.push(c)}}this._sendingStreams.set(i,n)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const i=this._sendingStreams.get(e);if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];this.context.connection.userIsInRoom(s.userId)?Ve&&(this.context.connection.connectionId===s.userId?console.warn(`You are still in the room [${n}] ${s.userId}`):console.log(`User is still in room [${n}] ${s.userId}`)):(Ve&&console.log(`Remove call ${[n]} to user that is not in room anymore ${s.userId}`),s.close(),i.splice(n,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function $n(o){if(o&&o instanceof MediaStream)for(const t of o.getTracks())t.stop()}var rM=Object.defineProperty,Lg=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&rM(t,e,n),n};const aM="noVoip",lM=S("debugvoip");class Do extends I{constructor(){super(...arguments);r(this,"autoConnect",!0);r(this,"runInBackground",!0);r(this,"createMenuButton",!0);r(this,"debug",!1);r(this,"_net");r(this,"_menubutton");r(this,"_allowSending",!0);r(this,"_outputStream",null);r(this,"onJoinedRoom",async()=>{this.debug&&console.log("VOIP: Joined room"),await Jn(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()});r(this,"onLeftRoom",()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())$n(e.srcObject);this._incomingStreams.clear()});r(this,"_incomingStreams",new Map);r(this,"onReceiveStream",e=>{const i=e.target.userId,n=e.stream;let s=this._incomingStreams.get(i);s||(s=new Audio,this._incomingStreams.set(i,s)),s.srcObject=n,s.setAttribute("autoplay","true"),vn.registerWaitForInteraction(()=>{s==null||s.play().catch(a=>{console.error("VOIP: Failed to play audio",a)})})});r(this,"onStreamEnded",e=>{const i=this._incomingStreams.get(e.userId);$n(i==null?void 0:i.srcObject),this._incomingStreams.delete(e.userId)});r(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const i=e[1];i.muted=!this.enabled}});r(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const i=!(document.visibilityState==="visible");this.setMuted(i);for(const n of this._incomingStreams){const s=n[1];s.muted=i}})}awake(){lM&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=gh.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Nn.StreamReceived,this.onReceiveStream),this._net.addEventListener(Nn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ee.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Nn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Nn.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable()),this.context.connection.stopListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ee.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){var e;(e=this._menubutton)==null||e.remove(),this._menubutton=void 0}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){var i,n;if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,(i=this._net)==null||i.stopSendingStream(this._outputStream),$n(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),(n=this._net)==null||n.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):nh("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||j())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){var i;e!=null&&e.remember&&(this._allowSending=!1),(i=this._net)==null||i.stopSendingStream(this._outputStream),$n(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){var n;const i=(n=this._outputStream)==null?void 0:n.getAudioTracks();if(i)for(const s of i)s.enabled=!e}get isMuted(){var i;if(this._outputStream===null)return!1;const e=(i=this._outputStream)==null?void 0:i.getAudioTracks();if(e){for(const n of e)if(!n.enabled)return!0}return!1}async updateButton(){var e;if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(i=>{i||me("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let i=(this.isSending,""),n=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(i="No Permission",n="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=i,this._menubutton.prepend(bt(n)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||(e=this._menubutton)==null||e.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,j()&&me("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const i=async s=>await navigator.mediaDevices.getUserMedia({audio:s??!0,video:!1}).catch(a=>(console.warn("VOIP failed getting audio stream",a),null)),n=await i(e);if(!n)return null;if(exports.DeviceUtilities.isiOS()&&(e==null?void 0:e.deviceId)===void 0){const a=(await navigator.mediaDevices.enumerateDevices()).find(l=>(l.kind==="audioinput"||l.kind==="audiooutput")&&!l.label.includes("iPhone"));if(a){const l=Object.assign({},e);return l.deviceId=a.deviceId,await i(l)}}return n}}Lg([m()],Do.prototype,"autoConnect");Lg([m()],Do.prototype,"runInBackground");Lg([m()],Do.prototype,"createMenuButton");var cM=Object.defineProperty,bw=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&cM(t,e,n),n};const hM=S("debugmouth");class yh extends I{constructor(){super(...arguments);r(this,"idle",[]);r(this,"talking",[]);r(this,"marker",null);r(this,"voip",null);r(this,"lastMouthChangeTime",0);r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=C.findObjectOfType(Do,this.context),this.marker||(this.marker=C.getComponentInParent(this.gameObject,At))},3e3)}update(){var n;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((n=this.marker)==null?void 0:n.connectionId)??null;if(!e){hM&&(e=null);return}const i=this.voip.getFrequency(e)??0;this.updateLips(i)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,i)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,i)}}}setMouthShapeActive(e,i){if(e){e!=this.idle?this.idle.map(n=>n.visible=!1):this.talking.map(n=>n.visible=!1);for(let n=0;n<e.length;n++){const s=e[n];s&&(s.visible=n===i)}}}}bw([m(d.Object3D)],yh.prototype,"idle");bw([m(d.Object3D)],yh.prototype,"talking");class Dg extends I{constructor(){super(...arguments);r(this,"voip",null);r(this,"marker",null);r(this,"_startPosition",null)}awake(){this.voip=C.findObjectOfType(Do,this.context),this.marker=C.getComponentInParent(this.gameObject,At)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,i=this.voip.getFrequency(e);if(i==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const n=i/100;this.gameObject.position.y=this._startPosition.y+n*.07}}var dM=Object.defineProperty,uM=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&dM(t,e,n),n};const ga=S("debugxrflags"),vw=S("disablexrflags");vw&&console.warn("XRFlags are disabled");var Bn=(o=>(o[o.Never=0]="Never",o[o.Browser=1]="Browser",o[o.AR=2]="AR",o[o.VR=4]="VR",o[o.FirstPerson=8]="FirstPerson",o[o.ThirdPerson=16]="ThirdPerson",o[o.All=4294967295]="All",o))(Bn||{});const Tu=class Tu{constructor(){r(this,"Mask",17)}Has(t){return(this.Mask&t)!==0}Set(t){ga&&console.warn("Set XR flag state to",t),this.Mask=t,$i.Apply()}Enable(t){this.Mask|=t,$i.Apply()}Disable(t){this.Mask&=~t,$i.Apply()}Toggle(t){this.Mask^=t,$i.Apply()}EnableAll(){this.Mask=-1,$i.Apply()}DisableAll(){this.Mask=0,$i.Apply()}};r(Tu,"Global",new Tu);let Qt=Tu;var Rt;const ww=(Rt=class extends I{constructor(){super(...arguments);r(this,"visibleIn")}static Apply(){for(const e of this.registry)e.UpdateVisible(Qt.Global)}awake(){Rt.registry.push(this)}onEnable(){Rt.firstApply?this.UpdateVisible(Qt.Global):(Rt.firstApply=!0,Rt.Apply())}onDestroy(){const e=Rt.registry.indexOf(this);e>=0&&Rt.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(vw)return;let i;const n=e;if(n&&typeof n=="number"&&(console.assert(typeof n=="number","XRFlag.UpdateVisible: state must be a number",n),ga&&console.log(n),Rt.buffer.Mask=n,e=Rt.buffer),e instanceof Qt?(ga&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),i=e.Has(this.visibleIn)):(ga&&console.log(this.name,"use global mask"),Qt.Global.Has(this.visibleIn)),i!==void 0)if(i)ga&&console.log(this.name,"is visible",this.gameObject.uuid),C.setActive(this.gameObject,!0);else{if(ga&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},r(Rt,"registry",[]),r(Rt,"firstApply"),r(Rt,"buffer",new Qt),Rt);uM([m()],ww.prototype,"visibleIn");let $i=ww;var fM=Object.defineProperty,Ju=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&fM(t,e,n),n};class zr extends I{constructor(){super(...arguments);r(this,"eyes",[]);r(this,"lastBlinkTime",0);r(this,"blinkLength",0);r(this,"eyesOpen",!0);r(this,"state",null)}awake(){this.state=C.getComponentInParent(this.gameObject,$i)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const i of this.eyes)i&&(i.visible=this.eyesOpen)}}}Ju([m(d.Object3D)],zr.prototype,"eyes");Ju([m()],zr.prototype,"lastBlinkTime");Ju([m()],zr.prototype,"blinkLength");Ju([m()],zr.prototype,"eyesOpen");var pM=Object.defineProperty,Ig=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&pM(t,e,n),n},hr;const ef=(hr=class extends I{constructor(){super(...arguments);r(this,"head",null);r(this,"eyes",null);r(this,"target",null);r(this,"brain",null);r(this,"vec",new d.Vector3);r(this,"currentTargetPoint",new d.Vector3)}awake(){this.brain||(this.brain=C.getComponentInParent(this.gameObject,Uc)),this.brain||(this.brain=C.addComponent(this.gameObject,Uc)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const e=this.target;if(e&&this.head){const i=this.eyes;if(i){const n=Q(e);this.currentTargetPoint.lerp(n,this.context.time.deltaTime/.1);const s=Q(this.head),a=this.vec.copy(this.currentTargetPoint).sub(s).normalize();if(a.length()<.1)return;const l=hr.forward;if(l.set(0,0,1),l.applyQuaternion(_e(this.head)),l.dot(a)>.45)for(let h=0;h<i.length;h++)i[h].lookAt(this.currentTargetPoint)}}}},r(hr,"forward",new d.Vector3(0,0,1)),hr);Ig([m(d.Object3D)],ef.prototype,"head");Ig([m(d.Object3D)],ef.prototype,"eyes");Ig([m(d.Object3D)],ef.prototype,"target");let jg=ef;var mM=Object.defineProperty,Bg=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&mM(t,e,n),n};class rl extends I{constructor(){super(...arguments);r(this,"length",1);r(this,"depthTest",!0);r(this,"isGizmo",!1);r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!rh)return;this._axes||(this._axes=new d.AxesHelper(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}Bg([m()],rl.prototype,"length");Bg([m()],rl.prototype,"depthTest");Bg([m()],rl.prototype,"isGizmo");class Fg extends I{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"hint");r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=Q(this.to).clone(),i=Q(this.from).clone(),n=e.distanceTo(i),s=e.clone();s.sub(i);const a=i.clone();a.add(e),a.multiplyScalar(.5);const l=Q(this.hint).clone();l.sub(a);const c=new d.Vector3;c.crossVectors(l,s),c.crossVectors(s,c),c.normalize();const h=n*.5,u=Math.max(this.desiredDistance,h),f=Math.sqrt(u*u-h*h),p=c.clone();p.multiplyScalar(f),p.add(a),st(this.gameObject,p);const g=a.clone();g.sub(c),this.gameObject.lookAt(g)}}const gM=S("gizmos"),yM=S("debugboxhelper"),$t=class $t extends I{constructor(){super(...arguments);r(this,"box",null);r(this,"_lastMatrixUpdateFrame",-1);r(this,"_helper",null);r(this,"_color",null)}isInBox(e){var n;if(!e)return;if(this.box||(this.box=new d.Box3),ci([e],void 0,void 0,$t.testBox),$t.testBox.isEmpty()){const s=Q(e,$t._position);$t.testBox.setFromCenterAndSize(s,$t._emptyObjectSize)}this.updateBox();const i=(n=this.box)==null?void 0:n.intersectsBox($t.testBox);return i&&yM&&$.DrawWireBox3($t.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new d.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const i=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const n=i,s=Q(this.gameObject,$t._position,n),a=Ue(this.gameObject,$t._size);this.box.setFromCenterAndSize(s,a)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,i=!1){var n;if(!(!gM&&!i)){if(this._helper){e&&((n=this._color)==null||n.set(e)),this.gameObject.add(this._helper);return}this._helper=dg(e),this.gameObject.add(this._helper)}}};r($t,"testBox",new d.Box3),r($t,"_position",new d.Vector3),r($t,"_size",new d.Vector3(.01,.01,.01)),r($t,"_emptyObjectSize",new d.Vector3(.01,.01,.01));let ts=$t;var _M=Object.defineProperty,di=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&_M(t,e,n),n};class ui extends I{constructor(){super(...arguments);r(this,"attachedRigidbody",null);r(this,"isTrigger",!1);r(this,"sharedMaterial");r(this,"membership",[0]);r(this,"filter");r(this,"updateProperties",()=>{var e;(e=this.context.physics.engine)==null||e.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ot))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ot))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ot))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}get body(){var e;return(e=this.context.physics.engine)==null?void 0:e.getBody(this)}updatePhysicsMaterial(){var e;(e=this.context.physics.engine)==null||e.updatePhysicsMaterial(this)}}di([m(ot)],ui.prototype,"attachedRigidbody");di([m()],ui.prototype,"isTrigger");di([m()],ui.prototype,"sharedMaterial");di([m()],ui.prototype,"membership");di([m()],ui.prototype,"filter");class al extends ui{constructor(){super(...arguments);r(this,"radius",.5);r(this,"center",new d.Vector3(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this),ju(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Wm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}di([Ct(),m()],al.prototype,"radius");di([m(d.Vector3)],al.prototype,"center");const Ug=class xw extends ui{constructor(){super(...arguments);r(this,"size",new d.Vector3(1,1,1));r(this,"center",new d.Vector3(0,0,0))}static add(e,i){const n=Oi(e,xw);return n.autoFit(),(i==null?void 0:i.rigidbody)===!0&&Oi(e,ot,{isKinematic:!1}),n}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.size),ju(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Wm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const i=this.gameObject,n=i.position.clone(),s=i.quaternion.clone(),a=i.scale.clone(),l=i.parent;i.position.set(0,0,0),i.quaternion.set(0,0,0,1),i.scale.set(1,1,1),i.parent=null,i.updateMatrix();const c=ci([i]);i.position.copy(n),i.quaternion.copy(s),i.scale.copy(a),i.parent=l,(e==null?void 0:e.debug)===!0&&$.DrawWireBox3(c,16768256,20),this.size=c.getSize(new d.Vector3)||new d.Vector3(1,1,1),this.center=c.getCenter(new d.Vector3)||new d.Vector3(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};di([Ct(),m(d.Vector3)],Ug.prototype,"size");di([m(d.Vector3)],Ug.prototype,"center");let tf=Ug;class Io extends ui{constructor(){super(...arguments);r(this,"sharedMesh");r(this,"convex",!1)}onEnable(){var i,n,s;if(super.onEnable(),!this.context.physics.engine)return;(i=this.sharedMesh)!=null&&i.isMesh||(this.gameObject instanceof d.Mesh||this.gameObject instanceof d.Group)&&(this.sharedMesh=this.gameObject);const e=0;if((n=this.sharedMesh)!=null&&n.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),le.NEEDLE_progressive.assignMeshLOD(this.sharedMesh,e).then(a=>{a&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=a,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const a=this.sharedMesh;if(a!=null&&a.isGroup){console.warn(`MeshCollider mesh is a group "${((s=this.sharedMesh)==null?void 0:s.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const l=new Array;for(const c in a.children){const h=a.children[c];h.isMesh&&(this.context.physics.engine.addMeshCollider(this,h,this.convex),l.push(le.NEEDLE_progressive.assignMeshLOD(h,e)))}Promise.all(l).then(c=>{var u,f;if(c.some(p=>p)==!1)return;(u=this.context.physics.engine)==null||u.removeBody(this);const h=new d.Mesh;for(const p of c)p&&this.activeAndEnabled&&(h.geometry=p,(f=this.context.physics.engine)==null||f.addMeshCollider(this,h,this.convex))})}else(j()||S("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}di([m(d.Mesh)],Io.prototype,"sharedMesh");di([m()],Io.prototype,"convex");class As extends ui{constructor(){super(...arguments);r(this,"center",new d.Vector3(0,0,0));r(this,"radius",.5);r(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.height,this.radius)}}di([m(d.Vector3)],As.prototype,"center");di([m()],As.prototype,"radius");di([m()],As.prototype,"height");var bM=Object.defineProperty,Is=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bM(t,e,n),n};const hb=S("debugcharactercontroller");class Nr extends I{constructor(){super(...arguments);r(this,"center",new d.Vector3(0,0,0));r(this,"radius",.5);r(this,"height",2);r(this,"_rigidbody",null);r(this,"_activeGroundCollisions");r(this,"_contactVelocity",new d.Vector3)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(ot),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(ot)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let i=this.gameObject.getComponent(As);i||(i=this.gameObject.addComponent(As)),i.center.copy(this.center),i.radius=this.radius,i.height=this.height;const n=new d.Vector3(0,0,1),s=new d.Vector3(1,0,0),a=new d.Vector3(0,1,0),l=this.gameObject.getWorldDirection(new d.Vector3);l.y=0;const c=s.dot(l)<0?-1:1,h=n.angleTo(l)*c;this.gameObject.setRotationFromAxisAngle(a,h),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(i=>i.normal.y>.2))&&(this._activeGroundCollisions.add(e),hb&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(i=>i.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),hb&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var e;this._contactVelocity.set(0,0,0);for(const i of this._activeGroundCollisions){const n=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(i.collider);n&&(this._contactVelocity.x+=n.x,this._contactVelocity.y+=n.y,this._contactVelocity.z+=n.z)}return this._contactVelocity}}Is([m(d.Vector3)],Nr.prototype,"center");Is([m()],Nr.prototype,"radius");Is([m()],Nr.prototype,"height");class js extends I{constructor(){super(...arguments);r(this,"controller");r(this,"movementSpeed",2);r(this,"rotationSpeed",2);r(this,"jumpForce",1);r(this,"doubleJumpForce",2);r(this,"animator");r(this,"lookForward",!0);r(this,"lookInput",new d.Vector2(0,0));r(this,"moveInput",new d.Vector2(0,0));r(this,"jumpInput",!1);r(this,"_currentSpeed",new d.Vector3(0,0,0));r(this,"_currentAngularSpeed",new d.Vector3(0,0,0));r(this,"_temp",new d.Vector3(0,0,0));r(this,"_jumpCount",0);r(this,"_currentRotation");r(this,"_raycastOptions",new Ds)}awake(){this._currentRotation=new d.Quaternion}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=e.isKeyDown("Space"))}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}handleInput(e,i,n){var s,a,l,c,h,u,f,p,g,y,b;if((s=this.controller)!=null&&s.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((a=this.animator)==null||a.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(l=this.animator)==null||l.setBool("running",e.length()>.01),(h=this.animator)==null||h.setBool("jumping",((c=this.controller)==null?void 0:c.isGrounded)===!0&&n),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=z.toRadians(-i.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const _=this.context.mainCameraComponent.forward;_.y=0,_.normalize(),this._currentRotation.setFromUnitVectors(new d.Vector3(0,0,1),_),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&n&&this.jumpForce>0){let _=(u=this.controller)==null?void 0:u.isGrounded;if(this.doubleJumpForce>0&&!((f=this.controller)!=null&&f.isGrounded)&&this._jumpCount===1&&(_=!0,(p=this.animator)==null||p.setBool("doubleJump",!0)),_){this._jumpCount+=1;const v=this.controller.rigidbody,w=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;v.applyImpulse(new d.Vector3(0,1,0).multiplyScalar(w))}}if(this.controller){const _=(g=this.controller)==null?void 0:g.rigidbody.getVelocity().y;if(_<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new d.Ray),this._raycastOptions.ray.origin.copy(Q(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const v=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const w=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(v),(w.length&&w[0].distance>2||_<-10)&&((y=this.animator)==null||y.setBool("falling",!0))}else(b=this.animator)==null||b.setBool("falling",!1)}}}Is([m(Nr)],js.prototype,"controller");Is([m()],js.prototype,"movementSpeed");Is([m()],js.prototype,"rotationSpeed");Is([m()],js.prototype,"jumpForce");Is([m()],js.prototype,"doubleJumpForce");Is([m(St)],js.prototype,"animator");var vM=Object.defineProperty,ll=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&vM(t,e,n),n};const Al=S("debugcontactshadows");Mg(o=>{const t=o.domElement.getAttribute("contactshadows")||o.domElement.getAttribute("contact-shadows");if(t!=null&&t!="0"&&t!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const e=_h.auto(o),i=parseFloat(t);isNaN(i)||(e.opacity=i,e.darkness=i)}});var Gn;const $r=(Gn=class extends I{constructor(){super(...arguments);r(this,"autoFit",!1);r(this,"darkness",.5);r(this,"opacity",.5);r(this,"blur",4);r(this,"occludeBelowGround",!1);r(this,"backfaceShadows",!0);r(this,"minSize");r(this,"manualUpdate",!1);r(this,"_needsUpdate",!1);r(this,"shadowsRoot",new d.Object3D);r(this,"shadowCamera");r(this,"shadowGroup",new d.Group);r(this,"renderTarget");r(this,"renderTargetBlur");r(this,"plane");r(this,"occluderMesh");r(this,"blurPlane");r(this,"depthMaterial");r(this,"horizontalBlurMaterial");r(this,"verticalBlurMaterial");r(this,"textureSize",512)}static auto(e){if(e||(e=X.Current),!e)throw new Error("No context provided and no current context set.");let i=this._instances.get(e);if(!i||i.destroyed){const n=new d.Object3D;i=Oi(n,Gn,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(e,i)}return e.scene.add(i.gameObject),i.fitShadows(),i}set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}fitShadows(){Al&&console.warn("Fitting shadows to scene"),Hd(this.shadowsRoot,!1);const e=ci(this.context.scene.children,[this.shadowsRoot]),i=Math.max(1,this.blur/32),n=e.max.x-e.min.x,s=e.max.z-e.min.z;e.expandByVector(new d.Vector3(i*n,0,i*s)),Al&&$.DrawWireBox3(e,16776960,60),this.gameObject.parent&&e.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const a=e.min,l=Math.max(1e-5,(e.max.y-a.y)*.002);e.max.y+=l,this.shadowsRoot.position.set((a.x+e.max.x)/2,a.y-l,(a.z+e.max.z)/2),this.shadowsRoot.scale.set(e.max.x-a.x,e.max.y-a.y,e.max.z-a.z),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,Al&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){Gn._instances.set(this.context,this),this.shadowsRoot.hideFlags=Zu.DontExport,Hd(this.shadowsRoot,!1)}start(){Al&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new d.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new d.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new d.PlaneGeometry(1,1).rotateX(Math.PI/2);this.gameObject instanceof d.Mesh&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),xs(this.gameObject,!1));const i=new d.MeshBasicMaterial({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:d.FrontSide});this.plane=new d.Mesh(e,i),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new d.Mesh(this.plane.geometry,new d.MeshBasicMaterial({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:d.BackSide})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new d.Mesh(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const n=0,s=1;this.shadowCamera=new d.OrthographicCamera(-1/2,1/2,1/2,-1/2,n,s),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new d.MeshDepthMaterial,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=d.CustomBlending,this.depthMaterial.blendEquation=d.MaxEquation,this.depthMaterial.onBeforeCompile=a=>{this.depthMaterial&&(a.uniforms.darkness=this.depthMaterial.userData.darkness,a.fragmentShader=`
945
+ Incoming:`,this._incomingCalls),l}else Ve&&console.error("Failed to make call",e,i,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(ee.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(ee.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=H0(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}registerCall(e,i,n){const s=e.metadata;(!s||!s.userId)&&console.error("Missing call metadata",e);const a=s.userId;i==="incoming"&&Ve?console.warn("← Receive call from",e.metadata,e.connectionId):Ve&&console.warn("→ Make call to",e.metadata);const l=i==="incoming"?this._incomingCalls:this._outgoingCalls,c=new oM(a,e,i,n);return l.push(c),e.on("error",h=>{console.error("Call error",h)}),e.on("close",()=>{Ve&&console.log("Call ended",e.metadata);const h=l.indexOf(c);h!==-1&&l.splice(h,1),c.close(),this.dispatchEvent(new Ag(a,i))}),c.addEventListener("call-ended",h=>{this.dispatchEvent(h)}),i==="incoming"&&(c.addEventListener("receive-stream",h=>{this.dispatchEvent(h)}),e.on("stream",()=>{Ve&&console.log("Received stream for call",e.metadata);let h=0;const u=setInterval(()=>{const f=h===0;!c.isOpen&&f&&(Ve&&console.warn("Close call because stream is not active",e.metadata),h+=1,clearInterval(u),c.close())},2e3)})),c}};r(or,"instances",new Map);let ja=or;class gh extends d.EventDispatcher{constructor(e,i){super();r(this,"context");r(this,"peer");r(this,"_sendingStreams",new Map);r(this,"debug",!1);r(this,"_enabled",!1);r(this,"_tickIntervalId");r(this,"tick",()=>{this.updateSendingCalls()});r(this,"onJoinedRoom",e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e!=null&&e.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())});r(this,"onLeftRoom",e=>{this.debug&&console.warn(`${(e==null?void 0:e.userId)||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()});r(this,"onCallStreamReceived",e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()});r(this,"onCallEnded",e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()});r(this,"onUserConnected",e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const i=this._sendingStreams.keys().next().value;this.peer.makeCall(e.peerId,i)}else Ve&&console.log("Unknown user connected",e.guid,e.peerId)});r(this,"onUserLeft",e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()});if(fw(e)){const n=e;e=n.context,i=ja.getOrCreate(n.context,n.guid)}else typeof i=="string"&&(i=ja.getOrCreate(e,i));if(e){if(!(e instanceof X))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!i)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=i,Ve&&(this.debug=!0)}static create(e,i){const n=ja.getOrCreate(e.context,i||e.context.connection.connectionId||e.guid);return new gh(e.context,n)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const i=this._sendingStreams.get(e);if(i){for(const n of i)n.close();i.length=0}this._sendingStreams.delete(e),i&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ee.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ee.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(ee.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ee.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ee.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(ee.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}updateSendingCalls(){const e=this.context.connection.connectionId;for(const i of this._sendingStreams.keys()){const n=this._sendingStreams.get(i)||[];for(const s of this.context.connection.usersInRoom()){if(s===e)continue;const a=this.peer.getPeerIdFromUserId(s);if(n.find(c=>{var h;return c.peerId===a&&c.direction==="outgoing"&&!c.isClosed&&((h=c.stream)==null?void 0:h.active)}))Ve&&console.debug("Already have a call with user "+s+" / peer "+a);else{const c=this.peer.makeCall(a,i);c&&n.push(c)}}this._sendingStreams.set(i,n)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const i=this._sendingStreams.get(e);if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];this.context.connection.userIsInRoom(s.userId)?Ve&&(this.context.connection.connectionId===s.userId?console.warn(`You are still in the room [${n}] ${s.userId}`):console.log(`User is still in room [${n}] ${s.userId}`)):(Ve&&console.log(`Remove call ${[n]} to user that is not in room anymore ${s.userId}`),s.close(),i.splice(n,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function $n(o){if(o&&o instanceof MediaStream)for(const t of o.getTracks())t.stop()}var rM=Object.defineProperty,Lg=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&rM(t,e,n),n};const aM="noVoip",lM=S("debugvoip");class Do extends I{constructor(){super(...arguments);r(this,"autoConnect",!0);r(this,"runInBackground",!0);r(this,"createMenuButton",!0);r(this,"debug",!1);r(this,"_net");r(this,"_menubutton");r(this,"_allowSending",!0);r(this,"_outputStream",null);r(this,"onJoinedRoom",async()=>{this.debug&&console.log("VOIP: Joined room"),await Jn(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()});r(this,"onLeftRoom",()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())$n(e.srcObject);this._incomingStreams.clear()});r(this,"_incomingStreams",new Map);r(this,"onReceiveStream",e=>{const i=e.target.userId,n=e.stream;let s=this._incomingStreams.get(i);s||(s=new Audio,this._incomingStreams.set(i,s)),s.srcObject=n,s.setAttribute("autoplay","true"),vn.registerWaitForInteraction(()=>{s==null||s.play().catch(a=>{console.error("VOIP: Failed to play audio",a)})})});r(this,"onStreamEnded",e=>{const i=this._incomingStreams.get(e.userId);$n(i==null?void 0:i.srcObject),this._incomingStreams.delete(e.userId)});r(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const i=e[1];i.muted=!this.enabled}});r(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const i=!(document.visibilityState==="visible");this.setMuted(i);for(const n of this._incomingStreams){const s=n[1];s.muted=i}})}awake(){lM&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=gh.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Nn.StreamReceived,this.onReceiveStream),this._net.addEventListener(Nn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ee.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Nn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Nn.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable()),this.context.connection.stopListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ee.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){var e;(e=this._menubutton)==null||e.remove(),this._menubutton=void 0}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){var i,n;if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,(i=this._net)==null||i.stopSendingStream(this._outputStream),$n(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),(n=this._net)==null||n.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):nh("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||j())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){var i;e!=null&&e.remember&&(this._allowSending=!1),(i=this._net)==null||i.stopSendingStream(this._outputStream),$n(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){var n;const i=(n=this._outputStream)==null?void 0:n.getAudioTracks();if(i)for(const s of i)s.enabled=!e}get isMuted(){var i;if(this._outputStream===null)return!1;const e=(i=this._outputStream)==null?void 0:i.getAudioTracks();if(e){for(const n of e)if(!n.enabled)return!0}return!1}async updateButton(){var e;if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(i=>{i||me("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let i=(this.isSending,""),n=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(i="No Permission",n="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=i,this._menubutton.prepend(_t(n)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||(e=this._menubutton)==null||e.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,j()&&me("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const i=async s=>await navigator.mediaDevices.getUserMedia({audio:s??!0,video:!1}).catch(a=>(console.warn("VOIP failed getting audio stream",a),null)),n=await i(e);if(!n)return null;if(exports.DeviceUtilities.isiOS()&&(e==null?void 0:e.deviceId)===void 0){const a=(await navigator.mediaDevices.enumerateDevices()).find(l=>(l.kind==="audioinput"||l.kind==="audiooutput")&&!l.label.includes("iPhone"));if(a){const l=Object.assign({},e);return l.deviceId=a.deviceId,await i(l)}}return n}}Lg([m()],Do.prototype,"autoConnect");Lg([m()],Do.prototype,"runInBackground");Lg([m()],Do.prototype,"createMenuButton");var cM=Object.defineProperty,bw=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&cM(t,e,n),n};const hM=S("debugmouth");class yh extends I{constructor(){super(...arguments);r(this,"idle",[]);r(this,"talking",[]);r(this,"marker",null);r(this,"voip",null);r(this,"lastMouthChangeTime",0);r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=C.findObjectOfType(Do,this.context),this.marker||(this.marker=C.getComponentInParent(this.gameObject,At))},3e3)}update(){var n;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((n=this.marker)==null?void 0:n.connectionId)??null;if(!e){hM&&(e=null);return}const i=this.voip.getFrequency(e)??0;this.updateLips(i)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,i)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,i)}}}setMouthShapeActive(e,i){if(e){e!=this.idle?this.idle.map(n=>n.visible=!1):this.talking.map(n=>n.visible=!1);for(let n=0;n<e.length;n++){const s=e[n];s&&(s.visible=n===i)}}}}bw([m(d.Object3D)],yh.prototype,"idle");bw([m(d.Object3D)],yh.prototype,"talking");class Dg extends I{constructor(){super(...arguments);r(this,"voip",null);r(this,"marker",null);r(this,"_startPosition",null)}awake(){this.voip=C.findObjectOfType(Do,this.context),this.marker=C.getComponentInParent(this.gameObject,At)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,i=this.voip.getFrequency(e);if(i==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const n=i/100;this.gameObject.position.y=this._startPosition.y+n*.07}}var dM=Object.defineProperty,uM=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&dM(t,e,n),n};const ga=S("debugxrflags"),vw=S("disablexrflags");vw&&console.warn("XRFlags are disabled");var Bn=(o=>(o[o.Never=0]="Never",o[o.Browser=1]="Browser",o[o.AR=2]="AR",o[o.VR=4]="VR",o[o.FirstPerson=8]="FirstPerson",o[o.ThirdPerson=16]="ThirdPerson",o[o.All=4294967295]="All",o))(Bn||{});const Tu=class Tu{constructor(){r(this,"Mask",17)}Has(t){return(this.Mask&t)!==0}Set(t){ga&&console.warn("Set XR flag state to",t),this.Mask=t,$i.Apply()}Enable(t){this.Mask|=t,$i.Apply()}Disable(t){this.Mask&=~t,$i.Apply()}Toggle(t){this.Mask^=t,$i.Apply()}EnableAll(){this.Mask=-1,$i.Apply()}DisableAll(){this.Mask=0,$i.Apply()}};r(Tu,"Global",new Tu);let Qt=Tu;var Rt;const ww=(Rt=class extends I{constructor(){super(...arguments);r(this,"visibleIn")}static Apply(){for(const e of this.registry)e.UpdateVisible(Qt.Global)}awake(){Rt.registry.push(this)}onEnable(){Rt.firstApply?this.UpdateVisible(Qt.Global):(Rt.firstApply=!0,Rt.Apply())}onDestroy(){const e=Rt.registry.indexOf(this);e>=0&&Rt.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(vw)return;let i;const n=e;if(n&&typeof n=="number"&&(console.assert(typeof n=="number","XRFlag.UpdateVisible: state must be a number",n),ga&&console.log(n),Rt.buffer.Mask=n,e=Rt.buffer),e instanceof Qt?(ga&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),i=e.Has(this.visibleIn)):(ga&&console.log(this.name,"use global mask"),Qt.Global.Has(this.visibleIn)),i!==void 0)if(i)ga&&console.log(this.name,"is visible",this.gameObject.uuid),C.setActive(this.gameObject,!0);else{if(ga&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},r(Rt,"registry",[]),r(Rt,"firstApply"),r(Rt,"buffer",new Qt),Rt);uM([m()],ww.prototype,"visibleIn");let $i=ww;var fM=Object.defineProperty,Ju=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&fM(t,e,n),n};class zr extends I{constructor(){super(...arguments);r(this,"eyes",[]);r(this,"lastBlinkTime",0);r(this,"blinkLength",0);r(this,"eyesOpen",!0);r(this,"state",null)}awake(){this.state=C.getComponentInParent(this.gameObject,$i)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const i of this.eyes)i&&(i.visible=this.eyesOpen)}}}Ju([m(d.Object3D)],zr.prototype,"eyes");Ju([m()],zr.prototype,"lastBlinkTime");Ju([m()],zr.prototype,"blinkLength");Ju([m()],zr.prototype,"eyesOpen");var pM=Object.defineProperty,Ig=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&pM(t,e,n),n},hr;const ef=(hr=class extends I{constructor(){super(...arguments);r(this,"head",null);r(this,"eyes",null);r(this,"target",null);r(this,"brain",null);r(this,"vec",new d.Vector3);r(this,"currentTargetPoint",new d.Vector3)}awake(){this.brain||(this.brain=C.getComponentInParent(this.gameObject,Uc)),this.brain||(this.brain=C.addComponent(this.gameObject,Uc)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const e=this.target;if(e&&this.head){const i=this.eyes;if(i){const n=Q(e);this.currentTargetPoint.lerp(n,this.context.time.deltaTime/.1);const s=Q(this.head),a=this.vec.copy(this.currentTargetPoint).sub(s).normalize();if(a.length()<.1)return;const l=hr.forward;if(l.set(0,0,1),l.applyQuaternion(_e(this.head)),l.dot(a)>.45)for(let h=0;h<i.length;h++)i[h].lookAt(this.currentTargetPoint)}}}},r(hr,"forward",new d.Vector3(0,0,1)),hr);Ig([m(d.Object3D)],ef.prototype,"head");Ig([m(d.Object3D)],ef.prototype,"eyes");Ig([m(d.Object3D)],ef.prototype,"target");let jg=ef;var mM=Object.defineProperty,Bg=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&mM(t,e,n),n};class rl extends I{constructor(){super(...arguments);r(this,"length",1);r(this,"depthTest",!0);r(this,"isGizmo",!1);r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!rh)return;this._axes||(this._axes=new d.AxesHelper(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}Bg([m()],rl.prototype,"length");Bg([m()],rl.prototype,"depthTest");Bg([m()],rl.prototype,"isGizmo");class Fg extends I{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"hint");r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=Q(this.to).clone(),i=Q(this.from).clone(),n=e.distanceTo(i),s=e.clone();s.sub(i);const a=i.clone();a.add(e),a.multiplyScalar(.5);const l=Q(this.hint).clone();l.sub(a);const c=new d.Vector3;c.crossVectors(l,s),c.crossVectors(s,c),c.normalize();const h=n*.5,u=Math.max(this.desiredDistance,h),f=Math.sqrt(u*u-h*h),p=c.clone();p.multiplyScalar(f),p.add(a),st(this.gameObject,p);const g=a.clone();g.sub(c),this.gameObject.lookAt(g)}}const gM=S("gizmos"),yM=S("debugboxhelper"),$t=class $t extends I{constructor(){super(...arguments);r(this,"box",null);r(this,"_lastMatrixUpdateFrame",-1);r(this,"_helper",null);r(this,"_color",null)}isInBox(e){var n;if(!e)return;if(this.box||(this.box=new d.Box3),ci([e],void 0,void 0,$t.testBox),$t.testBox.isEmpty()){const s=Q(e,$t._position);$t.testBox.setFromCenterAndSize(s,$t._emptyObjectSize)}this.updateBox();const i=(n=this.box)==null?void 0:n.intersectsBox($t.testBox);return i&&yM&&$.DrawWireBox3($t.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new d.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const i=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const n=i,s=Q(this.gameObject,$t._position,n),a=Ue(this.gameObject,$t._size);this.box.setFromCenterAndSize(s,a)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,i=!1){var n;if(!(!gM&&!i)){if(this._helper){e&&((n=this._color)==null||n.set(e)),this.gameObject.add(this._helper);return}this._helper=dg(e),this.gameObject.add(this._helper)}}};r($t,"testBox",new d.Box3),r($t,"_position",new d.Vector3),r($t,"_size",new d.Vector3(.01,.01,.01)),r($t,"_emptyObjectSize",new d.Vector3(.01,.01,.01));let ts=$t;var _M=Object.defineProperty,di=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&_M(t,e,n),n};class ui extends I{constructor(){super(...arguments);r(this,"attachedRigidbody",null);r(this,"isTrigger",!1);r(this,"sharedMaterial");r(this,"membership",[0]);r(this,"filter");r(this,"updateProperties",()=>{var e;(e=this.context.physics.engine)==null||e.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ot))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ot))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ot))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}get body(){var e;return(e=this.context.physics.engine)==null?void 0:e.getBody(this)}updatePhysicsMaterial(){var e;(e=this.context.physics.engine)==null||e.updatePhysicsMaterial(this)}}di([m(ot)],ui.prototype,"attachedRigidbody");di([m()],ui.prototype,"isTrigger");di([m()],ui.prototype,"sharedMaterial");di([m()],ui.prototype,"membership");di([m()],ui.prototype,"filter");class al extends ui{constructor(){super(...arguments);r(this,"radius",.5);r(this,"center",new d.Vector3(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this),ju(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Wm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}di([St(),m()],al.prototype,"radius");di([m(d.Vector3)],al.prototype,"center");const Ug=class xw extends ui{constructor(){super(...arguments);r(this,"size",new d.Vector3(1,1,1));r(this,"center",new d.Vector3(0,0,0))}static add(e,i){const n=Oi(e,xw);return n.autoFit(),(i==null?void 0:i.rigidbody)===!0&&Oi(e,ot,{isKinematic:!1}),n}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.size),ju(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Wm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const i=this.gameObject,n=i.position.clone(),s=i.quaternion.clone(),a=i.scale.clone(),l=i.parent;i.position.set(0,0,0),i.quaternion.set(0,0,0,1),i.scale.set(1,1,1),i.parent=null,i.updateMatrix();const c=ci([i]);i.position.copy(n),i.quaternion.copy(s),i.scale.copy(a),i.parent=l,(e==null?void 0:e.debug)===!0&&$.DrawWireBox3(c,16768256,20),this.size=c.getSize(new d.Vector3)||new d.Vector3(1,1,1),this.center=c.getCenter(new d.Vector3)||new d.Vector3(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};di([St(),m(d.Vector3)],Ug.prototype,"size");di([m(d.Vector3)],Ug.prototype,"center");let tf=Ug;class Io extends ui{constructor(){super(...arguments);r(this,"sharedMesh");r(this,"convex",!1)}onEnable(){var i,n,s;if(super.onEnable(),!this.context.physics.engine)return;(i=this.sharedMesh)!=null&&i.isMesh||(this.gameObject instanceof d.Mesh||this.gameObject instanceof d.Group)&&(this.sharedMesh=this.gameObject);const e=0;if((n=this.sharedMesh)!=null&&n.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),le.NEEDLE_progressive.assignMeshLOD(this.sharedMesh,e).then(a=>{a&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=a,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const a=this.sharedMesh;if(a!=null&&a.isGroup){console.warn(`MeshCollider mesh is a group "${((s=this.sharedMesh)==null?void 0:s.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const l=new Array;for(const c in a.children){const h=a.children[c];h.isMesh&&(this.context.physics.engine.addMeshCollider(this,h,this.convex),l.push(le.NEEDLE_progressive.assignMeshLOD(h,e)))}Promise.all(l).then(c=>{var u,f;if(c.some(p=>p)==!1)return;(u=this.context.physics.engine)==null||u.removeBody(this);const h=new d.Mesh;for(const p of c)p&&this.activeAndEnabled&&(h.geometry=p,(f=this.context.physics.engine)==null||f.addMeshCollider(this,h,this.convex))})}else(j()||S("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}di([m(d.Mesh)],Io.prototype,"sharedMesh");di([m()],Io.prototype,"convex");class As extends ui{constructor(){super(...arguments);r(this,"center",new d.Vector3(0,0,0));r(this,"radius",.5);r(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.height,this.radius)}}di([m(d.Vector3)],As.prototype,"center");di([m()],As.prototype,"radius");di([m()],As.prototype,"height");var bM=Object.defineProperty,Is=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bM(t,e,n),n};const hb=S("debugcharactercontroller");class Nr extends I{constructor(){super(...arguments);r(this,"center",new d.Vector3(0,0,0));r(this,"radius",.5);r(this,"height",2);r(this,"_rigidbody",null);r(this,"_activeGroundCollisions");r(this,"_contactVelocity",new d.Vector3)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(ot),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(ot)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let i=this.gameObject.getComponent(As);i||(i=this.gameObject.addComponent(As)),i.center.copy(this.center),i.radius=this.radius,i.height=this.height;const n=new d.Vector3(0,0,1),s=new d.Vector3(1,0,0),a=new d.Vector3(0,1,0),l=this.gameObject.getWorldDirection(new d.Vector3);l.y=0;const c=s.dot(l)<0?-1:1,h=n.angleTo(l)*c;this.gameObject.setRotationFromAxisAngle(a,h),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(i=>i.normal.y>.2))&&(this._activeGroundCollisions.add(e),hb&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(i=>i.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),hb&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var e;this._contactVelocity.set(0,0,0);for(const i of this._activeGroundCollisions){const n=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(i.collider);n&&(this._contactVelocity.x+=n.x,this._contactVelocity.y+=n.y,this._contactVelocity.z+=n.z)}return this._contactVelocity}}Is([m(d.Vector3)],Nr.prototype,"center");Is([m()],Nr.prototype,"radius");Is([m()],Nr.prototype,"height");class js extends I{constructor(){super(...arguments);r(this,"controller");r(this,"movementSpeed",2);r(this,"rotationSpeed",2);r(this,"jumpForce",1);r(this,"doubleJumpForce",2);r(this,"animator");r(this,"lookForward",!0);r(this,"lookInput",new d.Vector2(0,0));r(this,"moveInput",new d.Vector2(0,0));r(this,"jumpInput",!1);r(this,"_currentSpeed",new d.Vector3(0,0,0));r(this,"_currentAngularSpeed",new d.Vector3(0,0,0));r(this,"_temp",new d.Vector3(0,0,0));r(this,"_jumpCount",0);r(this,"_currentRotation");r(this,"_raycastOptions",new Ds)}awake(){this._currentRotation=new d.Quaternion}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=e.isKeyDown("Space"))}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}handleInput(e,i,n){var s,a,l,c,h,u,f,p,g,y,b;if((s=this.controller)!=null&&s.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((a=this.animator)==null||a.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(l=this.animator)==null||l.setBool("running",e.length()>.01),(h=this.animator)==null||h.setBool("jumping",((c=this.controller)==null?void 0:c.isGrounded)===!0&&n),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=z.toRadians(-i.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const _=this.context.mainCameraComponent.forward;_.y=0,_.normalize(),this._currentRotation.setFromUnitVectors(new d.Vector3(0,0,1),_),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&n&&this.jumpForce>0){let _=(u=this.controller)==null?void 0:u.isGrounded;if(this.doubleJumpForce>0&&!((f=this.controller)!=null&&f.isGrounded)&&this._jumpCount===1&&(_=!0,(p=this.animator)==null||p.setBool("doubleJump",!0)),_){this._jumpCount+=1;const v=this.controller.rigidbody,w=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;v.applyImpulse(new d.Vector3(0,1,0).multiplyScalar(w))}}if(this.controller){const _=(g=this.controller)==null?void 0:g.rigidbody.getVelocity().y;if(_<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new d.Ray),this._raycastOptions.ray.origin.copy(Q(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const v=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const w=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(v),(w.length&&w[0].distance>2||_<-10)&&((y=this.animator)==null||y.setBool("falling",!0))}else(b=this.animator)==null||b.setBool("falling",!1)}}}Is([m(Nr)],js.prototype,"controller");Is([m()],js.prototype,"movementSpeed");Is([m()],js.prototype,"rotationSpeed");Is([m()],js.prototype,"jumpForce");Is([m()],js.prototype,"doubleJumpForce");Is([m(xt)],js.prototype,"animator");var vM=Object.defineProperty,ll=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&vM(t,e,n),n};const Al=S("debugcontactshadows");Mg(o=>{const t=o.domElement.getAttribute("contactshadows")||o.domElement.getAttribute("contact-shadows");if(t!=null&&t!="0"&&t!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const e=_h.auto(o),i=parseFloat(t);isNaN(i)||(e.opacity=i,e.darkness=i)}});var Gn;const $r=(Gn=class extends I{constructor(){super(...arguments);r(this,"autoFit",!1);r(this,"darkness",.5);r(this,"opacity",.5);r(this,"blur",4);r(this,"occludeBelowGround",!1);r(this,"backfaceShadows",!0);r(this,"minSize");r(this,"manualUpdate",!1);r(this,"_needsUpdate",!1);r(this,"shadowsRoot",new d.Object3D);r(this,"shadowCamera");r(this,"shadowGroup",new d.Group);r(this,"renderTarget");r(this,"renderTargetBlur");r(this,"plane");r(this,"occluderMesh");r(this,"blurPlane");r(this,"depthMaterial");r(this,"horizontalBlurMaterial");r(this,"verticalBlurMaterial");r(this,"textureSize",512)}static auto(e){if(e||(e=X.Current),!e)throw new Error("No context provided and no current context set.");let i=this._instances.get(e);if(!i||i.destroyed){const n=new d.Object3D;i=Oi(n,Gn,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(e,i)}return e.scene.add(i.gameObject),i.fitShadows(),i}set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}fitShadows(){Al&&console.warn("Fitting shadows to scene"),Hd(this.shadowsRoot,!1);const e=ci(this.context.scene.children,[this.shadowsRoot]),i=Math.max(1,this.blur/32),n=e.max.x-e.min.x,s=e.max.z-e.min.z;e.expandByVector(new d.Vector3(i*n,0,i*s)),Al&&$.DrawWireBox3(e,16776960,60),this.gameObject.parent&&e.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const a=e.min,l=Math.max(1e-5,(e.max.y-a.y)*.002);e.max.y+=l,this.shadowsRoot.position.set((a.x+e.max.x)/2,a.y-l,(a.z+e.max.z)/2),this.shadowsRoot.scale.set(e.max.x-a.x,e.max.y-a.y,e.max.z-a.z),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,Al&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){Gn._instances.set(this.context,this),this.shadowsRoot.hideFlags=Zu.DontExport,Hd(this.shadowsRoot,!1)}start(){Al&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new d.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new d.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new d.PlaneGeometry(1,1).rotateX(Math.PI/2);this.gameObject instanceof d.Mesh&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),xs(this.gameObject,!1));const i=new d.MeshBasicMaterial({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:d.FrontSide});this.plane=new d.Mesh(e,i),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new d.Mesh(this.plane.geometry,new d.MeshBasicMaterial({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:d.BackSide})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new d.Mesh(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const n=0,s=1;this.shadowCamera=new d.OrthographicCamera(-1/2,1/2,1/2,-1/2,n,s),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new d.MeshDepthMaterial,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=d.CustomBlending,this.depthMaterial.blendEquation=d.MaxEquation,this.depthMaterial.onBeforeCompile=a=>{this.depthMaterial&&(a.uniforms.darkness=this.depthMaterial.userData.darkness,a.fragmentShader=`
946
946
  uniform float darkness;
947
947
  ${a.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
948
948
  `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new d.ShaderMaterial(H.HorizontalBlurShader),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new d.ShaderMaterial(H.VerticalBlurShader),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){var i,n,s,a,l,c,h,u;Gn._instances.get(this.context)===this&&Gn._instances.delete(this.context),(i=this.renderTarget)==null||i.dispose(),(n=this.renderTargetBlur)==null||n.dispose(),(s=this.depthMaterial)==null||s.dispose(),(a=this.horizontalBlurMaterial)==null||a.dispose(),(l=this.verticalBlurMaterial)==null||l.dispose(),(c=this.blurPlane)==null||c.geometry.dispose(),(h=this.plane)==null||h.geometry.dispose(),(u=this.occluderMesh)==null||u.geometry.dispose()}onBeforeRender(e){if(this.manualUpdate&&!this._needsUpdate)return;if(this._needsUpdate=!1,!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){Al&&console.error("ContactShadows: not initialized yet");return}const i=this.context.scene,n=this.context.renderer,s=n.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const a=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof d.Mesh&&xs(this.gameObject,!1);const l=i.background;i.background=null,i.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=d.DoubleSide:this.depthMaterial.side=d.FrontSide;const c=n.getClearAlpha();n.setClearAlpha(0);const h=n.xr.enabled;n.xr.enabled=!1;const u=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const f=n.renderLists.get(i,0),p=f.transparent;db.length=0,f.transparent=db,up.length=0;for(const y of f.opaque){if(!y.object.visible)continue;const b=y.material;let _=y.material.colorWrite==!1||b.wireframe===!0||k0(y.object)===!1;!_&&y.material.isLineMaterial&&(_=!0),!_&&y.material.isPointsMaterial&&(_=!0),_&&(up.push(y.object),y.object["needle:visible"]=y.object.visible,y.object.visible=!1)}n.setRenderTarget(this.renderTarget),n.clear(),n.render(i,this.shadowCamera),f.transparent=p;for(const y of up)y["needle:visible"]!=null&&(y.visible=y["needle:visible"]);i.overrideMaterial=null;const g=Math.max(this.blur,.05);this.blurShadow(g*2),this.blurShadow(g*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=a,n.setRenderTarget(s),n.setClearAlpha(c),i.background=l,n.xr.enabled=h,this.context.scene.matrixWorldAutoUpdate=u}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const i=this.shadowsRoot.worldScale,n=(i.x+i.z)/2,s=i.z/n,a=i.x/n;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*s;const l=this.context.renderer,c=l.getRenderTarget();l.setRenderTarget(this.renderTargetBlur),l.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*a,l.setRenderTarget(this.renderTarget),l.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,l.setRenderTarget(c)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}},r(Gn,"_instances",new Map),Gn);ll([m()],$r.prototype,"autoFit");ll([m()],$r.prototype,"darkness");ll([m()],$r.prototype,"opacity");ll([m()],$r.prototype,"blur");ll([m()],$r.prototype,"occludeBelowGround");ll([m()],$r.prototype,"backfaceShadows");let _h=$r;const db=[],up=new Array,wM=S("logstats");class zg extends I{onEnable(){console.log(this),wM&&this.startCoroutine(this.run(),we.OnAfterRender)}*run(){for(;this.enabled;){const t=this.context.renderer.info;console.log(t.memory,t.render,t.programs),yield}}}class bh extends I{constructor(){super(...arguments);r(this,"isUsed",!0);r(this,"usedBy",null)}}class Ng extends I{}const ub=S("debugdeletable"),ka=class ka extends ts{onEnable(){ka._instances.push(this)}onDisable(){const t=ka._instances.indexOf(this);t>=0&&ka._instances.splice(t,1)}};r(ka,"_instances",[]);let Xa=ka;class $g extends I{update(){for(const t of Xa._instances){const e=this.gameObject;if(t.isInBox(e)===!0){const n=C.getComponentInParent(this.gameObject,bh);if(n)ub&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,n);else{if(ub)try{if(t.box){const s=t.box,a=ts.testBox;$.DrawWireBox3(s,16711680,5),$.DrawWireBox3(a,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:s,deletedObjectArea:a})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}oh(this.gameObject,this.context.connection)}}}}}var xM=Object.defineProperty,SM=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&xM(t,e,n),n};class nf extends I{constructor(){super(...arguments);r(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||C.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:exports.DeviceUtilities.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}SM([m()],nf.prototype,"visibleOn");var CM=Object.defineProperty,Vr=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&CM(t,e,n),n};const Vn=S("debugdrag"),fp=[];var Vg=(o=>(o[o.XZPlane=0]="XZPlane",o[o.Attached=1]="Attached",o[o.HitNormal=2]="HitNormal",o[o.DynamicViewAngle=3]="DynamicViewAngle",o[o.SnapToSurfaces=4]="SnapToSurfaces",o[o.None=5]="None",o))(Vg||{}),nt;const jo=(nt=class extends I{constructor(){super(...arguments);r(this,"dragMode",3);r(this,"snapGridResolution",0);r(this,"keepRotation",!0);r(this,"xrDragMode",1);r(this,"xrKeepRotation",!1);r(this,"xrDistanceDragFactor",1);r(this,"showGizmo",!1);r(this,"_rigidbody",null);r(this,"_targetObject",null);r(this,"_dragHelper",null);r(this,"_draggingRigidbodies",[]);r(this,"_potentialDragStartEvt",null);r(this,"_dragHandlers",new Map);r(this,"_totalMovement",new d.Vector3);r(this,"_marker",null);r(this,"_isDragging",!1);r(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}static get CurrentlySelected(){fp.length=0;for(const e of this._instances)e._isDragging&&fp.push(e);return fp}get draggedObject(){return this._targetObject}setTargetObject(e){var n,s;this._targetObject=e;for(const a of this._dragHandlers.values())a.setTargetObject(e);const i="_rigidbody-was-kinematic";((n=this._rigidbody)==null?void 0:n[i])===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[i]=void 0),this._rigidbody=null,e&&(this._rigidbody=C.getComponentInChildren(e,ot),((s=this._rigidbody)==null?void 0:s.isKinematic)===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[i]=!1))}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new d.Vector3,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei)}onEnable(){nt._instances.push(this)}onDisable(){nt._instances=nt._instances.filter(e=>e!==this)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||e.mode!=="screen"||(e.event.mode==="tracked-pointer"||e.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const s=C.getComponentInParent(e.object,nt);!s||s!==this||(nt.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerExit(e){this.allowEdit(this.gameObject)&&e.mode==="screen"&&nt.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(e){if(!(!this.allowEdit(this.gameObject)||e.used||(e.mode==="tracked-pointer"||e.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(nt.lastHovered=e.object,e.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=e),this._targetObject||this.setTargetObject(this.gameObject),nt._active+=1;const s=new pp(this,this._targetObject);if(this._dragHandlers.set(e.event.space,s),s.onDragStart(e),this._dragHandlers.size===2){const a=this._dragHandlers.values(),l=a.next().value,c=a.next().value;if(l instanceof pp&&c instanceof pp){const h=new PM(this,this._targetObject,l,c);this._dragHandlers.set(this.gameObject,h),h.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:l,b:c})}e.use()}}onPointerUp(e){if(Vn&&$.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const i=this._dragHandlers.get(e.event.space),n=this._dragHandlers.get(this.gameObject);n&&(n.handlerA===i||n.handlerB===i)&&(this._dragHandlers.delete(this.gameObject),n.onDragEnd(e)),i&&(nt._active>0&&(nt._active-=1),this.setTargetObject(null),i.onDragEnd&&i.onDragEnd(e),this._dragHandlers.delete(e.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(e),e.use())}update(){for(const e of this._dragHandlers.values())e.collectMovementInfo&&e.collectMovementInfo(),e.getTotalMovement&&this._totalMovement.add(e.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const e=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(e)}for(const e of this._dragHandlers.values())e.onDragUpdate&&e.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(e){if(!e||!e.object)return;const i=C.getComponentInParent(e.object,nt);if(!i||i!==this&&i._isDragging)return;const n=this._targetObject||this.gameObject;if(!n)return;this._isDragging=!0;const s=C.getComponentInChildren(n,es);Vn&&console.log("DRAG START",s,n),s&&(s.fastMode=!0,s==null||s.requestOwnership()),this._marker=C.addComponent(n,bh),this._draggingRigidbodies.length=0;const a=C.getComponentsInChildren(n,ot);a&&this._draggingRigidbodies.push(...a)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const i of this._draggingRigidbodies)i.wakeUp(),i.resetVelocities(),i.resetForcesAndTorques();const e=this._targetObject||this.gameObject;Wi.markDirty(e)}onLastDragEnd(e){if(!this||!this._isDragging)return;this._isDragging=!1;for(const n of this._draggingRigidbodies)n.setVelocity(n.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,e!=null&&e.object){const n=C.getComponentInChildren(e.object,es);n&&(n.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const i=this._dragHelper.selected;Vn&&console.log("DRAG END",i,i==null?void 0:i.visible),this._dragHelper.setSelected(null,this.context)}},r(nt,"_active",0),r(nt,"_instances",[]),r(nt,"lastHovered"),nt);Vr([m()],jo.prototype,"dragMode");Vr([m()],jo.prototype,"snapGridResolution");Vr([m()],jo.prototype,"keepRotation");Vr([m()],jo.prototype,"xrDragMode");Vr([m()],jo.prototype,"xrKeepRotation");Vr([m()],jo.prototype,"xrDistanceDragFactor");Vr([m()],jo.prototype,"showGizmo");let lr=jo;class PM{constructor(t,e,i,n){r(this,"handlerA");r(this,"handlerB");r(this,"context");r(this,"settings");r(this,"gameObject");r(this,"_handlerAAttachmentPoint",new d.Vector3);r(this,"_handlerBAttachmentPoint",new d.Vector3);r(this,"_followObject");r(this,"_manipulatorObject");r(this,"_deviceMode");r(this,"_followObjectStartWorldQuaternion",new d.Quaternion);r(this,"_manipulatorPosOffset",new d.Vector3);r(this,"_manipulatorRotOffset",new d.Quaternion);r(this,"_manipulatorScaleOffset",new d.Vector3);r(this,"_tempVec1",new d.Vector3);r(this,"_tempVec2",new d.Vector3);r(this,"_tempVec3",new d.Vector3);r(this,"tempLookMatrix",new d.Matrix4);r(this,"_initialScale",new d.Vector3);r(this,"_initialDistance",0);var a,l;this.context=t.context,this.settings=t,this.gameObject=e,this.handlerA=i,this.handlerB=n,this._followObject=new d.Object3D,this._manipulatorObject=new d.Object3D,this.context.scene.add(this._manipulatorObject);const s=(l=(a=J.active)==null?void 0:a.rig)==null?void 0:l.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),s&&(s.worldToLocal(this._tempVec1),s.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(Vn&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now – controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(e.scale),Vn){this._followObject.add(new d.AxesHelper(2)),this._manipulatorObject.add(new d.AxesHelper(5));const c=h=>`${h.x.toFixed(2)}, ${h.y.toFixed(2)}, ${h.z.toFixed(2)}`;$.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),$.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
@@ -963,7 +963,7 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
963
963
 
964
964
  Content-Type: "${e.headers.get("content-type")}
965
965
  "Text: "${n}"
966
- Binary:`,i)}else console.debug("Could not determine file type from binary data");return"unknown"}var OM=Object.defineProperty,cl=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&OM(t,e,n),n};const vi=S("debugdroplistener");class kM extends CustomEvent{constructor(t){super("object-added",{detail:t})}}const RM="blob";class Bs extends I{constructor(){super(...arguments);r(this,"useNetworking",!0);r(this,"dropArea");r(this,"fitIntoVolume",!1);r(this,"fitVolumeSize",new d.Vector3(1,1,1));r(this,"placeAtHitPosition",!0);r(this,"onDropped",new ye);r(this,"onNetworkEvent",e=>{var i;if(!this.useNetworking){vi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if((i=e.guid)!=null&&i.startsWith(this.guid)){const n=e.url;if(console.debug("[DropListener] Received networked event",e),n)if(Array.isArray(n))for(const s of n)this.addFromUrl(s,{screenposition:new d.Vector2,point:e.point,size:e.size},!0);else this.addFromUrl(n,{screenposition:new d.Vector2,point:e.point,size:e.size},!0)}});r(this,"handlePaste",e=>{if(this.context.connection.allowEditing===!1||e.defaultPrevented)return;navigator.clipboard.readText().then(n=>{if(n&&(n.startsWith("http")||n.startsWith("https")||n.startsWith("blob"))){const a={screenposition:new d.Vector2(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(a)&&this.addFromUrl(n,a,!1)}}).catch(console.warn)});r(this,"onDrag",e=>{this.context.connection.allowEditing!==!1&&e.preventDefault()});r(this,"onDrop",async e=>{if(this.context.connection.allowEditing===!1||(vi&&console.log(e),!(e!=null&&e.dataTransfer))||e["droplistener:handled"])return;e.preventDefault();const i={screenposition:new d.Vector2(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(i)===!1)return;e["droplistener:handled"]=!0;const n=e.dataTransfer.items;if(!n)return;const s=[];for(const a in n){const l=n[a];if(l.kind==="file"){const c=l.getAsFile();if(!c)continue;s.push(c)}else l.kind==="string"&&l.type=="text/plain"&&l.getAsString(c=>{this.addFromUrl(c,i,!1)})}s.length>0&&await this.addDroppedFiles(s,i)});r(this,"_abort",null);r(this,"_addedObjects",new Array);r(this,"_addedModels",new Array)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent)}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}loadFromURL(e,i){this.addFromUrl(e,{screenposition:new d.Vector2,point:i==null?void 0:i.point,size:i==null?void 0:i.size},!0)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}async addFromUrl(e,i,n){vi&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const l=e.split("/"),c=l[3],h=l[4],u=l[6],f=l.slice(7).join("/");e=`https://raw.githubusercontent.com/${c}/${h}/${u}/${f}`}else e.startsWith("https://polyhaven.com/a")&&(e=EM(e));if(!e)return null;const s=e.toLowerCase();if(s.endsWith(".hdr")||s.endsWith(".hdri")||s.endsWith(".exr")||s.endsWith(".png")||s.endsWith(".jpg")||s.endsWith(".jpeg"))return null;this.removePreviouslyAddedObjects();const a=await uu.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:i.point,size:i.size});if(a&&this._addedObjects.length<=0)return i.url=e,this.addObject(a,i,n)}catch{console.warn("String is not a valid URL",e)}return null}async addDroppedFiles(e,i){var n,s;if(vi&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Oc(RM,null),(n=this._abort)==null||n.abort("New files dropped"),this._abort=new AbortController;for(const a of e){if(!a)continue;if(a.type.startsWith("image/")){vi&&console.warn("Ignoring dropped image file",a.name,a.type);continue}else if(a.name.endsWith(".bin")){vi&&console.warn("Ignoring dropped binary file",a.name,a.type);continue}console.debug("Load file "+a.name+" + "+a.type);const l=await uu.loadFile(a,this.context,{guid:this.guid});if(l){this.dispatchEvent(new CustomEvent("file-dropped",{detail:a})),i.file=a;const c=this.addObject(l,i,!1);c&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),exports.BlobStorage.upload(a,{abort:(s=this._abort)==null?void 0:s.signal}).then(h=>{h!=null&&h.download_url&&this._addedObjects.includes(c)&&this.sendDropEvent(h.download_url,c,l.contentMD5)}).catch(console.warn));break}}}}removePreviouslyAddedObjects(e=!0){if(e)for(const i of this._addedObjects)i.parent===this.gameObject&&Ri(i,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}addObject(e,i,n){var u,f;const{model:s,contentMD5:a}=e;if(vi&&console.log(`Dropped ${this.gameObject.name}`,s),!(s!=null&&s.scene))return console.warn("No object specified to add to scene",s),null;this.removePreviouslyAddedObjects();const l=s.scene;this.gameObject.attach(l),l.position.set(0,0,0),l.quaternion.identity(),this._addedObjects.push(l),this._addedModels.push(s);const c=new d.Box3().setFromCenterAndSize(new d.Vector3(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(vi&&$.DrawWireBox3(c,255,5),this.fitIntoVolume&&R0(l,c,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&i&&i.screenposition){l.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(i.screenposition.clone())});if(l.visible=!0,p&&p.length>0)for(const g of p){const y=g.point.clone();vi&&console.log("Place object at hit",g),E0(l,y);break}}Ha.assignAnimationsFromFile(s,{createAnimationComponent:p=>Oi(p,Tt)});const h=new kM({sender:this,gltf:s,model:s,object:l,contentMD5:a,dropped:i.file||(i.url?new URL(i.url):void 0)});return this.dispatchEvent(h),(u=this.onDropped)==null||u.invoke(h.detail),!n&&((f=i.url)!=null&&f.startsWith("http"))&&this.context.connection.isConnected&&l&&this.sendDropEvent(i.url,l,a),l}async sendDropEvent(e,i,n){if(!this.useNetworking){vi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+i.name+'"',e);const s=ci([i]),a={name:i.name,guid:this.guid,url:e,point:i.worldPosition.clone(),size:s.getSize(new d.Vector3),contentMD5:n};this.context.connection.send("droplistener",a)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){if(this.dropArea){const i=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:i,recursive:!0,testObject:s=>!this._addedObjects.includes(s)}).length)return j()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}cl([m()],Bs.prototype,"useNetworking");cl([m(d.Object3D)],Bs.prototype,"dropArea");cl([m()],Bs.prototype,"fitIntoVolume");cl([m(d.Vector3)],Bs.prototype,"fitVolumeSize");cl([m()],Bs.prototype,"placeAtHitPosition");cl([m(ye)],Bs.prototype,"onDropped");function EM(o){if(!o.startsWith("https://polyhaven.com/"))return o;const t="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",n=new URL(o).pathname.split("/").pop(),s=`${t}${n}/${n}_4k.gltf`;return console.log("Resolved polyhaven asset url",o,"→",s),s}var uu;(o=>{async function t(i,n,s){const a=s.guid,l=new vt(a),c=new Blob([i],{type:i.type||Cw(i.name)||void 0}),h=URL.createObjectURL(c),u=await bn().loadSync(n,h,i.name,l).catch(f=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,f),null));return URL.revokeObjectURL(h),u?new Promise((f,p)=>{const g=new FileReader;g.readAsArrayBuffer(i),g.onloadend=async y=>{const b=g.result,_=exports.BlobStorage.hashMD5(b);return f({model:u,contentMD5:_})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}o.loadFile=t;async function e(i,n){return new Promise(async(s,a)=>{const l=new vt(n.guid),c=i.toString();vi&&$.DrawWireSphere(n.point,.1,16711680,3);const h=exports.PreviewHelper.addPreview({guid:n.guid,parent:n.parent,position:n==null?void 0:n.point,size:n==null?void 0:n.size}),u=await bn().loadSync(n.context,c,c,l,f=>{h.onProgress(f.loaded/f.total)}).catch(console.warn);if(u){const f=await fetch(c).then(g=>g.arrayBuffer()),p=exports.BlobStorage.hashMD5(f);vi?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),s({model:u,contentMD5:p})}else vi?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),console.warn("Unsupported file type: "+i.toString())})}o.loadFileFromURL=e})(uu||(uu={}));var TM=Object.defineProperty,Wg=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&TM(t,e,n),n};const sf=class Ow extends I{constructor(){super(...arguments);r(this,"parent",null);r(this,"object",null);r(this,"limitCount",60);r(this,"_currentCount",0);r(this,"_startPosition",null);r(this,"_startQuaternion",null);r(this,"_forwardPointerEvents",new Map)}start(){var e,i;if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const s=new vt(this.guid);this.object=C.instantiate(this.object,{idProvider:s,keepWorldPosition:!1});const a=C.getComponent(this.object,Ow);a==null||a.destroy();let l=this.object.getComponentInChildren(lr);l||(l=this.object.addComponent(lr,{dragMode:Vg.SnapToSurfaces}),l.guid=s.generateUUID());let c=C.getComponent(l.gameObject,es);c||(c=l.gameObject.addComponent(es),c.guid=s.generateUUID())}this.object.visible=!1;const n=this.gameObject.getComponent(lr);n&&(n.enabled=!1),this._startPosition=((e=this.object.position)==null?void 0:e.clone())??new d.Vector3(0,0,0),this._startQuaternion=((i=this.object.quaternion)==null?void 0:i.clone())??new d.Quaternion(0,0,0,1)}this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const i=this.handleDuplication();if(i){const n=C.getComponent(i,lr);n?(n.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,n)):console.warn("Duplicated object does not have DragControls",i)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const i=this._forwardPointerEvents.get(e.event.space);i&&(i.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield Sg(1)}handleDuplication(){var n;if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(C.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new xn;this.parent||(this.parent=this.gameObject.parent),this.parent&&(e.parent=this.parent.guid??((n=this.parent.userData)==null?void 0:n.guid),e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const i=C.instantiateSynced(this.object,e);return console.assert(i!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),i}};Wg([m(d.Object3D)],sf.prototype,"parent");Wg([m(d.Object3D)],sf.prototype,"object");Wg([m()],sf.prototype,"limitCount");let Gg=sf;var gs=(o=>(o[o.PointerEnter=0]="PointerEnter",o[o.PointerExit=1]="PointerExit",o[o.PointerDown=2]="PointerDown",o[o.PointerUp=3]="PointerUp",o[o.PointerClick=4]="PointerClick",o[o.Drag=5]="Drag",o[o.Drop=6]="Drop",o[o.Scroll=7]="Scroll",o[o.UpdateSelected=8]="UpdateSelected",o[o.Select=9]="Select",o[o.Deselect=10]="Deselect",o[o.Move=11]="Move",o[o.InitializePotentialDrag=12]="InitializePotentialDrag",o[o.BeginDrag=13]="BeginDrag",o[o.EndDrag=14]="EndDrag",o[o.Submit=15]="Submit",o[o.Cancel=16]="Cancel",o))(gs||{}),AM=Object.defineProperty,Hg=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&AM(t,e,n),n};class qg{constructor(){r(this,"eventID");r(this,"callback",new ye)}}Hg([m()],qg.prototype,"eventID");Hg([m(ye)],qg.prototype,"callback");class of extends I{constructor(){super(...arguments);r(this,"triggers",[])}invoke(e){var i;if(this.triggers)for(const n of this.triggers)n.eventID===e&&((i=n.callback)==null||i.invoke())}hasTrigger(e){var i;return((i=this.triggers)==null?void 0:i.some(n=>n.eventID===e))??!1}shouldChangeCursor(){return this.hasTrigger(gs.PointerClick)||this.hasTrigger(gs.PointerDown)||this.hasTrigger(gs.PointerUp)}onPointerClick(e){this.invoke(gs.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(gs.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(gs.PointerExit)}onPointerDown(e){this.invoke(gs.PointerDown)}onPointerUp(e){this.invoke(gs.PointerUp)}}Hg([m(qg)],of.prototype,"triggers");class kw{constructor(t){r(this,"writer");this.writer=t}writeNode(t){}}class LM extends kw{beforeWriteNode(t,e){$.isGizmo(t)&&(e.keep=!1)}}class Rw extends kw{beforeWriteTexture(t,e){t.isRenderTargetTexture&&(e.newTexture=Cg(new ie(1,1,1,0)))}}function Pm(o){const t=Zu.DontExport;return!(o.hideFlags&t)}const mp=S("debugexr");class DM{constructor(t){r(this,"parser");this.parser=t,mp&&console.log(t)}get name(){return"EXT_texture_exr"}loadTexture(t){const e=this.name,i=this.parser,s=i.json.textures[t];if(mp&&console.log("EXT_texture_exr.loadTexture",t,s),!s.extensions||!s.extensions[e])return null;const a=s.extensions[e],l=new H.EXRLoader(i.options.manager);return mp&&console.log("EXT_texture_exr.loadTexture",a),i.loadTextureImage(t,a.source,l)}}typeof window<"u"&&window.addEventListener("unhandledrejection",o=>{});const us=dt,dd="$___Export_Components",IM="NEEDLE_components";var n0;n0=er;class jM{constructor(){r(this,n0)}}class BM{constructor(t,e,i){r(this,"node");r(this,"nodeIndex");r(this,"nodeDef");this.node=t,this.nodeIndex=e,this.nodeDef=i}}class Ew{constructor(){r(this,"parser");r(this,"nodeToObjectMap",{});r(this,"gltf",null);r(this,"exportContext");r(this,"objectToNodeMap",{});r(this,"context");r(this,"writer")}get name(){return IM}registerExport(t){t.register(e=>{if("serializeUserData"in e){const i=e.serializeUserData.bind(e);this.writer=e,e.serializeUserData=(n,s)=>{try{this.serializeUserData(n,s)&&(e.extensionsUsed[this.name]=!0),i(n,s)}finally{this.afterSerializeUserData(n,s)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(t,e){var n;const i=(n=t.userData)==null?void 0:n.components;return!i||i.length<=0?!1:(delete t.userData.components,t[dd]=i,!0)}afterSerializeUserData(t,e){if(t.type==="Scene"&&us&&console.log("DONE",JSON.stringify(e)),t[dd]===void 0)return;const i=t[dd];delete t[dd],i!==null&&(t.userData.components=i)}writeNode(t,e){const i=this.writer.json.nodes.length;us&&console.log(t.name,i,t.uuid);const n=new BM(t,i,e);this.exportContext[i]=n,this.objectToNodeMap[t.uuid]=i}afterParse(t){var e;us&&console.log("AFTER",t);for(const i in this.exportContext){const n=this.exportContext[i],s=n.node,a=n.nodeDef,l=n.nodeIndex,c=(e=s.userData)==null?void 0:e.components;if(!c||c.length<=0)continue;const h=new jM;a.extensions=a.extensions||{},a.extensions[this.name]=h,this.context.object=s,this.context.nodeId=l,this.context.objectToNode=this.objectToNodeMap;const u=[];for(const f of c){this.context.target=f;const p=bn().writeBuiltinComponentData(f,this.context);p!==null&&u.push(p)}u.length>0&&(h[er]=u,us&&console.log("DID WRITE",s,"nodeIndex",l,u))}}beforeRoot(){return us&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(t){this.gltf=t;const e=t.parser,i=e==null?void 0:e.extensions;if(!i)return;const n=i[this.name];us&&console.log("After root",t,this.parser,i);const s=[];if(n===!0){const a=e.json.nodes;if(a){for(let l=0;l<a.length;l++){const c=await e.getDependency("node",l);this.nodeToObjectMap[l]=c}for(let l=0;l<a.length;l++){const c=a[l],h=l,u=c.extensions;if(!u)continue;const f=u[this.name];if(!f)continue;us&&console.log("NODE",c);const p=this.nodeToObjectMap[h];if(!p){console.error("Could not find object for node index: "+h,c,e);continue}Wu(p),s.push(this.createComponents(p,f))}}}await Promise.all(s);for(const a of e.associations.keys()){const l=e.associations.get(a);if((l==null?void 0:l.materials)!=null){const c="/materials/"+l.materials;c1(a,c)}}}async createComponents(t,e){if(!e)return;const i=e[er];if(i){const n=new Array;us&&console.log(t.name,i);for(const s in i){const a=i[s];us&&console.log("Serialized data",JSON.parse(JSON.stringify(a))),a&&this.parser&&n.push(bg(this.parser,a).catch(l=>console.error(`Error while resolving references (see console for details)
966
+ Binary:`,i)}else console.debug("Could not determine file type from binary data");return"unknown"}var OM=Object.defineProperty,cl=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&OM(t,e,n),n};const vi=S("debugdroplistener");class kM extends CustomEvent{constructor(t){super("object-added",{detail:t})}}const RM="blob";class Bs extends I{constructor(){super(...arguments);r(this,"useNetworking",!0);r(this,"dropArea");r(this,"fitIntoVolume",!1);r(this,"fitVolumeSize",new d.Vector3(1,1,1));r(this,"placeAtHitPosition",!0);r(this,"onDropped",new ye);r(this,"onNetworkEvent",e=>{var i;if(!this.useNetworking){vi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if((i=e.guid)!=null&&i.startsWith(this.guid)){const n=e.url;if(console.debug("[DropListener] Received networked event",e),n)if(Array.isArray(n))for(const s of n)this.addFromUrl(s,{screenposition:new d.Vector2,point:e.point,size:e.size},!0);else this.addFromUrl(n,{screenposition:new d.Vector2,point:e.point,size:e.size},!0)}});r(this,"handlePaste",e=>{if(this.context.connection.allowEditing===!1||e.defaultPrevented)return;navigator.clipboard.readText().then(n=>{if(n&&(n.startsWith("http")||n.startsWith("https")||n.startsWith("blob"))){const a={screenposition:new d.Vector2(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(a)&&this.addFromUrl(n,a,!1)}}).catch(console.warn)});r(this,"onDrag",e=>{this.context.connection.allowEditing!==!1&&e.preventDefault()});r(this,"onDrop",async e=>{if(this.context.connection.allowEditing===!1||(vi&&console.log(e),!(e!=null&&e.dataTransfer))||e["droplistener:handled"])return;e.preventDefault();const i={screenposition:new d.Vector2(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(i)===!1)return;e["droplistener:handled"]=!0;const n=e.dataTransfer.items;if(!n)return;const s=[];for(const a in n){const l=n[a];if(l.kind==="file"){const c=l.getAsFile();if(!c)continue;s.push(c)}else l.kind==="string"&&l.type=="text/plain"&&l.getAsString(c=>{this.addFromUrl(c,i,!1)})}s.length>0&&await this.addDroppedFiles(s,i)});r(this,"_abort",null);r(this,"_addedObjects",new Array);r(this,"_addedModels",new Array)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent)}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}loadFromURL(e,i){this.addFromUrl(e,{screenposition:new d.Vector2,point:i==null?void 0:i.point,size:i==null?void 0:i.size},!0)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}async addFromUrl(e,i,n){vi&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const l=e.split("/"),c=l[3],h=l[4],u=l[6],f=l.slice(7).join("/");e=`https://raw.githubusercontent.com/${c}/${h}/${u}/${f}`}else e.startsWith("https://polyhaven.com/a")&&(e=EM(e));if(!e)return null;const s=e.toLowerCase();if(s.endsWith(".hdr")||s.endsWith(".hdri")||s.endsWith(".exr")||s.endsWith(".png")||s.endsWith(".jpg")||s.endsWith(".jpeg"))return null;this.removePreviouslyAddedObjects();const a=await uu.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:i.point,size:i.size});if(a&&this._addedObjects.length<=0)return i.url=e,this.addObject(a,i,n)}catch{console.warn("String is not a valid URL",e)}return null}async addDroppedFiles(e,i){var n,s;if(vi&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Oc(RM,null),(n=this._abort)==null||n.abort("New files dropped"),this._abort=new AbortController;for(const a of e){if(!a)continue;if(a.type.startsWith("image/")){vi&&console.warn("Ignoring dropped image file",a.name,a.type);continue}else if(a.name.endsWith(".bin")){vi&&console.warn("Ignoring dropped binary file",a.name,a.type);continue}console.debug("Load file "+a.name+" + "+a.type);const l=await uu.loadFile(a,this.context,{guid:this.guid});if(l){this.dispatchEvent(new CustomEvent("file-dropped",{detail:a})),i.file=a;const c=this.addObject(l,i,!1);c&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),exports.BlobStorage.upload(a,{abort:(s=this._abort)==null?void 0:s.signal}).then(h=>{h!=null&&h.download_url&&this._addedObjects.includes(c)&&this.sendDropEvent(h.download_url,c,l.contentMD5)}).catch(console.warn));break}}}}removePreviouslyAddedObjects(e=!0){if(e)for(const i of this._addedObjects)i.parent===this.gameObject&&Ri(i,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}addObject(e,i,n){var u,f;const{model:s,contentMD5:a}=e;if(vi&&console.log(`Dropped ${this.gameObject.name}`,s),!(s!=null&&s.scene))return console.warn("No object specified to add to scene",s),null;this.removePreviouslyAddedObjects();const l=s.scene;this.gameObject.attach(l),l.position.set(0,0,0),l.quaternion.identity(),this._addedObjects.push(l),this._addedModels.push(s);const c=new d.Box3().setFromCenterAndSize(new d.Vector3(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(vi&&$.DrawWireBox3(c,255,5),this.fitIntoVolume&&R0(l,c,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&i&&i.screenposition){l.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(i.screenposition.clone())});if(l.visible=!0,p&&p.length>0)for(const g of p){const y=g.point.clone();vi&&console.log("Place object at hit",g),E0(l,y);break}}Ha.assignAnimationsFromFile(s,{createAnimationComponent:p=>Oi(p,Tt)});const h=new kM({sender:this,gltf:s,model:s,object:l,contentMD5:a,dropped:i.file||(i.url?new URL(i.url):void 0)});return this.dispatchEvent(h),(u=this.onDropped)==null||u.invoke(h.detail),!n&&((f=i.url)!=null&&f.startsWith("http"))&&this.context.connection.isConnected&&l&&this.sendDropEvent(i.url,l,a),l}async sendDropEvent(e,i,n){if(!this.useNetworking){vi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+i.name+'"',e);const s=ci([i]),a={name:i.name,guid:this.guid,url:e,point:i.worldPosition.clone(),size:s.getSize(new d.Vector3),contentMD5:n};this.context.connection.send("droplistener",a)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){if(this.dropArea){const i=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:i,recursive:!0,testObject:s=>!this._addedObjects.includes(s)}).length)return j()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}cl([m()],Bs.prototype,"useNetworking");cl([m(d.Object3D)],Bs.prototype,"dropArea");cl([m()],Bs.prototype,"fitIntoVolume");cl([m(d.Vector3)],Bs.prototype,"fitVolumeSize");cl([m()],Bs.prototype,"placeAtHitPosition");cl([m(ye)],Bs.prototype,"onDropped");function EM(o){if(!o.startsWith("https://polyhaven.com/"))return o;const t="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",n=new URL(o).pathname.split("/").pop(),s=`${t}${n}/${n}_4k.gltf`;return console.log("Resolved polyhaven asset url",o,"→",s),s}var uu;(o=>{async function t(i,n,s){const a=s.guid,l=new bt(a),c=new Blob([i],{type:i.type||Cw(i.name)||void 0}),h=URL.createObjectURL(c),u=await bn().loadSync(n,h,i.name,l).catch(f=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,f),null));return URL.revokeObjectURL(h),u?new Promise((f,p)=>{const g=new FileReader;g.readAsArrayBuffer(i),g.onloadend=async y=>{const b=g.result,_=exports.BlobStorage.hashMD5(b);return f({model:u,contentMD5:_})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}o.loadFile=t;async function e(i,n){return new Promise(async(s,a)=>{const l=new bt(n.guid),c=i.toString();vi&&$.DrawWireSphere(n.point,.1,16711680,3);const h=exports.PreviewHelper.addPreview({guid:n.guid,parent:n.parent,position:n==null?void 0:n.point,size:n==null?void 0:n.size}),u=await bn().loadSync(n.context,c,c,l,f=>{h.onProgress(f.loaded/f.total)}).catch(console.warn);if(u){const f=await fetch(c).then(g=>g.arrayBuffer()),p=exports.BlobStorage.hashMD5(f);vi?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),s({model:u,contentMD5:p})}else vi?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),console.warn("Unsupported file type: "+i.toString())})}o.loadFileFromURL=e})(uu||(uu={}));var TM=Object.defineProperty,Wg=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&TM(t,e,n),n};const sf=class Ow extends I{constructor(){super(...arguments);r(this,"parent",null);r(this,"object",null);r(this,"limitCount",60);r(this,"_currentCount",0);r(this,"_startPosition",null);r(this,"_startQuaternion",null);r(this,"_forwardPointerEvents",new Map)}start(){var e,i;if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const s=new bt(this.guid);this.object=C.instantiate(this.object,{idProvider:s,keepWorldPosition:!1});const a=C.getComponent(this.object,Ow);a==null||a.destroy();let l=this.object.getComponentInChildren(lr);l||(l=this.object.addComponent(lr,{dragMode:Vg.SnapToSurfaces}),l.guid=s.generateUUID());let c=C.getComponent(l.gameObject,es);c||(c=l.gameObject.addComponent(es),c.guid=s.generateUUID())}this.object.visible=!1;const n=this.gameObject.getComponent(lr);n&&(n.enabled=!1),this._startPosition=((e=this.object.position)==null?void 0:e.clone())??new d.Vector3(0,0,0),this._startQuaternion=((i=this.object.quaternion)==null?void 0:i.clone())??new d.Quaternion(0,0,0,1)}this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const i=this.handleDuplication();if(i){const n=C.getComponent(i,lr);n?(n.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,n)):console.warn("Duplicated object does not have DragControls",i)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const i=this._forwardPointerEvents.get(e.event.space);i&&(i.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield Sg(1)}handleDuplication(){var n;if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(C.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new xn;this.parent||(this.parent=this.gameObject.parent),this.parent&&(e.parent=this.parent.guid??((n=this.parent.userData)==null?void 0:n.guid),e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const i=C.instantiateSynced(this.object,e);return console.assert(i!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),i}};Wg([m(d.Object3D)],sf.prototype,"parent");Wg([m(d.Object3D)],sf.prototype,"object");Wg([m()],sf.prototype,"limitCount");let Gg=sf;var gs=(o=>(o[o.PointerEnter=0]="PointerEnter",o[o.PointerExit=1]="PointerExit",o[o.PointerDown=2]="PointerDown",o[o.PointerUp=3]="PointerUp",o[o.PointerClick=4]="PointerClick",o[o.Drag=5]="Drag",o[o.Drop=6]="Drop",o[o.Scroll=7]="Scroll",o[o.UpdateSelected=8]="UpdateSelected",o[o.Select=9]="Select",o[o.Deselect=10]="Deselect",o[o.Move=11]="Move",o[o.InitializePotentialDrag=12]="InitializePotentialDrag",o[o.BeginDrag=13]="BeginDrag",o[o.EndDrag=14]="EndDrag",o[o.Submit=15]="Submit",o[o.Cancel=16]="Cancel",o))(gs||{}),AM=Object.defineProperty,Hg=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&AM(t,e,n),n};class qg{constructor(){r(this,"eventID");r(this,"callback",new ye)}}Hg([m()],qg.prototype,"eventID");Hg([m(ye)],qg.prototype,"callback");class of extends I{constructor(){super(...arguments);r(this,"triggers",[])}invoke(e){var i;if(this.triggers)for(const n of this.triggers)n.eventID===e&&((i=n.callback)==null||i.invoke())}hasTrigger(e){var i;return((i=this.triggers)==null?void 0:i.some(n=>n.eventID===e))??!1}shouldChangeCursor(){return this.hasTrigger(gs.PointerClick)||this.hasTrigger(gs.PointerDown)||this.hasTrigger(gs.PointerUp)}onPointerClick(e){this.invoke(gs.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(gs.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(gs.PointerExit)}onPointerDown(e){this.invoke(gs.PointerDown)}onPointerUp(e){this.invoke(gs.PointerUp)}}Hg([m(qg)],of.prototype,"triggers");class kw{constructor(t){r(this,"writer");this.writer=t}writeNode(t){}}class LM extends kw{beforeWriteNode(t,e){$.isGizmo(t)&&(e.keep=!1)}}class Rw extends kw{beforeWriteTexture(t,e){t.isRenderTargetTexture&&(e.newTexture=Cg(new ie(1,1,1,0)))}}function Pm(o){const t=Zu.DontExport;return!(o.hideFlags&t)}const mp=S("debugexr");class DM{constructor(t){r(this,"parser");this.parser=t,mp&&console.log(t)}get name(){return"EXT_texture_exr"}loadTexture(t){const e=this.name,i=this.parser,s=i.json.textures[t];if(mp&&console.log("EXT_texture_exr.loadTexture",t,s),!s.extensions||!s.extensions[e])return null;const a=s.extensions[e],l=new H.EXRLoader(i.options.manager);return mp&&console.log("EXT_texture_exr.loadTexture",a),i.loadTextureImage(t,a.source,l)}}typeof window<"u"&&window.addEventListener("unhandledrejection",o=>{});const us=dt,dd="$___Export_Components",IM="NEEDLE_components";var n0;n0=er;class jM{constructor(){r(this,n0)}}class BM{constructor(t,e,i){r(this,"node");r(this,"nodeIndex");r(this,"nodeDef");this.node=t,this.nodeIndex=e,this.nodeDef=i}}class Ew{constructor(){r(this,"parser");r(this,"nodeToObjectMap",{});r(this,"gltf",null);r(this,"exportContext");r(this,"objectToNodeMap",{});r(this,"context");r(this,"writer")}get name(){return IM}registerExport(t){t.register(e=>{if("serializeUserData"in e){const i=e.serializeUserData.bind(e);this.writer=e,e.serializeUserData=(n,s)=>{try{this.serializeUserData(n,s)&&(e.extensionsUsed[this.name]=!0),i(n,s)}finally{this.afterSerializeUserData(n,s)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(t,e){var n;const i=(n=t.userData)==null?void 0:n.components;return!i||i.length<=0?!1:(delete t.userData.components,t[dd]=i,!0)}afterSerializeUserData(t,e){if(t.type==="Scene"&&us&&console.log("DONE",JSON.stringify(e)),t[dd]===void 0)return;const i=t[dd];delete t[dd],i!==null&&(t.userData.components=i)}writeNode(t,e){const i=this.writer.json.nodes.length;us&&console.log(t.name,i,t.uuid);const n=new BM(t,i,e);this.exportContext[i]=n,this.objectToNodeMap[t.uuid]=i}afterParse(t){var e;us&&console.log("AFTER",t);for(const i in this.exportContext){const n=this.exportContext[i],s=n.node,a=n.nodeDef,l=n.nodeIndex,c=(e=s.userData)==null?void 0:e.components;if(!c||c.length<=0)continue;const h=new jM;a.extensions=a.extensions||{},a.extensions[this.name]=h,this.context.object=s,this.context.nodeId=l,this.context.objectToNode=this.objectToNodeMap;const u=[];for(const f of c){this.context.target=f;const p=bn().writeBuiltinComponentData(f,this.context);p!==null&&u.push(p)}u.length>0&&(h[er]=u,us&&console.log("DID WRITE",s,"nodeIndex",l,u))}}beforeRoot(){return us&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(t){this.gltf=t;const e=t.parser,i=e==null?void 0:e.extensions;if(!i)return;const n=i[this.name];us&&console.log("After root",t,this.parser,i);const s=[];if(n===!0){const a=e.json.nodes;if(a){for(let l=0;l<a.length;l++){const c=await e.getDependency("node",l);this.nodeToObjectMap[l]=c}for(let l=0;l<a.length;l++){const c=a[l],h=l,u=c.extensions;if(!u)continue;const f=u[this.name];if(!f)continue;us&&console.log("NODE",c);const p=this.nodeToObjectMap[h];if(!p){console.error("Could not find object for node index: "+h,c,e);continue}Wu(p),s.push(this.createComponents(p,f))}}}await Promise.all(s);for(const a of e.associations.keys()){const l=e.associations.get(a);if((l==null?void 0:l.materials)!=null){const c="/materials/"+l.materials;c1(a,c)}}}async createComponents(t,e){if(!e)return;const i=e[er];if(i){const n=new Array;us&&console.log(t.name,i);for(const s in i){const a=i[s];us&&console.log("Serialized data",JSON.parse(JSON.stringify(a))),a&&this.parser&&n.push(bg(this.parser,a).catch(l=>console.error(`Error while resolving references (see console for details)
967
967
  `,l,t,a))),t.userData=t.userData||{},t.userData[er]=t.userData[er]||[],t.userData[er].push(a)}await Promise.all(n).catch(s=>{console.error("Error while loading components",s)})}}}const pb="NEEDLE_gameobject_data";class FM{constructor(t){r(this,"parser");this.parser=t}get name(){return pb}afterRoot(t){var i;const e=[];for(let n=0;n<((i=this.parser.json.nodes)==null?void 0:i.length);n++){const s=this.parser.json.nodes[n];if(s&&s.extensions){const a=s.extensions[pb];if(a){const l=this.findAndApplyExtensionData(n,a);e.push(l)}}}return Promise.all(e).then(()=>null)}async findAndApplyExtensionData(t,e){const i=await this.parser.getDependency("node",t);i&&this.applyExtensionData(i,e)}applyExtensionData(t,e){e.layers===void 0&&(e.layers=0),t.userData.layer=e.layers,t.layers.disableAll(),t.layers.set(e.layers),t.userData.tag=e.tag??"none",t.hideFlags=0,t.userData.static=e.static??!1,t.visible=e.activeSelf??!0,t.guid=e.guid}}const mb="NEEDLE_lighting_settings",ya=S("debugenvlight");class UM{constructor(t,e,i){r(this,"parser");r(this,"sourceId");r(this,"context");this.parser=t,this.sourceId=e,this.context=i}get name(){return mb}afterRoot(t){const e=this.parser.json.extensions;if(e){const i=e[mb];if(i){ya&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(t.scene.children.length===1){const s=t.scene.children[0];n=C.addComponent(s,fu,{},{callAwake:!1})}else{const s=new d.Object3D;s.name="LightSettings "+this.sourceId,t.scene.add(s),n=C.addComponent(s,fu,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new d.Color().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(s=>new d.Color().fromArray(s))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}re.registerCallback(he.ContextCreated,o=>{const t=o.context,e=C.findObjectOfType(fu,t);e!=null&&e.sourceId&&(e.enabled=!0)});class fu extends I{constructor(){super(...arguments);r(this,"ambientMode",Ia.Skybox);r(this,"ambientLight");r(this,"ambientTrilight");r(this,"ambientIntensity",1);r(this,"environmentReflectionSource",ou.Skybox);r(this,"_hasReflection",!1);r(this,"_ambientLightObj");r(this,"_hemisphereLightObj")}awake(){var i;if(this.sourceId){const n=this.environmentReflectionSource===ou.Skybox?Dn.Skybox:Dn.Reflection,s=this.context.lightmaps.tryGet(this.sourceId,n,0);this._hasReflection=s!=null,s&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,s)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),ya&&window.addEventListener("keydown",n=>{if(!this.destroyed)switch(n.key){case"l":this.enabled=!this.enabled;break}});const e=(i=this.gameObject.userData)==null?void 0:i.components;if(e){const n=e.indexOf(this);e.splice(n,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const i=Math.max(e.r,e.g,e.b);return 2.2*z.lerp(0,1.33,i)}onEnable(){if(ya&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ia.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new d.AmbientLight(this.ambientLight,this.ambientIntensity*e),ya&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ia.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=this.calculateIntensityFactor(i);this._hemisphereLightObj=new d.HemisphereLight(i,e,this.ambientIntensity*n),this.gameObject.add(this._hemisphereLightObj),ya&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){ya&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const gp=S("debugstencil");function zM(o,t){return(o&1<<t.layer)!=0}const NM=Symbol("stencils"),co=class co{constructor(t,e){r(this,"parser");r(this,"source");this.parser=t,this.source=e}get name(){return"NEEDLE_render_objects"}static applyStencil(t){if(!t)return;const e=t.sourceId;if(gp&&console.log(e,co.stencils),!e)return;const i=co.stencils[e];if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];if(zM(s.layer,t)){gp&&console.log(s),setTimeout(()=>{Kt()&&Gu(t.gameObject)&&(me("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",t))},500);for(let a=0;a<t.sharedMaterials.length;a++){let l=t.sharedMaterials[a];l&&(l=l.clone(),l[NM]=!0,l.stencilWrite=!0,l.stencilWriteMask=255,l.stencilFuncMask=255,l.stencilRef=s.value,l.stencilFunc=s.compareFunc,l.stencilZPass=s.passOp,l.stencilFail=s.failOp,l.stencilZFail=s.zFailOp,t.sharedMaterials[a]=l)}t.gameObject.renderOrder=s.event*1e3+s.index*50;break}}}afterRoot(t){const e=this.parser.json.extensions;if(e){const i=e[VM];if(i){gp&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const s of n){const a={...s};a.compareFunc=$M(a.compareFunc),a.passOp=yp(a.passOp),a.failOp=yp(a.failOp),a.zFailOp=yp(a.zFailOp),co.stencils[this.source]||(co.stencils[this.source]=[]),co.stencils[this.source].push(a)}}}return null}};r(co,"stencils",{});let pu=co;function yp(o){switch(o){case 0:return d.KeepStencilOp;case 1:return d.ZeroStencilOp;case 2:return d.ReplaceStencilOp;case 3:return d.IncrementStencilOp;case 4:return d.DecrementStencilOp;case 6:return d.IncrementWrapStencilOp;case 7:return d.DecrementWrapStencilOp;case 5:return d.InvertStencilOp}return 0}function $M(o){switch(o){case 1:return d.NeverStencilFunc;case 2:return d.LessStencilFunc;case 3:return d.EqualStencilFunc;case 4:return d.LessEqualStencilFunc;case 5:return d.GreaterStencilFunc;case 6:return d.NotEqualStencilFunc;case 7:return d.GreaterEqualStencilFunc;case 8:return d.AlwaysStencilFunc}return d.NeverStencilFunc}const VM="NEEDLE_render_objects";var Tw=(o=>(o[o.INT=5124]="INT",o[o.FLOAT=5126]="FLOAT",o[o.FLOAT_VEC2=35664]="FLOAT_VEC2",o[o.FLOAT_VEC3=35665]="FLOAT_VEC3",o[o.FLOAT_VEC4=35666]="FLOAT_VEC4",o[o.INT_VEC2=35667]="INT_VEC2",o[o.INT_VEC3=35668]="INT_VEC3",o[o.INT_VEC4=35669]="INT_VEC4",o[o.BOOL=35670]="BOOL",o[o.BOOL_VEC2=35671]="BOOL_VEC2",o[o.BOOL_VEC3=35672]="BOOL_VEC3",o[o.BOOL_VEC4=35673]="BOOL_VEC4",o[o.FLOAT_MAT2=35674]="FLOAT_MAT2",o[o.FLOAT_MAT3=35675]="FLOAT_MAT3",o[o.FLOAT_MAT4=35676]="FLOAT_MAT4",o[o.SAMPLER_2D=35678]="SAMPLER_2D",o[o.SAMPLER_3D=35680]="SAMPLER_3D",o[o.SAMPLER_CUBE=35681]="SAMPLER_CUBE",o[o.UNKNOWN=0]="UNKNOWN",o))(Tw||{});const Tn=S("debugcustomshader"),ra="NEEDLE_techniques_webgl";class WM{constructor(){r(this,"objectToWorldMatrix",new d.Matrix4);r(this,"worldToObjectMatrix",new d.Matrix4);r(this,"objectToWorld",new Array);r(this,"worldToObject",new Array)}updateFrom(t){this.objectToWorldMatrix.copy(t.matrixWorld),su(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(t.matrixWorld).invert(),su(this.worldToObjectMatrix,this.worldToObject)}}const ue=class ue extends d.RawShaderMaterial{constructor(e,...i){super(...i);r(this,"identifier");r(this,"onBeforeRenderSceneCallback",this.onBeforeRenderScene.bind(this));r(this,"_sphericalHarmonicsName","unity_SpecCube0");r(this,"_objToWorldName","hlslcc_mtx4x4unity_ObjectToWorld");r(this,"_worldToObjectName","hlslcc_mtx4x4unity_WorldToObject");r(this,"_viewProjectionName","hlslcc_mtx4x4unity_MatrixVP");r(this,"_viewMatrixName","hlslcc_mtx4x4unity_MatrixV");r(this,"_rendererData",new WM);this.identifier=e,Tn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&X.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}clone(){const e=super.clone();return Aw(e),e}dispose(){super.dispose();const e=X.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&X.Current.pre_render_callbacks.splice(e,1)}get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&X.Current.setRequireColor(!0),this.depthTextureUniform&&X.Current.setRequireDepth(!0)}onBeforeRender(e,i,n,s,a,l){s.attributes.tangent||s.computeTangents(),this.onUpdateUniforms(n,a)}onUpdateUniforms(e,i){const n=X.Current;if(e&&(ue.viewProjection&&this.uniforms[this._viewProjectionName]&&(ue.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),su(ue.viewProjection,ue._viewProjectionValues)),ue.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ue.viewMatrix.copy(e.matrixWorldInverse),su(ue.viewMatrix,ue._viewMatrixValues)),this.uniforms[ue._worldSpaceCameraPosName]&&ue._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=n.sceneLighting.timeVec4),this.uniforms._Time){const c=this.uniforms._Time.value;c.x=n.sceneLighting.timeVec4.x/20,c.y=n.sceneLighting.timeVec4.x,c.z=n.sceneLighting.timeVec4.x*2,c.w=n.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const c=this.uniforms._SinTime.value;c.x=Math.sin(n.sceneLighting.timeVec4.x/8),c.y=Math.sin(n.sceneLighting.timeVec4.x/4),c.z=Math.sin(n.sceneLighting.timeVec4.x/2),c.w=Math.sin(n.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const c=this.uniforms._CosTime.value;c.x=Math.cos(n.sceneLighting.timeVec4.x/8),c.y=Math.cos(n.sceneLighting.timeVec4.x/4),c.z=Math.cos(n.sceneLighting.timeVec4.x/2),c.w=Math.cos(n.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const c=this.uniforms.unity_DeltaTime.value;c.x=n.time.deltaTime,c.y=1/n.time.deltaTime,c.z=n.time.smoothedDeltaTime,c.w=1/n.time.smoothedDeltaTime}const s=n.mainLight;if(s){const c=Q(s.gameObject,ue._mainLightPosition);this.uniforms._MainLightPosition={value:c.normalize()},ue._mainLightColor.set(s.color.r,s.color.g,s.color.b,0),this.uniforms._MainLightColor={value:ue._mainLightColor};const h=s.intensity;ue._lightData.z=h,this.uniforms.unity_LightData={value:ue._lightData}}if(e&&(ue.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ue._viewProjectionValues),ue.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ue._viewMatrixValues),this.uniforms[ue._worldSpaceCameraPosName]&&(this.uniforms[ue._worldSpaceCameraPosName]={value:ue._worldSpaceCameraPos}),n.mainCameraComponent)){if(this.uniforms._ProjectionParams){const c=this.uniforms._ProjectionParams.value;c.x=1,c.y=n.mainCameraComponent.nearClipPlane,c.z=n.mainCameraComponent.farClipPlane,c.w=1/c.z,this.uniforms._ProjectionParams.value=c}if(this.uniforms._ZBufferParams){const c=this.uniforms._ZBufferParams.value,h=n.mainCameraComponent;c.x=1-h.farClipPlane/h.nearClipPlane,c.y=h.farClipPlane/h.nearClipPlane,c.z=c.x/h.farClipPlane,c.w=c.y/h.farClipPlane,this.uniforms._ZBufferParams.value=c}if(this.uniforms._ScreenParams){const c=this.uniforms._ScreenParams.value;c.x=n.domWidth,c.y=n.domHeight,c.z=1+1/c.x,c.w=1+1/c.y,this.uniforms._ScreenParams.value=c}if(this.uniforms._ScaledScreenParams){const c=this.uniforms._ScaledScreenParams.value;c.x=n.domWidth,c.y=n.domHeight,c.z=1+1/c.x,c.w=1+1/c.y,this.uniforms._ScaledScreenParams.value=c}}const a=this.depthTextureUniform;a&&(a.value=n.depthTexture);const l=this.opaqueTextureUniform;if(l&&(l.value=n.opaqueColorTexture),i){const c=this._rendererData;c.updateFrom(i),this.uniforms[this._worldToObjectName].value=c.worldToObject,this.uniforms[this._objToWorldName].value=c.objectToWorld}this.uniformsNeedUpdate=!0}};r(ue,"viewProjection",new d.Matrix4),r(ue,"_viewProjectionValues",[]),r(ue,"viewMatrix",new d.Matrix4),r(ue,"_viewMatrixValues",[]),r(ue,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),r(ue,"_worldSpaceCameraPos",new d.Vector3),r(ue,"_mainLightColor",new d.Vector4),r(ue,"_mainLightPosition",new d.Vector3),r(ue,"_lightData",new d.Vector4);let mu=ue;class GM{constructor(t,e){r(this,"parser");r(this,"identifier");this.parser=t,this.identifier=e}get name(){return ra}loadMaterial(t){const e=this.parser.json.materials[t];if(!e)return Tn&&console.log(t,this.parser.json.materials),null;if(!e.extensions||!e.extensions[ra])return Tn&&console.log(`Material ${t} does not use NEEDLE_techniques_webgl`),null;Tn&&console.log(`Material ${t} uses NEEDLE_techniques_webgl`,e);const i=e.extensions[ra].technique;if(i<0)return console.debug(`Material ${t} does not have a valid technique index`),null;const n=this.parser.json.extensions[ra];if(!n)return Tn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Tn&&console.log(n);const s=n.techniques[i];return s?new Promise(async(a,l)=>{var v,w,x;const c=await U1(n,s.program),h=c==null?void 0:c.fragmentShader,u=c==null?void 0:c.vertexShader;if(!h||!u)return l();Tn&&console.log("loadMaterial",e,c);const f={},p=s.uniforms;(u.includes("_Time")||h.includes("_Time"))&&(f._Time={value:new d.Vector4(0,0,0,0)}),(u.includes("_SinTime")||h.includes("_SinTime"))&&(f._SinTime={value:new d.Vector4(0,0,0,0)}),(u.includes("_CosTime")||h.includes("_CosTime"))&&(f._CosTime={value:new d.Vector4(0,0,0,0)}),(u.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(f.unity_DeltaTime={value:new d.Vector4(0,0,0,0)});for(const O in p){const E=O;switch(E){case"_TimeParameters":const M=new d.Vector4;f[E]={value:M};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":f[E]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":f[E]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":f[E]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":f[E]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":f[E]={value:null};break}}let g=!1;if(e.extensions&&e.extensions[ra]){const O=e.extensions[ra];if(O.technique===i){Tn&&console.log(e.name,"Material Properties",O);for(const E in O.values){const M=O.values[E];if(typeof M=="string"){if(M.startsWith("/textures/")){const R=M.substring(10),F=Number.parseInt(R);if(F>=0){const D=await this.parser.getDependency("texture",F);D instanceof d.Texture&&(D.colorSpace=d.LinearSRGBColorSpace,D.needsUpdate=!0),f[E]={value:D};continue}}switch(E){case"alphaMode":M==="BLEND"&&(g=!0);continue}}if(Array.isArray(M)&&M.length===4){f[E]={value:new d.Vector4(M[0],M[1],M[2],M[3])};continue}f[E]={value:M}}}}const y=new mu(this.identifier,{name:e.name??"",uniforms:f,vertexShader:u,fragmentShader:h,lights:!1});switch(y.glslVersion=d.GLSL3,y.vertexShader=y.vertexShader.replace("#version 300 es",""),y.fragmentShader=y.fragmentShader.replace("#version 300 es",""),(v=f._Cull)==null?void 0:v.value){case 0:y.side=d.DoubleSide;break;case 1:y.side=d.BackSide;break;case 2:y.side=d.FrontSide;break;default:y.side=d.FrontSide;break}switch((w=f._ZTest)==null?void 0:w.value){case 3:y.depthTest=!0,y.depthFunc=d.EqualDepth;break;case 6:y.depthTest=!0,y.depthFunc=d.NotEqualDepth;break;case 2:y.depthTest=!0,y.depthFunc=d.LessDepth;break;case 4:y.depthTest=!0,y.depthFunc=d.LessEqualDepth;break;case 5:y.depthTest=!0,y.depthFunc=d.GreaterDepth;break;case 7:y.depthTest=!0,y.depthFunc=d.GreaterEqualDepth;break;case 8:y.depthTest=!1,y.depthFunc=d.AlwaysDepth;break}y.transparent=g,g&&(y.depthWrite=!1),B1(f),y.onUpdateUniforms();for(const O in p){const E=O,M=p[O].type;if(((x=f[E])==null?void 0:x.value)===void 0)switch(M){case Tw.SAMPLER_2D:f[E]={value:I1},console.warn("Missing/unassigned texture, fallback to white: "+E);break;default:E==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+E,p[O]);break}}Tn&&console.log(y.uuid,f),Aw(y),a(y)}):null}}function Aw(o){if(o.uniforms){Tn&&console.log("Uniforms:",o.uniforms);for(const e in o.uniforms)switch(t(e,e),e){case"_Color":t("color",e);break}}function t(e,i){Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{get:()=>o.uniforms[i].value,set:n=>{o.uniforms[i].value=n,o.needsUpdate=!0}})}}const HM=S("debugextensions");let gu;const qM=Promise.resolve().then(()=>require("./three-examples-DUcCNw9s.umd.cjs")).then(o=>o.GLTFLoaderAnimationPointer).then(async o=>(gu=o.GLTFAnimationPointerExtension,gu)).catch(o=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",o)}),Ar=new Array;function XM(o){Ar.includes(o)||Ar.push(o)}function QM(o){const t=Ar.indexOf(o);t>=0&&Ar.splice(t,1)}function Xg(o){if(o instanceof H.GLTFLoader){const t=new Ew;return o.register(e=>(t.parser=e,t)),t}return null}class YM{resolvePath(t){return t.includes("/extensions/builtin_components/")?t.replace("/extensions/builtin_components/","/userData/components/"):t.includes("extensions/builtin_components/")?t.replace("extensions/builtin_components/","/userData/components/"):t}}async function yu(o,t,e){const i=e.indexOf("?");i>=0&&(e=e.substring(0,i)),o.register(n=>new FM(n)),o.register(n=>new d1(n)),o.register(n=>new T1(n,t.lightmaps,e)),o.register(n=>new UM(n,e,t)),o.register(n=>new GM(n,e)),o.register(n=>new pu(n,e)),o.register(n=>new le.NEEDLE_progressive(n,e)),o.register(n=>new DM(n)),iv()&&o.register(n=>new Zd(n)),await qM.catch(n=>{}),o.register(n=>{if(gu){const s=new gu(n);return s.setAnimationPointerResolver.bind(s)(new YM),s}else return(HM||j())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const n of Ar)n.onImport&&n.onImport(o,e,t)}function Qg(o,t){for(const e of Ar)e.onExport&&e.onExport(o,t)}function Lw(o,t,e){for(const i of Ar)i.onLoaded&&i.onLoaded(o,t,e)}class Dw{constructor(t){this.writer=t,this.name="EXT_mesh_gpu_instancing"}writeNode(t,e){if(t.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,s={};e.extensions=e.extensions||{},e.extensions[this.name]=s;let a=new d.Matrix4;const l=new Array,c=new Array,h=new Array;for(let g=0;g<t.count;g++){t.getMatrixAt(g,a);let y=new d.Vector3,b=new d.Quaternion,_=new d.Vector3;a.decompose(y,b,_),l.push(y.x,y.y,y.z),c.push(b.x,b.y,b.z,b.w),h.push(_.x,_.y,_.z)}const u=new Float32Array(l),f=new Float32Array(c),p=new Float32Array(h);s.attributes={TRANSLATION:i.processAccessor(new d.BufferAttribute(u,3)),ROTATION:i.processAccessor(new d.BufferAttribute(f,4)),SCALE:i.processAccessor(new d.BufferAttribute(p,3))},n[this.name]=!0}}var KM=Object.defineProperty,Iw=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&KM(t,e,n),n};const Ll=S("debugreflectionprobe"),gb=S("noreflectionprobe"),_p=Symbol("reflectionProbeKey"),yb=Symbol("original material");var qt;const Yg=(qt=class extends I{constructor(){var e;super();r(this,"_texture");r(this,"center");r(this,"size");r(this,"_boxHelper");qt._probes.has(this.context)||qt._probes.set(this.context,[]),(e=qt._probes.get(this.context))==null||e.push(this)}static isUsingReflectionProbe(e){var i;return!!(e[_p]||(i=e[yb])!=null&&i[_p])}static get(e,i,n,s){if(!e||e.isObject3D!==!0||gb)return null;const a=qt._probes.get(i);if(a){for(const l of a)if(l.__didAwake||l.__internalAwake(),l.activeAndEnabled){if(s){if(l.gameObject===s)return l}else if(l.isInBox(e))return Ll&&console.log("Found reflection probe",e.name,l.name),l}}return Ll&&console.debug("Did not find reflection probe",e.name,n,e),null}set texture(e){if(e&&!(e instanceof d.Texture)){console.error("ReflectionProbe.texture must be a Texture",e);return}this._texture=e,e&&(e.mapping=d.EquirectangularReflectionMapping,e.colorSpace=d.LinearSRGBColorSpace,e.needsUpdate=!0)}get texture(){return this._texture}isInBox(e){var i;return(i=this._boxHelper)==null?void 0:i.isInBox(e)}awake(){this._boxHelper=this.gameObject.addComponent(ts),this._boxHelper.updateBox(!0),Ll&&this._boxHelper.showHelper(5592320,!0),this._texture&&(this._texture.mapping=d.EquirectangularReflectionMapping,this._texture.colorSpace=d.LinearSRGBColorSpace,this._texture.needsUpdate=!0)}start(){!this._texture&&j()&&(console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`),me("ReflectionProbe configuration hint: See browser console for details"))}onDestroy(){const e=qt._probes.get(this.context);if(e){const i=e.indexOf(this);i>=0&&e.splice(i,1)}}onSet(e){var n;if(gb||!this.enabled||((n=e.sharedMaterials)==null?void 0:n.length)<=0||!this.texture)return;let i=qt._rendererMaterialsCache.get(e);i||(i=[],qt._rendererMaterialsCache.set(e,i));for(let s=0;s<e.sharedMaterials.length;s++){const a=e.sharedMaterials[s];if(!a||a.envMap===void 0||a instanceof d.MeshBasicMaterial)continue;let l=i[s];const c=a===(l==null?void 0:l.copy),h=!l||l.material.uuid!==a.uuid||l.copy.version!==a.version;if(!c&&h){if(Ll){let p="";l?l.material!==a?p="reference changed; cached instance?: "+c:l.copy.version!==a.version&&(p="version changed"):p="not cached",console.warn("Cloning material",a.name,a.version,"Reason:",p,`
968
968
  `,a.uuid,`
969
969
  `,l==null?void 0:l.copy.uuid,`
@@ -1247,9 +1247,9 @@ ${c.has(1)?`
1247
1247
  `:""}
1248
1248
  ${l.join(`
1249
1249
  `)}`:""}
1250
- }`}function Pb(o){return`(${o.r}, ${o.g}, ${o.b})`}function Mb(o){return`(${o.x}, ${o.y})`}const iy=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];S("debugusdz");const Lu=class Lu{constructor(t,e,i){r(this,"id");r(this,"trigger");r(this,"action");r(this,"exclusive",!1);this.id="Behavior_"+Xi(t)+"_"+Lu.global_id++,this.trigger=e,this.action=i}makeExclusive(t){return this.exclusive=t,this}writeTo(t,e,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let s=0;s<this.trigger.length;s++){const a=this.trigger[s];n+="<"+a.id+">",s+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const s of this.trigger)s.writeTo(e,i),i.appendLine();else this.trigger.writeTo(e,i);i.appendLine(),this.action.writeTo(e,i),i.closeBlock()}};r(Lu,"global_id",0);let wt=Lu;const ha=new Set;function Om(o,t){var i,n;let e="";if(Array.isArray(o)){ha.clear();let s="[ ";for(let a=0;a<o.length;a++){let l=o[a];if(!l){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}if(typeof l=="string"){if(ha.has(l))continue;s+=l,ha.add(l)}else if(typeof l=="object"){if(l.isObject3D&&(l=t.findById(l.uuid),!l)){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}const c=(i=l.getPath)==null?void 0:i.call(l);if(ha.has(c))continue;s+=c,ha.add(c)}a+1<o.length&&(s+=", ")}s+=" ]",e=s,ha.clear()}else if(typeof o=="object"){const s=o;if(s.isObject3D&&(o=t.findById(s.uuid)),!o)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",s),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${s.uuid}.`);e=(n=o.getPath)==null?void 0:n.call(o)}return e}const Du=class Du{constructor(t,e){r(this,"id");r(this,"targetId");r(this,"tokenId");r(this,"type");r(this,"distance");t&&(this.targetId=t),e?this.id=e:this.id="Trigger_"+Du.global_id++}writeTo(t,e){e.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=Om(this.targetId,t)),e.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&e.appendLine(`token info:id = "${this.tokenId}"`),this.type&&e.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&e.appendLine(`double distance = ${this.distance}`),e.closeBlock()}};r(Du,"global_id",0);let Co=Du;function Ob(o,t={direct:!0,indirect:!0}){const e=Et.createEmpty();e.name="InputTarget_"+e.name,e.displayName=void 0,e.type="RealityKitComponent",e.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(t.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(t.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},o.add(e)}class xt{static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const t=new Co(void 0,"SceneStart");return t.tokenId="SceneTransition",t.type="enter",this.__sceneStartTrigger=t,t}static tapTrigger(t,e={direct:!0,indirect:!0}){const i=new Co(t);if(Array.isArray(t)&&t.length>1)for(const n of t)n instanceof Et&&Ob(n,e);else t instanceof Et&&Ob(t,e);return i.tokenId="TapGesture",i}static isTapTrigger(t){return(t==null?void 0:t.tokenId)==="TapGesture"}static proximityToCameraTrigger(t,e){const i=new Co(t);return i.tokenId="ProximityToCamera",i.distance=e,i}}r(xt,"__sceneStartTrigger");class yo{constructor(t,e){r(this,"id");r(this,"actions");r(this,"loops",0);r(this,"performCount",1);r(this,"type","serial");r(this,"multiplePerformOperation");this.id=t,this.actions=e}static getId(){return this.global_id++}addAction(t){return this.actions.push(t),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(t){return this.performCount=t,this}writeTo(t,e){e.beginBlock(`def Preliminary_Action "${this.id}"`),e.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];e.appendLine("<"+i.id+">"+(n?"":", "))}e.closeArray(),e.appendLine(),e.appendLine('token info:id = "Group"'),e.appendLine(`bool loops = ${this.loops}`),e.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),e.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&e.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),e.appendLine();for(const i of this.actions)i&&(i.writeTo(t,e),e.appendLine());e.closeBlock()}}r(yo,"global_id",0);const Cc=class Cc{constructor(t,e){r(this,"id");r(this,"tokenId");r(this,"affectedObjects");r(this,"easeType");r(this,"motionType");r(this,"duration");r(this,"moveDistance");r(this,"style");r(this,"type");r(this,"front");r(this,"up");r(this,"start");r(this,"animationSpeed");r(this,"reversed");r(this,"pingPong");r(this,"xFormTarget");r(this,"audio");r(this,"gain");r(this,"auralMode");r(this,"multiplePerformOperation");r(this,"velocity");r(this,"comment");r(this,"animationName");t&&(this.affectedObjects=t),e?this.id=e:this.id="Action",this.id+="_"+Cc.global_id++}clone(){const t=new Cc,e=t.id;return Object.assign(t,this),t.id=e,t}writeTo(t,e){e.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&e.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=Om(this.affectedObjects,t)),e.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?e.appendLine(`double duration = ${this.duration/this.animationSpeed} `):e.appendLine(`double duration = ${this.duration} `)),this.easeType&&e.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&e.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&e.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&e.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&e.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&e.appendLine(`token style = "${this.style}"`),this.type&&e.appendLine(`token type = "${this.type}"`),this.front&&e.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&e.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&e.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&e.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&e.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&e.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=Om(this.xFormTarget,t)),e.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&e.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&e.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&e.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&e.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&e.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),e.closeBlock()}};r(Cc,"global_id",0);let xi=Cc;class Vi{constructor(t,e,i){r(this,"x",0);r(this,"y",0);r(this,"z",0);this.x=t,this.y=e,this.z=i}static get up(){return new Vi(0,1,0)}static get right(){return new Vi(1,0,0)}static get forward(){return new Vi(0,0,1)}static get back(){return new Vi(0,0,-1)}static get zero(){return new Vi(0,0,0)}}class fe{static sequence(...t){return new yo("Group_"+yo.getId(),t).makeSequence()}static parallel(...t){return new yo("Group_"+yo.getId(),t).makeParallel()}static fadeAction(t,e,i){const n=new xi(t);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=e,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(t,e,i=!1,n=!1){const s=new xi(t);s.tokenId="StartAnimation";const a=e.start,l=e.duration,c=e.speed,h=e.clipName;if(s.comment=`Animation: ${h}, start=${a*60}, length=${l*60}, end=${(a+l)*60}`,s.animationName=h,s.start=a,s.duration=l,s.animationSpeed=c,s.reversed=i,s.pingPong=n,s.multiplePerformOperation="allow",i&&(s.start-=l),n){s.pingPong=!1;const u=s.clone();return u.reversed=!i,u.start=s.start,u.reversed&&(u.start-=l),fe.sequence(s,u)}return s}static waitAction(t){const e=new xi;return e.tokenId="Wait",e.duration=t,e.motionType=void 0,e}static lookAtCameraAction(t,e,i,n){const s=new xi(t);return s.tokenId="LookAtCamera",s.duration=e===void 0?9999999999999:e,s.front=i??Vi.forward,s.up=n??Vi.up,s}static emphasize(t,e,i="bounce",n=1,s="basic"){const a=new xi(t);return a.tokenId="Emphasize",a.duration=e,a.style=s??"basic",a.motionType=i,a.moveDistance=n,a}static transformAction(t,e,i,n,s="inout"){const a=new xi(t);return a.tokenId="Transform",a.duration=i,a.duration=Math.max(1e-6,i),a.type=n,a.easeType=i>0?s:"none",Array.isArray(e)&&console.error("Transform target must not be an array",e),a.xFormTarget=e,a}static playAudioAction(t,e,i="play",n=1,s="spatial"){const a=new xi(t);return a.tokenId="Audio",a.type=i,a.audio=e,a.gain=n,a.auralMode=s,a.multiplePerformOperation="allow",a}static impulseAction(t,e){const i=new xi(t);return i.tokenId="Impulse",i.velocity=e,i}}class SO{constructor(t){r(this,"object");r(this,"model");this.object=t}get id(){return this.object.uuid}apply(t){if(!this.model&&(this.model=t.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(t)}}class ny extends SO{constructor(e,i,n,s){super(e);r(this,"matrix");r(this,"material");r(this,"geometry");r(this,"_enableAction");r(this,"_disableAction");this.matrix=i,this.material=n,this.geometry=s}onApply(e){var s,a;const i=this.model;if(!i)return;(s=i.parent)!=null&&s.isDynamic||Et.createEmptyParent(i);const n=i.clone();this.matrix&&n.setMatrix(this.matrix),this.material&&(n.material=this.material),this.geometry&&(n.geometry=this.geometry),(a=i.parent)==null||a.add(n)}enable(){return this._enableAction?this._enableAction:(this._enableAction=fe.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=fe.fadeAction(this.object,0,!1),this._disableAction)}}class Zw{constructor(t){r(this,"actions");r(this,"sortedActions");this.actions=[...t]}organize(){this.sortedActions={};for(const t of this.actions){const e=t.id;this.sortedActions[e]||(this.sortedActions[e]=[]),this.sortedActions[e].push(t)}}getActions(t){return this.sortedActions||this.organize(),this.sortedActions[t.uuid]}}const In=S("debugusdzanimation"),km=S("debugusdzanimationserialization");class _o{constructor(t,e,i){r(this,"_start");r(this,"ext");r(this,"root");r(this,"_nearestAnimatedRoot");r(this,"clip");r(this,"speed");this.ext=t,this.root=e,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){var t;return((t=this.clip)==null?void 0:t.duration)??We.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){var t;return((t=this.clip)==null?void 0:t.name)??"rest"}static isDescendantOf(t,e){let i=e;if(!i||!t)return!1;for(;i;){if(!i)return!1;if(i===t)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){var e;let t;try{for(const i of((e=this.clip)==null?void 0:e.tracks)??[]){const n=d.PropertyBinding.parseTrackName(i.name);let s=d.PropertyBinding.findNode(this.root,n.nodeName);if(s)if(!t)t=s;else{if(s===t||_o.isDescendantOf(t,s))continue;if(!_o.isDescendantOf(s,t)){for(;!_o.isDescendantOf(s,t)&&s.parent;)s=s.parent;_o.isDescendantOf(s,t)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,t,s)}t=s}}}catch(i){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",i),t=void 0}return t}}const uo=class uo{constructor(t,e,i){r(this,"clip");r(this,"pos");r(this,"rot");r(this,"scale");r(this,"root");r(this,"target");r(this,"duration",0);r(this,"useRootMotion",!1);if(this.root=t,this.target=e,this.clip=i,i?this.duration=i.duration:this.duration=uo.restPoseClipDuration,i&&i.tracks){const s=Math.max(...i.tracks.map(a=>a.times[a.times.length-1]));s!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,s,this.duration),this.duration=s)}const n=C.getComponent(t,St);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(t){var e,i;if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it – this is likely a bug");return}t.name.endsWith("position")?this.pos=t:t.name.endsWith("quaternion")?this.rot=t:t.name.endsWith("scale")?this.scale=t:(t.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+t.name+" on "+(((e=this.root)==null?void 0:e.name)??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+t.name+" on "+(((i=this.root)==null?void 0:i.name)??this.target.name)+". Only .position, .rotation, .scale are supported."),j()&&me("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){var t,e,i,n,s,a;return this.clip?Math.max(((e=(t=this.pos)==null?void 0:t.times)==null?void 0:e.length)??0,((n=(i=this.rot)==null?void 0:i.times)==null?void 0:n.length)??0,((a=(s=this.scale)==null?void 0:s.times)==null?void 0:a.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(t=!0,e=!0,i=!0){var c,h,u;if(!this.clip)return[0,this.duration];const n=(c=this.pos)==null?void 0:c.times,s=(h=this.rot)==null?void 0:h.times,a=(u=this.scale)==null?void 0:u.times,l=[];if(t&&n)for(const f of n)l.push(f);if(e&&s)for(const f of s)l.push(f);if(i&&a)for(const f of a)l.push(f);return l.includes(0)||l.push(0),l.sort((f,p)=>f-p),[...new Set(l)]}*getValues(t,e=!0,i=!0,n=!0){var g,y,b;const s=new d.Vector3,a=new d.Quaternion,l=new d.Vector3(1,1,1),c=this.target,h=e?(g=this.pos)==null?void 0:g.createInterpolant():void 0,u=i?(y=this.rot)==null?void 0:y.createInterpolant():void 0,f=n?(b=this.scale)==null?void 0:b.createInterpolant():void 0;h||s.set(c.position.x,c.position.y,c.position.z),u||a.set(c.quaternion.x,c.quaternion.y,c.quaternion.z,c.quaternion.w),f||l.set(c.scale.x,c.scale.y,c.scale.z),h&&h.valueSize!==3&&(h.valueSize=3),u&&u.valueSize!==4&&(u.valueSize=4),f&&f.valueSize!==3&&(f.valueSize=3);const p=0;for(let _=0-p;_<t.length+p;_++){let v=0,w=0;if(_<0?(v=t[0],w=v-uo.animationDurationPadding/2+1/60):_>=t.length?(v=t[t.length-1],w=v+uo.animationDurationPadding/2-1/60):(v=t[_],w=v),h){const x=h.evaluate(v);s.set(x[0],x[1],x[2])}if(u){const x=u.evaluate(v);a.set(x[0],x[1],x[2],x[3])}if(f){const x=f.evaluate(v);l.set(x[0],x[1],x[2])}if(this.useRootMotion&&c===this.root){const x=new d.Matrix4;x.compose(s,a,l),x.multiply(c.matrix),x.decompose(s,a,l)}yield{time:w,translation:s,rotation:a,scale:l,index:_}}}};r(uo,"frameRate",60),r(uo,"animationDurationPadding",6/60),r(uo,"restPoseClipDuration",6/60);let We=uo;class af{constructor(t){r(this,"dict",new Map);r(this,"rootTargetMap",new Map);r(this,"rootAndClipToRegisteredAnimationMap",new Map);r(this,"rootToRegisteredClip",new Map);r(this,"lastClipEndTime",0);r(this,"clipToStartTime",new Map);r(this,"clipToHoldClip",new Map);r(this,"serializers",[]);r(this,"injectRestPoses",!1);r(this,"injectImplicitBehaviours",!1);this.injectRestPoses=t,this.injectImplicitBehaviours=t}get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(We.restPoseClipDuration+We.animationDurationPadding)*60}getEndTimeCode(){let t=0;for(const[e,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>t&&(t=n)}return t*60}getClipCount(t){var i;return((i=this.rootToRegisteredClip.get(t))==null?void 0:i.length)??0??0}getStartTimeByClip(t){return t?this.clipToStartTime.has(t)?this.clipToStartTime.get(t):(console.error("USDZExporter: Missing start time for clip – please report a bug.",t),0):0}registerAnimation(t,e){var h;if(!t)return null;this.rootTargetMap.has(t)||this.rootTargetMap.set(t,[]);const i=t.uuid+((e==null?void 0:e.uuid)??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);In&&console.log("registerAnimation",t,e);const n=this.injectRestPoses?1:0,s=(((h=this.rootToRegisteredClip.get(t))==null?void 0:h.length)??0)+n,a=this.rootTargetMap.get(t),l=new Set(a);if(e&&e.tracks)for(const u of e.tracks){const f=d.PropertyBinding.parseTrackName(u.name),p=d.PropertyBinding.findNode(t,f.nodeName);if(!p){console.warn("no object found for track",u.name,"using "+t.name+" instead");continue}this.dict.has(p)||this.dict.set(p,[]);const g=this.dict.get(p);if(!g){console.warn("no transform data found for target ",p,"at slot "+s+", this is likely a bug");continue}l.delete(p),this.injectRestPoses&&!g[0]&&(console.log("Injecting rest pose",p,e,"at slot",s),g[0]=new We(null,p,null));let y=g[s];y||(y=new We(t,p,e),g[s]=y),y.addTrack(u),a!=null&&a.includes(p)||a==null||a.push(p)}In&&console.log("Unregistered nodes for this clip",l,"clip",e,"at slot",s,"for root",t,"targets",a);for(const u of l){const f=this.dict.get(u);if(!f)continue;if(this.injectRestPoses&&!f[0]){console.warn("Adding rest pose for ",u,e,"at slot",s,"This is likely a bug, should have been added earlier.");const g=new We(null,u,null);f[0]=g}let p=f[s];p||(In&&console.log("Adding padding clip for ",u,e,"at slot",s),p=new We(t,u,e),f[s]=p)}const c=new _o(this,t,e);if(this.rootAndClipToRegisteredAnimationMap.set(i,c),In&&console.log({root:t,clip:e,info:c}),e){const u=this.rootToRegisteredClip.get(t);if(u?u.push(e):this.rootToRegisteredClip.set(t,[e]),!this.clipToStartTime.get(e)){this.lastClipEndTime==null&&(this.lastClipEndTime=We.restPoseClipDuration);let p=this.lastClipEndTime+We.animationDurationPadding,g=p+e.duration;const y=Math.round(p*60)/60,b=Math.round(g*60)/60;Math.abs(y-p)<.01&&(p=y),Math.abs(b-g)<.01&&(g=b),p=Math.ceil(p),g=p+e.duration,this.clipToStartTime.set(e,p),this.lastClipEndTime=g}}return c}onAfterHierarchy(t){In&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(t){var e,i;In&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const n of this.rootTargetMap.keys()){const s=this.rootTargetMap.get(n);if(!s)continue;let a;const l=[];for(const c of s){const h=this.dict.get(c);if(!h){console.error("No data found for target on USDZ export – please report a bug!",c);continue}a===void 0&&(a=h==null?void 0:h.length),a!==(h==null?void 0:h.length)&&console.error("Different array lengths for targets – please report a bug!",h);for(let u=0;u<h.length;u++){let f=h[u];if(!f){const g=u-(this.injectRestPoses?1:0);h[u]=new We(null,c,this.rootToRegisteredClip.get(n)[g]),f=h[u]}const p=f.getDuration();if(l[u]===void 0)l[u]=p;else if(l[u]!==p){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:h,target:c}),l[u]=p;continue}}}}for(const n of this.serializers){const s=(e=n.model)==null?void 0:e.parent,a=(s==null?void 0:s.isDynamic)===!0;km&&console.log(a,(i=n.model)==null?void 0:i.parent),a&&n.registerCallback(s)}}onExportObject(t,e,i){C.foreachComponent(t,s=>{const a=s;typeof a.createAnimation=="function"&&a.createAnimation(this,e,i)},!1);const n=new CO(t,this);this.serializers.push(n),n.registerCallback(e)}}class CO{constructor(t,e){r(this,"model");r(this,"object");r(this,"animationData");r(this,"ext");r(this,"callback");this.object=t,this.animationData=e.animationData,this.ext=e}registerCallback(t){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),km&&console.log("REPARENT",t),this.model=t,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(t,e,i){var a;const n=this.model,s=this.animationData;if(n&&n.skinnedMesh){let l=function(B){const L=[];for(const[N,Y]of B){let Z=`${N} : [`;const K=[];for(const de of Y)K.push(`(${se(de.x)}, ${se(de.y)}, ${se(de.z)})`);Z=Z.concat(K.join(", ")),Z=Z.concat("],"),L.push(Z)}return L},c=function(B){const L=[];for(const[N,Y]of B){let Z=`${N} : [`;const K=[];for(const de of Y)K.push(`(${se(de.w)}, ${se(de.x)}, ${se(de.y)}, ${se(de.z)})`);Z=Z.concat(K.join(", ")),Z=Z.concat("],"),L.push(Z)}return L},h=function(B){let L,N=!0;const Y=new Map;for(const[K,de]of B){L===void 0&&(L=de.length),L!==de.length&&(N=!1);let Fe=0;for(const mt of de)Fe++,mt||(Y.has(K)||Y.set(K,[]),Y.get(K).push(Fe))}In&&console.log("Bone count: ",B.size,"TransformData entries per bone: ",L,"Undefined bone entries: ",Y),console.assert(N,"All bones should have the same number of TransformData entries",B),console.assert(Y.size===0,"All TransformData entries should be set",Y);const Z=[];for(const[K,de]of B)for(let Fe=0;Fe<de.length;Fe++){const mt=de[Fe],kn=i.getStartTimeByClip(mt.clip);Z.length<=Fe&&Z.push({pos:[],rot:[],scale:[],timeOffset:kn});const nn=Z[Fe];nn.pos.push(...mt.getSortedTimesArray(!0,!1,!1)),nn.rot.push(...mt.getSortedTimesArray(!1,!0,!1)),nn.scale.push(...mt.getSortedTimesArray(!1,!1,!0))}for(const K of Z)K.pos.sort((de,Fe)=>de-Fe),K.rot.sort((de,Fe)=>de-Fe),K.scale.sort((de,Fe)=>de-Fe),K.pos=[...new Set(K.pos)],K.rot=[...new Set(K.rot)],K.scale=[...new Set(K.scale)];return Z},u=function(B,L,N){const Y=new Map,Z=new Map,K=new Map,de=L.length;for(const Fe of N){const mt=B.get(Fe);let kn;mt?console.assert(mt.length===de,"We should have the same number of TransformData entries for each bone",mt,L):kn=new We(null,Fe,null);for(let nn=0;nn<de;nn++){const Uf=mt?mt[nn]:kn,na=L[nn];for(const{time:Pl,translation:Ml}of Uf.getValues(na.pos,!0,!1,!1)){const sn=(Pl+na.timeOffset)*60;Y.has(sn)||Y.set(sn,new Array),Y.get(sn).push(Ml.clone())}for(const{time:Pl,rotation:Ml}of Uf.getValues(na.rot,!1,!0,!1)){const sn=(Pl+na.timeOffset)*60;Z.has(sn)||Z.set(sn,new Array),Z.get(sn).push(Ml.clone())}for(const{time:Pl,scale:Ml}of Uf.getValues(na.scale,!1,!1,!0)){const sn=(Pl+na.timeOffset)*60;K.has(sn)||K.set(sn,new Array),K.get(sn).push(Ml.clone())}}}return{position:Y.size==0?void 0:Y,quaternion:Z.size==0?void 0:Z,scale:K.size==0?void 0:K}},f=function(B){const L=[];for(const N of B)L.push(`(${se(N.x)}, ${se(N.y)}, ${se(N.z)})`);return L.join(", ")},p=function(B){const L=[];for(const N of B)L.push(`(${se(N.w)}, ${se(N.x)}, ${se(N.y)}, ${se(N.z)})`);return L.join(", ")},g=function(B){const L=new Map;if(In){const N=new Array;for(const[Y,Z]of s)N.push(Y.uuid+": "+Z.length+" "+Z.map(K=>{var de;return(de=K.clip)==null?void 0:de.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
1250
+ }`}function Pb(o){return`(${o.r}, ${o.g}, ${o.b})`}function Mb(o){return`(${o.x}, ${o.y})`}const iy=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];S("debugusdz");const Lu=class Lu{constructor(t,e,i){r(this,"id");r(this,"trigger");r(this,"action");r(this,"exclusive",!1);this.id="Behavior_"+Xi(t)+"_"+Lu.global_id++,this.trigger=e,this.action=i}makeExclusive(t){return this.exclusive=t,this}writeTo(t,e,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let s=0;s<this.trigger.length;s++){const a=this.trigger[s];n+="<"+a.id+">",s+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const s of this.trigger)s.writeTo(e,i),i.appendLine();else this.trigger.writeTo(e,i);i.appendLine(),this.action.writeTo(e,i),i.closeBlock()}};r(Lu,"global_id",0);let vt=Lu;const ha=new Set;function Om(o,t){var i,n;let e="";if(Array.isArray(o)){ha.clear();let s="[ ";for(let a=0;a<o.length;a++){let l=o[a];if(!l){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}if(typeof l=="string"){if(ha.has(l))continue;s+=l,ha.add(l)}else if(typeof l=="object"){if(l.isObject3D&&(l=t.findById(l.uuid),!l)){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}const c=(i=l.getPath)==null?void 0:i.call(l);if(ha.has(c))continue;s+=c,ha.add(c)}a+1<o.length&&(s+=", ")}s+=" ]",e=s,ha.clear()}else if(typeof o=="object"){const s=o;if(s.isObject3D&&(o=t.findById(s.uuid)),!o)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",s),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${s.uuid}.`);e=(n=o.getPath)==null?void 0:n.call(o)}return e}const Du=class Du{constructor(t,e){r(this,"id");r(this,"targetId");r(this,"tokenId");r(this,"type");r(this,"distance");t&&(this.targetId=t),e?this.id=e:this.id="Trigger_"+Du.global_id++}writeTo(t,e){e.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=Om(this.targetId,t)),e.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&e.appendLine(`token info:id = "${this.tokenId}"`),this.type&&e.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&e.appendLine(`double distance = ${this.distance}`),e.closeBlock()}};r(Du,"global_id",0);let Co=Du;function Ob(o,t={direct:!0,indirect:!0}){const e=Et.createEmpty();e.name="InputTarget_"+e.name,e.displayName=void 0,e.type="RealityKitComponent",e.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(t.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(t.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},o.add(e)}class wt{static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const t=new Co(void 0,"SceneStart");return t.tokenId="SceneTransition",t.type="enter",this.__sceneStartTrigger=t,t}static tapTrigger(t,e={direct:!0,indirect:!0}){const i=new Co(t);if(Array.isArray(t)&&t.length>1)for(const n of t)n instanceof Et&&Ob(n,e);else t instanceof Et&&Ob(t,e);return i.tokenId="TapGesture",i}static isTapTrigger(t){return(t==null?void 0:t.tokenId)==="TapGesture"}static proximityToCameraTrigger(t,e){const i=new Co(t);return i.tokenId="ProximityToCamera",i.distance=e,i}}r(wt,"__sceneStartTrigger");class yo{constructor(t,e){r(this,"id");r(this,"actions");r(this,"loops",0);r(this,"performCount",1);r(this,"type","serial");r(this,"multiplePerformOperation");this.id=t,this.actions=e}static getId(){return this.global_id++}addAction(t){return this.actions.push(t),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(t){return this.performCount=t,this}writeTo(t,e){e.beginBlock(`def Preliminary_Action "${this.id}"`),e.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];e.appendLine("<"+i.id+">"+(n?"":", "))}e.closeArray(),e.appendLine(),e.appendLine('token info:id = "Group"'),e.appendLine(`bool loops = ${this.loops}`),e.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),e.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&e.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),e.appendLine();for(const i of this.actions)i&&(i.writeTo(t,e),e.appendLine());e.closeBlock()}}r(yo,"global_id",0);const Cc=class Cc{constructor(t,e){r(this,"id");r(this,"tokenId");r(this,"affectedObjects");r(this,"easeType");r(this,"motionType");r(this,"duration");r(this,"moveDistance");r(this,"style");r(this,"type");r(this,"front");r(this,"up");r(this,"start");r(this,"animationSpeed");r(this,"reversed");r(this,"pingPong");r(this,"xFormTarget");r(this,"audio");r(this,"gain");r(this,"auralMode");r(this,"multiplePerformOperation");r(this,"velocity");r(this,"comment");r(this,"animationName");t&&(this.affectedObjects=t),e?this.id=e:this.id="Action",this.id+="_"+Cc.global_id++}clone(){const t=new Cc,e=t.id;return Object.assign(t,this),t.id=e,t}writeTo(t,e){e.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&e.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=Om(this.affectedObjects,t)),e.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?e.appendLine(`double duration = ${this.duration/this.animationSpeed} `):e.appendLine(`double duration = ${this.duration} `)),this.easeType&&e.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&e.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&e.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&e.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&e.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&e.appendLine(`token style = "${this.style}"`),this.type&&e.appendLine(`token type = "${this.type}"`),this.front&&e.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&e.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&e.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&e.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&e.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&e.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=Om(this.xFormTarget,t)),e.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&e.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&e.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&e.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&e.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&e.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),e.closeBlock()}};r(Cc,"global_id",0);let xi=Cc;class Vi{constructor(t,e,i){r(this,"x",0);r(this,"y",0);r(this,"z",0);this.x=t,this.y=e,this.z=i}static get up(){return new Vi(0,1,0)}static get right(){return new Vi(1,0,0)}static get forward(){return new Vi(0,0,1)}static get back(){return new Vi(0,0,-1)}static get zero(){return new Vi(0,0,0)}}class fe{static sequence(...t){return new yo("Group_"+yo.getId(),t).makeSequence()}static parallel(...t){return new yo("Group_"+yo.getId(),t).makeParallel()}static fadeAction(t,e,i){const n=new xi(t);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=e,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(t,e,i=!1,n=!1){const s=new xi(t);s.tokenId="StartAnimation";const a=e.start,l=e.duration,c=e.speed,h=e.clipName;if(s.comment=`Animation: ${h}, start=${a*60}, length=${l*60}, end=${(a+l)*60}`,s.animationName=h,s.start=a,s.duration=l,s.animationSpeed=c,s.reversed=i,s.pingPong=n,s.multiplePerformOperation="allow",i&&(s.start-=l),n){s.pingPong=!1;const u=s.clone();return u.reversed=!i,u.start=s.start,u.reversed&&(u.start-=l),fe.sequence(s,u)}return s}static waitAction(t){const e=new xi;return e.tokenId="Wait",e.duration=t,e.motionType=void 0,e}static lookAtCameraAction(t,e,i,n){const s=new xi(t);return s.tokenId="LookAtCamera",s.duration=e===void 0?9999999999999:e,s.front=i??Vi.forward,s.up=n??Vi.up,s}static emphasize(t,e,i="bounce",n=1,s="basic"){const a=new xi(t);return a.tokenId="Emphasize",a.duration=e,a.style=s??"basic",a.motionType=i,a.moveDistance=n,a}static transformAction(t,e,i,n,s="inout"){const a=new xi(t);return a.tokenId="Transform",a.duration=i,a.duration=Math.max(1e-6,i),a.type=n,a.easeType=i>0?s:"none",Array.isArray(e)&&console.error("Transform target must not be an array",e),a.xFormTarget=e,a}static playAudioAction(t,e,i="play",n=1,s="spatial"){const a=new xi(t);return a.tokenId="Audio",a.type=i,a.audio=e,a.gain=n,a.auralMode=s,a.multiplePerformOperation="allow",a}static impulseAction(t,e){const i=new xi(t);return i.tokenId="Impulse",i.velocity=e,i}}class SO{constructor(t){r(this,"object");r(this,"model");this.object=t}get id(){return this.object.uuid}apply(t){if(!this.model&&(this.model=t.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(t)}}class ny extends SO{constructor(e,i,n,s){super(e);r(this,"matrix");r(this,"material");r(this,"geometry");r(this,"_enableAction");r(this,"_disableAction");this.matrix=i,this.material=n,this.geometry=s}onApply(e){var s,a;const i=this.model;if(!i)return;(s=i.parent)!=null&&s.isDynamic||Et.createEmptyParent(i);const n=i.clone();this.matrix&&n.setMatrix(this.matrix),this.material&&(n.material=this.material),this.geometry&&(n.geometry=this.geometry),(a=i.parent)==null||a.add(n)}enable(){return this._enableAction?this._enableAction:(this._enableAction=fe.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=fe.fadeAction(this.object,0,!1),this._disableAction)}}class Zw{constructor(t){r(this,"actions");r(this,"sortedActions");this.actions=[...t]}organize(){this.sortedActions={};for(const t of this.actions){const e=t.id;this.sortedActions[e]||(this.sortedActions[e]=[]),this.sortedActions[e].push(t)}}getActions(t){return this.sortedActions||this.organize(),this.sortedActions[t.uuid]}}const In=S("debugusdzanimation"),km=S("debugusdzanimationserialization");class _o{constructor(t,e,i){r(this,"_start");r(this,"ext");r(this,"root");r(this,"_nearestAnimatedRoot");r(this,"clip");r(this,"speed");this.ext=t,this.root=e,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){var t;return((t=this.clip)==null?void 0:t.duration)??We.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){var t;return((t=this.clip)==null?void 0:t.name)??"rest"}static isDescendantOf(t,e){let i=e;if(!i||!t)return!1;for(;i;){if(!i)return!1;if(i===t)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){var e;let t;try{for(const i of((e=this.clip)==null?void 0:e.tracks)??[]){const n=d.PropertyBinding.parseTrackName(i.name);let s=d.PropertyBinding.findNode(this.root,n.nodeName);if(s)if(!t)t=s;else{if(s===t||_o.isDescendantOf(t,s))continue;if(!_o.isDescendantOf(s,t)){for(;!_o.isDescendantOf(s,t)&&s.parent;)s=s.parent;_o.isDescendantOf(s,t)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,t,s)}t=s}}}catch(i){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",i),t=void 0}return t}}const uo=class uo{constructor(t,e,i){r(this,"clip");r(this,"pos");r(this,"rot");r(this,"scale");r(this,"root");r(this,"target");r(this,"duration",0);r(this,"useRootMotion",!1);if(this.root=t,this.target=e,this.clip=i,i?this.duration=i.duration:this.duration=uo.restPoseClipDuration,i&&i.tracks){const s=Math.max(...i.tracks.map(a=>a.times[a.times.length-1]));s!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,s,this.duration),this.duration=s)}const n=C.getComponent(t,xt);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(t){var e,i;if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it – this is likely a bug");return}t.name.endsWith("position")?this.pos=t:t.name.endsWith("quaternion")?this.rot=t:t.name.endsWith("scale")?this.scale=t:(t.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+t.name+" on "+(((e=this.root)==null?void 0:e.name)??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+t.name+" on "+(((i=this.root)==null?void 0:i.name)??this.target.name)+". Only .position, .rotation, .scale are supported."),j()&&me("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){var t,e,i,n,s,a;return this.clip?Math.max(((e=(t=this.pos)==null?void 0:t.times)==null?void 0:e.length)??0,((n=(i=this.rot)==null?void 0:i.times)==null?void 0:n.length)??0,((a=(s=this.scale)==null?void 0:s.times)==null?void 0:a.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(t=!0,e=!0,i=!0){var c,h,u;if(!this.clip)return[0,this.duration];const n=(c=this.pos)==null?void 0:c.times,s=(h=this.rot)==null?void 0:h.times,a=(u=this.scale)==null?void 0:u.times,l=[];if(t&&n)for(const f of n)l.push(f);if(e&&s)for(const f of s)l.push(f);if(i&&a)for(const f of a)l.push(f);return l.includes(0)||l.push(0),l.sort((f,p)=>f-p),[...new Set(l)]}*getValues(t,e=!0,i=!0,n=!0){var g,y,b;const s=new d.Vector3,a=new d.Quaternion,l=new d.Vector3(1,1,1),c=this.target,h=e?(g=this.pos)==null?void 0:g.createInterpolant():void 0,u=i?(y=this.rot)==null?void 0:y.createInterpolant():void 0,f=n?(b=this.scale)==null?void 0:b.createInterpolant():void 0;h||s.set(c.position.x,c.position.y,c.position.z),u||a.set(c.quaternion.x,c.quaternion.y,c.quaternion.z,c.quaternion.w),f||l.set(c.scale.x,c.scale.y,c.scale.z),h&&h.valueSize!==3&&(h.valueSize=3),u&&u.valueSize!==4&&(u.valueSize=4),f&&f.valueSize!==3&&(f.valueSize=3);const p=0;for(let _=0-p;_<t.length+p;_++){let v=0,w=0;if(_<0?(v=t[0],w=v-uo.animationDurationPadding/2+1/60):_>=t.length?(v=t[t.length-1],w=v+uo.animationDurationPadding/2-1/60):(v=t[_],w=v),h){const x=h.evaluate(v);s.set(x[0],x[1],x[2])}if(u){const x=u.evaluate(v);a.set(x[0],x[1],x[2],x[3])}if(f){const x=f.evaluate(v);l.set(x[0],x[1],x[2])}if(this.useRootMotion&&c===this.root){const x=new d.Matrix4;x.compose(s,a,l),x.multiply(c.matrix),x.decompose(s,a,l)}yield{time:w,translation:s,rotation:a,scale:l,index:_}}}};r(uo,"frameRate",60),r(uo,"animationDurationPadding",6/60),r(uo,"restPoseClipDuration",6/60);let We=uo;class af{constructor(t){r(this,"dict",new Map);r(this,"rootTargetMap",new Map);r(this,"rootAndClipToRegisteredAnimationMap",new Map);r(this,"rootToRegisteredClip",new Map);r(this,"lastClipEndTime",0);r(this,"clipToStartTime",new Map);r(this,"clipToHoldClip",new Map);r(this,"serializers",[]);r(this,"injectRestPoses",!1);r(this,"injectImplicitBehaviours",!1);this.injectRestPoses=t,this.injectImplicitBehaviours=t}get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(We.restPoseClipDuration+We.animationDurationPadding)*60}getEndTimeCode(){let t=0;for(const[e,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>t&&(t=n)}return t*60}getClipCount(t){var i;return((i=this.rootToRegisteredClip.get(t))==null?void 0:i.length)??0??0}getStartTimeByClip(t){return t?this.clipToStartTime.has(t)?this.clipToStartTime.get(t):(console.error("USDZExporter: Missing start time for clip – please report a bug.",t),0):0}registerAnimation(t,e){var h;if(!t)return null;this.rootTargetMap.has(t)||this.rootTargetMap.set(t,[]);const i=t.uuid+((e==null?void 0:e.uuid)??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);In&&console.log("registerAnimation",t,e);const n=this.injectRestPoses?1:0,s=(((h=this.rootToRegisteredClip.get(t))==null?void 0:h.length)??0)+n,a=this.rootTargetMap.get(t),l=new Set(a);if(e&&e.tracks)for(const u of e.tracks){const f=d.PropertyBinding.parseTrackName(u.name),p=d.PropertyBinding.findNode(t,f.nodeName);if(!p){console.warn("no object found for track",u.name,"using "+t.name+" instead");continue}this.dict.has(p)||this.dict.set(p,[]);const g=this.dict.get(p);if(!g){console.warn("no transform data found for target ",p,"at slot "+s+", this is likely a bug");continue}l.delete(p),this.injectRestPoses&&!g[0]&&(console.log("Injecting rest pose",p,e,"at slot",s),g[0]=new We(null,p,null));let y=g[s];y||(y=new We(t,p,e),g[s]=y),y.addTrack(u),a!=null&&a.includes(p)||a==null||a.push(p)}In&&console.log("Unregistered nodes for this clip",l,"clip",e,"at slot",s,"for root",t,"targets",a);for(const u of l){const f=this.dict.get(u);if(!f)continue;if(this.injectRestPoses&&!f[0]){console.warn("Adding rest pose for ",u,e,"at slot",s,"This is likely a bug, should have been added earlier.");const g=new We(null,u,null);f[0]=g}let p=f[s];p||(In&&console.log("Adding padding clip for ",u,e,"at slot",s),p=new We(t,u,e),f[s]=p)}const c=new _o(this,t,e);if(this.rootAndClipToRegisteredAnimationMap.set(i,c),In&&console.log({root:t,clip:e,info:c}),e){const u=this.rootToRegisteredClip.get(t);if(u?u.push(e):this.rootToRegisteredClip.set(t,[e]),!this.clipToStartTime.get(e)){this.lastClipEndTime==null&&(this.lastClipEndTime=We.restPoseClipDuration);let p=this.lastClipEndTime+We.animationDurationPadding,g=p+e.duration;const y=Math.round(p*60)/60,b=Math.round(g*60)/60;Math.abs(y-p)<.01&&(p=y),Math.abs(b-g)<.01&&(g=b),p=Math.ceil(p),g=p+e.duration,this.clipToStartTime.set(e,p),this.lastClipEndTime=g}}return c}onAfterHierarchy(t){In&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(t){var e,i;In&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const n of this.rootTargetMap.keys()){const s=this.rootTargetMap.get(n);if(!s)continue;let a;const l=[];for(const c of s){const h=this.dict.get(c);if(!h){console.error("No data found for target on USDZ export – please report a bug!",c);continue}a===void 0&&(a=h==null?void 0:h.length),a!==(h==null?void 0:h.length)&&console.error("Different array lengths for targets – please report a bug!",h);for(let u=0;u<h.length;u++){let f=h[u];if(!f){const g=u-(this.injectRestPoses?1:0);h[u]=new We(null,c,this.rootToRegisteredClip.get(n)[g]),f=h[u]}const p=f.getDuration();if(l[u]===void 0)l[u]=p;else if(l[u]!==p){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:h,target:c}),l[u]=p;continue}}}}for(const n of this.serializers){const s=(e=n.model)==null?void 0:e.parent,a=(s==null?void 0:s.isDynamic)===!0;km&&console.log(a,(i=n.model)==null?void 0:i.parent),a&&n.registerCallback(s)}}onExportObject(t,e,i){C.foreachComponent(t,s=>{const a=s;typeof a.createAnimation=="function"&&a.createAnimation(this,e,i)},!1);const n=new CO(t,this);this.serializers.push(n),n.registerCallback(e)}}class CO{constructor(t,e){r(this,"model");r(this,"object");r(this,"animationData");r(this,"ext");r(this,"callback");this.object=t,this.animationData=e.animationData,this.ext=e}registerCallback(t){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),km&&console.log("REPARENT",t),this.model=t,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(t,e,i){var a;const n=this.model,s=this.animationData;if(n&&n.skinnedMesh){let l=function(B){const L=[];for(const[N,Y]of B){let Z=`${N} : [`;const K=[];for(const de of Y)K.push(`(${se(de.x)}, ${se(de.y)}, ${se(de.z)})`);Z=Z.concat(K.join(", ")),Z=Z.concat("],"),L.push(Z)}return L},c=function(B){const L=[];for(const[N,Y]of B){let Z=`${N} : [`;const K=[];for(const de of Y)K.push(`(${se(de.w)}, ${se(de.x)}, ${se(de.y)}, ${se(de.z)})`);Z=Z.concat(K.join(", ")),Z=Z.concat("],"),L.push(Z)}return L},h=function(B){let L,N=!0;const Y=new Map;for(const[K,de]of B){L===void 0&&(L=de.length),L!==de.length&&(N=!1);let Fe=0;for(const mt of de)Fe++,mt||(Y.has(K)||Y.set(K,[]),Y.get(K).push(Fe))}In&&console.log("Bone count: ",B.size,"TransformData entries per bone: ",L,"Undefined bone entries: ",Y),console.assert(N,"All bones should have the same number of TransformData entries",B),console.assert(Y.size===0,"All TransformData entries should be set",Y);const Z=[];for(const[K,de]of B)for(let Fe=0;Fe<de.length;Fe++){const mt=de[Fe],kn=i.getStartTimeByClip(mt.clip);Z.length<=Fe&&Z.push({pos:[],rot:[],scale:[],timeOffset:kn});const nn=Z[Fe];nn.pos.push(...mt.getSortedTimesArray(!0,!1,!1)),nn.rot.push(...mt.getSortedTimesArray(!1,!0,!1)),nn.scale.push(...mt.getSortedTimesArray(!1,!1,!0))}for(const K of Z)K.pos.sort((de,Fe)=>de-Fe),K.rot.sort((de,Fe)=>de-Fe),K.scale.sort((de,Fe)=>de-Fe),K.pos=[...new Set(K.pos)],K.rot=[...new Set(K.rot)],K.scale=[...new Set(K.scale)];return Z},u=function(B,L,N){const Y=new Map,Z=new Map,K=new Map,de=L.length;for(const Fe of N){const mt=B.get(Fe);let kn;mt?console.assert(mt.length===de,"We should have the same number of TransformData entries for each bone",mt,L):kn=new We(null,Fe,null);for(let nn=0;nn<de;nn++){const Uf=mt?mt[nn]:kn,na=L[nn];for(const{time:Pl,translation:Ml}of Uf.getValues(na.pos,!0,!1,!1)){const sn=(Pl+na.timeOffset)*60;Y.has(sn)||Y.set(sn,new Array),Y.get(sn).push(Ml.clone())}for(const{time:Pl,rotation:Ml}of Uf.getValues(na.rot,!1,!0,!1)){const sn=(Pl+na.timeOffset)*60;Z.has(sn)||Z.set(sn,new Array),Z.get(sn).push(Ml.clone())}for(const{time:Pl,scale:Ml}of Uf.getValues(na.scale,!1,!1,!0)){const sn=(Pl+na.timeOffset)*60;K.has(sn)||K.set(sn,new Array),K.get(sn).push(Ml.clone())}}}return{position:Y.size==0?void 0:Y,quaternion:Z.size==0?void 0:Z,scale:K.size==0?void 0:K}},f=function(B){const L=[];for(const N of B)L.push(`(${se(N.x)}, ${se(N.y)}, ${se(N.z)})`);return L.join(", ")},p=function(B){const L=[];for(const N of B)L.push(`(${se(N.w)}, ${se(N.x)}, ${se(N.y)}, ${se(N.z)})`);return L.join(", ")},g=function(B){const L=new Map;if(In){const N=new Array;for(const[Y,Z]of s)N.push(Y.uuid+": "+Z.length+" "+Z.map(K=>{var de;return(de=K.clip)==null?void 0:de.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
1251
1251
  `+N.join(`
1252
- `))}for(const N of B){const Y=s.get(N);Y&&L.set(N,Y)}return L},y=function(B){const L=g(B),N=h(L);return u(L,N,B)};const b=n.skinnedMesh.skeleton,_=new Array,v=[],w=[];for(const B of b.bones){v.push(B),w.push(B.uuid);const L=b.boneInverses[b.bones.indexOf(B)];_.push({bone:B,inverse:L})}let x=1e4;for(;w.length<b.bones.length&&x-- >0;)for(const B of v){const L=B.children;for(const N of L)if(w.indexOf(N.uuid)===-1&&b.bones.indexOf(N)!==-1){v.push(N),w.push(N.uuid);const Y=b.boneInverses[b.bones.indexOf(N)];_.push({bone:N,inverse:Y})}}x<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,b.bones,w);for(const B of $w(b.bones))_.push({bone:B,inverse:B.matrixWorld.clone().invert()});const O=_[0].bone.parent;O||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),_.sort((B,L)=>Ba(B.bone,O)>Ba(L.bone,O)?1:-1);const E=e.quickLookCompatible,M=[],R=[],F=[],D=[];for(const{bone:B}of _){if(E){const L=B.scale;L.x==0&&(L.x=1e-5),L.y==0&&(L.y=1e-5),L.z==0&&(L.z=1e-5),M.push(new d.Matrix4().compose(B.position,B.quaternion,B.scale))}else M.push(B.matrix.clone());R.push(B.position),F.push(B.quaternion),D.push(B.scale)}const A=_.map(B=>'"'+Ba(B.bone,O)+'"').join(", "),T=_.map(B=>Sb(B.inverse.clone().invert())).join(", ");t.beginBlock('def Skeleton "Rig"'),t.appendLine(`uniform matrix4d[] bindTransforms = [${T}]`),t.appendLine(`uniform token[] joints = [${A}]`),t.appendLine('uniform token purpose = "guide"'),t.appendLine(`uniform matrix4d[] restTransforms = [${M.map(B=>Sb(B)).join(", ")}]`);const G=y(_.map(B=>B.bone));if(In){let B=1e7,L=0;for(const N of((a=G.position)==null?void 0:a.keys())??[])B=Math.min(B,N),L=Math.max(L,N);console.log("Time samples",B,L,G)}if(t.beginBlock('def SkelAnimation "_anim"'),t.appendLine(`uniform token[] joints = [${A}]`),t.appendLine(`quatf[] rotations = [${p(F)}]`),G&&G.quaternion){t.beginBlock("quatf[] rotations.timeSamples = {","");const B=c(G.quaternion);for(const L of B)t.appendLine(L);t.closeBlock()}if(t.appendLine(`half3[] scales = [${f(D)}]`),G&&G.scale){t.beginBlock("half3[] scales.timeSamples = {","");const B=l(G.scale);for(const L of B)t.appendLine(L);t.closeBlock()}if(t.appendLine(`float3[] translations = [${f(R)}]`),G&&G.position){t.beginBlock("float3[] translations.timeSamples = {","");const B=l(G.position);for(const L of B)t.appendLine(L);t.closeBlock()}t.closeBlock(),t.closeBlock()}}onSerialize(t,e){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let u=0;u<i.length;u++)i[u]===void 0&&(i[u]=new We(null,this.object,null));const n=this.ext;this.skinnedMeshExport(t,e,n);const s=this.object,a=this.model,l=this.animationData.get(s);if(!l||s.isSkinnedMesh)return;km&&console.log("SERIALIZE",this.model.name,this.object.type,l);const c=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function h(u,f){var g;if(u.some(y=>y&&{position:y.pos,rotation:y.rot,scale:y.scale}[f])){switch(f){case"position":a.needsTranslate=!0,t.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":a.needsOrient=!0,t.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":a.needsScale=!0,t.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let y=0;y<u.length;y++){const b=u[y];if(!b)continue;const _=n.getStartTimeByClip(b.clip),v=b.getSortedTimesArray(f==="position",f==="rotation",f==="scale");if(!v||v.length===0){console.error("got an animated object but no time values?",s,b);continue}const w=!b.clip,x=f==="position"&&(b.pos||w),O=f==="rotation"&&(b.rot||w),E=f==="scale"&&(b.scale||w);if(x||O||E){const M=((g=b.clip)==null?void 0:g.name)??"rest",R=b.getDuration();In&&console.log("Write .timeSamples:",M,_,R,u),t.appendLine("# "+M+": start="+c.format(_*We.frameRate)+", length="+c.format(R*We.frameRate)+", frames="+b.getFrames())}if(x)for(const{time:M,translation:R}of b.getValues(v,!0,!1,!1)){const D=`${c.format((_+M)*We.frameRate)}: (${se(R.x)}, ${se(R.y)}, ${se(R.z)}),`;t.appendLine(D)}if(O)for(const{time:M,rotation:R}of b.getValues(v,!1,!0,!1)){const D=`${c.format((_+M)*We.frameRate)}: (${se(R.w)}, ${se(R.x)}, ${se(R.y)}, ${se(R.z)}),`;t.appendLine(D)}if(E)for(const{time:M,scale:R}of b.getValues(v,!1,!1,!0)){const D=`${c.format((_+M)*We.frameRate)}: (${se(R.x)}, ${se(R.y)}, ${se(R.z)}),`;t.appendLine(D)}}t.closeBlock()}}h(l,"position"),h(l,"rotation"),h(l,"scale")}}const PO=S("debugusdz");class Wr{constructor(){r(this,"files",new Array)}static getName(t){var s;const e=t.split(".").pop();let n=(s=t.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:s.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),Xi(n)+"."+e}get extensionName(){return"Audio"}onExportObject(t,e,i){const n=C.getComponents(t,qi);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const a=s.clip.split("/").pop()||"Audio",l=Wr.getName(s.clip),c=Xi(l);if(!this.files.some(h=>h.path===s.clip)){this.files.push({path:s.clip,name:l});const h=l.toLowerCase();i.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||e.addEventListener("serialize",(h,u)=>{h.appendLine(),h.beginBlock(`def SpatialAudio "${c}"`,"(",!1),h.appendLine(`displayName = "${a}"`),h.closeBlock(")"),h.beginBlock(),h.appendLine(`uniform asset filePath = @audio/${l}@`),h.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${s.volume}`),h.closeBlock()})}}async onAfterSerialize(t){for(const e of this.files){const i="audio/"+e.name;if(t.files[i]){PO&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const a=await(await(await fetch(e.path)).blob()).arrayBuffer(),l=new Uint8Array(a);t.files[i]=l}}}var MO=Object.defineProperty,Ie=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&MO(t,e,n),n};const kb=S("debugusdzbehaviours");function wh(o){o&&(o.getComponentInParent(qa)||(j()&&console.debug('Raycaster on "'+o.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),o.addComponent(Ei)))}class Gr extends I{constructor(){super(...arguments);r(this,"object");r(this,"target");r(this,"duration",1);r(this,"relativeMotion",!1);r(this,"coroutine",null);r(this,"targetPos",new d.Vector3);r(this,"targetRot",new d.Quaternion);r(this,"targetScale",new d.Vector3)}start(){wh(this.gameObject)}onPointerClick(e){e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=Q(this.object).clone(),i=Q(this.target).clone(),n=_e(this.object).clone(),s=_e(this.target).clone(),a=Ue(this.object).clone(),l=Ue(this.target).clone(),c=e.distanceTo(i),h=n.angleTo(s),u=a.distanceTo(l);if(c<.01&&h<.01&&u<.01){st(this.object,i),Hi(this.object,s),Na(this.object,l),this.coroutine=null;return}let f=0,p=0;for(;f<1;)f+=this.context.time.deltaTime/this.duration,f>1&&(f=1),p=f<.5?4*f*f*f:1-Math.pow(-2*f+2,3)/2,this.targetPos.lerpVectors(e,i,p),this.targetRot.slerpQuaternions(n,s,p),this.targetScale.lerpVectors(a,l,p),st(this.object,this.targetPos),Hi(this.object,this.targetRot),Na(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),i=this.object.quaternion.clone(),n=this.object.scale.clone(),s=this.target.position.clone(),a=this.target.quaternion.clone(),l=this.target.scale.clone();s.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(s),this.targetRot.copy(this.object.quaternion).multiply(a),this.targetScale.copy(this.object.scale).multiply(l);let c=0,h=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),h=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,h),this.object.quaternion.slerpQuaternions(i,this.targetRot,h),this.object.scale.lerpVectors(n,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(e){var i;if(this.target&&this.object&&this.gameObject){const n=new wt("Move to "+((i=this.target)==null?void 0:i.name),xt.tapTrigger(this.gameObject),fe.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(n)}}}Ie([m(d.Object3D)],Gr.prototype,"object");Ie([m(d.Object3D)],Gr.prototype,"target");Ie([m()],Gr.prototype,"duration");Ie([m()],Gr.prototype,"relativeMotion");var De;const lf=(De=class extends I{constructor(){super(...arguments);r(this,"materialToSwitch");r(this,"variantMaterial");r(this,"fadeDuration",0);r(this,"_objectsWithThisMaterial",null);r(this,"selfModel");r(this,"targetModels")}start(){var e;this._objectsWithThisMaterial=this.objectsWithThisMaterial,wh(this.gameObject),j()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((e=this.materialToSwitch)==null?void 0:e.name)+'"')}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let i=0;i<this.objectsWithThisMaterial.length;i++){const n=this.objectsWithThisMaterial[i];n.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof d.Mesh)if(Array.isArray(e.material)){for(const i of e.material)if(i===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):bv(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}async beforeCreateDocument(e,i){this.targetModels=[],De._materialTriggersPerId={},De.variantSwitchIndex=0,this.materialToSwitch&&await le.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await le.NEEDLE_progressive.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,i,n){this.objectsWithThisMaterial.find(a=>a.uuid===i.uuid)&&this.targetModels.push(i),this.gameObject.uuid===i.uuid&&(this.selfModel=i,this.materialToSwitch&&(De._materialTriggersPerId[this.materialToSwitch.uuid]||(De._materialTriggersPerId[this.materialToSwitch.uuid]=[]),De._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,i){if(!this.materialToSwitch)return;const n=De._materialTriggersPerId[this.materialToSwitch.uuid];if(n){const s={};for(const a of n){const l=a.createVariants();l&&l.length>0&&(s[a.selfModel.uuid]=l)}for(const a of n){const l=[];for(const c in s)c!==a.selfModel.uuid&&l.push(...s[c]);a.createAndAttachBehaviors(e,s[a.selfModel.uuid],l)}}delete De._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,i,n){const s=[],a=Math.max(0,this.fadeDuration);s.push(fe.fadeAction([...this.targetModels,...n],a,!1)),s.push(fe.fadeAction(i,a,!0)),e.addBehavior(new wt("Select_"+this.selfModel.name,xt.tapTrigger(this.selfModel),fe.parallel(...s))),De._parallelStartHiddenActions.push(...i),De._startHiddenBehaviour||(De._startHiddenBehaviour=new wt("StartHidden_"+this.selfModel.name,xt.sceneStartTrigger(),fe.fadeAction(De._parallelStartHiddenActions,a,!1)),e.addBehavior(De._startHiddenBehaviour))}static getMaterialName(e){return Xi(e.name||"Material")+"_"+e.id}createVariants(){if(!this.variantMaterial)return null;const e=[];for(const i of this.targetModels){const n=i.clone();n.name+="_Variant_"+De.variantSwitchIndex+++"_"+De.getMaterialName(this.variantMaterial),n.displayName=n.displayName+": Variant with material "+this.variantMaterial.name,n.material=this.variantMaterial,n.geometry=i.geometry,n.transform=i.transform,(!i.parent||!i.parent.isEmpty())&&Et.createEmptyParent(i),i.parent&&i.parent.add(n),e.push(n)}return e}},r(De,"_materialTriggersPerId",{}),r(De,"_startHiddenBehaviour",null),r(De,"_parallelStartHiddenActions",[]),r(De,"variantSwitchIndex",0),De);Ie([m(d.Material)],lf.prototype,"materialToSwitch");Ie([m(d.Material)],lf.prototype,"variantMaterial");Ie([m()],lf.prototype,"fadeDuration");let sy=lf;var pe;const xh=(pe=class extends I{constructor(){super(...arguments);r(this,"target");r(this,"toggleOnClick",!1);r(this,"targetState",!0);r(this,"hideSelf",!0);r(this,"selfModel");r(this,"selfModelClone");r(this,"targetModel");r(this,"toggleModel");r(this,"stateBeforeCreatingDocument",!1);r(this,"targetStateBeforeCreatingDocument",!1)}start(){wh(this.gameObject)}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(e,i,n){i.uuid===this.gameObject.uuid&&(this.selfModel=i,this.selfModelClone=i.clone())}beforeCreateDocument(){this.target&&(this.gameObject[pe.wasVisible]===void 0&&(this.gameObject[pe.wasVisible]=this.gameObject.activeSelf),this.target[pe.wasVisible]===void 0&&(this.target[pe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[pe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[pe.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,i){if(!this.target)return;this.targetModel=i.document.findById(this.target.uuid);const n=this.selfModel;if(this.selfModel&&this.targetModel){let s=this.selfModel,a=this.targetState;if(this.toggleOnClick)if(a=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&ty.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[pe.toggleClone]){const h=this.selfModelClone.clone();h.setMatrix(new d.Matrix4),h.name+="_toggle"+pe.clonedToggleIndex++,n.add(h),this.gameObject[pe.toggleClone]=h,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const c=this.gameObject[pe.toggleClone];if(!this.gameObject[pe.reverseToggleClone]){const h=this.selfModelClone.clone();h.setMatrix(new d.Matrix4),h.name+="_toggleReverse"+pe.clonedToggleIndex++,n.add(h),this.gameObject[pe.reverseToggleClone]=h}this.toggleModel=this.gameObject[pe.reverseToggleClone],(!this.toggleModel.geometry||!c.geometry)&&console.error("triggers without childs and without geometry won't work!",this,n.geometry),s=c,n.geometry=null,n.material=null}if(this.toggleModel){if(this.toggleOnClick){const c=[];c.push(fe.fadeAction(s,0,!1)),c.push(fe.fadeAction(this.toggleModel,0,!0)),c.push(fe.fadeAction(this.targetModel,0,a)),e.addBehavior(new wt("Toggle_"+s.name+"_ToggleTo"+(a?"On":"Off"),xt.tapTrigger(s),fe.parallel(...c)));const h=[];h.push(fe.fadeAction(this.toggleModel,0,!1)),h.push(fe.fadeAction(s,0,!0)),h.push(fe.fadeAction(this.targetModel,0,!a)),e.addBehavior(new wt("Toggle_"+s.name+"_ToggleTo"+(a?"Off":"On"),xt.tapTrigger(this.toggleModel),fe.parallel(...h)))}}else{const c=[];this.hideSelf&&c.push(fe.fadeAction(s,0,!1)),c.push(fe.fadeAction(this.targetModel,0,a)),e.addBehavior(new wt("Toggle_"+s.name+"_ToggleTo"+(a?"On":"Off"),xt.tapTrigger(s),c.length>1?fe.parallel(...c):c[0]))}const l=new Array;this.targetStateBeforeCreatingDocument||l.push(this.targetModel),this.stateBeforeCreatingDocument||l.push(n),this.toggleModel&&l.push(this.toggleModel),Ya.add(l,e)}}afterSerialize(e,i){this.gameObject[pe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[pe.wasVisible],delete this.gameObject[pe.wasVisible]),this.target&&this.target[pe.wasVisible]!==void 0&&(this.target.visible=this.target[pe.wasVisible],delete this.target[pe.wasVisible]),delete this.gameObject[pe.toggleClone],delete this.gameObject[pe.reverseToggleClone]}},r(pe,"clonedToggleIndex",0),r(pe,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),r(pe,"toggleClone",Symbol("clone for toggling")),r(pe,"reverseToggleClone",Symbol("clone for reverse toggling")),pe);Ie([m(d.Object3D)],xh.prototype,"target");Ie([m()],xh.prototype,"toggleOnClick");Ie([m()],xh.prototype,"targetState");Ie([m()],xh.prototype,"hideSelf");let oy=xh;const dn=class dn extends I{constructor(){super(...arguments);r(this,"wasVisible",!1)}static add(e,i){const n=Array.isArray(e)?e:[e];for(const s of n)dn._fadeObjects.includes(s)||(console.log("adding hide on start",s),dn._fadeObjects.push(s));dn._fadeBehaviour===void 0&&(dn._fadeBehaviour=new wt("HideOnStart",xt.sceneStartTrigger(),fe.fadeAction(dn._fadeObjects,0,!1)),i.addBehavior(dn._fadeBehaviour))}start(){C.setActive(this.gameObject,!1)}createBehaviours(e,i,n){i.uuid===this.gameObject.uuid&&(this.wasVisible||dn.add(i,e))}beforeCreateDocument(){this.wasVisible=C.isActiveSelf(this.gameObject)}};r(dn,"_fadeBehaviour"),r(dn,"_fadeObjects",[]);let Ya=dn;class hl extends I{constructor(){super(...arguments);r(this,"target");r(this,"duration",.5);r(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(e,i,n){if(this.target&&i.uuid===this.gameObject.uuid){const s=new wt("emphasize "+this.name,xt.tapTrigger(this.gameObject),fe.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(s)}}afterCreateDocument(e,i){}}Ie([m()],hl.prototype,"target");Ie([m()],hl.prototype,"duration");Ie([m()],hl.prototype,"motionType");class Mo extends I{constructor(){super(...arguments);r(this,"target");r(this,"clip","");r(this,"toggleOnClick",!1);r(this,"trigger","tap")}start(){wh(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(qi);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){var i;e.use(),!(!((i=this.target)!=null&&i.clip)&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,i,n){if(!(!this.target&&!this.clip)&&i.uuid===this.gameObject.uuid){const s=this.clip?this.clip:this.target?this.target.clip:void 0;if(!s||typeof s!="string")return;const a=this.target?this.target.gameObject:this.gameObject;Wr.getName(s);const l=this.target?this.target.volume:1,c=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let h=!1;this.gameObject.traverse(g=>{g instanceof d.Mesh&&g.visible&&(h=!0)}),h=!0;const u=e.addAudioClip(s);let f=fe.playAudioAction(a,u,"play",l,c);this.target&&this.target.loop&&(f=fe.sequence(f).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(f.multiplePerformOperation="stop");const g=new wt("playAudio"+p,xt.tapTrigger(i),f);e.addBehavior(g)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(h&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const g=new wt("playAudioOnStart"+p,xt.sceneStartTrigger(),f);e.addBehavior(g)}}}}Ie([m(qi)],Mo.prototype,"target");Ie([m(URL)],Mo.prototype,"clip");Ie([m()],Mo.prototype,"toggleOnClick");var kt;const ry=(kt=class extends I{constructor(){super(...arguments);r(this,"animator");r(this,"stateName");r(this,"trigger","tap");r(this,"animation");r(this,"selfModel");r(this,"stateAnimationModel");r(this,"animationSequence",new Array);r(this,"animationLoopAfterSequence",new Array);r(this,"randomOffsetNormalized",0)}get target(){var e,i;return((e=this.animator)==null?void 0:e.gameObject)||((i=this.animation)==null?void 0:i.gameObject)}start(){wh(this.gameObject)}onPointerClick(e){var i;e.use(),this.target&&this.stateName&&((i=this.animator)==null||i.play(this.stateName,0,0,.1))}createBehaviours(e,i,n){i.uuid===this.gameObject.uuid&&(this.selfModel=i)}afterSerialize(){if(kt.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';j()&&me(e),console.warn(e,...kt.rootsWithExclusivePlayback)}kt.animationActions=[],kt.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,i){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const n=i.document,s=i.extensions.find(c=>c instanceof af);if(!s)return;const a=s.getClipCount(this.target)>1;a&&(j()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+s.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),kt.rootsWithExclusivePlayback.add(this.target));const l=this.name?this.name:"";n.traverse(c=>{var h,u;if(c.uuid===((h=this.target)==null?void 0:h.uuid)){const f=kt.getActionForSequences(n,c,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),p=new wt(this.trigger+"_"+l+"_toPlayAnimation_"+this.stateName+"_on_"+((u=this.target)==null?void 0:u.name),this.trigger=="tap"?xt.tapTrigger(this.selfModel):xt.sceneStartTrigger(),f);a&&p.makeExclusive(!0),e.addBehavior(p)}})}static getActionForSequences(e,i,n,s,a){const l=(h,u)=>{let f=kt.animationActions.find(p=>p.affectedObjects==h&&p.start==u.start&&p.duration==u.duration&&p.animationSpeed==u.speed);return f||(f=fe.startAnimationAction(h,u),kt.animationActions.push(f)),f},c=fe.sequence();if(n&&n.length>0)for(const h of n)c.addAction(l(i,h));if(s&&s.length>0){const h=c.actions.length==0?c:fe.sequence();for(const u of s)h.addAction(l(i,u));h.makeLooping(),c!==h&&c.addAction(h)}return a&&a>0&&c.actions.unshift(fe.waitAction(a)),c}static getAndRegisterAnimationSequences(e,i,n){var b,_,v,w,x,O,E,M;if(!i)return;const s=i.getComponent(St),a=i.getComponent(Tt);if(!s&&!a)return;if(s&&!n)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+s.name+" on "+i.name);let l=[],c=[];if(a){const R=e.registerAnimation(i,a.clip);R&&(a.loop?c.push(R):l.push(R));let F=0;if(a.minMaxOffsetNormalized){const D=a.minMaxOffsetNormalized.x,A=a.minMaxOffsetNormalized.y;F=(((b=a.clip)==null?void 0:b.duration)||1)*(D+Math.random()*(A-D))}return{animationSequence:l,animationLoopAfterSequence:c,randomTimeOffset:F}}const h=s==null?void 0:s.runtimeAnimatorController;let u=h==null?void 0:h.findState(n),f=[],p=[];if(h&&u){const R=new Array;R.push(u);let F=!1;for(;R.length<100;){if(!u||u===null||!u.transitions||u.transitions.length===0){(_=u.motion)!=null&&_.isLooping&&(F=!0);break}const D=u.transitions.find(T=>T.conditions.length===0),A=D?h.getState(D.destinationState,0):null;if(A&&R.includes(A)){u=A,F=!0;break}else if(D){if(u=A,!u)break;R.push(u)}else{F=((v=u.motion)==null?void 0:v.isLooping)??!1;break}}if(F&&u){const D=R.indexOf(u);f=R.slice(0,D),p=R.slice(D),kb&&console.log("found loop from "+n,"states until loop",f,"states looping",p)}else f=R,p=[],kb&&console.log("found no loop from "+n,"states",f);if(!p.length){const D=f[f.length-1],A=(w=D.motion)==null?void 0:w.clip;if(A){let T;if(e.holdClipMap.has(A))T=e.holdClipMap.get(A);else{const G=D.name+"_hold";T=A.clone(),T.duration=1,T.name=G;const B=A.duration;T.tracks=A.tracks.map(L=>{const N=L.clone();N.times=new Float32Array([0,B]);const Y=L.values.length,Z=L.getValueSize(),K=L.values.slice(Y-Z,Y);return N.values=new Float32Array(2*Z),N.values.set(K,0),N.values.set(K,Z),N}),T.name=G,e.holdClipMap.set(A,T)}if(T){const G={name:T.name,motion:{clip:T,isLooping:!1,name:T.name},speed:1,transitions:[],behaviours:[],hash:D.hash+1};p.push(G)}}}}if(f.length===1&&(!((x=f[0].motion)!=null&&x.clip)||((E=(O=f[0].motion)==null?void 0:O.clip.tracks)==null?void 0:E.length)===0)){l=new Array;const R=e.registerAnimation(i,null);R&&l.push(R);return}if(f=f.filter(R=>{var F,D,A;return((F=R.motion)==null?void 0:F.clip)&&((A=(D=R.motion)==null?void 0:D.clip.tracks)==null?void 0:A.length)>0}),p=p.filter(R=>{var F,D,A;return((F=R.motion)==null?void 0:F.clip)&&((A=(D=R.motion)==null?void 0:D.clip.tracks)==null?void 0:A.length)>0}),f.length===0&&p.length===0){console.warn("No clips found for state "+n+" on "+(s==null?void 0:s.name)+", can't export animation data");return}const g=(R,F)=>{if(!i)return;const D=e.registerAnimation(i,R.motion.clip??null);D?(D.speed=R.speed,F.push(D)):console.warn("Couldn't register animation for state "+R.name+" on "+(s==null?void 0:s.name))};if(f.length>0){l=new Array;for(const R of f)g(R,l)}if(p.length>0){c=new Array;for(const R of p)g(R,c)}let y=0;if(s&&h&&s.minMaxOffsetNormalized){const R=s.minMaxOffsetNormalized.x,F=s.minMaxOffsetNormalized.y,D=f.length?f[0]:p.length?p[0]:null;y=(((M=D==null?void 0:D.motion.clip)==null?void 0:M.duration)||1)*(R+Math.random()*(F-R))}return{animationSequence:l,animationLoopAfterSequence:c,randomTimeOffset:y}}createAnimation(e,i,n){if(!this.target||!this.animator&&!this.animation)return;const s=kt.getAndRegisterAnimationSequences(e,this.target,this.stateName);s&&(this.animationSequence=s.animationSequence,this.animationLoopAfterSequence=s.animationLoopAfterSequence,this.randomOffsetNormalized=s.randomTimeOffset,this.stateAnimationModel=i)}},r(kt,"animationActions",[]),r(kt,"rootsWithExclusivePlayback",new Set),kt);Ie([m(St)],ry.prototype,"animator");Ie([m()],ry.prototype,"stateName");let $c=ry;class dl extends I{constructor(){super(...arguments);r(this,"target")}getType(){}getDuration(){}}Ie([m(d.Object3D)],dl.prototype,"target");class Sh extends I{constructor(){super(...arguments);r(this,"target")}}Ie([m(dl)],Sh.prototype,"target");class Ch extends dl{constructor(){super(...arguments);r(this,"type",1);r(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ie([m()],Ch.prototype,"type");Ie([m()],Ch.prototype,"duration");class ay extends Sh{}const Iu=class Iu{constructor(){r(this,"_quicklookButton");r(this,"_arButton");r(this,"_vrButton");r(this,"_sendToQuestButton")}static create(){return new Iu}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return zn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const t=document.createElement("button");this._quicklookButton=t,t.dataset.needle="quicklook-button";const e=exports.DeviceUtilities.supportsQuickLookAR();t.innerText="View in AR",t.prepend(bt("view_in_ar"));let i=!1,n=null;return t.addEventListener("click",()=>{n=hh(Kn),n||(i=!0,n=new Kn),i&&(n.objectToExport=X.Current.scene),n?(t.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{t.classList.remove("this-mode-is-requested")}).catch(s=>{t.classList.remove("this-mode-is-requested"),console.error(s)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(t),t}createARButton(t){var n;if(this._arButton)return this._arButton;const e="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(bt("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>J.start(e,t)),this.updateSessionSupported(i,e),this.listenToXRSessionState(i,e),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||(n=navigator.xr)==null||n.addEventListener("devicechange",()=>this.updateSessionSupported(i,e)),i}createVRButton(t){var n;if(this._vrButton)return this._vrButton;const e="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(bt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>J.start(e,t)),this.updateSessionSupported(i,e),this.listenToXRSessionState(i,e),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||(n=navigator.xr)==null||n.addEventListener("devicechange",()=>this.updateSessionSupported(i,e)),i}createSendToQuestButton(){var i;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",e=document.createElement("button");return this._sendToQuestButton=e,e.dataset.needle="webxr-sendtoquest-button",e.innerText="Open on Quest",e.prepend(bt("share_windows")),e.title="Click to send this page to the Oculus Browser on your Quest",e.addEventListener("click",()=>{const n=encodeURIComponent(window.location.href),s=t+n;window.open(s)==null&&Ee("This page doesn't allow popups. Please paste "+s+" into your browser.")}),this.listenToXRSessionState(e),this.hideElementDuringXRSession(e),exports.DeviceUtilities.isMozillaXR()||(i=navigator.xr)==null||i.addEventListener("devicechange",()=>{var n;(n=navigator.xr)!=null&&n.isSessionSupported("immersive-vr")?e.style.display="none":e.style.display=""}),e}createQRCode(){return zn.getOrCreate().createQRCode()}updateSessionSupported(t,e){if(!("xr"in navigator)){t.style.display="none";return}J.isSessionSupported(e).then(i=>{t.style.display=i?"":"none",j()&&!i&&console.log('[WebXR] "'+e+'" is not supported on this device – make sure your server runs using HTTPS and you have a device connected that supports '+e)})}hideElementDuringXRSession(t){zu(e=>{t["previous-display"]=t.style.display,t.style.display="none"}),sg(e=>{t["previous-display"]!=null&&(t.style.display=t["previous-display"])})}listenToXRSessionState(t,e){e&&(J.onSessionRequestStart(i=>{i.mode===e?t.classList.add("this-mode-is-requested"):(t["was-disabled"]=t.disabled,t.disabled=!0,t.classList.add("other-mode-is-requested"))}),J.onSessionRequestEnd(i=>{t.classList.remove("this-mode-is-requested"),t.classList.remove("other-mode-is-requested"),t.disabled=t["was-disabled"]}))}};r(Iu,"_instance");let Po=Iu;var OO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,ut=(o,t,e,i)=>{for(var n=i>1?void 0:i?kO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&OO(t,e,n),n};const bu=S("debugspriterenderer"),RO=S("wireframe"),Pc=class Pc{static getOrCreateGeometry(t){if(t.__cached_geometry)return t.__cached_geometry;if(t.guid&&Pc.cache[t.guid])return bu&&console.log("Take cached geometry for sprite",t.guid),Pc.cache[t.guid];const e=new d.BufferGeometry;t.__cached_geometry=e;const i=new Float32Array(t.triangles.length*3),n=new Float32Array(t.triangles.length*2);for(let s=0;s<t.triangles.length;s+=1){const a=t.triangles[s];i[s*3]=-t.vertices[a].x,i[s*3+1]=t.vertices[a].y,i[s*3+2]=0;const l=t.uv[a];n[s*2]=l.x,n[s*2+1]=1-l.y}return e.setAttribute("position",new d.BufferAttribute(i,3)),e.setAttribute("uv",new d.BufferAttribute(n,2)),t.guid&&(this.cache[t.guid]=e),bu&&console.log("Built sprite geometry",t,e),e}};r(Pc,"cache",{});let Ka=Pc;class EO{constructor(){r(this,"x");r(this,"y")}}function Jw(o){o&&(o.colorSpace!=d.SRGBColorSpace&&(o.colorSpace=d.SRGBColorSpace,o.needsUpdate=!0),o.minFilter==d.NearestFilter&&o.magFilter==d.NearestFilter&&(o.anisotropy=1,o.needsUpdate=!0))}let Us=class{constructor(t){r(this,"guid");r(this,"texture");r(this,"triangles");r(this,"uv");r(this,"vertices");r(this,"__cached_geometry");r(this,"_mesh");r(this,"_material");t&&(this.texture=t,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}get mesh(){return this._mesh||(this._mesh=new d.Mesh(Ka.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&Jw(this.texture),this._material=new d.MeshBasicMaterial({map:this.texture,color:16777215,side:d.DoubleSide,transparent:!0})),this._material}getGeometry(){return Ka.getOrCreateGeometry(this)}};ut([m()],Us.prototype,"guid",2);ut([m(d.Texture)],Us.prototype,"texture",2);ut([Br()],Us.prototype,"triangles",2);ut([Br()],Us.prototype,"uv",2);ut([Br()],Us.prototype,"vertices",2);const Cp=Symbol("spriteOwner");class Za{constructor(){r(this,"sprites");this.sprites=[]}}ut([m(Us)],Za.prototype,"sprites",2);const ly=class Rm{constructor(){r(this,"spriteSheet");r(this,"index",0)}static create(){const t=new Rm;return t.spriteSheet=new Za,t}clone(){const t=new Rm;return t.index=this.index,t.spriteSheet=this.spriteSheet,t}set sprite(t){t&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=t):(this.spriteSheet=new Za,this.spriteSheet.sprites=[t],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(t){if(!this.spriteSheet)return;const e=this.index;if(e<0||e>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[e],n=i==null?void 0:i.texture;if(n&&(Jw(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;le.NEEDLE_progressive.assignTextureLOD(n,0).then(a=>{a instanceof d.Texture&&(i.texture=a,(t==null?void 0:t.map)===s&&(t.map=a,t.needsUpdate=!0))})}}};ut([m(Za)],ly.prototype,"spriteSheet",2);ut([m()],ly.prototype,"index",2);let Fa=ly;class fi extends I{constructor(){super(...arguments);r(this,"drawMode",0);r(this,"size",{x:1,y:1});r(this,"color");r(this,"sharedMaterial");r(this,"transparent",!0);r(this,"cutoutThreshold",0);r(this,"castShadows",!1);r(this,"renderOrder",0);r(this,"toneMapped",!0);r(this,"_spriteSheet");r(this,"_currentSprite")}set texture(e){var n;if(!this._spriteSheet)return;const i=(n=this._spriteSheet.spriteSheet)==null?void 0:n.sprites[this.spriteIndex];i&&(i.texture=e,this.updateSprite())}addSprite(e,i=!1){var s,a;if(this._spriteSheet||(this._spriteSheet=Fa.create()),!this._spriteSheet.spriteSheet)return-1;(s=this._spriteSheet.spriteSheet)==null||s.sprites.push(e);const n=((a=this._spriteSheet.spriteSheet)==null?void 0:a.sprites.length)-1;return i&&(this.spriteIndex=n),n}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const i=Math.floor(e);this.spriteIndex=i}else e instanceof Us?(this._spriteSheet||(this._spriteSheet=Fa.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){var e;return((e=this._spriteSheet)==null?void 0:e.index)??0}get spriteFrames(){var e,i;return((i=(e=this._spriteSheet)==null?void 0:e.spriteSheet)==null?void 0:i.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=Fa.create(),bu&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){var s;if(!this.__didAwake&&!e)return!1;const i=this._spriteSheet;if(!((s=i==null?void 0:i.spriteSheet)!=null&&s.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const n=i.spriteSheet.sprites[this.spriteIndex];if(!n)return bu&&console.warn("Sprite not found",this.spriteIndex,i.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=Ka.getOrCreateGeometry(n),this._currentSprite.material.map=n.texture;else{const a=new d.MeshBasicMaterial({color:16777215,side:d.DoubleSide});if(RO&&(a.wireframe=!0),this.color&&(a.color||(a.color=new d.Color),a.color.copy(this.color),a.opacity=this.color.alpha),a.transparent=!0,a.toneMapped=this.toneMapped,a.depthWrite=!1,n.texture&&!a.wireframe){let l=n.texture;l[Cp]!==void 0&&l[Cp]!==this&&this.spriteFrames>1&&(l=n.texture=l.clone()),l[Cp]=this,a.map=l}this.sharedMaterial=a,this._currentSprite=new d.Mesh(Ka.getOrCreateGeometry(n),a),this._currentSprite.renderOrder=Math.round(this.renderOrder),le.NEEDLE_progressive.assignTextureLOD(a,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,i==null||i.update(this.sharedMaterial),!0}}ut([m()],fi.prototype,"drawMode",2);ut([m(EO)],fi.prototype,"size",2);ut([m(ie)],fi.prototype,"color",2);ut([m(d.Material)],fi.prototype,"sharedMaterial",2);ut([m()],fi.prototype,"transparent",2);ut([m()],fi.prototype,"cutoutThreshold",2);ut([m()],fi.prototype,"castShadows",2);ut([m()],fi.prototype,"renderOrder",2);ut([m()],fi.prototype,"toneMapped",2);ut([m(Fa)],fi.prototype,"sprite",1);const Rb=S("debugwebxr"),TO=new d.Matrix4().makeRotationY(Math.PI),fo=class fo extends I{constructor(){super(...arguments);r(this,"_arScale",1);r(this,"invertForward",!1);r(this,"customReticle");r(this,"arTouchTransform",!0);r(this,"autoPlace",!1);r(this,"autoCenter",!1);r(this,"useXRAnchor",!1);r(this,"_isPlacing",!0);r(this,"_startOffset",new d.Matrix4);r(this,"_createdPlacementObject",null);r(this,"_reparentedComponents",[]);r(this,"_placementScene",new d.Scene);r(this,"_reticle",[]);r(this,"_hits",[]);r(this,"_placementStartTime",-1);r(this,"_rigPlacementMatrix");r(this,"_anchor",null);r(this,"userInput");r(this,"onPlaceScene",e=>{var s;if(this._isPlacing==!1||e!=null&&e.used)return;let i=this._reticle[0];if(!i){console.warn("No reticle to place...");return}if(!i.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((s=J.active)!=null&&s.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let n=this._hits[0];if(e&&e.origin instanceof og){const a=this._reticle[e.origin.index];a&&(i=a,n=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),i.position.copy(i.lastPos),i.quaternion.copy(i.lastQuat),this.onApplyPose(i),fo._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(J.active,n),this.context.xr)for(const a of this.context.xr.controllers)a.cancelHitTestSource()});r(this,"upVec",new d.Vector3(0,1,0));r(this,"lookPoint",new d.Vector3);r(this,"worldUpVec",new d.Vector3(0,1,0))}static onPlaced(e){const i="placed";return this._eventListeners[i]||(this._eventListeners[i]=[]),this._eventListeners[i].push(e),()=>{const n=this._eventListeners[i].indexOf(e);n>=0&&this._eventListeners[i].splice(n,1)}}static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}onEnable(){var e;(e=this.customReticle)==null||e.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){Rb&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,fo._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const i=new d.Object3D;this._createdPlacementObject=i,i.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let n=this.context.scene.children.length-1;n>=0;n--){const s=this.context.scene.children[n];this._placementScene.add(s)}if(this.context.scene.add(i),this.autoCenter){const n=ci(this._placementScene.children),s=n.getCenter(new d.Vector3),a=n.getSize(new d.Vector3),l=new d.Matrix4;l.makeTranslation(s.x,s.y-a.y*.5,s.z),this._startOffset.multiply(l)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),C.addComponent(i,this);for(const n of this._reticle)Ri(n);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ri.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ri.Early}),this.onRevertSceneChanges(),this._anchor=null,fo._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){var i,n,s,a;if(e.xr.isTrackingImages){for(const l of this._reticle)l.visible=!1;return}if(this._isPlacing){const l=(i=e.xr.rig)==null?void 0:i.gameObject;l&&l.parent!==this.context.scene&&this.context.scene.add(l);let c=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const h of e.xr.controllers){const u=h.getHitTest();u&&(c=!0,this.updateReticleAndHits(e.xr,h.index,u,e.xr.rigScale))}if(!c){const h=e.xr.getHitTest();h&&this.updateReticleAndHits(e.xr,0,h,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const l=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(l&&this.context.time.frame%20===0){const c=e.xr.convertSpace(l.transform),h=this._reticle[0];h&&(h.position.copy(c.position),h.quaternion.copy(c.quaternion),this.onApplyPose(h))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Em(this.context)),(n=this.userInput)==null||n.enable()):(s=this.userInput)==null||s.disable(),this.arTouchTransform&&((a=this.userInput)!=null&&a.hasChanged)){if(e.xr.rig){const l=e.xr.rig.gameObject;this.userInput.applyMatrixTo(l.matrix,!0),l.matrix.decompose(l.position,l.quaternion,l.scale),this.userInput.factor=l.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,i,n,s){this._hits[i]=n.hit;let a=this._reticle[i];if(!a){if(this.customReticle)if(this.customReticle.asset)a=Er(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else a=new d.Mesh(new d.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new d.MeshBasicMaterial({side:d.DoubleSide,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),a.name="AR Placement Reticle";if(Rb){const l=new d.AxesHelper(1);l.position.y+=.01,a.add(l)}this._reticle[i]=a,a.matrixAutoUpdate=!1,a.visible=!1}if(a.lastPos=a.lastPos||n.position.clone(),a.lastQuat=a.lastQuat||n.quaternion.clone(),a.position.copy(a.lastPos.lerp(n.position,this.context.time.deltaTime/.1)),a.lastPos.copy(a.position),a.quaternion.copy(a.lastQuat.slerp(n.quaternion,this.context.time.deltaTime/.05)),a.lastQuat.copy(a.quaternion),a.scale.set(s,s,s),this.customReticle&&this.applyViewBasedTransform(a),a.updateMatrix(),a.visible=!0,a.parent!==this.context.scene&&this.context.scene.add(a),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(a.quaternion),this.upVec.dot(V(0,1,0))>.9){let c=a["autoplace:timer"]||0;c>=1?(a.visible=!1,this.onPlaceScene(null)):(c+=this.context.time.deltaTime,a["autoplace:timer"]=c)}else a["autoplace:timer"]=0}onSetScale(){var i,n,s;if(!fo._hasPlaced)return;const e=(n=(i=J.active)==null?void 0:i.rig)==null?void 0:n.gameObject;if(e){const a=((s=J.active)==null?void 0:s.rigScale)||1,l=1/this._arScale*a,c=new d.Matrix4().makeScale(l,l,l).invert();e.matrix.premultiply(c),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){var e;for(const i of this._reticle)i&&(i.visible=!1,i==null||i.removeFromParent());this._reticle.length=0;for(let i=this._placementScene.children.length-1;i>=0;i--){const n=this._placementScene.children[i];this.context.scene.add(n)}(e=this._createdPlacementObject)==null||e.removeFromParent();for(const i of this._reparentedComponents)C.addComponent(i.originalObject,i.comp)}async onCreateAnchor(e,i){if(i.createAnchor===void 0){console.warn("Hit does not support creating an anchor",i),j()&&me("Hit does not support creating an anchor");return}else{const n=await i.createAnchor(e.viewerPose.transform);e.running&&n&&(this._anchor=n)}}applyViewBasedTransform(e){const i=this.context.mainCamera,n=e,s=i.worldPosition,a=n.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const l=i.worldPosition;l&&e.position.clone().sub(l).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const c=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,h=30;c>h&&c<180-h||c<-h&&c>-180+h?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(s.y=a.y,e.lookAt(s))}onApplyPose(e){var s,a,l;const i=(a=(s=J.active)==null?void 0:s.rig)==null?void 0:a.gameObject;if(!i){console.warn("No rig object to place");return}const n=i.parent||this.context.scene;this._rigPlacementMatrix?(l=this._rigPlacementMatrix)==null||l.decompose(i.position,i.quaternion,i.scale):this._rigPlacementMatrix=i.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(i),e.removeFromParent(),i.scale.set(this.arScale,this.arScale,this.arScale),i.position.multiplyScalar(this.arScale),i.updateMatrix(),this.invertForward&&i.matrix.premultiply(TO),i.matrix.premultiply(this._startOffset),i.matrix.decompose(i.position,i.quaternion,i.scale),n.add(i)}};r(fo,"_eventListeners",{}),r(fo,"_hasPlaced",!1);let is=fo;const rr=class rr{constructor(t){r(this,"oneFingerDrag",!0);r(this,"twoFingerRotate",!0);r(this,"twoFingerScale",!0);r(this,"factor",1);r(this,"context");r(this,"offset");r(this,"plane");r(this,"_scale",1);r(this,"_hasChanged",!1);r(this,"_enabled",!1);r(this,"currentlyUsedPointerIds",new Set);r(this,"currentlyUnusedPointerIds",new Set);r(this,"onPointerDownEarly",t=>{this.isActive&&t.stopPropagation()});r(this,"onPointerDownLate",t=>{t.used?this.currentlyUsedPointerIds.add(t.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(t.pointerId)});r(this,"onPointerUpEarly",t=>{this.currentlyUsedPointerIds.delete(t.pointerId),this.currentlyUnusedPointerIds.delete(t.pointerId)});r(this,"prev",new Map);r(this,"_didMultitouch",!1);r(this,"touchStart",t=>{if(!t.defaultPrevented)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=exports.DeviceUtilities.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const s=this.prev.get(i.identifier);if(s){const a=this.getPositionOnPlane(i.clientX,i.clientY);s.x=a.x,s.z=a.z,s.screenx=i.clientX,s.screeny=i.clientY}}});r(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e];this.prev.delete(i.identifier)}});r(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const e=t.touches[0],i=this.prev.get(e.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(e.clientX,e.clientY),s=n.x-i.x,a=n.z-i.z;if(s===0&&a===0)return;this.oneFingerDrag&&this.addMovement(s,a),i.x=n.x,i.z=n.z,i.screenx=e.clientX,i.screeny=e.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const e=t.touches[0],i=t.touches[1],n=this.prev.get(e.identifier),s=this.prev.get(i.identifier);if(!n||!s)return;if(this.twoFingerRotate){const a=Math.atan2(e.clientY-i.clientY,e.clientX-i.clientX),l=Math.atan2(n.screeny-s.screeny,n.screenx-s.screenx),c=a-l;Math.abs(c)>.001&&this.addRotation(c)}if(this.twoFingerScale){const a=e.clientX-i.clientX,l=e.clientY-i.clientY,c=Math.sqrt(a*a+l*l),h=n.screenx-s.screenx,u=n.screeny-s.screeny,f=Math.sqrt(h*h+u*u),p=c-f;Math.abs(p)>2&&this.addScale(p)}n.screenx=e.clientX,n.screeny=e.clientY,s.screenx=i.clientX,s.screeny=i.clientY}}});r(this,"_raycaster",new d.Raycaster);r(this,"_intersection",new d.Vector3);r(this,"_screenPos",new d.Vector3);r(this,"_tempMatrix",new d.Matrix4);this.context=t,this.offset=new d.Matrix4,this.plane=new d.Plane,this.plane.setFromNormalAndCoplanarPoint(rr.up,rr.zero)}get scale(){return this._scale}reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(t,e){this._hasChanged=!1,e?(this.offset.invert(),t.premultiply(this.offset)):t.multiply(this.offset)}get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:ri.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ri.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ri.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:ri.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ri.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ri.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(t,e){const i=this.context.mainCamera;return this._screenPos.x=t/window.innerWidth*2-1,this._screenPos.y=-(e/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(t,e){t/=this._scale,e/=this._scale,t*=this.factor,e*=this.factor,this.offset.elements[12]+=t,this.offset.elements[14]+=e,(t!==0||e!==0)&&(this._hasChanged=!0)}addScale(t){t/=window.innerWidth,t*=-1,this._scale*=1+t,this._tempMatrix.makeScale(1-t,1-t,1-t),this.offset.premultiply(this._tempMatrix),t!==0&&(this._hasChanged=!0)}addRotation(t){t*=-1,this._tempMatrix.makeRotationY(t),this.offset.premultiply(this._tempMatrix),t!==0&&(this._hasChanged=!0)}};r(rr,"up",new d.Vector3(0,1,0)),r(rr,"zero",new d.Vector3(0,0,0)),r(rr,"one",new d.Vector3(1,1,1));let Em=rr;const mo=S("debugautosync"),Pp=Symbol("syncerId");class AO{constructor(){r(this,"_syncers",{})}getOrCreateSyncer(t){if(!t.guid)return null;if(this._syncers[t.guid])return this._syncers[t.guid];const e=new LO(t);return e[Pp]=t.guid,this._syncers[e[Pp]]=e,e}removeSyncer(t){delete this._syncers[t[Pp]]}}const cy=new AO;class LO{constructor(t){r(this,"comp");r(this,"hasChanges",!1);r(this,"changedProperties",{});r(this,"_isReceiving",!1);r(this,"_isInit",!1);r(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const t=this.comp.context.connection;if(!t||!t.isConnected||!t.isInRoom){for(const e in this.changedProperties)delete this.changedProperties[e];return}for(const e in this.changedProperties){const i=this.changedProperties[e];mo&&console.log("SEND",this.comp.guid,this.networkingKey),t.send(this.networkingKey,{guid:this.comp.guid,property:e,data:i},fn.Queued),delete this.changedProperties[e]}});r(this,"onHandleReceiving",t=>{if(mo&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,t),!!this._isInit&&this.comp&&t.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[t.property]=t.data}catch(e){console.error(e)}finally{this._isReceiving=!1}});this.comp=t}get networkingKey(){return this.comp.guid}init(t){if(this._isInit)return;this._isInit=!0,this.comp=t,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const e=this.comp.context.connection.tryGetState(this.comp.guid);e&&this.onHandleReceiving(e)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(t,e){this._isReceiving||(mo&&console.log("Property changed: "+t,e),this.hasChanges=!0,this.changedProperties[t]=e)}}function DO(o,t){let e=t!==o;return!e&&o&&t&&(Array.isArray(o)&&Array.isArray(t)||typeof o=="object"&&typeof t=="object")&&(e=!0),e}const yc=Symbol("AutoSyncHandler");function IO(o){if(o[yc])return o[yc];const t=cy.getOrCreateSyncer(o);return t==null||t.init(o),o[yc]=t,t}function jO(o){const t=o[yc];t&&(cy.removeSyncer(t),t.destroy(),delete o[yc])}const hy=function(o=null){return function(t,e){var u;let i="";typeof e=="string"?i=e:i=e.name;let n=null,s;typeof o=="string"?s=t[o]:typeof o=="function"&&(s=o),s==null&&(j()||mo)&&o!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+o+'"');const a=t,l=a.__internalAwake;if(typeof l!="function"){(mo||j())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((u=t==null?void 0:t.constructor)==null?void 0:u.name)+'" is not supported',t);return}mo&&console.log(i);const c=Symbol(i);a.__internalAwake=function(){if(this[c]!==void 0)return;this[c]=this[i],n=cy.getOrCreateSyncer(this);const f=Object.getOwnPropertyDescriptor(this,i);if((f==null?void 0:f.set)===void 0){let p=!1;Object.defineProperty(this,i,{set:function(g){var b;const y=this[c];if(this[c]=g,p){(j()||mo)&&console.warn("Recursive call detected",i);return}p=!0;try{const _=DO(g,y);mo&&console.log("SyncField assignment",i,"changed?",_,g,s),_&&(s==null?void 0:s.call(this,g,y))!==!1&&((b=IO(this))==null||b.notifyChanged(i,g))}finally{p=!1}},get:function(){return this[c]},configurable:!0,enumerable:!0})}n==null||n.init(this),l.call(this)};const h=a.__internalDestroy;a.__internalDestroy=function(){jO(this),h.call(this)}}};var BO=Object.defineProperty,cf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&BO(t,e,n),n};const Wt=S("debugplayersync"),hf=class ex extends I{constructor(){super(...arguments);r(this,"autoSync",!0);r(this,"asset");r(this,"onPlayerSpawned");r(this,"_localInstance");r(this,"onJoinedRoom",()=>{Wt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()});r(this,"destroyInstance",()=>{var e;(e=this._localInstance)==null||e.then(i=>{Wt&&console.log("PlayerSync.destroyInstance",i),oh(i,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(e,i){const n=te.getOrCreateFromUrl(e);if(!n.asset){const l=await n.loadAssetAsync();l&&C.getOrAddComponent(l,yn)}const s=new ex;s._internalInit(i),s.asset=n;const a=new d.Object3D;return a.guid=e,C.addComponent(a,s),s}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new ye)}onEnable(){this.context.connection.beginListen(ee.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ee.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ee.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ee.LeftRoom,this.destroyInstance)}async getInstance(){var i,n,s,a,l,c;if(this._localInstance)return this._localInstance;if(Wt&&console.log("PlayerSync.createInstance",(i=this.asset)==null?void 0:i.url),!((n=this.asset)!=null&&n.asset)&&!((s=this.asset)!=null&&s.url))return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=(a=this.asset)==null?void 0:a.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const h=C.getComponentsInChildren(e,yn);if(Wt&&console.log(`PlayerSync.createInstance: found ${h==null?void 0:h.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),h!=null&&h.length){for(const u of h)u.owner=this.context.connection.connectionId;(l=this.onPlayerSpawned)==null||l.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((c=this.asset)==null?void 0:c.url)+"</strong>: please make sure the asset has a PlayerState component!"),C.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let i=yn.all.length-1;i>=0;i--){const n=yn.all[i];(!n.owner||!this.context.connection.userIsInRoom(n.owner))&&n.doDestroy()}})}};cf([m()],hf.prototype,"autoSync");cf([m(te)],hf.prototype,"asset");cf([m(ye)],hf.prototype,"onPlayerSpawned");let dy=hf;var tx=(o=>(o.OwnerChanged="ownerChanged",o))(tx||{}),ke;const Tm=(ke=class extends I{constructor(){super(...arguments);r(this,"onOwnerChangeEvent",new ye);r(this,"onFirstOwnerChangeEvent",new ye);r(this,"hasOwner",!1);r(this,"owner");r(this,"dontDestroy",!1);r(this,"onUserLeftRoom",e=>{if(e.userId===this.owner){Wt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return ke._all}static get local(){return ke._local}static getFor(e){if(e instanceof d.Object3D)return C.getComponentInParent(e,ke);if(e instanceof I)return C.getComponentInParent(e.gameObject,ke)}static isLocalPlayer(e){const i=ke.getFor(e);return(i==null?void 0:i.isLocalPlayer)??!1}static addEventListener(e,i){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(i),i}static removeEventListener(e,i){if(!this._callbacks[e])return;const n=this._callbacks[e].indexOf(i);n>=0&&this._callbacks[e].splice(n,1)}static dispatchEvent(e,i){if(this._callbacks[e])for(const n of this._callbacks[e])n(i)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,i){var l,c;Wt&&console.log(`PlayerSync.onOwnerChange: ${i} → ${e} (me: ${this.context.connection.connectionId})`);const n=ke._local.indexOf(this);n>=0&&ke._local.splice(n,1);const s={playerState:this,oldValue:i,newValue:e};if(this.hasOwner||(this.hasOwner=!0,(l=this.onFirstOwnerChangeEvent)==null||l.invoke(s)),(c=this.onOwnerChangeEvent)==null||c.invoke(s),this.owner===this.context.connection.connectionId){ke._local.push(this);const h=new CustomEvent("local-owner-changed",{detail:s});this.dispatchEvent(h)}const a=new CustomEvent("owner-changed",{detail:s});this.dispatchEvent(a),ke.dispatchEvent("ownerChanged",a)}awake(){ke.all.push(this),Wt&&console.log("Registered new PlayerState",this.guid,ke.all.length-1,ke.all),this.context.connection.beginListen(ee.UserLeftRoom,this.onUserLeftRoom)}async start(){Wt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Jn(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Wt&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Wt&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Wt&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Wt&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Wt&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Wt&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),oh(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Wt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ee.UserLeftRoom,this.onUserLeftRoom),ke.all.splice(ke.all.indexOf(this),1),this.isLocalPlayer){const e=ke._local.indexOf(this);e>=0&&ke._local.splice(e,1)}}},r(ke,"_all",[]),r(ke,"_local",[]),r(ke,"_callbacks",{}),ke);cf([hy(Tm.prototype.onOwnerChange)],Tm.prototype,"owner");let yn=Tm;var FO=Object.defineProperty,ul=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&FO(t,e,n),n};class rs extends I{constructor(){super(...arguments);r(this,"position","bottom");r(this,"showNeedleLogo",!1);r(this,"showSpatialMenu");r(this,"createFullscreenButton");r(this,"createMuteButton");r(this,"createQRCodeButton")}onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(exports.DeviceUtilities.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}ul([m()],rs.prototype,"position");ul([m()],rs.prototype,"showNeedleLogo");ul([m()],rs.prototype,"showSpatialMenu");ul([m()],rs.prototype,"createFullscreenButton");ul([m()],rs.prototype,"createMuteButton");ul([m()],rs.prototype,"createQRCodeButton");var UO=Object.defineProperty,uy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&UO(t,e,n),n};const Dl=S("debugwebxr"),Eb=new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI);class Oo extends I{constructor(){super(...arguments);r(this,"head");r(this,"leftHand");r(this,"rightHand");r(this,"_leftHandMeshes");r(this,"_rightHandMeshes");r(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;Dl&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const i=yn.getFor(this);if(i!=null&&i.owner){const n=this.gameObject.addComponent(At);n.avatar=this.gameObject,n.connectionId=i.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):i&&!this.context.connection.isConnected&&(i.dontDestroy=!0)}onLeaveXR(e){const i=this.gameObject.getComponent(At);i&&i.destroy()}onUpdateXR(e){var h,u;if(!this.activeAndEnabled)return;const i=yn.isLocalPlayer(this);if(!i)return;const n=e.xr;if(n.rig&&n.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),n.rig.gameObject.add(this.gameObject)),this._syncTransforms&&i)for(const f of this._syncTransforms)f.fastMode=!0,f.isOwned()||f.requestOwnership();if(this.head&&this.context.mainCamera){const f=this.head.asset;if(f.position.copy(this.context.mainCamera.position),f.position.x*=-1,f.position.z*=-1,f.quaternion.copy(this.context.mainCamera.quaternion),f.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const p=C.getComponentsInChildren(this.head.asset,$i);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const s=e.xr.leftController,a=(h=this.leftHand)==null?void 0:h.asset;s&&a?(a.position.copy(s.gripPosition),a.quaternion.copy(s.gripQuaternion),a.quaternion.multiply(Eb),a.visible=s.isTracking,this.updateHandVisibility(s,a,this._leftHandMeshes)):a&&a.visible&&(a.visible=!1);const l=e.xr.rightController,c=(u=this.rightHand)==null?void 0:u.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(Eb),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._rightHandMeshes)):c&&c.visible&&(c.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,i,n){if(n){const s=e.model&&e.model.visible&&e.model!==i;n.forEach(a=>{xs(a,!s)})}}updateRemoteAvatarVisibility(){var e,i,n;if(this.context.connection.isConnected){const s=yn.getFor(this);if(s&&s.isLocalPlayer==!1){const a=J.getXRSync(this.context);if(a&&a.hasState(s.owner)){this.tryFindAvatarObjectsIfMissing();const l=(e=this.leftHand)==null?void 0:e.asset;l&&(l.visible=(a==null?void 0:a.isTracking(s.owner,"left"))??!1);const c=(i=this.rightHand)==null?void 0:i.asset;c&&(c.visible=(a==null?void 0:a.isTracking(s.owner,"right"))??!1)}if((n=this.head)!=null&&n.asset){const l=C.getComponentsInChildren(this.head.asset,$i);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};J0.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){var e,i;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof d.Object3D&&(this.head=new te("",this.sourceId,this.head));else{const n=new d.Object3D;n.name="Head";const s=Lo.createPrimitive(Or.Cube);n.add(s),this.gameObject.add(n),this.head=new te("",this.sourceId,n),Dl&&console.log("Create head",n)}if(this.rightHand)this.rightHand instanceof d.Object3D&&(this.rightHand=new te("",this.sourceId,this.rightHand));else{const n=new d.Object3D;n.name="Right Hand",this.gameObject.add(n),this.rightHand=new te("",this.sourceId,n),Dl&&console.log("Create right hand",n)}if(this.leftHand)this.leftHand instanceof d.Object3D&&(this.leftHand=new te("",this.sourceId,this.leftHand));else{const n=new d.Object3D;n.name="Left Hand",this.gameObject.add(n),this.leftHand=new te("",this.sourceId,n),Dl&&console.log("Create left hand",n)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(e=this.leftHand.asset)==null||e.traverse(n=>{n!=null&&n.isMesh&&this._leftHandMeshes.push(n)}),this._rightHandMeshes=[],(i=this.rightHand.asset)==null||i.traverse(n=>{n!=null&&n.isMesh&&this._rightHandMeshes.push(n)}),yn.isLocalPlayer(this.gameObject)&&(this._syncTransforms=C.getComponentsInChildren(this.gameObject,es))}async loadAvatarObjects(e,i,n){const s=e.loadAssetAsync(),a=i.loadAssetAsync(),l=n.loadAssetAsync(),c=new Array;s&&c.push(s),a&&c.push(a),l&&c.push(l);const h=await Gm(c);Dl&&console.log("Avatar loaded results:",h)}}uy([m(te)],Oo.prototype,"head");uy([m(te)],Oo.prototype,"leftHand");uy([m(te)],Oo.prototype,"rightHand");var zO=Object.defineProperty,df=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&zO(t,e,n),n};const fs=S("debugwebxr"),Ks=new Array;class ns extends I{constructor(){super(...arguments);r(this,"createControllerModel",!0);r(this,"createHandModel",!0);r(this,"customLeftHand");r(this,"customRightHand");r(this,"_models",new Array)}supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}async onXRControllerAdded(e){var s;if(!(e.xr.isVR||e.xr.isPassThrough))return;const{controller:n}=e;if(fs&&console.warn("Add Controller Model for",n.side,n.index),this.createControllerModel||this.createHandModel){if(n.hand){if(this.createHandModel){const a=await this.loadHandModel(this,n);if(!a||!n.connected||!n.isHand){a!=null&&a.handObject&&pa(a.handObject,!1),(s=a==null?void 0:a.handObject)==null||s.destroy();return}this._models.push({controller:n,model:a.handObject,handmesh:a.handmesh}),this._models.sort((l,c)=>l.controller.index-c.controller.index),this.scene.add(a.handObject),n.model=a.handObject}}else if(this.createControllerModel){const a=await n.getModelUrl();if(a){const l=await this.loadModel(n,a);if(!l||!n.connected||n.isHand)return;this._models.push({controller:n,model:l}),this._models.sort((c,h)=>c.controller.index-h.controller.index),this.scene.add(l),l.traverse(c=>{c.layers.set(2),c.matrixAutoUpdate=!1,c.updateMatrix()}),n.model=l}else n.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+n.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const i=this._models.findIndex(s=>s.controller===e.controller),n=this._models[i];n&&(this._models.splice(i,1),n.model&&(pa(n.model,!1),n.model.destroy(),n.model=void 0))}onBeforeXR(e,i){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.includes("hand-tracking")||i.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const i of this._models)i&&(i.model&&(pa(i.model,!1),i.model.destroy(),i.model=void 0),i.controller.model===i.model&&(i.controller.model=null));this._models.length=0}onBeforeRender(){if(J.active&&(fs&&(Ks[0]=Date.now()),this.updateRendering(J.active),fs)){const e=Date.now()-Ks[0];Ks.push(e),Ks.length>=30&&(Ks[0]=0,Ks.reduce((i,n)=>i+n,0)/Ks.length,Ks.length=0)}}updateRendering(e){var i,n,s,a,l;for(let c=0;c<this._models.length;c++){const h=this._models[c];if(!h)continue;const u=h.controller;if(!u.connected){fs&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",u.side,u.hand);continue}if(h.model&&!h.handmesh)h.model.matrixAutoUpdate=!1,h.model.matrix.copy(u.gripMatrix),h.model.visible=u.isTracking,(i=e.rig)==null||i.gameObject.add(h.model);else if(u.inputSource.hand&&h.handmesh){const f=e.referenceSpace,p=this.context.renderer.xr.getHand(u.index);if(f&&e.frame.getJointPose){for(const g of u.inputSource.hand.values()){const y=p.joints[g.jointName];if(y){const b=u.getHandJointPose(g);if(b){const _=b.transform.position,v=b.transform.orientation;y.position.copy(_),y.quaternion.copy(v),y.matrixAutoUpdate=!1}y.visible=b!=null}}h.model&&(h.model.visible=u.isTracking,h.model.visible&&h.model.parent!==((n=e.rig)==null?void 0:n.gameObject)&&((s=e.rig)==null||s.gameObject.add(h.model))),(a=h.model)!=null&&a.visible&&((l=h.handmesh)==null||l.updateMesh(),h.model.matrixAutoUpdate=!1,h.model.matrix.identity(),h.model.applyMatrix4(Aa))}}}}async loadModel(e,i){var a;if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const s=await te.getOrCreate("",i).instantiate();return pa(s),(a=J.active)!=null&&a.isPassThrough&&s.traverseVisible(l=>{this.makeOccluder(l)}),s}async loadHandModel(e,i){const n=this.context,s=n.renderer.xr.getHand(i.index);s||(fs?$.DrawLabel(i.rayWorldPosition,"No hand found for index "+i.index,.05,5):console.warn("No hand found for index "+i.index));const a=new H.GLTFLoader;Og(a,n),await yu(a,n,this.sourceId??"");const l=Xg(a);let c="";const h=i.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),a.setPath("")):(c=i.inputSource.handedness==="left"?"left":"right",a.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const u=new d.Object3D;pa(u);const f=new H.XRHandMeshModel(u,s,a.path,c,a,p=>{var y;const g=l==null?void 0:l.gltf;((y=g==null?void 0:g.scene.children)==null?void 0:y.length)===0&&(g.scene.children[0]=p),l!=null&&l.gltf&&bn().createBuiltinComponents(e.context,e.sourceId||c,l.gltf,null,l),p.traverse(b=>{var _;b.layers.set(2),(_=J.active)!=null&&_.isPassThrough&&!h&&this.makeOccluder(b),b instanceof d.Mesh&&le.NEEDLE_progressive.assignMeshLOD(b,0)}),i.connected||(fs&&$.DrawLabel(i.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if(fs&&u.add(new d.AxesHelper(.5)),i.inputSource.hand){fs&&console.log(i.inputSource.hand);for(const p of i.inputSource.hand.values())if(s.joints[p.jointName]===void 0){const g=new d.Group;g.matrixAutoUpdate=!1,g.visible=!0,s.joints[p.jointName]=g,s.add(g)}}else fs&&$.DrawLabel(i.rayWorldPosition,"No inputSource.hand found for index "+i.index,.05,5);return{handObject:u,handmesh:f}}makeOccluder(e){if(e instanceof d.Mesh){let i=e.material;i instanceof d.Material&&(i=e.material=i.clone(),i.depthWrite=!0,i.depthTest=!0,i.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}r(ns,"factory",new H.XRControllerModelFactory);df([m()],ns.prototype,"createControllerModel");df([m()],ns.prototype,"createHandModel");df([m(te)],ns.prototype,"customLeftHand");df([m(te)],ns.prototype,"customRightHand");class uf extends I{}var NO=Object.defineProperty,Bo=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&NO(t,e,n),n};const Mp=S("debugwebxr");class Ai extends I{constructor(){super(...arguments);r(this,"movementSpeed",1.5);r(this,"rotationStep",30);r(this,"useTeleport",!0);r(this,"usePinchToTeleport",!0);r(this,"useTeleportTarget",!1);r(this,"useTeleportFade",!1);r(this,"showRays",!0);r(this,"showHits",!0);r(this,"isXRMovementHandler",!0);r(this,"xrSessionMode","immersive-vr");r(this,"_didApplyRotation",!1);r(this,"_didTeleport",!1);r(this,"_teleportBuffer",new Array);r(this,"_plane",null);r(this,"_lines",[]);r(this,"_hitDiscs",[]);r(this,"_hitDistances",[]);r(this,"_lastHitDistances",[]);r(this,"hitPointRaycastFilter",e=>e.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(e){const i=e.xr.rig;if(!(i!=null&&i.gameObject)||e.xr.isPassThrough)return;const n=e.xr.leftController,s=e.xr.rightController;n&&this.onHandleMovement(n,i.gameObject),s&&(this.onHandleRotation(s,i.gameObject),this.useTeleport&&this.onHandleTeleport(s,i.gameObject))}onLeaveXR(e){for(const i of this._lines)i.removeFromParent();for(const i of this._hitDiscs)i==null||i.removeFromParent()}onBeforeRender(){var e;(e=this.context.xr)!=null&&e.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,i){const n=e.getStick("xr-standard-thumbstick");if(n.x!=0||n.y!=0){const s=V(n.x,0,n.y);s.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const a=Ue(i);s.multiplyScalar(a.x),s.applyQuaternion(e.xr.poseOrientation),s.y=0,s.applyQuaternion(i.worldQuaternion),i.position.add(s),i.updateWorldMatrix(!1,!1);for(const l of i.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(e,i){if(e._isMxInk)return;const s=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(s)<.3&&(this._didApplyRotation=!1);else if(Math.abs(s)>.5){this._didApplyRotation=!0;const a=s>0?1:-1,l=Q(this.context.mainCamera).clone();i.rotateY(a*z.toRadians(this.rotationStep));const h=Q(this.context.mainCamera).clone().sub(l);h.y=0,i.position.sub(h)}}onHandleTeleport(e,i){var s,a,l,c,h;let n=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const u=e.getPointerId("primary");if(u!=null&&this.context.input.getIsPointerIdInUse(u))return;const f=e.getGesture("pinch");f&&(n=f.value)}else n=(s=e.getStick("xr-standard-thumbstick"))==null?void 0:s.y;if(this._didTeleport)n>=0&&n<.4?this._didTeleport=!1:n<0&&n>-.4&&(this._didTeleport=!1);else if(n>.8){this._didTeleport=!0;const u=this.context.physics.raycastFromRay(e.ray)[0];if(u&&u.object instanceof H.GroundedSkybox){const p=(a=u.normal)==null?void 0:a.dot(V(0,1,0));if(p!==void 0&&p<.4)return}let f=u==null?void 0:u.point;if(!f&&!this.useTeleportTarget){this._plane||(this._plane=new d.Plane(new d.Vector3(0,1,0),0));const p=i.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new d.Vector3(0,1,0),p);const g=e.ray;f=p.clone(),this._plane.intersectLine(new d.Line3(g.origin,V(g.direction).multiplyScalar(1e4).add(g.origin)),f),f.distanceTo(p)>i.scale.x*10&&(f=null)}if(f){if(this.useTeleportTarget&&!C.getComponentInParent(u.object,uf))return;const p=f.clone();if(Mp&&$.DrawSphere(f,.025,16711680,5),(l=this.context.mainCamera)==null?void 0:l.position){const y=(c=this.context.xr)==null?void 0:c.getUserOffsetInRig();y&&(y.y=0,p.sub(y),Mp&&$.DrawWireSphere(y.add(p),.025,65280,5))}this._teleportBuffer.push(i.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(h=e.xr.fadeTransition())==null||h.then(()=>{i.worldPosition=p}):i.worldPosition=p}}else if(n<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const u=this._teleportBuffer.pop();u&&u.decompose(i.position,i.quaternion,i.scale)}}renderRays(e){var i;for(let n=0;n<this._lines.length;n++){const s=this._lines[n];s&&(s.visible=!1)}for(let n=0;n<e.controllers.length;n++){const s=e.controllers[n];let a=this._lines[n];if(!s.connected||!s.isTracking||!s.ray||s.targetRayMode==="transient-pointer"||!s.hasSelectEvent){a&&(a.visible=!1);continue}a||(a=this.createRayLineObject(),a.scale.z=.5,this._lines[n]=a),s.updateRayWorldPosition(),s.updateRayWorldQuaternion();const l=s.rayWorldPosition,c=s.rayWorldQuaternion;a.position.copy(l),a.quaternion.copy(c);const h=e.rigScale,u=this.usePinchToTeleport&&s.isTeleportGesture,f=this._lastHitDistances[n],p=this._hitDistances[n]!=null,g=f??h;a.scale.set(h,h,g),a.visible=!0,a.layers.disableAll(),a.layers.enable(2);let y=a.material.opacity;u?y=1:this.showHits&&g<e.rigScale*.5?y=0:(i=s.getButton("primary"))!=null&&i.pressed?y=.5:y=p?.2:.1,a.material.opacity=z.lerp(a.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),a.parent!==this.context.scene&&this.context.scene.add(a)}}renderHits(e){var i;for(const n of this._hitDiscs){if(!n)continue;const s=n.controller;if(!s||!s.connected||!s.isTracking){n.visible=!1;continue}}for(let n=0;n<e.controllers.length;n++){const s=e.controllers[n];if(!s.connected||!s.isTracking||!s.ray||!s.hasSelectEvent)continue;let a=this._hitDiscs[n],l=!0;const c=s.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(a&&(a.visible=!1),this._hitDistances[n]=null,this._lastHitDistances[n]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+s.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[n];p&&p.visible&&p.hit&&this.updateHitPointerPosition(s,p,p.hit.distance);continue}const u=this.context.physics.raycastFromRay(s.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let f=u.find(p=>this.usePinchToTeleport&&s.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(f||(f=u[0]),a&&(a.controller=s,a.hit=f),this._hitDistances[n]=(f==null?void 0:f.distance)||null,f){this._lastHitDistances[n]=f.distance;const p=e.rigScale??1;Mp&&($.DrawWireSphere(f.point,.025*p,16711680),$.DrawLabel(V(0,.2,0).add(f.point),f.object.name,.02,0)),a||(a=this.createHitPointObject(),this._hitDiscs[n]=a),a.hit=f,a.visible=f.distance>p*.05;let g=.01*(p+f.distance);const y=(i=s.getButton("primary"))==null?void 0:i.pressed;y&&(g*=1.1),a.scale.set(g,g,g),a.layers.set(2);let b=a.material.opacity;if(y?b=1:b=f.distance<.15*p?.2:.6,a.material.opacity=z.lerp(a.material.opacity,b,this.context.time.deltaTimeUnscaled/.1),a.visible){if(f.normal){this.updateHitPointerPosition(s,a,f.distance);const _=f.normal.applyQuaternion(_e(f.object));a.quaternion.setFromUnitVectors($O,_)}else this.updateHitPointerPosition(s,a,f.distance);a.parent!==this.context.scene&&this.context.scene.add(a)}}else this._hitDiscs[n]&&(this._hitDiscs[n].visible=!1)}}isObjectWithInteractiveComponent(e,i=0){return cu(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,i+1):!1}updateHitPointerPosition(e,i,n){const s=V(e.rayWorldPosition);s.add(V(0,0,n-.01).applyQuaternion(e.rayWorldQuaternion)),i.position.lerp(s,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const e=new d.Mesh(new d.SphereGeometry(.3,6,6),new d.MeshBasicMaterial({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:d.DoubleSide}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new H.Line2;e.layers.disableAll(),e.layers.enable(2);const i=new H.LineGeometry;e.geometry=i;const n=new Float32Array(9);n.set([0,0,.02,0,0,.4,0,0,1]),i.setPositions(n);const s=new Float32Array(9);s.set([1,1,1,.1,.1,.1,0,0,0]),i.setColors(s);const a=new H.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:d.AdditiveBlending,dashed:!1});return e.material=a,e}}Bo([m()],Ai.prototype,"movementSpeed");Bo([m()],Ai.prototype,"rotationStep");Bo([m()],Ai.prototype,"useTeleport");Bo([m()],Ai.prototype,"usePinchToTeleport");Bo([m()],Ai.prototype,"useTeleportTarget");Bo([m()],Ai.prototype,"useTeleportFade");Bo([m()],Ai.prototype,"showRays");Bo([m()],Ai.prototype,"showHits");const $O=new d.Vector3(0,1,0);var VO=Object.defineProperty,ft=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&VO(t,e,n),n};const Il=S("debugwebxr"),WO=S("debugusdz");var mn;const at=(mn=class extends I{constructor(){super(...arguments);r(this,"createVRButton",!0);r(this,"createARButton",!0);r(this,"createSendToQuestButton",!0);r(this,"createQRCode",!0);r(this,"useDefaultControls",!0);r(this,"showControllerModels",!0);r(this,"showHandModels",!0);r(this,"usePlacementReticle",!0);r(this,"customARPlacementReticle");r(this,"usePlacementAdjustment",!0);r(this,"arScale",1);r(this,"useXRAnchor",!1);r(this,"autoPlace",!1);r(this,"autoCenter",!1);r(this,"useQuicklookExport",!1);r(this,"useDepthSensing",!1);r(this,"useSpatialGrab",!0);r(this,"defaultAvatar");r(this,"_playerSync");r(this,"_createdComponentsInSession",[]);r(this,"_usdzExporter");r(this,"_exitXRMenuButton");r(this,"_previousXRState",0);r(this,"_spatialGrabRaycaster");r(this,"_activeWebARSessionRoot",null);r(this,"onAvatarSpawned",e=>{Il&&console.log("WebXR.onAvatarSpawned",e),C.getComponentInChildren(e,Oo)??(i=C.addComponent(e,Oo))});r(this,"_buttonFactory");r(this,"_buttons",[])}awake(){J.getXRSync(this.context)}onEnable(){var e,i;window.location.protocol!=="https:"&&me('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),this.useQuicklookExport&&(C.findObjectOfType(Kn)||(Il&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=C.addComponent(this.gameObject,Kn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(Il&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new te("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(dy),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(e=this._playerSync.onPlayerSpawned)==null||e.removeEventListener(this.onAvatarSpawned),(i=this._playerSync.onPlayerSpawned)==null||i.addEventListener(this.onAvatarSpawned))}onDisable(){var e;(e=this._usdzExporter)==null||e.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await J.isVRSupported()&&this.createVRButton?J.offerSession("immersive-vr","default",this.context):this.createARButton&&await J.isARSupported()&&this.createARButton?J.offerSession("immersive-ar","default",this.context):!1}get session(){return J.active??null}get sessionMode(){return J.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return J.start("immersive-vr",e,this.context)}async enterAR(e){return J.start("immersive-ar",e,this.context)}exitXR(){J.stop()}get isActiveWebXR(){return!mn.activeWebXRComponent||mn.activeWebXRComponent===this}onBeforeXR(e,i){var n;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(n=mn.activeWebXRComponent)==null?void 0:n.name}). This is ignored: ${this.name}`);return}mn.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;Il&&console.log("WebXR onEnterXR"),this._previousXRState=Qt.Global.Mask;const i=e.xr.isVR;if(Qt.Global.Set(i?Bn.VR:Bn.AR),e.xr.isAR){let n=C.findObjectOfType(is);if(!n)if(this.usePlacementReticle){const s=new d.Object3D;for(const a of this.context.scene.children)s.add(a);this.context.scene.add(s),n=C.addComponent(s,is),this._createdComponentsInSession.push(n)}else(Il||j())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=n,n&&(n.customReticle=this.customARPlacementReticle,n.arScale=this.arScale,n.arTouchTransform=this.usePlacementAdjustment,n.autoPlace=this.autoPlace,n.autoCenter=this.autoCenter,n.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=C.findObjectOfType(Tr)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Tr))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){var i,n;if((i=this._exitXRMenuButton)==null||i.remove(),!!this.isActiveWebXR){Qt.Global.Set(this._previousXRState),(n=this._playerSync)==null||n.destroyInstance();for(const s of this._createdComponentsInSession)s.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),eh(1).then(()=>mn.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let i=this.gameObject.getComponent(Ai);return!i&&e&&(i=this.gameObject.addComponent(Ai),this._createdComponentsInSession.push(i)),i&&(i.enabled=e),i}setDefaultControllerRenderingEnabled(e){let i=this.gameObject.getComponent(ns);return!i&&e&&(i=this.gameObject.addComponent(ns),this._createdComponentsInSession.push(i),i.createControllerModel=this.showControllerModels,i.createHandModel==this.showHandModels),i&&(i.enabled=e),i}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Po.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||WO)&&this.useQuicklookExport){const i=C.findObjectOfType(Kn);if(!i||i&&i.allowCreateQuicklookButton){const n=this.getButtonsFactory().createQuicklookButton();this.addButton(n,50)}}if(this.createARButton){const i=this.getButtonsFactory().createARButton();this.addButton(i,50)}if(this.createVRButton){const i=this.getButtonsFactory().createVRButton();this.addButton(i,50)}}if(this.createSendToQuestButton&&!exports.DeviceUtilities.isQuest()&&J.isVRSupported().then(i=>{if(!i){const n=this.getButtonsFactory().createSendToQuestButton();this.addButton(n,50)}}),this.createQRCode){const i=hh(rs);if(i&&i.createQRCodeButton===!1)j()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const n=zn.getOrCreate().createQRCode();this.addButton(n,50)}}}addButton(e,i){this._buttons.push(e),e.setAttribute("priority",i.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}},r(mn,"activeWebXRComponent",null),mn);ft([m()],at.prototype,"createVRButton");ft([m()],at.prototype,"createARButton");ft([m()],at.prototype,"createSendToQuestButton");ft([m()],at.prototype,"createQRCode");ft([m()],at.prototype,"useDefaultControls");ft([m()],at.prototype,"showControllerModels");ft([m()],at.prototype,"showHandModels");ft([m()],at.prototype,"usePlacementReticle");ft([m(te)],at.prototype,"customARPlacementReticle");ft([m()],at.prototype,"usePlacementAdjustment");ft([m()],at.prototype,"arScale");ft([m()],at.prototype,"useXRAnchor");ft([m()],at.prototype,"autoPlace");ft([m()],at.prototype,"autoCenter");ft([m()],at.prototype,"useQuicklookExport");ft([m()],at.prototype,"useDepthSensing");ft([m()],at.prototype,"useSpatialGrab");ft([m(te)],at.prototype,"defaultAvatar");let ff=at;const _d=S("debugusdzbehaviours");class fy{constructor(){r(this,"behaviours",[]);r(this,"behaviourComponents",[]);r(this,"behaviourComponentsCopy",[]);r(this,"audioClips",[]);r(this,"audioClipsCopy",[]);r(this,"targetUuids",new Set)}get extensionName(){return"Behaviour"}addBehavior(t){this.behaviours.push(t)}addAudioClip(t){if(!t||typeof t!="string")return"";const i="audio/"+Wr.getName(t);return this.audioClips.push({clipUrl:t,filesKey:i}),i}getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(t){if(!t.root)return Promise.resolve();const e=[];return t.root.traverse(i=>{C.foreachComponent(i,n=>{var a;const s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const l=(a=s.beforeCreateDocument)==null?void 0:a.call(s,this,t);l instanceof Promise&&e.push(l)}},!1)}),_d&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(e)}onExportObject(t,e,i){var n;for(const s of this.behaviourComponents)(n=s.createBehaviours)==null||n.call(s,this,e,i)}onAfterBuildDocument(t){for(const f of this.behaviourComponents)typeof f.afterCreateDocument=="function"&&f.afterCreateDocument(this,t);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const e=new Set,i=new Set,n=new Set,s=new Set,a=_d;let l=`graph LR
1252
+ `))}for(const N of B){const Y=s.get(N);Y&&L.set(N,Y)}return L},y=function(B){const L=g(B),N=h(L);return u(L,N,B)};const b=n.skinnedMesh.skeleton,_=new Array,v=[],w=[];for(const B of b.bones){v.push(B),w.push(B.uuid);const L=b.boneInverses[b.bones.indexOf(B)];_.push({bone:B,inverse:L})}let x=1e4;for(;w.length<b.bones.length&&x-- >0;)for(const B of v){const L=B.children;for(const N of L)if(w.indexOf(N.uuid)===-1&&b.bones.indexOf(N)!==-1){v.push(N),w.push(N.uuid);const Y=b.boneInverses[b.bones.indexOf(N)];_.push({bone:N,inverse:Y})}}x<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,b.bones,w);for(const B of $w(b.bones))_.push({bone:B,inverse:B.matrixWorld.clone().invert()});const O=_[0].bone.parent;O||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),_.sort((B,L)=>Ba(B.bone,O)>Ba(L.bone,O)?1:-1);const E=e.quickLookCompatible,M=[],R=[],F=[],D=[];for(const{bone:B}of _){if(E){const L=B.scale;L.x==0&&(L.x=1e-5),L.y==0&&(L.y=1e-5),L.z==0&&(L.z=1e-5),M.push(new d.Matrix4().compose(B.position,B.quaternion,B.scale))}else M.push(B.matrix.clone());R.push(B.position),F.push(B.quaternion),D.push(B.scale)}const A=_.map(B=>'"'+Ba(B.bone,O)+'"').join(", "),T=_.map(B=>Sb(B.inverse.clone().invert())).join(", ");t.beginBlock('def Skeleton "Rig"'),t.appendLine(`uniform matrix4d[] bindTransforms = [${T}]`),t.appendLine(`uniform token[] joints = [${A}]`),t.appendLine('uniform token purpose = "guide"'),t.appendLine(`uniform matrix4d[] restTransforms = [${M.map(B=>Sb(B)).join(", ")}]`);const G=y(_.map(B=>B.bone));if(In){let B=1e7,L=0;for(const N of((a=G.position)==null?void 0:a.keys())??[])B=Math.min(B,N),L=Math.max(L,N);console.log("Time samples",B,L,G)}if(t.beginBlock('def SkelAnimation "_anim"'),t.appendLine(`uniform token[] joints = [${A}]`),t.appendLine(`quatf[] rotations = [${p(F)}]`),G&&G.quaternion){t.beginBlock("quatf[] rotations.timeSamples = {","");const B=c(G.quaternion);for(const L of B)t.appendLine(L);t.closeBlock()}if(t.appendLine(`half3[] scales = [${f(D)}]`),G&&G.scale){t.beginBlock("half3[] scales.timeSamples = {","");const B=l(G.scale);for(const L of B)t.appendLine(L);t.closeBlock()}if(t.appendLine(`float3[] translations = [${f(R)}]`),G&&G.position){t.beginBlock("float3[] translations.timeSamples = {","");const B=l(G.position);for(const L of B)t.appendLine(L);t.closeBlock()}t.closeBlock(),t.closeBlock()}}onSerialize(t,e){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let u=0;u<i.length;u++)i[u]===void 0&&(i[u]=new We(null,this.object,null));const n=this.ext;this.skinnedMeshExport(t,e,n);const s=this.object,a=this.model,l=this.animationData.get(s);if(!l||s.isSkinnedMesh)return;km&&console.log("SERIALIZE",this.model.name,this.object.type,l);const c=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function h(u,f){var g;if(u.some(y=>y&&{position:y.pos,rotation:y.rot,scale:y.scale}[f])){switch(f){case"position":a.needsTranslate=!0,t.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":a.needsOrient=!0,t.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":a.needsScale=!0,t.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let y=0;y<u.length;y++){const b=u[y];if(!b)continue;const _=n.getStartTimeByClip(b.clip),v=b.getSortedTimesArray(f==="position",f==="rotation",f==="scale");if(!v||v.length===0){console.error("got an animated object but no time values?",s,b);continue}const w=!b.clip,x=f==="position"&&(b.pos||w),O=f==="rotation"&&(b.rot||w),E=f==="scale"&&(b.scale||w);if(x||O||E){const M=((g=b.clip)==null?void 0:g.name)??"rest",R=b.getDuration();In&&console.log("Write .timeSamples:",M,_,R,u),t.appendLine("# "+M+": start="+c.format(_*We.frameRate)+", length="+c.format(R*We.frameRate)+", frames="+b.getFrames())}if(x)for(const{time:M,translation:R}of b.getValues(v,!0,!1,!1)){const D=`${c.format((_+M)*We.frameRate)}: (${se(R.x)}, ${se(R.y)}, ${se(R.z)}),`;t.appendLine(D)}if(O)for(const{time:M,rotation:R}of b.getValues(v,!1,!0,!1)){const D=`${c.format((_+M)*We.frameRate)}: (${se(R.w)}, ${se(R.x)}, ${se(R.y)}, ${se(R.z)}),`;t.appendLine(D)}if(E)for(const{time:M,scale:R}of b.getValues(v,!1,!1,!0)){const D=`${c.format((_+M)*We.frameRate)}: (${se(R.x)}, ${se(R.y)}, ${se(R.z)}),`;t.appendLine(D)}}t.closeBlock()}}h(l,"position"),h(l,"rotation"),h(l,"scale")}}const PO=S("debugusdz");class Wr{constructor(){r(this,"files",new Array)}static getName(t){var s;const e=t.split(".").pop();let n=(s=t.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:s.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),Xi(n)+"."+e}get extensionName(){return"Audio"}onExportObject(t,e,i){const n=C.getComponents(t,qi);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const a=s.clip.split("/").pop()||"Audio",l=Wr.getName(s.clip),c=Xi(l);if(!this.files.some(h=>h.path===s.clip)){this.files.push({path:s.clip,name:l});const h=l.toLowerCase();i.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||e.addEventListener("serialize",(h,u)=>{h.appendLine(),h.beginBlock(`def SpatialAudio "${c}"`,"(",!1),h.appendLine(`displayName = "${a}"`),h.closeBlock(")"),h.beginBlock(),h.appendLine(`uniform asset filePath = @audio/${l}@`),h.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${s.volume}`),h.closeBlock()})}}async onAfterSerialize(t){for(const e of this.files){const i="audio/"+e.name;if(t.files[i]){PO&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const a=await(await(await fetch(e.path)).blob()).arrayBuffer(),l=new Uint8Array(a);t.files[i]=l}}}var MO=Object.defineProperty,Ie=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&MO(t,e,n),n};const kb=S("debugusdzbehaviours");function wh(o){o&&(o.getComponentInParent(qa)||(j()&&console.debug('Raycaster on "'+o.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),o.addComponent(Ei)))}class Gr extends I{constructor(){super(...arguments);r(this,"object");r(this,"target");r(this,"duration",1);r(this,"relativeMotion",!1);r(this,"coroutine",null);r(this,"targetPos",new d.Vector3);r(this,"targetRot",new d.Quaternion);r(this,"targetScale",new d.Vector3)}start(){wh(this.gameObject)}onPointerClick(e){e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=Q(this.object).clone(),i=Q(this.target).clone(),n=_e(this.object).clone(),s=_e(this.target).clone(),a=Ue(this.object).clone(),l=Ue(this.target).clone(),c=e.distanceTo(i),h=n.angleTo(s),u=a.distanceTo(l);if(c<.01&&h<.01&&u<.01){st(this.object,i),Hi(this.object,s),Na(this.object,l),this.coroutine=null;return}let f=0,p=0;for(;f<1;)f+=this.context.time.deltaTime/this.duration,f>1&&(f=1),p=f<.5?4*f*f*f:1-Math.pow(-2*f+2,3)/2,this.targetPos.lerpVectors(e,i,p),this.targetRot.slerpQuaternions(n,s,p),this.targetScale.lerpVectors(a,l,p),st(this.object,this.targetPos),Hi(this.object,this.targetRot),Na(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),i=this.object.quaternion.clone(),n=this.object.scale.clone(),s=this.target.position.clone(),a=this.target.quaternion.clone(),l=this.target.scale.clone();s.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(s),this.targetRot.copy(this.object.quaternion).multiply(a),this.targetScale.copy(this.object.scale).multiply(l);let c=0,h=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),h=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,h),this.object.quaternion.slerpQuaternions(i,this.targetRot,h),this.object.scale.lerpVectors(n,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(e){var i;if(this.target&&this.object&&this.gameObject){const n=new vt("Move to "+((i=this.target)==null?void 0:i.name),wt.tapTrigger(this.gameObject),fe.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(n)}}}Ie([m(d.Object3D)],Gr.prototype,"object");Ie([m(d.Object3D)],Gr.prototype,"target");Ie([m()],Gr.prototype,"duration");Ie([m()],Gr.prototype,"relativeMotion");var De;const lf=(De=class extends I{constructor(){super(...arguments);r(this,"materialToSwitch");r(this,"variantMaterial");r(this,"fadeDuration",0);r(this,"_objectsWithThisMaterial",null);r(this,"selfModel");r(this,"targetModels")}start(){var e;this._objectsWithThisMaterial=this.objectsWithThisMaterial,wh(this.gameObject),j()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((e=this.materialToSwitch)==null?void 0:e.name)+'"')}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let i=0;i<this.objectsWithThisMaterial.length;i++){const n=this.objectsWithThisMaterial[i];n.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof d.Mesh)if(Array.isArray(e.material)){for(const i of e.material)if(i===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):bv(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}async beforeCreateDocument(e,i){this.targetModels=[],De._materialTriggersPerId={},De.variantSwitchIndex=0,this.materialToSwitch&&await le.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await le.NEEDLE_progressive.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,i,n){this.objectsWithThisMaterial.find(a=>a.uuid===i.uuid)&&this.targetModels.push(i),this.gameObject.uuid===i.uuid&&(this.selfModel=i,this.materialToSwitch&&(De._materialTriggersPerId[this.materialToSwitch.uuid]||(De._materialTriggersPerId[this.materialToSwitch.uuid]=[]),De._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,i){if(!this.materialToSwitch)return;const n=De._materialTriggersPerId[this.materialToSwitch.uuid];if(n){const s={};for(const a of n){const l=a.createVariants();l&&l.length>0&&(s[a.selfModel.uuid]=l)}for(const a of n){const l=[];for(const c in s)c!==a.selfModel.uuid&&l.push(...s[c]);a.createAndAttachBehaviors(e,s[a.selfModel.uuid],l)}}delete De._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,i,n){const s=[],a=Math.max(0,this.fadeDuration);s.push(fe.fadeAction([...this.targetModels,...n],a,!1)),s.push(fe.fadeAction(i,a,!0)),e.addBehavior(new vt("Select_"+this.selfModel.name,wt.tapTrigger(this.selfModel),fe.parallel(...s))),De._parallelStartHiddenActions.push(...i),De._startHiddenBehaviour||(De._startHiddenBehaviour=new vt("StartHidden_"+this.selfModel.name,wt.sceneStartTrigger(),fe.fadeAction(De._parallelStartHiddenActions,a,!1)),e.addBehavior(De._startHiddenBehaviour))}static getMaterialName(e){return Xi(e.name||"Material")+"_"+e.id}createVariants(){if(!this.variantMaterial)return null;const e=[];for(const i of this.targetModels){const n=i.clone();n.name+="_Variant_"+De.variantSwitchIndex+++"_"+De.getMaterialName(this.variantMaterial),n.displayName=n.displayName+": Variant with material "+this.variantMaterial.name,n.material=this.variantMaterial,n.geometry=i.geometry,n.transform=i.transform,(!i.parent||!i.parent.isEmpty())&&Et.createEmptyParent(i),i.parent&&i.parent.add(n),e.push(n)}return e}},r(De,"_materialTriggersPerId",{}),r(De,"_startHiddenBehaviour",null),r(De,"_parallelStartHiddenActions",[]),r(De,"variantSwitchIndex",0),De);Ie([m(d.Material)],lf.prototype,"materialToSwitch");Ie([m(d.Material)],lf.prototype,"variantMaterial");Ie([m()],lf.prototype,"fadeDuration");let sy=lf;var pe;const xh=(pe=class extends I{constructor(){super(...arguments);r(this,"target");r(this,"toggleOnClick",!1);r(this,"targetState",!0);r(this,"hideSelf",!0);r(this,"selfModel");r(this,"selfModelClone");r(this,"targetModel");r(this,"toggleModel");r(this,"stateBeforeCreatingDocument",!1);r(this,"targetStateBeforeCreatingDocument",!1)}start(){wh(this.gameObject)}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(e,i,n){i.uuid===this.gameObject.uuid&&(this.selfModel=i,this.selfModelClone=i.clone())}beforeCreateDocument(){this.target&&(this.gameObject[pe.wasVisible]===void 0&&(this.gameObject[pe.wasVisible]=this.gameObject.activeSelf),this.target[pe.wasVisible]===void 0&&(this.target[pe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[pe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[pe.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,i){if(!this.target)return;this.targetModel=i.document.findById(this.target.uuid);const n=this.selfModel;if(this.selfModel&&this.targetModel){let s=this.selfModel,a=this.targetState;if(this.toggleOnClick)if(a=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&ty.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[pe.toggleClone]){const h=this.selfModelClone.clone();h.setMatrix(new d.Matrix4),h.name+="_toggle"+pe.clonedToggleIndex++,n.add(h),this.gameObject[pe.toggleClone]=h,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const c=this.gameObject[pe.toggleClone];if(!this.gameObject[pe.reverseToggleClone]){const h=this.selfModelClone.clone();h.setMatrix(new d.Matrix4),h.name+="_toggleReverse"+pe.clonedToggleIndex++,n.add(h),this.gameObject[pe.reverseToggleClone]=h}this.toggleModel=this.gameObject[pe.reverseToggleClone],(!this.toggleModel.geometry||!c.geometry)&&console.error("triggers without childs and without geometry won't work!",this,n.geometry),s=c,n.geometry=null,n.material=null}if(this.toggleModel){if(this.toggleOnClick){const c=[];c.push(fe.fadeAction(s,0,!1)),c.push(fe.fadeAction(this.toggleModel,0,!0)),c.push(fe.fadeAction(this.targetModel,0,a)),e.addBehavior(new vt("Toggle_"+s.name+"_ToggleTo"+(a?"On":"Off"),wt.tapTrigger(s),fe.parallel(...c)));const h=[];h.push(fe.fadeAction(this.toggleModel,0,!1)),h.push(fe.fadeAction(s,0,!0)),h.push(fe.fadeAction(this.targetModel,0,!a)),e.addBehavior(new vt("Toggle_"+s.name+"_ToggleTo"+(a?"Off":"On"),wt.tapTrigger(this.toggleModel),fe.parallel(...h)))}}else{const c=[];this.hideSelf&&c.push(fe.fadeAction(s,0,!1)),c.push(fe.fadeAction(this.targetModel,0,a)),e.addBehavior(new vt("Toggle_"+s.name+"_ToggleTo"+(a?"On":"Off"),wt.tapTrigger(s),c.length>1?fe.parallel(...c):c[0]))}const l=new Array;this.targetStateBeforeCreatingDocument||l.push(this.targetModel),this.stateBeforeCreatingDocument||l.push(n),this.toggleModel&&l.push(this.toggleModel),Ya.add(l,e)}}afterSerialize(e,i){this.gameObject[pe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[pe.wasVisible],delete this.gameObject[pe.wasVisible]),this.target&&this.target[pe.wasVisible]!==void 0&&(this.target.visible=this.target[pe.wasVisible],delete this.target[pe.wasVisible]),delete this.gameObject[pe.toggleClone],delete this.gameObject[pe.reverseToggleClone]}},r(pe,"clonedToggleIndex",0),r(pe,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),r(pe,"toggleClone",Symbol("clone for toggling")),r(pe,"reverseToggleClone",Symbol("clone for reverse toggling")),pe);Ie([m(d.Object3D)],xh.prototype,"target");Ie([m()],xh.prototype,"toggleOnClick");Ie([m()],xh.prototype,"targetState");Ie([m()],xh.prototype,"hideSelf");let oy=xh;const dn=class dn extends I{constructor(){super(...arguments);r(this,"wasVisible",!1)}static add(e,i){const n=Array.isArray(e)?e:[e];for(const s of n)dn._fadeObjects.includes(s)||(console.log("adding hide on start",s),dn._fadeObjects.push(s));dn._fadeBehaviour===void 0&&(dn._fadeBehaviour=new vt("HideOnStart",wt.sceneStartTrigger(),fe.fadeAction(dn._fadeObjects,0,!1)),i.addBehavior(dn._fadeBehaviour))}start(){C.setActive(this.gameObject,!1)}createBehaviours(e,i,n){i.uuid===this.gameObject.uuid&&(this.wasVisible||dn.add(i,e))}beforeCreateDocument(){this.wasVisible=C.isActiveSelf(this.gameObject)}};r(dn,"_fadeBehaviour"),r(dn,"_fadeObjects",[]);let Ya=dn;class hl extends I{constructor(){super(...arguments);r(this,"target");r(this,"duration",.5);r(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(e,i,n){if(this.target&&i.uuid===this.gameObject.uuid){const s=new vt("emphasize "+this.name,wt.tapTrigger(this.gameObject),fe.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(s)}}afterCreateDocument(e,i){}}Ie([m()],hl.prototype,"target");Ie([m()],hl.prototype,"duration");Ie([m()],hl.prototype,"motionType");class Mo extends I{constructor(){super(...arguments);r(this,"target");r(this,"clip","");r(this,"toggleOnClick",!1);r(this,"trigger","tap")}start(){wh(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(qi);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){var i;e.use(),!(!((i=this.target)!=null&&i.clip)&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,i,n){if(!(!this.target&&!this.clip)&&i.uuid===this.gameObject.uuid){const s=this.clip?this.clip:this.target?this.target.clip:void 0;if(!s||typeof s!="string")return;const a=this.target?this.target.gameObject:this.gameObject;Wr.getName(s);const l=this.target?this.target.volume:1,c=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let h=!1;this.gameObject.traverse(g=>{g instanceof d.Mesh&&g.visible&&(h=!0)}),h=!0;const u=e.addAudioClip(s);let f=fe.playAudioAction(a,u,"play",l,c);this.target&&this.target.loop&&(f=fe.sequence(f).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(f.multiplePerformOperation="stop");const g=new vt("playAudio"+p,wt.tapTrigger(i),f);e.addBehavior(g)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(h&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const g=new vt("playAudioOnStart"+p,wt.sceneStartTrigger(),f);e.addBehavior(g)}}}}Ie([m(qi)],Mo.prototype,"target");Ie([m(URL)],Mo.prototype,"clip");Ie([m()],Mo.prototype,"toggleOnClick");var kt;const ry=(kt=class extends I{constructor(){super(...arguments);r(this,"animator");r(this,"stateName");r(this,"trigger","tap");r(this,"animation");r(this,"selfModel");r(this,"stateAnimationModel");r(this,"animationSequence",new Array);r(this,"animationLoopAfterSequence",new Array);r(this,"randomOffsetNormalized",0)}get target(){var e,i;return((e=this.animator)==null?void 0:e.gameObject)||((i=this.animation)==null?void 0:i.gameObject)}start(){wh(this.gameObject)}onPointerClick(e){var i;e.use(),this.target&&this.stateName&&((i=this.animator)==null||i.play(this.stateName,0,0,.1))}createBehaviours(e,i,n){i.uuid===this.gameObject.uuid&&(this.selfModel=i)}afterSerialize(){if(kt.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';j()&&me(e),console.warn(e,...kt.rootsWithExclusivePlayback)}kt.animationActions=[],kt.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,i){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const n=i.document,s=i.extensions.find(c=>c instanceof af);if(!s)return;const a=s.getClipCount(this.target)>1;a&&(j()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+s.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),kt.rootsWithExclusivePlayback.add(this.target));const l=this.name?this.name:"";n.traverse(c=>{var h,u;if(c.uuid===((h=this.target)==null?void 0:h.uuid)){const f=kt.getActionForSequences(n,c,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),p=new vt(this.trigger+"_"+l+"_toPlayAnimation_"+this.stateName+"_on_"+((u=this.target)==null?void 0:u.name),this.trigger=="tap"?wt.tapTrigger(this.selfModel):wt.sceneStartTrigger(),f);a&&p.makeExclusive(!0),e.addBehavior(p)}})}static getActionForSequences(e,i,n,s,a){const l=(h,u)=>{let f=kt.animationActions.find(p=>p.affectedObjects==h&&p.start==u.start&&p.duration==u.duration&&p.animationSpeed==u.speed);return f||(f=fe.startAnimationAction(h,u),kt.animationActions.push(f)),f},c=fe.sequence();if(n&&n.length>0)for(const h of n)c.addAction(l(i,h));if(s&&s.length>0){const h=c.actions.length==0?c:fe.sequence();for(const u of s)h.addAction(l(i,u));h.makeLooping(),c!==h&&c.addAction(h)}return a&&a>0&&c.actions.unshift(fe.waitAction(a)),c}static getAndRegisterAnimationSequences(e,i,n){var b,_,v,w,x,O,E,M;if(!i)return;const s=i.getComponent(xt),a=i.getComponent(Tt);if(!s&&!a)return;if(s&&!n)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+s.name+" on "+i.name);let l=[],c=[];if(a){const R=e.registerAnimation(i,a.clip);R&&(a.loop?c.push(R):l.push(R));let F=0;if(a.minMaxOffsetNormalized){const D=a.minMaxOffsetNormalized.x,A=a.minMaxOffsetNormalized.y;F=(((b=a.clip)==null?void 0:b.duration)||1)*(D+Math.random()*(A-D))}return{animationSequence:l,animationLoopAfterSequence:c,randomTimeOffset:F}}const h=s==null?void 0:s.runtimeAnimatorController;let u=h==null?void 0:h.findState(n),f=[],p=[];if(h&&u){const R=new Array;R.push(u);let F=!1;for(;R.length<100;){if(!u||u===null||!u.transitions||u.transitions.length===0){(_=u.motion)!=null&&_.isLooping&&(F=!0);break}const D=u.transitions.find(T=>T.conditions.length===0),A=D?h.getState(D.destinationState,0):null;if(A&&R.includes(A)){u=A,F=!0;break}else if(D){if(u=A,!u)break;R.push(u)}else{F=((v=u.motion)==null?void 0:v.isLooping)??!1;break}}if(F&&u){const D=R.indexOf(u);f=R.slice(0,D),p=R.slice(D),kb&&console.log("found loop from "+n,"states until loop",f,"states looping",p)}else f=R,p=[],kb&&console.log("found no loop from "+n,"states",f);if(!p.length){const D=f[f.length-1],A=(w=D.motion)==null?void 0:w.clip;if(A){let T;if(e.holdClipMap.has(A))T=e.holdClipMap.get(A);else{const G=D.name+"_hold";T=A.clone(),T.duration=1,T.name=G;const B=A.duration;T.tracks=A.tracks.map(L=>{const N=L.clone();N.times=new Float32Array([0,B]);const Y=L.values.length,Z=L.getValueSize(),K=L.values.slice(Y-Z,Y);return N.values=new Float32Array(2*Z),N.values.set(K,0),N.values.set(K,Z),N}),T.name=G,e.holdClipMap.set(A,T)}if(T){const G={name:T.name,motion:{clip:T,isLooping:!1,name:T.name},speed:1,transitions:[],behaviours:[],hash:D.hash+1};p.push(G)}}}}if(f.length===1&&(!((x=f[0].motion)!=null&&x.clip)||((E=(O=f[0].motion)==null?void 0:O.clip.tracks)==null?void 0:E.length)===0)){l=new Array;const R=e.registerAnimation(i,null);R&&l.push(R);return}if(f=f.filter(R=>{var F,D,A;return((F=R.motion)==null?void 0:F.clip)&&((A=(D=R.motion)==null?void 0:D.clip.tracks)==null?void 0:A.length)>0}),p=p.filter(R=>{var F,D,A;return((F=R.motion)==null?void 0:F.clip)&&((A=(D=R.motion)==null?void 0:D.clip.tracks)==null?void 0:A.length)>0}),f.length===0&&p.length===0){console.warn("No clips found for state "+n+" on "+(s==null?void 0:s.name)+", can't export animation data");return}const g=(R,F)=>{if(!i)return;const D=e.registerAnimation(i,R.motion.clip??null);D?(D.speed=R.speed,F.push(D)):console.warn("Couldn't register animation for state "+R.name+" on "+(s==null?void 0:s.name))};if(f.length>0){l=new Array;for(const R of f)g(R,l)}if(p.length>0){c=new Array;for(const R of p)g(R,c)}let y=0;if(s&&h&&s.minMaxOffsetNormalized){const R=s.minMaxOffsetNormalized.x,F=s.minMaxOffsetNormalized.y,D=f.length?f[0]:p.length?p[0]:null;y=(((M=D==null?void 0:D.motion.clip)==null?void 0:M.duration)||1)*(R+Math.random()*(F-R))}return{animationSequence:l,animationLoopAfterSequence:c,randomTimeOffset:y}}createAnimation(e,i,n){if(!this.target||!this.animator&&!this.animation)return;const s=kt.getAndRegisterAnimationSequences(e,this.target,this.stateName);s&&(this.animationSequence=s.animationSequence,this.animationLoopAfterSequence=s.animationLoopAfterSequence,this.randomOffsetNormalized=s.randomTimeOffset,this.stateAnimationModel=i)}},r(kt,"animationActions",[]),r(kt,"rootsWithExclusivePlayback",new Set),kt);Ie([m(xt)],ry.prototype,"animator");Ie([m()],ry.prototype,"stateName");let $c=ry;class dl extends I{constructor(){super(...arguments);r(this,"target")}getType(){}getDuration(){}}Ie([m(d.Object3D)],dl.prototype,"target");class Sh extends I{constructor(){super(...arguments);r(this,"target")}}Ie([m(dl)],Sh.prototype,"target");class Ch extends dl{constructor(){super(...arguments);r(this,"type",1);r(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ie([m()],Ch.prototype,"type");Ie([m()],Ch.prototype,"duration");class ay extends Sh{}const Iu=class Iu{constructor(){r(this,"_quicklookButton");r(this,"_arButton");r(this,"_vrButton");r(this,"_sendToQuestButton")}static create(){return new Iu}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return zn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const t=document.createElement("button");this._quicklookButton=t,t.dataset.needle="quicklook-button";const e=exports.DeviceUtilities.supportsQuickLookAR();t.innerText="View in AR",t.prepend(_t("view_in_ar"));let i=!1,n=null;return t.addEventListener("click",()=>{n=hh(Kn),n||(i=!0,n=new Kn),i&&(n.objectToExport=X.Current.scene),n?(t.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{t.classList.remove("this-mode-is-requested")}).catch(s=>{t.classList.remove("this-mode-is-requested"),console.error(s)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(t),t}createARButton(t){var n;if(this._arButton)return this._arButton;const e="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(_t("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>J.start(e,t)),this.updateSessionSupported(i,e),this.listenToXRSessionState(i,e),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||(n=navigator.xr)==null||n.addEventListener("devicechange",()=>this.updateSessionSupported(i,e)),i}createVRButton(t){var n;if(this._vrButton)return this._vrButton;const e="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(_t("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>J.start(e,t)),this.updateSessionSupported(i,e),this.listenToXRSessionState(i,e),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||(n=navigator.xr)==null||n.addEventListener("devicechange",()=>this.updateSessionSupported(i,e)),i}createSendToQuestButton(){var i;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",e=document.createElement("button");return this._sendToQuestButton=e,e.dataset.needle="webxr-sendtoquest-button",e.innerText="Open on Quest",e.prepend(_t("share_windows")),e.title="Click to send this page to the Oculus Browser on your Quest",e.addEventListener("click",()=>{const n=encodeURIComponent(window.location.href),s=t+n;window.open(s)==null&&Ee("This page doesn't allow popups. Please paste "+s+" into your browser.")}),this.listenToXRSessionState(e),this.hideElementDuringXRSession(e),exports.DeviceUtilities.isMozillaXR()||(i=navigator.xr)==null||i.addEventListener("devicechange",()=>{var n;(n=navigator.xr)!=null&&n.isSessionSupported("immersive-vr")?e.style.display="none":e.style.display=""}),e}createQRCode(){return zn.getOrCreate().createQRCode()}updateSessionSupported(t,e){if(!("xr"in navigator)){t.style.display="none";return}J.isSessionSupported(e).then(i=>{t.style.display=i?"":"none",j()&&!i&&console.log('[WebXR] "'+e+'" is not supported on this device – make sure your server runs using HTTPS and you have a device connected that supports '+e)})}hideElementDuringXRSession(t){zu(e=>{t["previous-display"]=t.style.display,t.style.display="none"}),sg(e=>{t["previous-display"]!=null&&(t.style.display=t["previous-display"])})}listenToXRSessionState(t,e){e&&(J.onSessionRequestStart(i=>{i.mode===e?t.classList.add("this-mode-is-requested"):(t["was-disabled"]=t.disabled,t.disabled=!0,t.classList.add("other-mode-is-requested"))}),J.onSessionRequestEnd(i=>{t.classList.remove("this-mode-is-requested"),t.classList.remove("other-mode-is-requested"),t.disabled=t["was-disabled"]}))}};r(Iu,"_instance");let Po=Iu;var OO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,ut=(o,t,e,i)=>{for(var n=i>1?void 0:i?kO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&OO(t,e,n),n};const bu=S("debugspriterenderer"),RO=S("wireframe"),Pc=class Pc{static getOrCreateGeometry(t){if(t.__cached_geometry)return t.__cached_geometry;if(t.guid&&Pc.cache[t.guid])return bu&&console.log("Take cached geometry for sprite",t.guid),Pc.cache[t.guid];const e=new d.BufferGeometry;t.__cached_geometry=e;const i=new Float32Array(t.triangles.length*3),n=new Float32Array(t.triangles.length*2);for(let s=0;s<t.triangles.length;s+=1){const a=t.triangles[s];i[s*3]=-t.vertices[a].x,i[s*3+1]=t.vertices[a].y,i[s*3+2]=0;const l=t.uv[a];n[s*2]=l.x,n[s*2+1]=1-l.y}return e.setAttribute("position",new d.BufferAttribute(i,3)),e.setAttribute("uv",new d.BufferAttribute(n,2)),t.guid&&(this.cache[t.guid]=e),bu&&console.log("Built sprite geometry",t,e),e}};r(Pc,"cache",{});let Ka=Pc;class EO{constructor(){r(this,"x");r(this,"y")}}function Jw(o){o&&(o.colorSpace!=d.SRGBColorSpace&&(o.colorSpace=d.SRGBColorSpace,o.needsUpdate=!0),o.minFilter==d.NearestFilter&&o.magFilter==d.NearestFilter&&(o.anisotropy=1,o.needsUpdate=!0))}let Us=class{constructor(t){r(this,"guid");r(this,"texture");r(this,"triangles");r(this,"uv");r(this,"vertices");r(this,"__cached_geometry");r(this,"_mesh");r(this,"_material");t&&(this.texture=t,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}get mesh(){return this._mesh||(this._mesh=new d.Mesh(Ka.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&Jw(this.texture),this._material=new d.MeshBasicMaterial({map:this.texture,color:16777215,side:d.DoubleSide,transparent:!0})),this._material}getGeometry(){return Ka.getOrCreateGeometry(this)}};ut([m()],Us.prototype,"guid",2);ut([m(d.Texture)],Us.prototype,"texture",2);ut([Br()],Us.prototype,"triangles",2);ut([Br()],Us.prototype,"uv",2);ut([Br()],Us.prototype,"vertices",2);const Cp=Symbol("spriteOwner");class Za{constructor(){r(this,"sprites");this.sprites=[]}}ut([m(Us)],Za.prototype,"sprites",2);const ly=class Rm{constructor(){r(this,"spriteSheet");r(this,"index",0)}static create(){const t=new Rm;return t.spriteSheet=new Za,t}clone(){const t=new Rm;return t.index=this.index,t.spriteSheet=this.spriteSheet,t}set sprite(t){t&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=t):(this.spriteSheet=new Za,this.spriteSheet.sprites=[t],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(t){if(!this.spriteSheet)return;const e=this.index;if(e<0||e>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[e],n=i==null?void 0:i.texture;if(n&&(Jw(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;le.NEEDLE_progressive.assignTextureLOD(n,0).then(a=>{a instanceof d.Texture&&(i.texture=a,(t==null?void 0:t.map)===s&&(t.map=a,t.needsUpdate=!0))})}}};ut([m(Za)],ly.prototype,"spriteSheet",2);ut([m()],ly.prototype,"index",2);let Fa=ly;class fi extends I{constructor(){super(...arguments);r(this,"drawMode",0);r(this,"size",{x:1,y:1});r(this,"color");r(this,"sharedMaterial");r(this,"transparent",!0);r(this,"cutoutThreshold",0);r(this,"castShadows",!1);r(this,"renderOrder",0);r(this,"toneMapped",!0);r(this,"_spriteSheet");r(this,"_currentSprite")}set texture(e){var n;if(!this._spriteSheet)return;const i=(n=this._spriteSheet.spriteSheet)==null?void 0:n.sprites[this.spriteIndex];i&&(i.texture=e,this.updateSprite())}addSprite(e,i=!1){var s,a;if(this._spriteSheet||(this._spriteSheet=Fa.create()),!this._spriteSheet.spriteSheet)return-1;(s=this._spriteSheet.spriteSheet)==null||s.sprites.push(e);const n=((a=this._spriteSheet.spriteSheet)==null?void 0:a.sprites.length)-1;return i&&(this.spriteIndex=n),n}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const i=Math.floor(e);this.spriteIndex=i}else e instanceof Us?(this._spriteSheet||(this._spriteSheet=Fa.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){var e;return((e=this._spriteSheet)==null?void 0:e.index)??0}get spriteFrames(){var e,i;return((i=(e=this._spriteSheet)==null?void 0:e.spriteSheet)==null?void 0:i.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=Fa.create(),bu&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){var s;if(!this.__didAwake&&!e)return!1;const i=this._spriteSheet;if(!((s=i==null?void 0:i.spriteSheet)!=null&&s.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const n=i.spriteSheet.sprites[this.spriteIndex];if(!n)return bu&&console.warn("Sprite not found",this.spriteIndex,i.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=Ka.getOrCreateGeometry(n),this._currentSprite.material.map=n.texture;else{const a=new d.MeshBasicMaterial({color:16777215,side:d.DoubleSide});if(RO&&(a.wireframe=!0),this.color&&(a.color||(a.color=new d.Color),a.color.copy(this.color),a.opacity=this.color.alpha),a.transparent=!0,a.toneMapped=this.toneMapped,a.depthWrite=!1,n.texture&&!a.wireframe){let l=n.texture;l[Cp]!==void 0&&l[Cp]!==this&&this.spriteFrames>1&&(l=n.texture=l.clone()),l[Cp]=this,a.map=l}this.sharedMaterial=a,this._currentSprite=new d.Mesh(Ka.getOrCreateGeometry(n),a),this._currentSprite.renderOrder=Math.round(this.renderOrder),le.NEEDLE_progressive.assignTextureLOD(a,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,i==null||i.update(this.sharedMaterial),!0}}ut([m()],fi.prototype,"drawMode",2);ut([m(EO)],fi.prototype,"size",2);ut([m(ie)],fi.prototype,"color",2);ut([m(d.Material)],fi.prototype,"sharedMaterial",2);ut([m()],fi.prototype,"transparent",2);ut([m()],fi.prototype,"cutoutThreshold",2);ut([m()],fi.prototype,"castShadows",2);ut([m()],fi.prototype,"renderOrder",2);ut([m()],fi.prototype,"toneMapped",2);ut([m(Fa)],fi.prototype,"sprite",1);const Rb=S("debugwebxr"),TO=new d.Matrix4().makeRotationY(Math.PI),fo=class fo extends I{constructor(){super(...arguments);r(this,"_arScale",1);r(this,"invertForward",!1);r(this,"customReticle");r(this,"arTouchTransform",!0);r(this,"autoPlace",!1);r(this,"autoCenter",!1);r(this,"useXRAnchor",!1);r(this,"_isPlacing",!0);r(this,"_startOffset",new d.Matrix4);r(this,"_createdPlacementObject",null);r(this,"_reparentedComponents",[]);r(this,"_placementScene",new d.Scene);r(this,"_reticle",[]);r(this,"_hits",[]);r(this,"_placementStartTime",-1);r(this,"_rigPlacementMatrix");r(this,"_anchor",null);r(this,"userInput");r(this,"onPlaceScene",e=>{var s;if(this._isPlacing==!1||e!=null&&e.used)return;let i=this._reticle[0];if(!i){console.warn("No reticle to place...");return}if(!i.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((s=J.active)!=null&&s.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let n=this._hits[0];if(e&&e.origin instanceof og){const a=this._reticle[e.origin.index];a&&(i=a,n=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),i.position.copy(i.lastPos),i.quaternion.copy(i.lastQuat),this.onApplyPose(i),fo._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(J.active,n),this.context.xr)for(const a of this.context.xr.controllers)a.cancelHitTestSource()});r(this,"upVec",new d.Vector3(0,1,0));r(this,"lookPoint",new d.Vector3);r(this,"worldUpVec",new d.Vector3(0,1,0))}static onPlaced(e){const i="placed";return this._eventListeners[i]||(this._eventListeners[i]=[]),this._eventListeners[i].push(e),()=>{const n=this._eventListeners[i].indexOf(e);n>=0&&this._eventListeners[i].splice(n,1)}}static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}onEnable(){var e;(e=this.customReticle)==null||e.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){Rb&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,fo._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const i=new d.Object3D;this._createdPlacementObject=i,i.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let n=this.context.scene.children.length-1;n>=0;n--){const s=this.context.scene.children[n];this._placementScene.add(s)}if(this.context.scene.add(i),this.autoCenter){const n=ci(this._placementScene.children),s=n.getCenter(new d.Vector3),a=n.getSize(new d.Vector3),l=new d.Matrix4;l.makeTranslation(s.x,s.y-a.y*.5,s.z),this._startOffset.multiply(l)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),C.addComponent(i,this);for(const n of this._reticle)Ri(n);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ri.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ri.Early}),this.onRevertSceneChanges(),this._anchor=null,fo._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){var i,n,s,a;if(e.xr.isTrackingImages){for(const l of this._reticle)l.visible=!1;return}if(this._isPlacing){const l=(i=e.xr.rig)==null?void 0:i.gameObject;l&&l.parent!==this.context.scene&&this.context.scene.add(l);let c=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const h of e.xr.controllers){const u=h.getHitTest();u&&(c=!0,this.updateReticleAndHits(e.xr,h.index,u,e.xr.rigScale))}if(!c){const h=e.xr.getHitTest();h&&this.updateReticleAndHits(e.xr,0,h,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const l=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(l&&this.context.time.frame%20===0){const c=e.xr.convertSpace(l.transform),h=this._reticle[0];h&&(h.position.copy(c.position),h.quaternion.copy(c.quaternion),this.onApplyPose(h))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Em(this.context)),(n=this.userInput)==null||n.enable()):(s=this.userInput)==null||s.disable(),this.arTouchTransform&&((a=this.userInput)!=null&&a.hasChanged)){if(e.xr.rig){const l=e.xr.rig.gameObject;this.userInput.applyMatrixTo(l.matrix,!0),l.matrix.decompose(l.position,l.quaternion,l.scale),this.userInput.factor=l.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,i,n,s){this._hits[i]=n.hit;let a=this._reticle[i];if(!a){if(this.customReticle)if(this.customReticle.asset)a=Er(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else a=new d.Mesh(new d.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new d.MeshBasicMaterial({side:d.DoubleSide,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),a.name="AR Placement Reticle";if(Rb){const l=new d.AxesHelper(1);l.position.y+=.01,a.add(l)}this._reticle[i]=a,a.matrixAutoUpdate=!1,a.visible=!1}if(a.lastPos=a.lastPos||n.position.clone(),a.lastQuat=a.lastQuat||n.quaternion.clone(),a.position.copy(a.lastPos.lerp(n.position,this.context.time.deltaTime/.1)),a.lastPos.copy(a.position),a.quaternion.copy(a.lastQuat.slerp(n.quaternion,this.context.time.deltaTime/.05)),a.lastQuat.copy(a.quaternion),a.scale.set(s,s,s),this.customReticle&&this.applyViewBasedTransform(a),a.updateMatrix(),a.visible=!0,a.parent!==this.context.scene&&this.context.scene.add(a),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(a.quaternion),this.upVec.dot(V(0,1,0))>.9){let c=a["autoplace:timer"]||0;c>=1?(a.visible=!1,this.onPlaceScene(null)):(c+=this.context.time.deltaTime,a["autoplace:timer"]=c)}else a["autoplace:timer"]=0}onSetScale(){var i,n,s;if(!fo._hasPlaced)return;const e=(n=(i=J.active)==null?void 0:i.rig)==null?void 0:n.gameObject;if(e){const a=((s=J.active)==null?void 0:s.rigScale)||1,l=1/this._arScale*a,c=new d.Matrix4().makeScale(l,l,l).invert();e.matrix.premultiply(c),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){var e;for(const i of this._reticle)i&&(i.visible=!1,i==null||i.removeFromParent());this._reticle.length=0;for(let i=this._placementScene.children.length-1;i>=0;i--){const n=this._placementScene.children[i];this.context.scene.add(n)}(e=this._createdPlacementObject)==null||e.removeFromParent();for(const i of this._reparentedComponents)C.addComponent(i.originalObject,i.comp)}async onCreateAnchor(e,i){if(i.createAnchor===void 0){console.warn("Hit does not support creating an anchor",i),j()&&me("Hit does not support creating an anchor");return}else{const n=await i.createAnchor(e.viewerPose.transform);e.running&&n&&(this._anchor=n)}}applyViewBasedTransform(e){const i=this.context.mainCamera,n=e,s=i.worldPosition,a=n.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const l=i.worldPosition;l&&e.position.clone().sub(l).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const c=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,h=30;c>h&&c<180-h||c<-h&&c>-180+h?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(s.y=a.y,e.lookAt(s))}onApplyPose(e){var s,a,l;const i=(a=(s=J.active)==null?void 0:s.rig)==null?void 0:a.gameObject;if(!i){console.warn("No rig object to place");return}const n=i.parent||this.context.scene;this._rigPlacementMatrix?(l=this._rigPlacementMatrix)==null||l.decompose(i.position,i.quaternion,i.scale):this._rigPlacementMatrix=i.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(i),e.removeFromParent(),i.scale.set(this.arScale,this.arScale,this.arScale),i.position.multiplyScalar(this.arScale),i.updateMatrix(),this.invertForward&&i.matrix.premultiply(TO),i.matrix.premultiply(this._startOffset),i.matrix.decompose(i.position,i.quaternion,i.scale),n.add(i)}};r(fo,"_eventListeners",{}),r(fo,"_hasPlaced",!1);let is=fo;const rr=class rr{constructor(t){r(this,"oneFingerDrag",!0);r(this,"twoFingerRotate",!0);r(this,"twoFingerScale",!0);r(this,"factor",1);r(this,"context");r(this,"offset");r(this,"plane");r(this,"_scale",1);r(this,"_hasChanged",!1);r(this,"_enabled",!1);r(this,"currentlyUsedPointerIds",new Set);r(this,"currentlyUnusedPointerIds",new Set);r(this,"onPointerDownEarly",t=>{this.isActive&&t.stopPropagation()});r(this,"onPointerDownLate",t=>{t.used?this.currentlyUsedPointerIds.add(t.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(t.pointerId)});r(this,"onPointerUpEarly",t=>{this.currentlyUsedPointerIds.delete(t.pointerId),this.currentlyUnusedPointerIds.delete(t.pointerId)});r(this,"prev",new Map);r(this,"_didMultitouch",!1);r(this,"touchStart",t=>{if(!t.defaultPrevented)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=exports.DeviceUtilities.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const s=this.prev.get(i.identifier);if(s){const a=this.getPositionOnPlane(i.clientX,i.clientY);s.x=a.x,s.z=a.z,s.screenx=i.clientX,s.screeny=i.clientY}}});r(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e];this.prev.delete(i.identifier)}});r(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const e=t.touches[0],i=this.prev.get(e.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(e.clientX,e.clientY),s=n.x-i.x,a=n.z-i.z;if(s===0&&a===0)return;this.oneFingerDrag&&this.addMovement(s,a),i.x=n.x,i.z=n.z,i.screenx=e.clientX,i.screeny=e.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const e=t.touches[0],i=t.touches[1],n=this.prev.get(e.identifier),s=this.prev.get(i.identifier);if(!n||!s)return;if(this.twoFingerRotate){const a=Math.atan2(e.clientY-i.clientY,e.clientX-i.clientX),l=Math.atan2(n.screeny-s.screeny,n.screenx-s.screenx),c=a-l;Math.abs(c)>.001&&this.addRotation(c)}if(this.twoFingerScale){const a=e.clientX-i.clientX,l=e.clientY-i.clientY,c=Math.sqrt(a*a+l*l),h=n.screenx-s.screenx,u=n.screeny-s.screeny,f=Math.sqrt(h*h+u*u),p=c-f;Math.abs(p)>2&&this.addScale(p)}n.screenx=e.clientX,n.screeny=e.clientY,s.screenx=i.clientX,s.screeny=i.clientY}}});r(this,"_raycaster",new d.Raycaster);r(this,"_intersection",new d.Vector3);r(this,"_screenPos",new d.Vector3);r(this,"_tempMatrix",new d.Matrix4);this.context=t,this.offset=new d.Matrix4,this.plane=new d.Plane,this.plane.setFromNormalAndCoplanarPoint(rr.up,rr.zero)}get scale(){return this._scale}reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(t,e){this._hasChanged=!1,e?(this.offset.invert(),t.premultiply(this.offset)):t.multiply(this.offset)}get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:ri.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ri.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ri.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:ri.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ri.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ri.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(t,e){const i=this.context.mainCamera;return this._screenPos.x=t/window.innerWidth*2-1,this._screenPos.y=-(e/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(t,e){t/=this._scale,e/=this._scale,t*=this.factor,e*=this.factor,this.offset.elements[12]+=t,this.offset.elements[14]+=e,(t!==0||e!==0)&&(this._hasChanged=!0)}addScale(t){t/=window.innerWidth,t*=-1,this._scale*=1+t,this._tempMatrix.makeScale(1-t,1-t,1-t),this.offset.premultiply(this._tempMatrix),t!==0&&(this._hasChanged=!0)}addRotation(t){t*=-1,this._tempMatrix.makeRotationY(t),this.offset.premultiply(this._tempMatrix),t!==0&&(this._hasChanged=!0)}};r(rr,"up",new d.Vector3(0,1,0)),r(rr,"zero",new d.Vector3(0,0,0)),r(rr,"one",new d.Vector3(1,1,1));let Em=rr;const mo=S("debugautosync"),Pp=Symbol("syncerId");class AO{constructor(){r(this,"_syncers",{})}getOrCreateSyncer(t){if(!t.guid)return null;if(this._syncers[t.guid])return this._syncers[t.guid];const e=new LO(t);return e[Pp]=t.guid,this._syncers[e[Pp]]=e,e}removeSyncer(t){delete this._syncers[t[Pp]]}}const cy=new AO;class LO{constructor(t){r(this,"comp");r(this,"hasChanges",!1);r(this,"changedProperties",{});r(this,"_isReceiving",!1);r(this,"_isInit",!1);r(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const t=this.comp.context.connection;if(!t||!t.isConnected||!t.isInRoom){for(const e in this.changedProperties)delete this.changedProperties[e];return}for(const e in this.changedProperties){const i=this.changedProperties[e];mo&&console.log("SEND",this.comp.guid,this.networkingKey),t.send(this.networkingKey,{guid:this.comp.guid,property:e,data:i},fn.Queued),delete this.changedProperties[e]}});r(this,"onHandleReceiving",t=>{if(mo&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,t),!!this._isInit&&this.comp&&t.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[t.property]=t.data}catch(e){console.error(e)}finally{this._isReceiving=!1}});this.comp=t}get networkingKey(){return this.comp.guid}init(t){if(this._isInit)return;this._isInit=!0,this.comp=t,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const e=this.comp.context.connection.tryGetState(this.comp.guid);e&&this.onHandleReceiving(e)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(t,e){this._isReceiving||(mo&&console.log("Property changed: "+t,e),this.hasChanges=!0,this.changedProperties[t]=e)}}function DO(o,t){let e=t!==o;return!e&&o&&t&&(Array.isArray(o)&&Array.isArray(t)||typeof o=="object"&&typeof t=="object")&&(e=!0),e}const yc=Symbol("AutoSyncHandler");function IO(o){if(o[yc])return o[yc];const t=cy.getOrCreateSyncer(o);return t==null||t.init(o),o[yc]=t,t}function jO(o){const t=o[yc];t&&(cy.removeSyncer(t),t.destroy(),delete o[yc])}const hy=function(o=null){return function(t,e){var u;let i="";typeof e=="string"?i=e:i=e.name;let n=null,s;typeof o=="string"?s=t[o]:typeof o=="function"&&(s=o),s==null&&(j()||mo)&&o!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+o+'"');const a=t,l=a.__internalAwake;if(typeof l!="function"){(mo||j())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((u=t==null?void 0:t.constructor)==null?void 0:u.name)+'" is not supported',t);return}mo&&console.log(i);const c=Symbol(i);a.__internalAwake=function(){if(this[c]!==void 0)return;this[c]=this[i],n=cy.getOrCreateSyncer(this);const f=Object.getOwnPropertyDescriptor(this,i);if((f==null?void 0:f.set)===void 0){let p=!1;Object.defineProperty(this,i,{set:function(g){var b;const y=this[c];if(this[c]=g,p){(j()||mo)&&console.warn("Recursive call detected",i);return}p=!0;try{const _=DO(g,y);mo&&console.log("SyncField assignment",i,"changed?",_,g,s),_&&(s==null?void 0:s.call(this,g,y))!==!1&&((b=IO(this))==null||b.notifyChanged(i,g))}finally{p=!1}},get:function(){return this[c]},configurable:!0,enumerable:!0})}n==null||n.init(this),l.call(this)};const h=a.__internalDestroy;a.__internalDestroy=function(){jO(this),h.call(this)}}};var BO=Object.defineProperty,cf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&BO(t,e,n),n};const Wt=S("debugplayersync"),hf=class ex extends I{constructor(){super(...arguments);r(this,"autoSync",!0);r(this,"asset");r(this,"onPlayerSpawned");r(this,"_localInstance");r(this,"onJoinedRoom",()=>{Wt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()});r(this,"destroyInstance",()=>{var e;(e=this._localInstance)==null||e.then(i=>{Wt&&console.log("PlayerSync.destroyInstance",i),oh(i,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(e,i){const n=te.getOrCreateFromUrl(e);if(!n.asset){const l=await n.loadAssetAsync();l&&C.getOrAddComponent(l,yn)}const s=new ex;s._internalInit(i),s.asset=n;const a=new d.Object3D;return a.guid=e,C.addComponent(a,s),s}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new ye)}onEnable(){this.context.connection.beginListen(ee.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ee.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ee.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ee.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ee.LeftRoom,this.destroyInstance)}async getInstance(){var i,n,s,a,l,c;if(this._localInstance)return this._localInstance;if(Wt&&console.log("PlayerSync.createInstance",(i=this.asset)==null?void 0:i.url),!((n=this.asset)!=null&&n.asset)&&!((s=this.asset)!=null&&s.url))return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=(a=this.asset)==null?void 0:a.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const h=C.getComponentsInChildren(e,yn);if(Wt&&console.log(`PlayerSync.createInstance: found ${h==null?void 0:h.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),h!=null&&h.length){for(const u of h)u.owner=this.context.connection.connectionId;(l=this.onPlayerSpawned)==null||l.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((c=this.asset)==null?void 0:c.url)+"</strong>: please make sure the asset has a PlayerState component!"),C.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let i=yn.all.length-1;i>=0;i--){const n=yn.all[i];(!n.owner||!this.context.connection.userIsInRoom(n.owner))&&n.doDestroy()}})}};cf([m()],hf.prototype,"autoSync");cf([m(te)],hf.prototype,"asset");cf([m(ye)],hf.prototype,"onPlayerSpawned");let dy=hf;var tx=(o=>(o.OwnerChanged="ownerChanged",o))(tx||{}),ke;const Tm=(ke=class extends I{constructor(){super(...arguments);r(this,"onOwnerChangeEvent",new ye);r(this,"onFirstOwnerChangeEvent",new ye);r(this,"hasOwner",!1);r(this,"owner");r(this,"dontDestroy",!1);r(this,"onUserLeftRoom",e=>{if(e.userId===this.owner){Wt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return ke._all}static get local(){return ke._local}static getFor(e){if(e instanceof d.Object3D)return C.getComponentInParent(e,ke);if(e instanceof I)return C.getComponentInParent(e.gameObject,ke)}static isLocalPlayer(e){const i=ke.getFor(e);return(i==null?void 0:i.isLocalPlayer)??!1}static addEventListener(e,i){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(i),i}static removeEventListener(e,i){if(!this._callbacks[e])return;const n=this._callbacks[e].indexOf(i);n>=0&&this._callbacks[e].splice(n,1)}static dispatchEvent(e,i){if(this._callbacks[e])for(const n of this._callbacks[e])n(i)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,i){var l,c;Wt&&console.log(`PlayerSync.onOwnerChange: ${i} → ${e} (me: ${this.context.connection.connectionId})`);const n=ke._local.indexOf(this);n>=0&&ke._local.splice(n,1);const s={playerState:this,oldValue:i,newValue:e};if(this.hasOwner||(this.hasOwner=!0,(l=this.onFirstOwnerChangeEvent)==null||l.invoke(s)),(c=this.onOwnerChangeEvent)==null||c.invoke(s),this.owner===this.context.connection.connectionId){ke._local.push(this);const h=new CustomEvent("local-owner-changed",{detail:s});this.dispatchEvent(h)}const a=new CustomEvent("owner-changed",{detail:s});this.dispatchEvent(a),ke.dispatchEvent("ownerChanged",a)}awake(){ke.all.push(this),Wt&&console.log("Registered new PlayerState",this.guid,ke.all.length-1,ke.all),this.context.connection.beginListen(ee.UserLeftRoom,this.onUserLeftRoom)}async start(){Wt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Jn(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Wt&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Wt&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Wt&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Wt&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Wt&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Wt&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),oh(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Wt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ee.UserLeftRoom,this.onUserLeftRoom),ke.all.splice(ke.all.indexOf(this),1),this.isLocalPlayer){const e=ke._local.indexOf(this);e>=0&&ke._local.splice(e,1)}}},r(ke,"_all",[]),r(ke,"_local",[]),r(ke,"_callbacks",{}),ke);cf([hy(Tm.prototype.onOwnerChange)],Tm.prototype,"owner");let yn=Tm;var FO=Object.defineProperty,ul=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&FO(t,e,n),n};class rs extends I{constructor(){super(...arguments);r(this,"position","bottom");r(this,"showNeedleLogo",!1);r(this,"showSpatialMenu");r(this,"createFullscreenButton");r(this,"createMuteButton");r(this,"createQRCodeButton")}onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(exports.DeviceUtilities.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}ul([m()],rs.prototype,"position");ul([m()],rs.prototype,"showNeedleLogo");ul([m()],rs.prototype,"showSpatialMenu");ul([m()],rs.prototype,"createFullscreenButton");ul([m()],rs.prototype,"createMuteButton");ul([m()],rs.prototype,"createQRCodeButton");var UO=Object.defineProperty,uy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&UO(t,e,n),n};const Dl=S("debugwebxr"),Eb=new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI);class Oo extends I{constructor(){super(...arguments);r(this,"head");r(this,"leftHand");r(this,"rightHand");r(this,"_leftHandMeshes");r(this,"_rightHandMeshes");r(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;Dl&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const i=yn.getFor(this);if(i!=null&&i.owner){const n=this.gameObject.addComponent(At);n.avatar=this.gameObject,n.connectionId=i.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):i&&!this.context.connection.isConnected&&(i.dontDestroy=!0)}onLeaveXR(e){const i=this.gameObject.getComponent(At);i&&i.destroy()}onUpdateXR(e){var h,u;if(!this.activeAndEnabled)return;const i=yn.isLocalPlayer(this);if(!i)return;const n=e.xr;if(n.rig&&n.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),n.rig.gameObject.add(this.gameObject)),this._syncTransforms&&i)for(const f of this._syncTransforms)f.fastMode=!0,f.isOwned()||f.requestOwnership();if(this.head&&this.context.mainCamera){const f=this.head.asset;if(f.position.copy(this.context.mainCamera.position),f.position.x*=-1,f.position.z*=-1,f.quaternion.copy(this.context.mainCamera.quaternion),f.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const p=C.getComponentsInChildren(this.head.asset,$i);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const s=e.xr.leftController,a=(h=this.leftHand)==null?void 0:h.asset;s&&a?(a.position.copy(s.gripPosition),a.quaternion.copy(s.gripQuaternion),a.quaternion.multiply(Eb),a.visible=s.isTracking,this.updateHandVisibility(s,a,this._leftHandMeshes)):a&&a.visible&&(a.visible=!1);const l=e.xr.rightController,c=(u=this.rightHand)==null?void 0:u.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(Eb),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._rightHandMeshes)):c&&c.visible&&(c.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,i,n){if(n){const s=e.model&&e.model.visible&&e.model!==i;n.forEach(a=>{xs(a,!s)})}}updateRemoteAvatarVisibility(){var e,i,n;if(this.context.connection.isConnected){const s=yn.getFor(this);if(s&&s.isLocalPlayer==!1){const a=J.getXRSync(this.context);if(a&&a.hasState(s.owner)){this.tryFindAvatarObjectsIfMissing();const l=(e=this.leftHand)==null?void 0:e.asset;l&&(l.visible=(a==null?void 0:a.isTracking(s.owner,"left"))??!1);const c=(i=this.rightHand)==null?void 0:i.asset;c&&(c.visible=(a==null?void 0:a.isTracking(s.owner,"right"))??!1)}if((n=this.head)!=null&&n.asset){const l=C.getComponentsInChildren(this.head.asset,$i);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};J0.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){var e,i;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof d.Object3D&&(this.head=new te("",this.sourceId,this.head));else{const n=new d.Object3D;n.name="Head";const s=Lo.createPrimitive(Or.Cube);n.add(s),this.gameObject.add(n),this.head=new te("",this.sourceId,n),Dl&&console.log("Create head",n)}if(this.rightHand)this.rightHand instanceof d.Object3D&&(this.rightHand=new te("",this.sourceId,this.rightHand));else{const n=new d.Object3D;n.name="Right Hand",this.gameObject.add(n),this.rightHand=new te("",this.sourceId,n),Dl&&console.log("Create right hand",n)}if(this.leftHand)this.leftHand instanceof d.Object3D&&(this.leftHand=new te("",this.sourceId,this.leftHand));else{const n=new d.Object3D;n.name="Left Hand",this.gameObject.add(n),this.leftHand=new te("",this.sourceId,n),Dl&&console.log("Create left hand",n)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(e=this.leftHand.asset)==null||e.traverse(n=>{n!=null&&n.isMesh&&this._leftHandMeshes.push(n)}),this._rightHandMeshes=[],(i=this.rightHand.asset)==null||i.traverse(n=>{n!=null&&n.isMesh&&this._rightHandMeshes.push(n)}),yn.isLocalPlayer(this.gameObject)&&(this._syncTransforms=C.getComponentsInChildren(this.gameObject,es))}async loadAvatarObjects(e,i,n){const s=e.loadAssetAsync(),a=i.loadAssetAsync(),l=n.loadAssetAsync(),c=new Array;s&&c.push(s),a&&c.push(a),l&&c.push(l);const h=await Gm(c);Dl&&console.log("Avatar loaded results:",h)}}uy([m(te)],Oo.prototype,"head");uy([m(te)],Oo.prototype,"leftHand");uy([m(te)],Oo.prototype,"rightHand");var zO=Object.defineProperty,df=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&zO(t,e,n),n};const fs=S("debugwebxr"),Ks=new Array;class ns extends I{constructor(){super(...arguments);r(this,"createControllerModel",!0);r(this,"createHandModel",!0);r(this,"customLeftHand");r(this,"customRightHand");r(this,"_models",new Array)}supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}async onXRControllerAdded(e){var s;if(!(e.xr.isVR||e.xr.isPassThrough))return;const{controller:n}=e;if(fs&&console.warn("Add Controller Model for",n.side,n.index),this.createControllerModel||this.createHandModel){if(n.hand){if(this.createHandModel){const a=await this.loadHandModel(this,n);if(!a||!n.connected||!n.isHand){a!=null&&a.handObject&&pa(a.handObject,!1),(s=a==null?void 0:a.handObject)==null||s.destroy();return}this._models.push({controller:n,model:a.handObject,handmesh:a.handmesh}),this._models.sort((l,c)=>l.controller.index-c.controller.index),this.scene.add(a.handObject),n.model=a.handObject}}else if(this.createControllerModel){const a=await n.getModelUrl();if(a){const l=await this.loadModel(n,a);if(!l||!n.connected||n.isHand)return;this._models.push({controller:n,model:l}),this._models.sort((c,h)=>c.controller.index-h.controller.index),this.scene.add(l),l.traverse(c=>{c.layers.set(2),c.matrixAutoUpdate=!1,c.updateMatrix()}),n.model=l}else n.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+n.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const i=this._models.findIndex(s=>s.controller===e.controller),n=this._models[i];n&&(this._models.splice(i,1),n.model&&(pa(n.model,!1),n.model.destroy(),n.model=void 0))}onBeforeXR(e,i){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.includes("hand-tracking")||i.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const i of this._models)i&&(i.model&&(pa(i.model,!1),i.model.destroy(),i.model=void 0),i.controller.model===i.model&&(i.controller.model=null));this._models.length=0}onBeforeRender(){if(J.active&&(fs&&(Ks[0]=Date.now()),this.updateRendering(J.active),fs)){const e=Date.now()-Ks[0];Ks.push(e),Ks.length>=30&&(Ks[0]=0,Ks.reduce((i,n)=>i+n,0)/Ks.length,Ks.length=0)}}updateRendering(e){var i,n,s,a,l;for(let c=0;c<this._models.length;c++){const h=this._models[c];if(!h)continue;const u=h.controller;if(!u.connected){fs&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",u.side,u.hand);continue}if(h.model&&!h.handmesh)h.model.matrixAutoUpdate=!1,h.model.matrix.copy(u.gripMatrix),h.model.visible=u.isTracking,(i=e.rig)==null||i.gameObject.add(h.model);else if(u.inputSource.hand&&h.handmesh){const f=e.referenceSpace,p=this.context.renderer.xr.getHand(u.index);if(f&&e.frame.getJointPose){for(const g of u.inputSource.hand.values()){const y=p.joints[g.jointName];if(y){const b=u.getHandJointPose(g);if(b){const _=b.transform.position,v=b.transform.orientation;y.position.copy(_),y.quaternion.copy(v),y.matrixAutoUpdate=!1}y.visible=b!=null}}h.model&&(h.model.visible=u.isTracking,h.model.visible&&h.model.parent!==((n=e.rig)==null?void 0:n.gameObject)&&((s=e.rig)==null||s.gameObject.add(h.model))),(a=h.model)!=null&&a.visible&&((l=h.handmesh)==null||l.updateMesh(),h.model.matrixAutoUpdate=!1,h.model.matrix.identity(),h.model.applyMatrix4(Aa))}}}}async loadModel(e,i){var a;if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const s=await te.getOrCreate("",i).instantiate();return pa(s),(a=J.active)!=null&&a.isPassThrough&&s.traverseVisible(l=>{this.makeOccluder(l)}),s}async loadHandModel(e,i){const n=this.context,s=n.renderer.xr.getHand(i.index);s||(fs?$.DrawLabel(i.rayWorldPosition,"No hand found for index "+i.index,.05,5):console.warn("No hand found for index "+i.index));const a=new H.GLTFLoader;Og(a,n),await yu(a,n,this.sourceId??"");const l=Xg(a);let c="";const h=i.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),a.setPath("")):(c=i.inputSource.handedness==="left"?"left":"right",a.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const u=new d.Object3D;pa(u);const f=new H.XRHandMeshModel(u,s,a.path,c,a,p=>{var y;const g=l==null?void 0:l.gltf;((y=g==null?void 0:g.scene.children)==null?void 0:y.length)===0&&(g.scene.children[0]=p),l!=null&&l.gltf&&bn().createBuiltinComponents(e.context,e.sourceId||c,l.gltf,null,l),p.traverse(b=>{var _;b.layers.set(2),(_=J.active)!=null&&_.isPassThrough&&!h&&this.makeOccluder(b),b instanceof d.Mesh&&le.NEEDLE_progressive.assignMeshLOD(b,0)}),i.connected||(fs&&$.DrawLabel(i.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if(fs&&u.add(new d.AxesHelper(.5)),i.inputSource.hand){fs&&console.log(i.inputSource.hand);for(const p of i.inputSource.hand.values())if(s.joints[p.jointName]===void 0){const g=new d.Group;g.matrixAutoUpdate=!1,g.visible=!0,s.joints[p.jointName]=g,s.add(g)}}else fs&&$.DrawLabel(i.rayWorldPosition,"No inputSource.hand found for index "+i.index,.05,5);return{handObject:u,handmesh:f}}makeOccluder(e){if(e instanceof d.Mesh){let i=e.material;i instanceof d.Material&&(i=e.material=i.clone(),i.depthWrite=!0,i.depthTest=!0,i.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}r(ns,"factory",new H.XRControllerModelFactory);df([m()],ns.prototype,"createControllerModel");df([m()],ns.prototype,"createHandModel");df([m(te)],ns.prototype,"customLeftHand");df([m(te)],ns.prototype,"customRightHand");class uf extends I{}var NO=Object.defineProperty,Bo=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&NO(t,e,n),n};const Mp=S("debugwebxr");class Ai extends I{constructor(){super(...arguments);r(this,"movementSpeed",1.5);r(this,"rotationStep",30);r(this,"useTeleport",!0);r(this,"usePinchToTeleport",!0);r(this,"useTeleportTarget",!1);r(this,"useTeleportFade",!1);r(this,"showRays",!0);r(this,"showHits",!0);r(this,"isXRMovementHandler",!0);r(this,"xrSessionMode","immersive-vr");r(this,"_didApplyRotation",!1);r(this,"_didTeleport",!1);r(this,"_teleportBuffer",new Array);r(this,"_plane",null);r(this,"_lines",[]);r(this,"_hitDiscs",[]);r(this,"_hitDistances",[]);r(this,"_lastHitDistances",[]);r(this,"hitPointRaycastFilter",e=>e.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(e){const i=e.xr.rig;if(!(i!=null&&i.gameObject)||e.xr.isPassThrough)return;const n=e.xr.leftController,s=e.xr.rightController;n&&this.onHandleMovement(n,i.gameObject),s&&(this.onHandleRotation(s,i.gameObject),this.useTeleport&&this.onHandleTeleport(s,i.gameObject))}onLeaveXR(e){for(const i of this._lines)i.removeFromParent();for(const i of this._hitDiscs)i==null||i.removeFromParent()}onBeforeRender(){var e;(e=this.context.xr)!=null&&e.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,i){const n=e.getStick("xr-standard-thumbstick");if(n.x!=0||n.y!=0){const s=V(n.x,0,n.y);s.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const a=Ue(i);s.multiplyScalar(a.x),s.applyQuaternion(e.xr.poseOrientation),s.y=0,s.applyQuaternion(i.worldQuaternion),i.position.add(s),i.updateWorldMatrix(!1,!1);for(const l of i.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(e,i){if(e._isMxInk)return;const s=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(s)<.3&&(this._didApplyRotation=!1);else if(Math.abs(s)>.5){this._didApplyRotation=!0;const a=s>0?1:-1,l=Q(this.context.mainCamera).clone();i.rotateY(a*z.toRadians(this.rotationStep));const h=Q(this.context.mainCamera).clone().sub(l);h.y=0,i.position.sub(h)}}onHandleTeleport(e,i){var s,a,l,c,h;let n=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const u=e.getPointerId("primary");if(u!=null&&this.context.input.getIsPointerIdInUse(u))return;const f=e.getGesture("pinch");f&&(n=f.value)}else n=(s=e.getStick("xr-standard-thumbstick"))==null?void 0:s.y;if(this._didTeleport)n>=0&&n<.4?this._didTeleport=!1:n<0&&n>-.4&&(this._didTeleport=!1);else if(n>.8){this._didTeleport=!0;const u=this.context.physics.raycastFromRay(e.ray)[0];if(u&&u.object instanceof H.GroundedSkybox){const p=(a=u.normal)==null?void 0:a.dot(V(0,1,0));if(p!==void 0&&p<.4)return}let f=u==null?void 0:u.point;if(!f&&!this.useTeleportTarget){this._plane||(this._plane=new d.Plane(new d.Vector3(0,1,0),0));const p=i.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new d.Vector3(0,1,0),p);const g=e.ray;f=p.clone(),this._plane.intersectLine(new d.Line3(g.origin,V(g.direction).multiplyScalar(1e4).add(g.origin)),f),f.distanceTo(p)>i.scale.x*10&&(f=null)}if(f){if(this.useTeleportTarget&&!C.getComponentInParent(u.object,uf))return;const p=f.clone();if(Mp&&$.DrawSphere(f,.025,16711680,5),(l=this.context.mainCamera)==null?void 0:l.position){const y=(c=this.context.xr)==null?void 0:c.getUserOffsetInRig();y&&(y.y=0,p.sub(y),Mp&&$.DrawWireSphere(y.add(p),.025,65280,5))}this._teleportBuffer.push(i.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(h=e.xr.fadeTransition())==null||h.then(()=>{i.worldPosition=p}):i.worldPosition=p}}else if(n<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const u=this._teleportBuffer.pop();u&&u.decompose(i.position,i.quaternion,i.scale)}}renderRays(e){var i;for(let n=0;n<this._lines.length;n++){const s=this._lines[n];s&&(s.visible=!1)}for(let n=0;n<e.controllers.length;n++){const s=e.controllers[n];let a=this._lines[n];if(!s.connected||!s.isTracking||!s.ray||s.targetRayMode==="transient-pointer"||!s.hasSelectEvent){a&&(a.visible=!1);continue}a||(a=this.createRayLineObject(),a.scale.z=.5,this._lines[n]=a),s.updateRayWorldPosition(),s.updateRayWorldQuaternion();const l=s.rayWorldPosition,c=s.rayWorldQuaternion;a.position.copy(l),a.quaternion.copy(c);const h=e.rigScale,u=this.usePinchToTeleport&&s.isTeleportGesture,f=this._lastHitDistances[n],p=this._hitDistances[n]!=null,g=f??h;a.scale.set(h,h,g),a.visible=!0,a.layers.disableAll(),a.layers.enable(2);let y=a.material.opacity;u?y=1:this.showHits&&g<e.rigScale*.5?y=0:(i=s.getButton("primary"))!=null&&i.pressed?y=.5:y=p?.2:.1,a.material.opacity=z.lerp(a.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),a.parent!==this.context.scene&&this.context.scene.add(a)}}renderHits(e){var i;for(const n of this._hitDiscs){if(!n)continue;const s=n.controller;if(!s||!s.connected||!s.isTracking){n.visible=!1;continue}}for(let n=0;n<e.controllers.length;n++){const s=e.controllers[n];if(!s.connected||!s.isTracking||!s.ray||!s.hasSelectEvent)continue;let a=this._hitDiscs[n],l=!0;const c=s.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(a&&(a.visible=!1),this._hitDistances[n]=null,this._lastHitDistances[n]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+s.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[n];p&&p.visible&&p.hit&&this.updateHitPointerPosition(s,p,p.hit.distance);continue}const u=this.context.physics.raycastFromRay(s.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let f=u.find(p=>this.usePinchToTeleport&&s.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(f||(f=u[0]),a&&(a.controller=s,a.hit=f),this._hitDistances[n]=(f==null?void 0:f.distance)||null,f){this._lastHitDistances[n]=f.distance;const p=e.rigScale??1;Mp&&($.DrawWireSphere(f.point,.025*p,16711680),$.DrawLabel(V(0,.2,0).add(f.point),f.object.name,.02,0)),a||(a=this.createHitPointObject(),this._hitDiscs[n]=a),a.hit=f,a.visible=f.distance>p*.05;let g=.01*(p+f.distance);const y=(i=s.getButton("primary"))==null?void 0:i.pressed;y&&(g*=1.1),a.scale.set(g,g,g),a.layers.set(2);let b=a.material.opacity;if(y?b=1:b=f.distance<.15*p?.2:.6,a.material.opacity=z.lerp(a.material.opacity,b,this.context.time.deltaTimeUnscaled/.1),a.visible){if(f.normal){this.updateHitPointerPosition(s,a,f.distance);const _=f.normal.applyQuaternion(_e(f.object));a.quaternion.setFromUnitVectors($O,_)}else this.updateHitPointerPosition(s,a,f.distance);a.parent!==this.context.scene&&this.context.scene.add(a)}}else this._hitDiscs[n]&&(this._hitDiscs[n].visible=!1)}}isObjectWithInteractiveComponent(e,i=0){return cu(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,i+1):!1}updateHitPointerPosition(e,i,n){const s=V(e.rayWorldPosition);s.add(V(0,0,n-.01).applyQuaternion(e.rayWorldQuaternion)),i.position.lerp(s,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const e=new d.Mesh(new d.SphereGeometry(.3,6,6),new d.MeshBasicMaterial({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:d.DoubleSide}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new H.Line2;e.layers.disableAll(),e.layers.enable(2);const i=new H.LineGeometry;e.geometry=i;const n=new Float32Array(9);n.set([0,0,.02,0,0,.4,0,0,1]),i.setPositions(n);const s=new Float32Array(9);s.set([1,1,1,.1,.1,.1,0,0,0]),i.setColors(s);const a=new H.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:d.AdditiveBlending,dashed:!1});return e.material=a,e}}Bo([m()],Ai.prototype,"movementSpeed");Bo([m()],Ai.prototype,"rotationStep");Bo([m()],Ai.prototype,"useTeleport");Bo([m()],Ai.prototype,"usePinchToTeleport");Bo([m()],Ai.prototype,"useTeleportTarget");Bo([m()],Ai.prototype,"useTeleportFade");Bo([m()],Ai.prototype,"showRays");Bo([m()],Ai.prototype,"showHits");const $O=new d.Vector3(0,1,0);var VO=Object.defineProperty,ft=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&VO(t,e,n),n};const Il=S("debugwebxr"),WO=S("debugusdz");var mn;const at=(mn=class extends I{constructor(){super(...arguments);r(this,"createVRButton",!0);r(this,"createARButton",!0);r(this,"createSendToQuestButton",!0);r(this,"createQRCode",!0);r(this,"useDefaultControls",!0);r(this,"showControllerModels",!0);r(this,"showHandModels",!0);r(this,"usePlacementReticle",!0);r(this,"customARPlacementReticle");r(this,"usePlacementAdjustment",!0);r(this,"arScale",1);r(this,"useXRAnchor",!1);r(this,"autoPlace",!1);r(this,"autoCenter",!1);r(this,"useQuicklookExport",!1);r(this,"useDepthSensing",!1);r(this,"useSpatialGrab",!0);r(this,"defaultAvatar");r(this,"_playerSync");r(this,"_createdComponentsInSession",[]);r(this,"_usdzExporter");r(this,"_exitXRMenuButton");r(this,"_previousXRState",0);r(this,"_spatialGrabRaycaster");r(this,"_activeWebARSessionRoot",null);r(this,"onAvatarSpawned",e=>{Il&&console.log("WebXR.onAvatarSpawned",e),C.getComponentInChildren(e,Oo)??(i=C.addComponent(e,Oo))});r(this,"_buttonFactory");r(this,"_buttons",[])}awake(){J.getXRSync(this.context)}onEnable(){var e,i;window.location.protocol!=="https:"&&me('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),this.useQuicklookExport&&(C.findObjectOfType(Kn)||(Il&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=C.addComponent(this.gameObject,Kn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(Il&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new te("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(dy),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(e=this._playerSync.onPlayerSpawned)==null||e.removeEventListener(this.onAvatarSpawned),(i=this._playerSync.onPlayerSpawned)==null||i.addEventListener(this.onAvatarSpawned))}onDisable(){var e;(e=this._usdzExporter)==null||e.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await J.isVRSupported()&&this.createVRButton?J.offerSession("immersive-vr","default",this.context):this.createARButton&&await J.isARSupported()&&this.createARButton?J.offerSession("immersive-ar","default",this.context):!1}get session(){return J.active??null}get sessionMode(){return J.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return J.start("immersive-vr",e,this.context)}async enterAR(e){return J.start("immersive-ar",e,this.context)}exitXR(){J.stop()}get isActiveWebXR(){return!mn.activeWebXRComponent||mn.activeWebXRComponent===this}onBeforeXR(e,i){var n;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(n=mn.activeWebXRComponent)==null?void 0:n.name}). This is ignored: ${this.name}`);return}mn.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;Il&&console.log("WebXR onEnterXR"),this._previousXRState=Qt.Global.Mask;const i=e.xr.isVR;if(Qt.Global.Set(i?Bn.VR:Bn.AR),e.xr.isAR){let n=C.findObjectOfType(is);if(!n)if(this.usePlacementReticle){const s=new d.Object3D;for(const a of this.context.scene.children)s.add(a);this.context.scene.add(s),n=C.addComponent(s,is),this._createdComponentsInSession.push(n)}else(Il||j())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=n,n&&(n.customReticle=this.customARPlacementReticle,n.arScale=this.arScale,n.arTouchTransform=this.usePlacementAdjustment,n.autoPlace=this.autoPlace,n.autoCenter=this.autoCenter,n.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=C.findObjectOfType(Tr)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Tr))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){var i,n;if((i=this._exitXRMenuButton)==null||i.remove(),!!this.isActiveWebXR){Qt.Global.Set(this._previousXRState),(n=this._playerSync)==null||n.destroyInstance();for(const s of this._createdComponentsInSession)s.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),eh(1).then(()=>mn.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let i=this.gameObject.getComponent(Ai);return!i&&e&&(i=this.gameObject.addComponent(Ai),this._createdComponentsInSession.push(i)),i&&(i.enabled=e),i}setDefaultControllerRenderingEnabled(e){let i=this.gameObject.getComponent(ns);return!i&&e&&(i=this.gameObject.addComponent(ns),this._createdComponentsInSession.push(i),i.createControllerModel=this.showControllerModels,i.createHandModel==this.showHandModels),i&&(i.enabled=e),i}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Po.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||WO)&&this.useQuicklookExport){const i=C.findObjectOfType(Kn);if(!i||i&&i.allowCreateQuicklookButton){const n=this.getButtonsFactory().createQuicklookButton();this.addButton(n,50)}}if(this.createARButton){const i=this.getButtonsFactory().createARButton();this.addButton(i,50)}if(this.createVRButton){const i=this.getButtonsFactory().createVRButton();this.addButton(i,50)}}if(this.createSendToQuestButton&&!exports.DeviceUtilities.isQuest()&&J.isVRSupported().then(i=>{if(!i){const n=this.getButtonsFactory().createSendToQuestButton();this.addButton(n,50)}}),this.createQRCode){const i=hh(rs);if(i&&i.createQRCodeButton===!1)j()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const n=zn.getOrCreate().createQRCode();this.addButton(n,50)}}}addButton(e,i){this._buttons.push(e),e.setAttribute("priority",i.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}},r(mn,"activeWebXRComponent",null),mn);ft([m()],at.prototype,"createVRButton");ft([m()],at.prototype,"createARButton");ft([m()],at.prototype,"createSendToQuestButton");ft([m()],at.prototype,"createQRCode");ft([m()],at.prototype,"useDefaultControls");ft([m()],at.prototype,"showControllerModels");ft([m()],at.prototype,"showHandModels");ft([m()],at.prototype,"usePlacementReticle");ft([m(te)],at.prototype,"customARPlacementReticle");ft([m()],at.prototype,"usePlacementAdjustment");ft([m()],at.prototype,"arScale");ft([m()],at.prototype,"useXRAnchor");ft([m()],at.prototype,"autoPlace");ft([m()],at.prototype,"autoCenter");ft([m()],at.prototype,"useQuicklookExport");ft([m()],at.prototype,"useDepthSensing");ft([m()],at.prototype,"useSpatialGrab");ft([m(te)],at.prototype,"defaultAvatar");let ff=at;const _d=S("debugusdzbehaviours");class fy{constructor(){r(this,"behaviours",[]);r(this,"behaviourComponents",[]);r(this,"behaviourComponentsCopy",[]);r(this,"audioClips",[]);r(this,"audioClipsCopy",[]);r(this,"targetUuids",new Set)}get extensionName(){return"Behaviour"}addBehavior(t){this.behaviours.push(t)}addAudioClip(t){if(!t||typeof t!="string")return"";const i="audio/"+Wr.getName(t);return this.audioClips.push({clipUrl:t,filesKey:i}),i}getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(t){if(!t.root)return Promise.resolve();const e=[];return t.root.traverse(i=>{C.foreachComponent(i,n=>{var a;const s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const l=(a=s.beforeCreateDocument)==null?void 0:a.call(s,this,t);l instanceof Promise&&e.push(l)}},!1)}),_d&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(e)}onExportObject(t,e,i){var n;for(const s of this.behaviourComponents)(n=s.createBehaviours)==null||n.call(s,this,e,i)}onAfterBuildDocument(t){for(const f of this.behaviourComponents)typeof f.afterCreateDocument=="function"&&f.afterCreateDocument(this,t);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const e=new Set,i=new Set,n=new Set,s=new Set,a=_d;let l=`graph LR
1253
1253
  `,c="";function h(f){if(f instanceof yo){a&&(l+=`subgraph Group_${f.id}
1254
1254
  `);for(const p of f.actions)a&&(l+=`${f.id}[${f.id}] -- ${f.type},loops:${f.loops} --> ${p.id}[${p.id}]
1255
1255
  `),h(p);a&&(l+=`end
@@ -1271,7 +1271,7 @@ dateFormat X
1271
1271
  axisFormat %s
1272
1272
  `;const p=Array.from(s),g=new Set;for(const v of p)if(v.affectedObjects&&typeof v.affectedObjects!="string"){if(Array.isArray(v.affectedObjects))for(const w of v.affectedObjects)g.add(w);else g.add(v.affectedObjects);a&&(f+=`section ${v.animationName} (${v.id})
1273
1273
  `,f+=`${v.id} : ${v.start}, ${v.duration}s
1274
- `)}a&&s.size&&console.log(f);const y=new Set;for(const v of g){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let w=v.getPath();w.startsWith("<")&&(w=w.substring(1)),w.endsWith(">")&&(w=w.substring(0,w.length-1)),y.add({path:w,obj:v})}const b=Array.from(y).sort((v,w)=>v.path.length-w.path.length),_=new Array;for(let v=0;v<b.length;v++)for(let w=v+1;w<b.length;w++)if(b[w].path.startsWith(b[v].path)){const x=b[w],O=b[v];_.push({child:x.obj.displayName+" ("+x.path+")",parent:O.obj.displayName+" ("+O.path+")"})}_.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:_,playAnimationActions:s})}for(const f of new Set([...e,...i]))if(Array.isArray(f))for(const p of f)n.add(p.uuid);else n.add(f.uuid);_d&&console.log("All Behavior trigger sources and action targets",e,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(t,e){var i;if((i=this.behaviours)!=null&&i.length){e.beginBlock('def Scope "Behaviors"');for(const n of this.behaviours)n.writeTo(this,t.document,e);e.closeBlock()}}async onAfterSerialize(t){_d&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)typeof e.afterSerialize=="function"&&(e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,t):e.afterSerialize(this,t));for(const{clipUrl:e,filesKey:i}of this.audioClipsCopy){if(t.files[i])return;const a=await(await(await fetch(e)).blob()).arrayBuffer(),l=new Uint8Array(a);t.files[i]=l}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class py{get extensionName(){return"Physics"}onExportObject(t,e,i){const n=C.getComponents(t,ot).filter(c=>c.enabled),s=C.getComponents(t,ui).filter(c=>c.enabled&&!c.isTrigger);let a=n.length>0?n[0]:null;const l=s.length>0?s[0]:null;l&&!a&&(a=new ot,a.isKinematic=!0),a&&e.addEventListener("serialize",(c,h)=>{var u,f,p;if(a){if(c.appendLine(),c.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),a.useGravity||c.appendLine("bool gravityEnabled = 0"),c.appendLine('uniform token info:id = "RealityKit.RigidBody"'),a.isKinematic&&c.appendLine('token motionType = "Kinematic"'),c.beginBlock('def RealityKitStruct "massFrame"',"{",!0),c.appendLine(`float m_mass = ${a.mass}`),c.beginBlock('def RealityKitStruct "m_pose"',"{",!0),c.appendLine(`float3 position = (${a.centerOfMass.x}, ${a.centerOfMass.y}, ${a.centerOfMass.z})`),c.closeBlock("}"),c.closeBlock("}"),s.length>0){const g=s[0];c.beginBlock('def RealityKitStruct "material"',"{",!0);const y=g.sharedMaterial;y&&y.dynamicFriction!==void 0&&c.appendLine(`double dynamicFriction = ${(u=g.sharedMaterial)==null?void 0:u.dynamicFriction}`),y&&y.bounciness!==void 0&&c.appendLine(`double restitution = ${(f=g.sharedMaterial)==null?void 0:f.bounciness}`),y&&y.staticFriction!==void 0&&c.appendLine(`double staticFriction = ${(p=g.sharedMaterial)==null?void 0:p.staticFriction}`),c.closeBlock("}")}c.closeBlock("}")}}),l&&(e.addEventListener("serialize",(c,h)=>{var p;c.beginBlock('def RealityKitComponent "Collider"',"{",!0),c.appendLine("uint group = 1"),c.appendLine('uniform token info:id = "RealityKit.Collider"'),c.appendLine("uint mask = 4294967295");const f=l.isTrigger?"Trigger":"Default";if(c.appendLine(`token type = "${f}"`),c.beginBlock('def RealityKitStruct "Shape"',"{",!0),l instanceof al){const g=l;c.appendLine('token shapeType = "Sphere"'),c.appendLine(`float radius = ${g.radius}`)}else if(l instanceof tf){const g=l;c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(l instanceof As){const g=l;c.appendLine('token shapeType = "Capsule"'),c.appendLine(`float radius = ${g.radius}`),c.appendLine(`float height = ${g.height}`)}else if(l instanceof Io&&((p=l.sharedMesh)!=null&&p.geometry)){const g=l.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const y=l.sharedMesh.geometry.boundingBox;y&&(c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${y.max.x-y.min.x}, ${y.max.y-y.min.y}, ${y.max.z-y.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",l))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",l);c.beginBlock('def RealityKitStruct "pose"',"{",!0),c.closeBlock("}"),c.closeBlock("}"),c.closeBlock("}")}),s.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",l))}}const GO=S("debugshadowcomponents");ne.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class Qi extends I{constructor(){super(...arguments);r(this,"_shadowComponent",null);r(this,"_controlsChildLayout",!0);r(this,"_root");r(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Yt.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=C.getComponentInParent(this.gameObject,Ph)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,i){var a;if(!e)return;this.removeShadowComponent();const n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=C.getComponentInParent(n,Qi),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Si]=this,this.setShadowComponentOwner(e);let s=!1;if(((a=this.Root)==null?void 0:a.gameObject)===this.gameObject)this.gameObject.add(e);else{const l=this._parentComponent.shadowComponent;l&&(l==null||l.add(e),s=!0)}this.shadowComponent=e,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),rh&&e.add(new d.AxesHelper(.5)),this.onAfterAddedToScene(),s&&ne.__webpack_exports__update(),GO&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Si]===void 0||e[Si]===this)&&(e[Si]=this,e.children))for(const i of e.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(e,i,n){if(e&&e[Si]===i){n(e);for(const s of e.children)this.traverseOwnedShadowComponents(s,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class Ph extends Qi{awake(){super.awake()}}var HO=Object.defineProperty,qO=Object.getOwnPropertyDescriptor,Mh=(o,t,e,i)=>{for(var n=i>1?void 0:i?qO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&HO(t,e,n),n};const Op=S("debugui"),kp=S("debuguilayout");class ix{constructor(){r(this,"width");r(this,"height")}}class nx{constructor(){r(this,"x");r(this,"y");r(this,"width");r(this,"height")}}const cn=new d.Vector3,jl=new d.Matrix4,bd=new d.Quaternion,fl=class sx extends Qi{constructor(){super(...arguments);r(this,"_anchoredPosition");r(this,"sizeDelta",new d.Vector2(100,100));r(this,"pivot",new d.Vector2(.5,.5));r(this,"anchorMin",new d.Vector2(0,0));r(this,"anchorMax",new d.Vector2(1,1));r(this,"minWidth");r(this,"minHeight");r(this,"lastMatrix");r(this,"rectBlock");r(this,"_transformNeedsUpdate",!1);r(this,"_initialPosition");r(this,"_parentRectTransform");r(this,"_lastUpdateFrame",-1);r(this,"_lastAnchoring");r(this,"_createdBlocks",[]);r(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new d.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const i=this._parentRectTransform.width,n=this.anchorMax.x-this.anchorMin.x;e=i*n,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const i=this._parentRectTransform.height,n=this.anchorMax.y-this.anchorMin.y;e=i*n,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new d.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new d.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new d.Vector2),ma(this,"_anchoredPosition",()=>{this.markDirty()}),ma(this,"sizeDelta",()=>{this.markDirty()}),ma(this,"pivot",()=>{this.markDirty()}),ma(this,"anchorMin",()=>{this.markDirty()}),ma(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.rectBlock||(this.rectBlock=new d.Object3D),this.lastMatrix||(this.lastMatrix=new d.Matrix4),this._lastAnchoring||(this._lastAnchoring=new d.Vector2),this._initialPosition||(this._initialPosition=new d.Vector3),this._anchoredPosition||(this._anchoredPosition=new d.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(kp?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(kp&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){var s;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const i=this.shadowComponent;if(!i)return;this.gameObject.parent?this._parentRectTransform=C.getComponentInParent(this.gameObject.parent,sx):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,kp&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(i.rotation.y=Math.PI):(i.matrix.identity(),i.matrixAutoUpdate=!1,cn.set(0,0,0),this.applyPivot(cn),i.matrix.setPosition(cn.x,cn.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(bd.copy(this.gameObject.quaternion),bd.x*=-1,bd.z*=-1,jl.makeRotationFromQuaternion(bd),i.matrix.premultiply(jl)),cn.set(0,0,0),this.applyAnchoring(cn),(s=this.canvas)!=null&&s.screenspace?cn.z+=.1:cn.z+=.01,jl.identity(),jl.setPosition(cn.x,cn.y,cn.z),i.matrix.premultiply(jl),i.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const a of Hu(this.gameObject,Qi,n,1)){if(a===this||!a.activeAndEnabled)continue;const l=a;l.onParentRectTransformChanged&&l.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new d.Vector2);const i=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=i.x,this.gameObject.position.y+=i.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const n=this._parentRectTransform;if(n){let s=0;const a=1-this.anchorMax.y-this.anchorMin.y;s-=n.height*.5*a,e.y+=s;let l=0;const c=1-this.anchorMax.x-this.anchorMin.x;l-=n.width*.5*c,e.x+=l}}applyPivot(e){if(this.pivot&&!this.isRoot()){const i=this.pivot.x-.5;e.x-=i*this.sizeDelta.x*this.gameObject.scale.x;const n=this.pivot.y-.5;e.y-=n*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,i=1e-4){return e.width<=0&&(e.width=i),e.height<=0&&(e.height=1e-4),e}createNewBlock(e){e={...this.getBasicOptions(),...e},Op&&console.log(this.name,e);const i=new ne.__webpack_exports__Block(e);return this._createdBlocks.push(i),i}createNewText(e){Op&&console.log(e),e={...this.getBasicOptions(),...e},Op&&console.log(this.name,e);const i=new ne.__webpack_exports__Text(e);return this._createdTextBlocks.push(i),i}};Mh([m(d.Vector2)],fl.prototype,"anchoredPosition",1);Mh([m(d.Vector2)],fl.prototype,"sizeDelta",2);Mh([m(d.Vector2)],fl.prototype,"pivot",2);Mh([m(d.Vector2)],fl.prototype,"anchorMin",2);Mh([m(d.Vector2)],fl.prototype,"anchorMax",2);let wn=fl;var XO=Object.defineProperty,ox=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&XO(t,e,n),n};class pl extends I{constructor(){super(...arguments);r(this,"effectColor");r(this,"effectDistance")}}ox([m(ie)],pl.prototype,"effectColor");ox([m(d.Vector2)],pl.prototype,"effectDistance");var QO=Object.defineProperty,YO=Object.getOwnPropertyDescriptor,rx=(o,t,e,i)=>{for(var n=i>1?void 0:i?YO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QO(t,e,n),n};const vd={backgroundColor:new d.Color(1,1,1),backgroundOpacity:1,borderColor:new d.Color(1,1,1),borderOpacity:1};var Hn;const my=(Hn=class extends Qi{constructor(){super(...arguments);r(this,"_alphaFactor",1);r(this,"sRGBColor",new d.Color(1,0,1));r(this,"raycastTarget",!0);r(this,"uiObject",null);r(this,"_color",null);r(this,"_rect",null);r(this,"_stateManager",null);r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new ie(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new ie(1,1,1,1)),this._color.copy(e),this.onColorChanged())}setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),vd.backgroundColor=this.sRGBColor,vd.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(vd,this._alphaFactor),this.uiObject.set(vd),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=C.getComponent(this.gameObject,wn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var e;(e=this.uiObject)==null||e.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this==null||this.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new ne.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),ma(this,"_color",()=>HP(this,this.onColorChanged))}onEnable(){var e;super.onEnable(),this.uiObject&&((e=this.rectTransform.shadowComponent)==null||e.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const i={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(i),this.applyEffects(i),this.onCreate(i),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,i=1){var s;const n=(s=this.gameObject)==null?void 0:s.getComponent(pl);n&&(n.effectDistance&&(e.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(e.borderColor=n.effectColor,e.borderOpacity=n.effectColor.alpha*i))}async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(Hn.textureCache.has(e))e=Hn.textureCache.get(e);else if(!e.isRenderTargetTexture){const i=e.clone();i.colorSpace=d.LinearSRGBColorSpace,Hn.textureCache.set(e,i),e=i}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),le.NEEDLE_progressive.assignTextureLOD(e,0).then(i=>{i instanceof d.Texture&&(e&&Hn.textureCache.set(e,i),this.setOptions({backgroundImage:i}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},r(Hn,"textureCache",new Map),Hn);rx([m(ie)],my.prototype,"color",1);rx([m()],my.prototype,"raycastTarget",2);let Oh=my;class kh extends Oh{constructor(){super(...arguments);r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var KO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,zs=(o,t,e,i)=>{for(var n=i>1?void 0:i?ZO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&KO(t,e,n),n};const Xo=S("debugtext");var tt=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(tt||{}),ax=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(ax||{});class Dt extends Oh{constructor(){super(...arguments);r(this,"alignment",0);r(this,"verticalOverflow",0);r(this,"horizontalOverflow",0);r(this,"lineSpacing",1);r(this,"supportRichText",!1);r(this,"font");r(this,"fontStyle",0);r(this,"sRGBTextColor",new d.Color(1,0,1));r(this,"_text","");r(this,"_fontSize",12);r(this,"_textMeshUi",null);r(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var i;super.setAlphaFactor(e),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var i;this._fontSize=e,(i=this.uiObject)==null||i.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var i;const e=(i=this.uiObject)==null?void 0:i._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Xo&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Xo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const i=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Xo&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=i.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,i){var n,s,a;if(Xo&&console.log("feedText",this.uiObject,e,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||e.length===0)this.uiObject.textContent=e;else{let l=this.getNextTag(e);if(l){if(l.startIndex>0){for(let u=this.uiObject.children.length-1;u>=0;u--){const f=this.uiObject.children[u];f.isUI&&(this.uiObject.remove(f),f.clear())}const h=new ne.__webpack_exports__Inline({textContent:e.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const c=[];for(;l;){const h=this.getNextTag(e,l.endIndex),u={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(h){u.textContent=this.getText(e,l,h),this.handleTag(l,u,c);const f=new ne.__webpack_exports__Inline(u);(s=this.uiObject)==null||s.add(f)}else{u.textContent=e.substring(l.endIndex),this.handleTag(l,u,c);const f=new ne.__webpack_exports__Inline(u);(a=this.uiObject)==null||a.add(f)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let s=!1;if(this._textMeshUi)for(let a=0;a<this._textMeshUi.length;a++){if(e[a]===!0)continue;s=!0;const l=this._textMeshUi[a];l.textContent&&(du(l,n),e[a]=!0)}if(!s)break;yield}}handleTag(e,i,n){if(!e.isEndTag){if(e.type.includes("color")){const s=new Rp(e,{color:i.color});if(n.push(s),e.type.length>6){const a=parseInt("0x"+e.type.substring(7));i.color=a}else i.color=new d.Color(1,1,1)}else if(e.type=="b"){this.setFont(i,1);const s=new Rp(e,{fontWeight:700});n.push(s)}else if(e.type=="i"){this.setFont(i,2);const s=new Rp(e,{fontStyle:"italic"});n.push(s)}}}getText(e,i,n){return e.substring(i.endIndex,n.startIndex)}getNextTag(e,i=0){const n=e.indexOf("<",i),s=e.indexOf(">",n);if(n>=0&&s>=0){const a=e.substring(n+1,s);return{type:a,startIndex:n,endIndex:s+1,isEndTag:a.startsWith("/")}}return null}setFont(e,i){if(!this.font)return;const n=this.font,s=this.getFamilyNameWithCorrectSuffix(n,i);Xo&&console.log("Selected font family:"+s);let a=ne.__webpack_exports__FontLibrary.getFontFamily(s);switch(a||(a=ne.__webpack_exports__FontLibrary.addFontFamily(s)),e.fontFamily=a,i){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let l=a.getVariant(e.fontWeight,e.fontStyle);if(!l){let c=s;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=s;h!=null&&h.endsWith(".png")||(h+=".png"),l=a.addVariant(e.fontWeight,e.fontStyle,c,h),l==null||l.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,i){var u;const n=e.lastIndexOf("-");if(n<0)return e;const s=(u=e.substring(n+1))==null?void 0:u.toLowerCase();if(JO.includes(s))return Xo&&console.warn("Unsupported font style: "+s),e;const a=e.lastIndexOf("/");let l=e;a>=0&&(l=l.substring(a+1));const c=l[0]===l[0].toUpperCase(),h=e.substring(0,n);switch(Xo&&console.log("Select font: ",e,ax[i],l,c,h),i){case 0:return c?h+"-Regular":h+"-regular";case 1:return c?h+"-Bold":h+"-bold";case 2:return c?h+"-Italic":h+"-italic";case 3:return c?h+"-BoldItalic":h+"-bolditalic";default:return e}}}zs([m()],Dt.prototype,"alignment",2);zs([m()],Dt.prototype,"verticalOverflow",2);zs([m()],Dt.prototype,"horizontalOverflow",2);zs([m()],Dt.prototype,"lineSpacing",2);zs([m()],Dt.prototype,"supportRichText",2);zs([m(URL)],Dt.prototype,"font",2);zs([m()],Dt.prototype,"fontStyle",2);zs([m()],Dt.prototype,"text",1);zs([m()],Dt.prototype,"fontSize",1);class Rp{constructor(t,e){r(this,"tag");r(this,"previousValues");this.tag=t,this.previousValues=e}}const JO=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class cr{constructor(t){r(this,"id");r(this,"content","");r(this,"font",[]);r(this,"pointSize",144);r(this,"width");r(this,"height");r(this,"depth");r(this,"wrapMode");r(this,"horizontalAlignment");r(this,"verticalAlignment");r(this,"material");this.id=t}static getId(){return this.global_id++}setDepth(t){return this.depth=t,this}setPointSize(t){return this.pointSize=t,this}setHorizontalAlignment(t){return this.horizontalAlignment=t,this}setVerticalAlignment(t){return this.verticalAlignment=t,this}writeTo(t,e){var n;e.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),e.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),e.closeBlock(")"),e.beginBlock(),this.content&&e.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const i=this.font.map(s=>`"${s}"`).join(", ");e.appendLine(`string[] font = [ ${i} ]`),e.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&e.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&e.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&e.appendLine(`double depth = ${this.depth}`),this.wrapMode&&e.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&e.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&e.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&e.appendLine(`rel material:binding = </StageRoot/Materials/${rf(this.material)}>`),e.closeBlock()}}r(cr,"global_id",0);class gy{static singleLine(t,e,i){const n=new cr("text_"+cr.getId());return n.content=t,e&&(n.pointSize=e),i&&(n.depth=i),n}static multiLine(t,e,i,n,s,a){const l=new cr("text_"+cr.getId());return l.content=t,l.width=e,l.height=i,l.horizontalAlignment=n,l.verticalAlignment=s,a!==void 0&&(l.wrapMode=a),l}}const ek=new d.Matrix4().makeRotationY(Math.PI),tk=new d.Matrix4().makeScale(-1,1,-1);class pf{get extensionName(){return"text"}exportText(t,e,i){const n=C.getComponent(t,Dt);if(!n)return;const s=C.getComponent(t,wn);let a=100,l=100;s&&(a=s.width,l=s.height);const c=ek.clone();s&&c.premultiply(tk),e.setMatrix(c);const h=n.color.clone();e.material=new d.MeshStandardMaterial({color:h,emissive:h}),e.addEventListener("serialize",(u,f)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const g=gy.multiLine(p,a,l,"center","bottom","flowing");this.setTextAlignment(g,n.alignment),this.setOverflow(g,n),e.material&&(g.material=e.material),g.pointSize=this.convertToTextSize(n.fontSize),g.depth=.001,g.writeTo(void 0,u)})}convertToTextSize(t){return 1/.0502*144*t}setOverflow(t,e){e.horizontalOverflow?t.wrapMode="singleLine":t.wrapMode="flowing"}setTextAlignment(t,e){switch(e){case tt.LowerLeft:case tt.MiddleLeft:case tt.UpperLeft:t.horizontalAlignment="left";break;case tt.LowerCenter:case tt.MiddleCenter:case tt.UpperCenter:t.horizontalAlignment="center";break;case tt.LowerRight:case tt.MiddleRight:case tt.UpperRight:t.horizontalAlignment="right";break}switch(e){case tt.LowerLeft:case tt.LowerCenter:case tt.LowerRight:t.verticalAlignment="bottom";break;case tt.MiddleLeft:case tt.MiddleCenter:case tt.MiddleRight:t.verticalAlignment="middle";break;case tt.UpperLeft:case tt.UpperCenter:case tt.UpperRight:t.verticalAlignment="top";break}}}var ik=Object.defineProperty,Ke=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&ik(t,e,n),n};const Tb=S("debuguilayout");class Hr{constructor(){r(this,"left",0);r(this,"right",0);r(this,"top",0);r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ke([m()],Hr.prototype,"left");Ke([m()],Hr.prototype,"right");Ke([m()],Hr.prototype,"top");Ke([m()],Hr.prototype,"bottom");class Di extends I{constructor(){super(...arguments);r(this,"_rectTransform",null);r(this,"_needsUpdate",!1);r(this,"childAlignment",0);r(this,"reverseArrangement",!1);r(this,"spacing",0);r(this,"padding");r(this,"minWidth",0);r(this,"minHeight",0);r(this,"flexibleHeight",0);r(this,"flexibleWidth",0);r(this,"preferredHeight",0);r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Tb&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){Tb&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(wn);const e=this.gameObject.getComponentInParent(Ja);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Ja);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ke([m()],Di.prototype,"childAlignment");Ke([m()],Di.prototype,"reverseArrangement");Ke([m()],Di.prototype,"spacing");Ke([m(Hr)],Di.prototype,"padding");Ke([m()],Di.prototype,"minWidth");Ke([m()],Di.prototype,"minHeight");Ke([m()],Di.prototype,"flexibleHeight");Ke([m()],Di.prototype,"flexibleWidth");Ke([m()],Di.prototype,"preferredHeight");Ke([m()],Di.prototype,"preferredWidth");class Fo extends Di{constructor(){super(...arguments);r(this,"childControlHeight",!0);r(this,"childControlWidth",!0);r(this,"childForceExpandHeight",!1);r(this,"childForceExpandWidth",!1);r(this,"childScaleHeight",!1);r(this,"childScaleWidth",!1)}onCalculateLayout(e){var F;const i=this.primaryAxis,n=e.width;let s=n;const a=e.height;let l=a;s-=this.padding.horizontal,l-=this.padding.vertical,i==="x"?this.padding.horizontal:this.padding.vertical;const c=i==="x",h=c?"y":"x",u=c?this.childControlWidth:this.childControlHeight,f=c?this.childControlHeight:this.childControlWidth,p=c?this.childForceExpandWidth:this.childForceExpandHeight,g=c?this.childForceExpandHeight:this.childForceExpandWidth,y=c?l:s,b=c?n:a,_=.5*(c?this.childAlignment%3:Math.floor(this.childAlignment/3));let v=0;c?v+=this.padding.left:v+=this.padding.top;let w=0,x=0;for(let D=0;D<this.gameObject.children.length;D++){const A=this.gameObject.children[D],T=C.getComponent(A,wn);T!=null&&T.activeAndEnabled&&(x+=1,c?w+=T.width:w+=T.height)}let O=0;const E=this.spacing*(x-1);if(p||u){let D=0;c?D=s-=E:D=l-=E,x>0&&(O=D/x)}let M=0;M+=this.padding.left,M-=this.padding.right,_!==0&&(v=b-w,v*=_,v-=E*_,c?(v-=this.padding.right*_,v+=this.padding.left*(1-_),v<this.padding.left&&(v=this.padding.left)):(v-=this.padding.bottom*_,v+=this.padding.top*(1-_),v<this.padding.top&&(v=this.padding.top)));let R=1;for(let D=0;D<this.gameObject.children.length;D++){const A=this.gameObject.children[D],T=C.getComponent(A,wn);if(T!=null&&T.activeAndEnabled){(F=T.pivot)==null||F.set(.5,.5),T.anchorMin.set(0,1),T.anchorMax.set(0,1);const G=n*.5+M*.5;T.anchoredPosition.x!==G&&(T.anchoredPosition.x=G);const B=a*-.5;T.anchoredPosition.y!==B&&(T.anchoredPosition.y=B),g&&f&&T.sizeDelta[h]!==y&&(T.sizeDelta[h]=y),p&&u&&T.sizeDelta[i]!==O&&(T.sizeDelta[i]=O);const L=c?T.width:T.height,N=L*.5;if(v+=N,p){const Z=O*R-O*.5;Z>v&&(v=Z-O*.5+L+this.padding.left,v-=N)}let Y=v;i==="y"&&(Y=-Y),T.anchoredPosition[i]!==Y&&(T.anchoredPosition[i]=Y),v+=N,v+=this.spacing,R+=1}}}}Ke([m()],Fo.prototype,"childControlHeight");Ke([m()],Fo.prototype,"childControlWidth");Ke([m()],Fo.prototype,"childForceExpandHeight");Ke([m()],Fo.prototype,"childForceExpandWidth");Ke([m()],Fo.prototype,"childScaleHeight");Ke([m()],Fo.prototype,"childScaleWidth");class yy extends Fo{get primaryAxis(){return"y"}}class _y extends Fo{get primaryAxis(){return"x"}}class by extends Di{onCalculateLayout(){}}var nk=Object.defineProperty,sk=Object.getOwnPropertyDescriptor,as=(o,t,e,i)=>{for(var n=i>1?void 0:i?sk(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&nk(t,e,n),n},lx=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(lx||{});const Ep=S("debuguilayout"),Yi=class cx extends Ph{constructor(){super(...arguments);r(this,"_renderOnTop");r(this,"_depthWrite",!1);r(this,"_doubleSided",!0);r(this,"_castShadows",!1);r(this,"_receiveShadows",!1);r(this,"_renderMode",-1);r(this,"_rootCanvas");r(this,"_scaleFactor",1);r(this,"worldCamera");r(this,"planeDistance",-1);r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this));r(this,"previousParent",null);r(this,"_lastMatrixWorld",null);r(this,"_rectTransforms",[]);r(this,"_layoutGroups",new Map);r(this,"_receivers",[]);r(this,"onBeforeRenderRoutine",()=>{var e,i,n,s;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(i=this.context.xr)!=null&&i.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(n=this.shadowComponent)==null||n.updateMatrixWorld(!0),(s=this.shadowComponent)==null||s.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),Yt.ensureUpdateMeshUI(ne.ThreeMeshUI,this.context))});r(this,"onAfterRenderRoutine",()=>{var e,i,n,s,a;if(((e=this.context.xr)!=null&&e.isVR||(i=this.context.xr)!=null&&i.isPassThrough)&&this.screenspace){(n=this.previousParent)==null||n.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const h=this.context.mainCamera;h==null||h.add(this.gameObject)}else this.previousParent.add(this.gameObject);const l=this.context.renderer.autoClear,c=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),Yt.ensureUpdateMeshUI(ne.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=l,this.context.renderer.autoClearColor=c,this.previousParent.add(this.gameObject)}(a=this._lastMatrixWorld)==null||a.copy(this.gameObject.matrixWorld)});r(this,"_updateRenderSettingsRoutine");r(this,"_activeRenderMode",-1);r(this,"_lastWidth",-1);r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof cx||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,Ep&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new d.Matrix4,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);i!==-1&&this.context.post_render_callbacks.splice(i,1)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const i=this._rectTransforms.indexOf(e);i!==-1&&this._rectTransforms.splice(i,1)}registerLayoutGroup(e){const i=e.gameObject;this._layoutGroups.set(i,e)}unregisterLayoutGroup(e){const i=e.gameObject;this._layoutGroups.delete(i)}registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const i=this._receivers.indexOf(e);i!==-1&&this._receivers.splice(i,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await eh(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const i of this._receivers)(e=i.onBeforeCanvasRender)==null||e.call(i,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new d.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);Ep&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const i of this._rectTransforms){e&&i.markDirty();let n=this._layoutGroups.get(i.gameObject);i.isDirty&&!n&&(n=i.gameObject.getComponentInParent(Di)),(i.isDirty||n!=null&&n.isDirty)&&(Ep&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),n==null||n.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),we.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),du(this.shadowComponent,this);for(const e of C.getComponentsInChildren(this.gameObject,Qi))du(e.shadowComponent,this)}}onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let i=this.context.mainCameraComponent,n=10;switch(i&&i.nearClipPlane>0&&i.farClipPlane>0&&(n=z.lerp(i.nearClipPlane,i.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(i=this.worldCamera),this.planeDistance>0&&(n=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!i)return;const s=n+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-s,this.gameObject.quaternion.identity();const a=this.gameObject.getComponent(wn);let l=!1;a.sizeDelta.x!==this.context.domWidth&&(l=!0),a.sizeDelta.y!==this.context.domHeight&&(l=!0);const c=i.fieldOfView*Math.PI/180,h=2*Math.tan(c/2)*Math.abs(s);this.gameObject.scale.x=h/this.context.domHeight,this.gameObject.scale.y=h/this.context.domHeight,this.gameObject.scale.z=.01,l&&(a.sizeDelta.x=this.context.domWidth,a.sizeDelta.y=this.context.domHeight,a==null||a.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};as([m()],Yi.prototype,"renderOnTop",1);as([m()],Yi.prototype,"depthWrite",1);as([m()],Yi.prototype,"doubleSided",1);as([m()],Yi.prototype,"castShadows",1);as([m()],Yi.prototype,"receiveShadows",1);as([m()],Yi.prototype,"renderMode",1);as([m(Yi)],Yi.prototype,"rootCanvas",1);as([m()],Yi.prototype,"scaleFactor",1);as([m(ai)],Yi.prototype,"worldCamera",2);as([m()],Yi.prototype,"planeDistance",2);let Ja=Yi;var ok=Object.defineProperty,rk=Object.getOwnPropertyDescriptor,vy=(o,t,e,i)=>{for(var n=i>1?void 0:i?rk(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&ok(t,e,n),n};class ko extends I{constructor(){super(...arguments);r(this,"_alpha",1);r(this,"interactable",!0);r(this,"blocksRaycasts",!0);r(this,"_isDirty",!1);r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),we.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of C.getComponentsInChildren(this.gameObject,Qi,this._buffer)){const i=e;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}vy([m()],ko.prototype,"alpha",1);vy([m()],ko.prototype,"interactable",2);vy([m()],ko.prototype,"blocksRaycasts",2);class wy{get extensionName(){return"tmui"}onExportObject(t,e,i){const n=C.getComponent(t,Ja);if(n&&n.enabled&&n.renderMode===lx.WorldSpace){const s=new pf,a=C.getComponent(t,wn),l=C.getComponent(t,ko),c=new Array;if(a){if(!C.isActiveSelf(t)){const f=C.isActiveSelf(t);C.setActive(t,!0),a.onEnable(),a.updateTransform(),c.push(()=>{a.onDisable(),C.setActive(t,f)})}t.traverse(f=>{if(!C.isActiveInHierarchy(f)){const p=C.isActiveSelf(f);C.setActive(f,!0);const g=C.getComponent(f,Qi);g&&(g.onEnable(),c.push(()=>{g.onDisable()}));const y=C.getComponent(f,wn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),c.push(()=>{y.onDisable()}));const b=C.getComponent(f,Dt);b&&(b.onEnable(),c.push(()=>{b.onDisable()})),c.push(()=>{C.setActive(f,p)})}}),a.width,a.height;const h=Et.createEmpty(),u=a.shadowComponent;if(e.add(h),u){const f=u.matrix;h.setMatrix(f);const p=new Map,g=new Map;p.set(u,h),g.set(u,l?l.alpha:1),u.traverse(y=>{if(y===u)return;const b=Et.createEmpty();b.setMatrix(y.matrix);const _=y.parent,v=!!_&&typeof _.textContent=="string"&&_.textContent.length>0;let w=g.get(_)||1;const x=C.getComponent(y,ko);if(x&&(w*=x.alpha),y instanceof d.Mesh&&v){const E=y[Si];E?s.exportText(E.gameObject,b,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof d.Mesh&&!v){const E=y.geometry.clone();E.scale(1,1,-1),this.flipWindingOrder(E),b.geometry=E;const M=new d.Color,R=y.material.opacity;M.copy(y.material.color),b.material=new d.MeshBasicMaterial({color:M,opacity:R*w,map:y.material.map,transparent:!0})}p.set(y,b),g.set(y,w);const O=p.get(_);if(!O){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}O.add(b)})}}for(const h of c)h()}}flipWindingOrder(t){const e=t.index.array;for(let i=0,n=e.length/3;i<n;i++){const s=e[i*3];e[i*3]=e[i*3+2],e[i*3+2]=s}t.index.needsUpdate=!0}}const ic=S("debugusdz");function ak(o,t){var l;const e=[],i=C.getComponentsInChildren(o,St),n=C.getComponentsInChildren(o,Tt),s=new Array,a=new Array;if(t.injectImplicitBehaviours)for(const c of i){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;const h=c.runtimeAnimatorController.activeState;if(!h||!h.motion||!h.motion.clip||((l=h.motion.clip.tracks)==null?void 0:l.length)<1||s.includes(c))continue;const u=new $c;u.animator=c,u.stateName=h.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const f=new d.Object3D;C.addComponent(f,u),a.push(f),s.push(c),o.add(f)}else for(const c of i){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;ic&&console.log(c);const h=[];for(const u of c.runtimeAnimatorController.enumerateActions()){ic&&console.log(u);const f=u.getClip();h.includes(f)||h.push(f)}e.push({root:c.gameObject,clips:h})}if(t.injectImplicitBehaviours)for(const c of n){if(!c||!c.clip||!c.enabled||!c.playAutomatically||s.includes(c))continue;const h=new $c;h.animation=c,h.stateName=c.clip.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const u=new d.Object3D;C.addComponent(u,h),a.push(u),s.push(c),o.add(u)}else for(const c of n){ic&&console.log(c);const h=[];for(const u of c.animations)h.includes(u)||h.push(u);e.push({root:c.gameObject,clips:h})}ic&&(e==null?void 0:e.length)>0&&console.log("USDZ Animation Clips without behaviours",e);for(const c of e)for(const h of c.clips)t.registerAnimation(c.root,h);return a}function lk(o,t){const e=C.getComponentsInChildren(o,qi),i=C.getComponentsInChildren(o,Mo),n=new Array,s=new Array;ic&&console.log({audioSources:e,playAudioOnClicks:i});for(const a of i){if(!a.target)continue;const l=e.indexOf(a.target);l>-1&&e.splice(l,1)}for(const a of e){if(!a||!a.clip||a.volume<=0||n.includes(a))continue;const l=new Mo;l.target=a,l.name="PlayAudioOnClick_implicitAtStart_",l.trigger="start";const c=new d.Object3D;C.addComponent(c,l),console.log("implicit PlayAudioOnStart",c,l),s.push(c),n.push(a),o.add(c)}return s}function ck(o){return new wt("DisableAtStart",xt.sceneStartTrigger(),fe.fadeAction(o,0,!1))}function Ab(o,t){const e=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(e)return e;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",t?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const a=document.createElement("img");return a.id="button",s.appendChild(a),o.domElement.shadowRoot.appendChild(i),s}var hk=Object.defineProperty,Pt=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&hk(t,e,n),n};const yi=S("debugusdz"),dk=S("debugusdzpruning");class qr{constructor(){r(this,"callToAction");r(this,"checkoutTitle");r(this,"checkoutSubtitle");r(this,"callToActionURL")}}Pt([m()],qr.prototype,"callToAction");Pt([m()],qr.prototype,"checkoutTitle");Pt([m()],qr.prototype,"checkoutSubtitle");Pt([m()],qr.prototype,"callToActionURL");var Ps;const pi=(Ps=class extends I{constructor(){super(...arguments);r(this,"objectToExport");r(this,"autoExportAnimations",!0);r(this,"autoExportAudioSources",!0);r(this,"exportFileName");r(this,"customUsdzFile");r(this,"customBranding");r(this,"anchoringType","plane");r(this,"maxTextureSize",2048);r(this,"planeAnchoringAlignment","horizontal");r(this,"interactive",!0);r(this,"physics",!0);r(this,"allowCreateQuicklookButton",!0);r(this,"quickLookCompatible",!0);r(this,"extensions",[]);r(this,"link");r(this,"button");r(this,"onClickedOpenInARElement",e=>{e.preventDefault(),this.exportAndOpen()});r(this,"_currentExportTasks",new Map);r(this,"_previousTimeScale",1);r(this,"lastCallback");r(this,"_rootSessionRootWasAppliedTo",null);r(this,"_rootPositionBeforeExport",new d.Vector3);r(this,"_rootRotationBeforeExport",new d.Quaternion);r(this,"_rootScaleBeforeExport",new d.Vector3)}start(){var e,i,n;yi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((i=(e=this.objectToExport)==null?void 0:e.children)!=null&&i.length)&&!((n=this.objectToExport)!=null&&n.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var n;const e=exports.DeviceUtilities.supportsQuickLookAR(),i=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(yi||e||i)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=Ab(this.context,e),this.link.addEventListener("message",this.lastCallback)),yi&&Ee("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement),Rc.registerExporter(this)}onDisable(){var e,i,n;(e=this.button)==null||e.remove(),(i=this.link)==null||i.removeEventListener("message",this.lastCallback),yi&&Ee("USDZ Exporter disabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.removeEventListener("click",this.onClickedOpenInARElement),Rc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var n;let e=this.exportFileName??((n=this.objectToExport)==null?void 0:n.name)??this.name;if(e+="-"+Uw(),Qn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=Ab(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return yi&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const i=await this.export(this.objectToExport);return i?(yi&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(i,e),i):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const i=this._currentExportTasks.get(e);if(i)return i;const n=this.internalExport(e);return n instanceof Promise?(this._currentExportTasks.set(e,n),n.then(s=>(this._currentExportTasks.delete(e),s)).catch(s=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",s),null))):n}async internalExport(e){oe.start("export-usdz",{onProgress:M=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:M}}))}}),oe.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),oe.report("export-usdz",{message:"Load progressive textures",autoStep:5}),oe.start("export-usdz-textures","export-usdz");const i=C.getComponentsInChildren(e,fi);for(const M of i)M&&M.enabled&&M.updateSprite(!0);const n=C.getComponentsInChildren(e,Ti),s=new Array;let a=0;for(const M of n){for(const R of M.sharedMeshes)if(R){const F=le.NEEDLE_progressive.assignMeshLOD(R,0);F instanceof Promise&&s.push(new Promise((D,A)=>{F.then(()=>{a++,oe.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:a,totalSteps:s.length}),D()}).catch(T=>A(T))}))}for(const R of M.sharedMaterials)if(R){const F=le.NEEDLE_progressive.assignTextureLOD(R,0);F instanceof Promise&&s.push(new Promise((D,A)=>{F.then(()=>{a++,oe.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:a,totalSteps:s.length}),D()}).catch(T=>A(T))}))}}yi&&Ee("Progressive Loading: "+s.length),await Promise.all(s),yi&&Ee("Progressive Loading: done"),oe.end("export-usdz-textures");const l=Qt.Global.Mask;Qt.Global.Set(Bn.AR);const c=new Ww,h=new af(this.quickLookCompatible);let u;const f=[];this.interactive&&(f.push(new fy),f.push(new Wr),globalThis.NEEDLE_USE_RAPIER&&C.getComponentsInChildren(e,ot).length>0&&(this.physics?(u=new py,f.push(u)):j()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),f.push(new pf),f.push(new wy));const p=[h,...f,...this.extensions],g={self:this,exporter:c,extensions:p,object:e};oe.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:g})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,oe.report("export-usdz","auto export animations and audio sources");const y=new Array;this.autoExportAnimations&&y.push(...ak(e,h)),p.find(M=>M.extensionName==="Audio")&&this.autoExportAudioSources&&y.push(...lk(e)),c.debug=yi,c.pruneUnusedNodes=!dk;const _=Qa.instance.objs.map(M=>M.batchedMesh);c.keepObject=M=>{let R=!0;const F=C.getComponent(M,Ti);return F&&!F.enabled&&(R=!1),R&&_.includes(M)&&(R=!1),R&&C.getComponentInParent(M,_h)&&(R=!1),R&&C.getComponentInParent(M,ss)&&(R=!1),yi&&!R&&console.log("USDZExporter: Discarding object",M),R},c.beforeWritingDocument=()=>{if(j()&&h&&u){const M=h.animatedRoots;for(const R of M){const F=C.getComponentsInChildren(R,ot).filter(A=>A.enabled),D=C.getComponents(R,ui).filter(A=>A.enabled&&!A.isTrigger);(F.length>0||D.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",R)}}};const v=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(M=>{M.visible||v.push(M)});const w=p.find(M=>M.extensionName==="Behaviour");this.interactive&&w&&v.length>0&&w.addBehavior(ck(v));let x=!0;this.quickLookCompatible&&!this.interactive&&(x=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),oe.report("export-usdz","Invoking exporter.parse");const O=await c.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:p,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:x}),E=new Blob([O],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,oe.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:g}));for(const M of y)C.destroy(M);return Qt.Global.Set(l),oe.end("export-usdz"),E}openInQuickLook(e,i){const n=e instanceof Blob?URL.createObjectURL(e):e,s=this.buildQuicklookOverlay();yi&&console.log("QuickLook Overlay",s);const a=s.callToAction?encodeURIComponent(s.callToAction):"",l=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",c=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=n+`#callToAction=${a}&checkoutTitle=${l}&checkoutSubtitle=${c}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=i+".usdz",this.link.click()}download(e,i){Ps.save(e,i)}static save(e,i){const n=document.createElement("a");n.style.display="none",document.body.appendChild(n),typeof e=="string"?n.href=e:n.href=URL.createObjectURL(e),n.download=i,n.click(),n.remove()}quicklookCallback(e){if((e==null?void 0:e.data)=="_apple_ar_quicklook_button_tapped"){yi&&me("Quicklook closed via call to action button");var i=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(i),!i.defaultPrevented){const n=new URLSearchParams(this.link.href);if(n){const s=n.get("callToActionURL");yi&&Ee("Quicklook url: "+s),s&&(Qn()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var n,s,a,l,c,h;const e={};return this.customBranding&&Object.assign(e,this.customBranding),Qn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(((n=e.callToAction)==null?void 0:n.length)||((s=e.checkoutTitle)==null?void 0:s.length)||((a=e.checkoutSubtitle)==null?void 0:a.length))&&((l=e.callToAction)!=null&&l.length||(e.callToAction="\0"),(c=e.checkoutTitle)!=null&&c.length||(e.checkoutTitle="\0"),(h=e.checkoutSubtitle)!=null&&h.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=C.findObjectOfType(ff);let i=C.getComponentInParent(this.objectToExport,is);i||(i=C.getComponentInChildren(this.objectToExport,is));let n=1,s=!1;const a=this.objectToExport;return e?n=e.arScale:i&&(n=i.arScale,s=i.invertForward),{scale:1/n,_invertForward:s,target:a,sessionRoot:(i==null?void 0:i.gameObject)??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:i,target:n,sessionRoot:s}=this.getARScaleAndTarget(),a=s==null?void 0:s.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=n,this._rootPositionBeforeExport.copy(n.position),this._rootRotationBeforeExport.copy(n.quaternion),this._rootScaleBeforeExport.copy(n.scale),n.scale.multiplyScalar(e),i&&n.quaternion.multiply(Ps.invertForwardQuaternion),n.updateMatrix(),n.updateMatrixWorld(!0),s&&a&&n.matrix.premultiply(a)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const i=Po.getOrCreate().createQuicklookButton();return i.parentNode||this.context.menu.appendChild(i),i}},r(Ps,"invertForwardMatrix",new d.Matrix4().makeRotationY(Math.PI)),r(Ps,"invertForwardQuaternion",new d.Quaternion().setFromEuler(new d.Euler(0,Math.PI,0))),Ps);Pt([m(d.Object3D)],pi.prototype,"objectToExport");Pt([m()],pi.prototype,"autoExportAnimations");Pt([m()],pi.prototype,"autoExportAudioSources");Pt([m()],pi.prototype,"exportFileName");Pt([m(URL)],pi.prototype,"customUsdzFile");Pt([m(qr)],pi.prototype,"customBranding");Pt([m()],pi.prototype,"anchoringType");Pt([m()],pi.prototype,"maxTextureSize");Pt([m()],pi.prototype,"planeAnchoringAlignment");Pt([m()],pi.prototype,"interactive");Pt([m()],pi.prototype,"physics");Pt([m()],pi.prototype,"allowCreateQuicklookButton");Pt([m()],pi.prototype,"quickLookCompatible");let Kn=pi;var uk=Object.defineProperty,fk=Object.getOwnPropertyDescriptor,xy=(o,t,e,i)=>{for(var n=fk(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&uk(t,e,n),n};class ml extends I{constructor(){super(...arguments);r(this,"_fog")}get fog(){return this._fog||(this._fog=new d.Fog(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}xy([m()],ml.prototype,"near");xy([m()],ml.prototype,"far");xy([m(d.Color)],ml.prototype,"color");var pk=Object.defineProperty,Sy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&pk(t,e,n),n};class Xr extends I{constructor(){super(...arguments);r(this,"objectBounds",!1);r(this,"color");r(this,"isGizmo",!0);r(this,"_gizmoObject",null);r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!rh||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new d.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=dg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),we.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var e;for(;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}Sy([m()],Xr.prototype,"objectBounds");Sy([m(d.Color)],Xr.prototype,"color");Sy([m()],Xr.prototype,"isGizmo");var mk=Object.defineProperty,Cy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&mk(t,e,n),n};class gl extends I{constructor(){super(...arguments);r(this,"isGizmo",!1);r(this,"color0");r(this,"color1");r(this,"gridHelper");r(this,"size");r(this,"divisions");r(this,"offset")}onEnable(){if(this.isGizmo&&!rh)return;const e=this.size,i=this.divisions;this.gridHelper||(this.gridHelper=new d.GridHelper(e,i,this.color0??new d.Color(.4,.4,.4),this.color1??new d.Color(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}Cy([m()],gl.prototype,"isGizmo");Cy([m(d.Color)],gl.prototype,"color0");Cy([m(d.Color)],gl.prototype,"color1");var gk=Object.defineProperty,Py=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&gk(t,e,n),n};class My extends I{constructor(){super(...arguments);r(this,"connectedBody");r(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(ot)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}Py([m(ot)],My.prototype,"connectedBody");class Oy extends My{createJoint(t,e){var i;(i=this.context.physics.engine)==null||i.addFixedJoint(t,e)}}class Rh extends My{constructor(){super(...arguments);r(this,"anchor");r(this,"axis")}createJoint(e,i){var n;this.axis&&this.anchor&&((n=this.context.physics.engine)==null||n.addHingeJoint(e,i,this.anchor,this.axis))}}Py([m(d.Vector3)],Rh.prototype,"anchor");Py([m(d.Vector3)],Rh.prototype,"axis");var yk=Object.defineProperty,_k=Object.getOwnPropertyDescriptor,ls=(o,t,e,i)=>{for(var n=i>1?void 0:i?_k(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&yk(t,e,n),n};function Tp(o){return o*Math.PI/180}const Lb=300,Zs=S("debuglights");class mi extends I{constructor(){super(...arguments);r(this,"type",0);r(this,"range",1);r(this,"spotAngle",1);r(this,"innerSpotAngle",1);r(this,"_color",new d.Color(16777215));r(this,"_shadowNearPlane",.1);r(this,"_shadowBias",0);r(this,"_shadowNormalBias",0);r(this,"_overrideShadowBiasSettings",!1);r(this,"_shadows",1);r(this,"lightmapBakeType",4);r(this,"_intensity",-1);r(this,"_shadowDistance");r(this,"shadowWidth");r(this,"shadowHeight");r(this,"_shadowResolution");r(this,"light");r(this,"_webXRStartedListener");r(this,"_webXREndedListener");r(this,"_webARRoot")}set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(e){var i,n;if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.camera)!==void 0)){const s=this.light.shadow.camera;s.near=e}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(e){var i,n;e!==this._shadowBias&&(this._shadowBias=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.bias)!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(e){var i,n;e!==this._shadowNormalBias&&(this._shadowNormalBias=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.normalBias)!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(e){var i;if(this._intensity=e,this.light){let n=1;if(this.context.isInXR&&this._webARRoot){const s=(i=this._webARRoot)==null?void 0:i.arScale;typeof s=="number"&&s>0&&(n/=s)}this.light.intensity=e*n}Zs&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}get shadowDistance(){const e=this.light;return e!=null&&e.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const i=this.light;if(i!=null&&i.shadow){const n=i.shadow.camera;n.far=e,n.updateProjectionMatrix()}}get shadowResolution(){const e=this.light;return e!=null&&e.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const i=this.light;i!=null&&i.shadow&&(i.shadow.mapSize.set(e,e),i.shadow.needsUpdate=!0)}get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new d.Color(this.color??16777215),Zs&&console.log(this.name,this)}onEnable(){Zs&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Zs&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),we.LateUpdate))}onDisable(){Zs&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(e){this._webARRoot=C.getComponentInParent(this.gameObject,is)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const i=new d.DirectionalLight(this.color,this.intensity*Math.PI);if(i.position.set(0,0,-Lb*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(i.target),Pr(i.target,0,0,0),this.light=i,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Zs){const l=new d.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const n=new d.SpotLight(this.color,this.intensity*Math.PI,this.range,Tp(this.spotAngle/2),1-Tp(this.innerSpotAngle/2)/Tp(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;const s=n.target;n.add(s),s.position.set(0,0,this.range),s.rotation.set(0,0,0);break;case 2:const a=new d.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=a;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Zs&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const i=this.light.shadow.camera;if(i.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?i.far=this._shadowDistance:i.far=Lb*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)i.left=-this.shadowWidth/2,i.right=this.shadowWidth/2;else{const n=this.gameObject.scale.x;i.left*=n,i.right*=n}if(this.shadowHeight!==void 0)i.top=this.shadowHeight/2,i.bottom=-this.shadowHeight/2;else{const n=this.gameObject.scale.y;i.top*=n,i.bottom*=n}this.light.shadow.needsUpdate=!0,Zs&&this.context.scene.add(new d.CameraHelper(i))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}r(mi,"allowChangingRendererShadowMapType",!0);ls([m()],mi.prototype,"type",2);ls([m(d.Color)],mi.prototype,"color",1);ls([m()],mi.prototype,"shadowNearPlane",1);ls([m()],mi.prototype,"shadowBias",1);ls([m()],mi.prototype,"shadowNormalBias",1);ls([m()],mi.prototype,"shadows",1);ls([m()],mi.prototype,"lightmapBakeType",2);ls([m()],mi.prototype,"intensity",1);ls([m()],mi.prototype,"shadowDistance",1);ls([m()],mi.prototype,"shadowResolution",1);new d.Vector3(0,0,0);var bk=Object.defineProperty,Eh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bk(t,e,n),n};const Ap=S("debuglods"),vk=S("nolods");class yl{constructor(){r(this,"screenRelativeTransitionHeight");r(this,"distance");r(this,"renderers")}}Eh([m()],yl.prototype,"screenRelativeTransitionHeight");Eh([m()],yl.prototype,"distance");Eh([m(Ti)],yl.prototype,"renderers");class wk{constructor(t){r(this,"model");this.model=t}get renderers(){return this.model.renderers}}class Th extends I{constructor(){super(...arguments);r(this,"fadeMode",0);r(this,"localReferencePoint");r(this,"lodCount",0);r(this,"size",0);r(this,"animateCrossFading",!1);r(this,"lodModels");r(this,"_lods",[]);r(this,"_settings",[]);r(this,"_lodsHandler");r(this,"_distanceFactor",1)}start(){if(Ap&&console.log("LODGROUP",this.name,this.lodModels,this),!vk&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const n of this.lodModels){const s=new wk(n);this._lods.push(s);for(const a of s.renderers)e.includes(a)||e.push(a)}this._lodsHandler=new Array;for(let n=0;n<e.length;n++){const s=new d.LOD;this._lodsHandler.push(s),this.gameObject.add(s)}const i=new d.Object3D;i.name="Cull "+this.name;for(let n=0;n<e.length;n++){const s=e[n],a=this._lodsHandler[n],l=s.gameObject;Ap&&console.log(n,l.name);for(const c of this._lods){const h=c.model.distance;let u=null;if(c.renderers.includes(s)?u=l:u=i,u.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${u.name}`);continue}Ap&&console.log("LEVEL",u.name,h),a.autoUpdate=!1,this.onAddLodLevel(a,u,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const i of this._lodsHandler){i.update(e);const n=i.getCurrentLevel(),s=i.levels[n];i.layers.mask=s.object.layers.mask}}onAddLodLevel(e,i,n){if(i===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",i.name,i);return}e.addLevel(i,n*this._distanceFactor,.01);const s={lod:e,levelIndex:e.levels.length-1,distance:n};this._settings.push(s)}distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const i of this._settings){const n=i.lod.levels[i.levelIndex];n.distance=i.distance*e}}}}Eh([m(d.Vector3)],Th.prototype,"localReferencePoint");Eh([m(yl)],Th.prototype,"lodModels");var xk=Object.defineProperty,Sk=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&xk(t,e,n),n};const wd=S("debugnestedgltf");class mf extends I{constructor(){super(...arguments);r(this,"filePath");r(this,"loadAssetInParent",!0);r(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(e){var i;(i=this.filePath)==null||i.beginListenDownload(e)}preload(){var e;(e=this.filePath)==null||e.preload()}async start(){var i,n,s,a,l;if(this._isLoadingOrDoneLoading)return;wd&&console.log(this,this.guid);const e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;const c=new xn;c.idProvider=new vt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;wd&&console.log("Load nested:",((i=this.filePath)==null?void 0:i.url)??this.filePath,this.gameObject.position);const u=await((s=(n=this.filePath)==null?void 0:n.instantiate)==null?void 0:s.call(this.filePath,c));wd&&console.log("Nested loaded:",((a=this.filePath)==null?void 0:a.url)??this.filePath,u),u&&this.loadAssetInParent!==!1&&(u.matrixAutoUpdate=!1,u.matrix.identity(),u.applyMatrix4(h),u.matrixAutoUpdate=!0,u.layers.disableAll(),u.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:u,assetReference:this.filePath}}))),wd&&console.log("Nested loading done:",((l=this.filePath)==null?void 0:l.url)??this.filePath,u)}}onDestroy(){var e;(e=this.filePath)==null||e.unload()}hash(e){let i=0;for(let n=0;n<e.length;n++)i=e.charCodeAt(n)+((i<<5)-i);return i}}Sk([m(te)],mf.prototype,"filePath");var Ck=Object.defineProperty,ky=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Ck(t,e,n),n};const Pk=S("debugnet"),gf=class Am extends I{constructor(){super(...arguments);r(this,"url",null);r(this,"urlParameterName",null);r(this,"localhost",null)}awake(){Pk&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Am.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const a=S(this.urlParameterName);a&&typeof a=="string"&&(e=a)}if(!e)return null;const n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n!=null&&n.groups?(n==null?void 0:n.groups.socket_prefix)?e:"wss://"+(n==null?void 0:n.groups.url):null}static GetUrl(e,i){let n=e;const s=Am.IsLocalNetwork()&&i;if(s&&(n=i),e!=null&&e.startsWith("/")){const a=s?n:window.location.origin;a!=null&&a.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),n=a+e}return n}static IsLocalNetwork(e=window.location.hostname){return Kt(e)}};ky([m()],gf.prototype,"url");ky([m()],gf.prototype,"urlParameterName");ky([m()],gf.prototype,"localhost");let Ry=gf;var Mk=Object.defineProperty,yf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Mk(t,e,n),n};class Qr extends I{constructor(){super(...arguments);r(this,"referenceSpace");r(this,"from");r(this,"affectPosition",!1);r(this,"affectRotation",!1);r(this,"alignLookDirection",!1);r(this,"levelLookDirection",!1);r(this,"levelPosition",!1);r(this,"positionOffset",new d.Vector3(0,0,0));r(this,"rotationOffset",new d.Vector3(0,0,0));r(this,"offset",new d.Vector3(0,0,0))}update(){if(!this.from)return;var e=Q(this.from),i=_e(this.from);this.offset.copy(this.positionOffset);const n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),e.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new d.Plane(this.gameObject.up,0),h=Q(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const u=new d.Vector3(0,0,0);c.projectPoint(e,u),e.copy(u)}this.affectPosition&&st(this.gameObject,e);const s=new d.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),a=new d.Quaternion().setFromEuler(s);this.affectRotation&&Hi(this.gameObject,i.multiply(a));const l=new d.Vector3;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}yf([m(C)],Qr.prototype,"referenceSpace");yf([m(C)],Qr.prototype,"from");yf([m(d.Vector3)],Qr.prototype,"positionOffset");yf([m(d.Vector3)],Qr.prototype,"rotationOffset");var Ok=Object.defineProperty,Uo=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Ok(t,e,n),n};class li{constructor(t=0,e=0){r(this,"time",0);r(this,"value",0);r(this,"inTangent",1/0);r(this,"inWeight");r(this,"outTangent",1/0);r(this,"outWeight");r(this,"weightedMode");this.time=t,this.value=e}}Uo([m()],li.prototype,"time");Uo([m()],li.prototype,"value");Uo([m()],li.prototype,"inTangent");Uo([m()],li.prototype,"inWeight");Uo([m()],li.prototype,"outTangent");Uo([m()],li.prototype,"outWeight");Uo([m()],li.prototype,"weightedMode");const hx=class nc{constructor(){r(this,"keys",[])}static linearFromTo(t,e,i){const n=new nc,s=new li;s.time=0,s.value=t;const a=new li;return a.time=i,a.value=e,n.keys.push(s,a),n}static constant(t){const e=new nc,i=new li;return i.time=0,i.value=t,e.keys.push(i),e}clone(){var e;const t=new nc;return t.keys=((e=this.keys)==null?void 0:e.map(i=>{const n=new li;return n.time=i.time,n.value=i.value,n.inTangent=i.inTangent,n.inWeight=i.inWeight,n.outTangent=i.outTangent,n.outWeight=i.outWeight,n.weightedMode=i.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(t){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=t)return this.keys[0].value;for(let e=0;e<this.keys.length;e++){const i=this.keys[e];if(i.time<=t)if(e+1<this.keys.length){const s=this.keys[e+1];if(s.time<t)continue;return!isFinite(i.outTangent)||!isFinite(s.inTangent)?i.value:nc.interpolateValue(t,i,s)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(t,e,i){const n=e.time,s=e.value,a=e.outTangent,l=i.time,c=i.value,h=i.inTangent,u=l-n,f=u*u,p=f*u,g=((a+h)*u-2*(c-s))/p,y=(3*(c-s)-(h+2*a)*u)/f,b=a,_=s,v=t-n,w=v*v,x=w*v;return g*x+y*w+b*v+_}};Uo([m(li)],hx.prototype,"keys");let Ah=hx;var kk=Object.defineProperty,P=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&kk(t,e,n),n};const xd=S("debugparticles");var bs=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(bs||{});class Yr{constructor(){r(this,"alphaKeys",[]);r(this,"colorKeys",[])}get duration(){return 1}evaluate(t,e){let i,n=0,s=null,a=0;for(let l=0;l<this.alphaKeys.length;l++){const c=this.alphaKeys[l];(c.time<t||!i)&&(i=c,n=l)}for(let l=0;l<this.colorKeys.length;l++){const c=this.colorKeys[l];(c.time<t||!s)&&(s=c,a=l)}if(s)if(a+1<this.colorKeys.length){const c=this.colorKeys[a+1],h=z.remap(t,s.time,c.time,0,1);e.r=z.lerp(s.color.r,c.color.r,h),e.g=z.lerp(s.color.g,c.color.g,h),e.b=z.lerp(s.color.b,c.color.b,h)}else e.r=s.color.r,e.g=s.color.g,e.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const c=this.alphaKeys[n+1],h=z.remap(t,i.time,c.time,0,1);e.alpha=z.lerp(i.alpha,c.alpha,h)}else e.alpha=i.alpha;return e}}P([m()],Yr.prototype,"alphaKeys");P([m()],Yr.prototype,"colorKeys");var Vc=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(Vc||{}),vu=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(vu||{});const Ns=class sc{constructor(){r(this,"mode","Constant");r(this,"constant");r(this,"constantMin");r(this,"constantMax");r(this,"curve");r(this,"curveMin");r(this,"curveMax");r(this,"curveMultiplier")}static constant(t){const e=new sc;return e.setConstant(t),e}static betweenTwoConstants(t,e){const i=new sc;return i.setMinMaxConstant(t,e),i}static curve(t,e=1){const i=new sc;return i.setCurve(t,e),i}setConstant(t){this.mode=0,this.constant=t}setMinMaxConstant(t,e){this.mode=3,this.constantMin=t,this.constantMax=e}setCurve(t,e=1){this.mode=1,this.curve=t,this.curveMultiplier=e}clone(){var e,i,n;const t=new sc;return t.mode=this.mode,t.constant=this.constant,t.constantMin=this.constantMin,t.constantMax=this.constantMax,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMin=(i=this.curveMin)==null?void 0:i.clone(),t.curveMax=(n=this.curveMax)==null?void 0:n.clone(),t.curveMultiplier=this.curveMultiplier,t}evaluate(t,e){const i=e===void 0?Math.random():e;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return t=z.clamp01(t),this.curve.evaluate(t)*this.curveMultiplier;case 2:case"TwoCurves":const n=t*this.curveMin.duration,s=t*this.curveMax.duration;return z.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return z.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(t)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(t){if(!t)return 0;let e=Number.MIN_VALUE;for(let i=0;i<t.keys.length;i++){const n=t.keys[i];n.value>e&&(e=n.value)}return e}};P([m()],Ns.prototype,"mode");P([m()],Ns.prototype,"constant");P([m()],Ns.prototype,"constantMin");P([m()],Ns.prototype,"constantMax");P([m(Ah)],Ns.prototype,"curve");P([m(Ah)],Ns.prototype,"curveMin");P([m(Ah)],Ns.prototype,"curveMax");P([m()],Ns.prototype,"curveMultiplier");let q=Ns;var Le;const zo=(Le=class{constructor(){r(this,"mode",0);r(this,"color");r(this,"colorMin");r(this,"colorMax");r(this,"gradient");r(this,"gradientMin");r(this,"gradientMax")}static constant(t){const e=new Le;return e.constant(t),e}static betweenTwoColors(t,e){const i=new Le;return i.betweenTwoColors(t,e),i}constant(t){return this.mode=0,this.color=t,this}betweenTwoColors(t,e){return this.mode=2,this.colorMin=t,this.colorMax=e,this}evaluate(t,e){const i=e===void 0?Math.random():e;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(t,Le._temp),Le._temp;case 2:case"TwoColors":return Le._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(t,Le._temp),this.gradientMax.evaluate(t,Le._temp2),Le._temp.lerp(Le._temp2,i);case 4:case"RandomColor":const s=Math.random();return this.gradientMin.evaluate(t,Le._temp),this.gradientMax.evaluate(t,Le._temp2),Le._temp.lerp(Le._temp2,s)}return Le._temp.set(16777215),Le._temp.alpha=1,Le._temp}},r(Le,"_temp",new ie(0,0,0,1)),r(Le,"_temp2",new ie(0,0,0,1)),Le);P([m()],zo.prototype,"mode");P([m(ie)],zo.prototype,"color");P([m(ie)],zo.prototype,"colorMin");P([m(ie)],zo.prototype,"colorMax");P([m(Yr)],zo.prototype,"gradient");P([m(Yr)],zo.prototype,"gradientMin");P([m(Yr)],zo.prototype,"gradientMax");let Kr=zo;var Lm=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(Lm||{});class It{constructor(){r(this,"cullingMode");r(this,"duration");r(this,"emitterVelocityMode");r(this,"flipRotation");r(this,"gravityModifier");r(this,"gravityModifierMultiplier");r(this,"loop");r(this,"maxParticles");r(this,"playOnAwake");r(this,"prewarm");r(this,"ringBufferLoopRange");r(this,"ringBufferMode");r(this,"scalingMode");r(this,"simulationSpace");r(this,"simulationSpeed");r(this,"startColor");r(this,"startDelay");r(this,"startDelayMultiplier");r(this,"startLifetime");r(this,"startLifetimeMultiplier");r(this,"startRotation");r(this,"startRotationMultiplier");r(this,"startRotation3D");r(this,"startRotationX");r(this,"startRotationXMultiplier");r(this,"startRotationY");r(this,"startRotationYMultiplier");r(this,"startRotationZ");r(this,"startRotationZMultiplier");r(this,"startSize");r(this,"startSize3D");r(this,"startSizeMultiplier");r(this,"startSizeX");r(this,"startSizeXMultiplier");r(this,"startSizeY");r(this,"startSizeYMultiplier");r(this,"startSizeZ");r(this,"startSizeZMultiplier");r(this,"startSpeed");r(this,"startSpeedMultiplier");r(this,"stopAction");r(this,"useUnscaledTime")}}P([m(q)],It.prototype,"gravityModifier");P([m(Kr)],It.prototype,"startColor");P([m(q)],It.prototype,"startDelay");P([m(q)],It.prototype,"startLifetime");P([m(q)],It.prototype,"startRotation");P([m(q)],It.prototype,"startRotationX");P([m(q)],It.prototype,"startRotationY");P([m(q)],It.prototype,"startRotationZ");P([m(q)],It.prototype,"startSize");P([m(q)],It.prototype,"startSizeX");P([m(q)],It.prototype,"startSizeY");P([m(q)],It.prototype,"startSizeZ");P([m(q)],It.prototype,"startSpeed");class wu{constructor(){r(this,"cycleCount");r(this,"maxCount");r(this,"minCount");r(this,"probability");r(this,"repeatInterval");r(this,"time");r(this,"count");r(this,"_performed",0)}reset(){this._performed=0}run(t){if(t<=this.time)return 0;let e=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(t>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:e=this.count.constant;break;case 3:e=z.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:e=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();e=z.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return e}}class $s{constructor(){r(this,"enabled");r(this,"bursts");r(this,"rateOverTime");r(this,"rateOverTimeMultiplier");r(this,"rateOverDistance");r(this,"rateOverDistanceMultiplier");r(this,"system")}get burstCount(){var t;return((t=this.bursts)==null?void 0:t.length)??0}reset(){var t;(t=this.bursts)==null||t.forEach(e=>e.reset())}getBurst(){let t=0;if(this.burstCount>0)for(let e=0;e<this.burstCount;e++){const i=this.bursts[e];this.system.main.loop&&i.time>=this.system.time&&i.reset(),t+=Math.round(i.run(this.system.time))}return t}}P([m()],$s.prototype,"enabled");P([m()],$s.prototype,"bursts");P([m(q)],$s.prototype,"rateOverTime");P([m()],$s.prototype,"rateOverTimeMultiplier");P([m(q)],$s.prototype,"rateOverDistance");P([m()],$s.prototype,"rateOverDistanceMultiplier");class _f{constructor(){r(this,"enabled");r(this,"color")}}P([m(Kr)],_f.prototype,"color");class Zr{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_time",0);r(this,"_temp",new d.Vector3)}evaluate(t,e,i){if(e||(e=this._temp),!this.enabled)return e.x=e.y=e.z=1,e;if(this.separateAxes)e.x=this.x.evaluate(t,i)*this.xMultiplier,e.y=this.y.evaluate(t,i)*this.yMultiplier,e.z=this.z.evaluate(t,i)*this.zMultiplier;else{const n=this.size.evaluate(t,i)*this.sizeMultiplier;e.x=n}return e}}P([m(q)],Zr.prototype,"size");P([m(q)],Zr.prototype,"x");P([m(q)],Zr.prototype,"y");P([m(q)],Zr.prototype,"z");var gn;const Ze=(gn=class{constructor(){r(this,"shapeType",5);r(this,"enabled",!0);r(this,"alignToDirection",!1);r(this,"angle",0);r(this,"arc",360);r(this,"arcSpread");r(this,"arcSpeedMultiplier");r(this,"arcMode");r(this,"boxThickness");r(this,"position");r(this,"rotation");r(this,"_rotation",new d.Euler);r(this,"scale");r(this,"radius");r(this,"radiusThickness");r(this,"sphericalDirectionAmount");r(this,"randomDirectionAmount");r(this,"randomPositionAmount");r(this,"meshShapeType");r(this,"meshRenderer");r(this,"_meshObj");r(this,"_meshGeometry");r(this,"system");r(this,"_space");r(this,"_worldSpaceMatrix",new d.Matrix4);r(this,"_worldSpaceMatrixInverse",new d.Matrix4);r(this,"_vector",new d.Vector3(0,0,0));r(this,"_temp",new d.Vector3(0,0,0));r(this,"_triangle",new d.Triangle);r(this,"_dir",new d.Vector3);r(this,"_loopTime",0);r(this,"_loopDirection",1);xd&&console.log(this)}get type(){return vu[this.shapeType]}initialize(t){this.onInitialize(t),t.position.x=this._vector.x,t.position.y=this._vector.y,t.position.z=this._vector.z}toJSON(){return this}clone(){return new gn}setMesh(t){this.meshRenderer=t,t?(this._meshObj=t.sharedMeshes[Math.floor(Math.random()*t.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(t,e){}onUpdate(t,e,i,n){this.system=t,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(t){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=z.toRadians(this.rotation.x),this._rotation.y=z.toRadians(this.rotation.y),this._rotation.z=z.toRadians(this.rotation.z),this._rotation.order="ZYX",t.applyEuler(this._rotation)),e}onInitialize(t){this._vector.set(0,0,0),t.mesh=void 0,t.mesh_geometry=void 0;const e=this._temp.copy(this.position),i=this._space===1;i&&e.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:xd&&$.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const s=this.meshRenderer;(s==null?void 0:s.destroyed)==!1&&this.setMesh(s);const a=t.mesh=this._meshObj,l=t.mesh_geometry=this._meshGeometry;if(a&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(a.matrixWorld),t.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),u=Math.random();h+u>1&&(h=1-h,u=1-u);const f=Math.floor(Math.random()*(c.count/3));let p=f*3,g=f*3+1,y=f*3+2;p=c.getX(p),g=c.getX(g),y=c.getX(y);const b=l.getAttribute("position");this._triangle.a.fromBufferAttribute(b,p),this._triangle.b.fromBufferAttribute(b,g),this._triangle.c.fromBufferAttribute(b,y),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,u).addScaledVector(this._triangle.c,1-(h+u)),this._vector.applyMatrix4(a.matrixWorld),t.mesh_normal=f}}break}break;default:this._vector.set(0,0,0),j()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",vu[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),xd&&$.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(t,e){var i;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const n=e.x,s=e.y,a=e.z;this._dir.set(n,s,a),(i=this.system)!=null&&i.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=t.mesh,c=t.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),u=t.mesh_normal;this._dir.fromBufferAttribute(h,u)}break;case 1:break;case 2:{const h=c.index;if(h){const u=t.mesh_normal,f=h.getX(u*3),p=h.getX(u*3+1),g=h.getX(u*3+2),y=c.getAttribute("position"),b=V(),_=V(),v=V();b.fromBufferAttribute(y,f),_.fromBufferAttribute(y,p),v.fromBufferAttribute(y,g),b.sub(_),v.sub(_),b.cross(v),this._dir.copy(b).multiplyScalar(-1);const w=_e(l);this._dir.applyQuaternion(w)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),xd&&($.DrawSphere(e,.01,8925952,.5,!0),$.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(t,e){if(e<=0)return;const i=gn._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=e*this.scale.x,i.y*=e*this.scale.y,i.z*=e*this.scale.z,t.add(i)}randomizeDirection(t,e){if(e===0)return;const i=gn._randomQuat,n=gn._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,e*Math.random()*Math.PI),t.applyQuaternion(i)}spherizeDirection(t,e){if(e===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),s=Math.sin(n)*Math.cos(i),a=Math.sin(n)*Math.sin(i),l=Math.cos(n),c=new d.Vector3(s,a,l);t.lerp(c,e)}randomSpherePoint(t,e,i,n,s){const a=Math.random(),l=Math.random(),c=2*Math.PI*a*(n/360),h=Math.acos(2*l-1),u=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*e,f=t.x+this.scale.x*(-u*Math.sin(h)*Math.cos(c)),p=t.y+this.scale.y*(u*Math.sin(h)*Math.sin(c)),g=t.z+this.scale.z*(u*Math.cos(h));s.x=f,s.y=p,s.z=g}randomCirclePoint(t,e,i,n,s){const a=Math.random(),l=2*Math.PI*a*(n/360),c=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*e,h=t.x+this.scale.x*c*Math.cos(l),u=t.y+this.scale.y*c*Math.sin(l),f=t.z;s.x=h,s.y=u,s.z=f}randomConePoint(t,e,i,n,s,a,l){let c=0,h=0;switch(a){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let u=2*Math.PI*c*(s/360);switch(a){case 2:case 1:u+=Math.PI+.5,u+=this._loopTime*Math.PI*2,u%=z.toRadians(s);break}const f=Math.acos(2*h-1),p=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=t.x+-p*Math.sin(f)*Math.cos(u),y=t.y+p*Math.sin(f)*Math.sin(u),b=t.z;l.x=g*this.scale.x,l.y=y*this.scale.y,l.z=b*this.scale.z}},r(gn,"_randomQuat",new d.Quaternion),r(gn,"_tempVec",new d.Vector3),gn);P([m()],Ze.prototype,"shapeType");P([m()],Ze.prototype,"enabled");P([m()],Ze.prototype,"alignToDirection");P([m()],Ze.prototype,"angle");P([m()],Ze.prototype,"arc");P([m()],Ze.prototype,"arcSpread");P([m()],Ze.prototype,"arcSpeedMultiplier");P([m()],Ze.prototype,"arcMode");P([m(d.Vector3)],Ze.prototype,"boxThickness");P([m(d.Vector3)],Ze.prototype,"position");P([m(d.Vector3)],Ze.prototype,"rotation");P([m(d.Vector3)],Ze.prototype,"scale");P([m()],Ze.prototype,"radius");P([m()],Ze.prototype,"radiusThickness");P([m()],Ze.prototype,"sphericalDirectionAmount");P([m()],Ze.prototype,"randomDirectionAmount");P([m()],Ze.prototype,"randomPositionAmount");P([m()],Ze.prototype,"meshShapeType");P([m(vh)],Ze.prototype,"meshRenderer");let Ey=Ze;class be{constructor(){r(this,"damping");r(this,"enabled");r(this,"frequency");r(this,"octaveCount");r(this,"octaveMultiplier");r(this,"octaveScale");r(this,"positionAmount");r(this,"quality");r(this,"remap");r(this,"remapEnabled");r(this,"remapMultiplier");r(this,"remapX");r(this,"remapXMultiplier");r(this,"remapY");r(this,"remapYMultiplier");r(this,"remapZ");r(this,"remapZMultiplier");r(this,"scrollSpeedMultiplier");r(this,"separateAxes");r(this,"strengthMultiplier");r(this,"strengthX");r(this,"strengthXMultiplier");r(this,"strengthY");r(this,"strengthYMultiplier");r(this,"strengthZ");r(this,"strengthZMultiplier");r(this,"_noise");r(this,"_time",0);r(this,"_temp",new d.Vector3)}update(t){this._time+=t.time.deltaTime*this.scrollSpeedMultiplier}apply(t,e,i,n,s,a){if(!this.enabled)return;this._noise||(this._noise=ae.createNoise4D(()=>0));const l=this._temp.set(e.x,e.y,e.z).multiplyScalar(this.frequency),c=this._noise(l.x,l.y,l.z,this._time),h=this._noise(l.x,l.y,l.z,this._time+1e3*this.frequency),u=this._noise(l.x,l.y,l.z,this._time+2e3*this.frequency);this._temp.set(c,h,u).normalize();const f=s/a;let p=this.positionAmount.evaluate(f);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(f)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}P([m()],be.prototype,"damping");P([m()],be.prototype,"enabled");P([m()],be.prototype,"frequency");P([m()],be.prototype,"octaveCount");P([m()],be.prototype,"octaveMultiplier");P([m()],be.prototype,"octaveScale");P([m(q)],be.prototype,"positionAmount");P([m()],be.prototype,"quality");P([m(q)],be.prototype,"remap");P([m()],be.prototype,"remapEnabled");P([m()],be.prototype,"remapMultiplier");P([m(q)],be.prototype,"remapX");P([m()],be.prototype,"remapXMultiplier");P([m(q)],be.prototype,"remapY");P([m()],be.prototype,"remapYMultiplier");P([m(q)],be.prototype,"remapZ");P([m()],be.prototype,"remapZMultiplier");P([m()],be.prototype,"scrollSpeedMultiplier");P([m()],be.prototype,"separateAxes");P([m()],be.prototype,"strengthMultiplier");P([m(q)],be.prototype,"strengthX");P([m()],be.prototype,"strengthXMultiplier");P([m(q)],be.prototype,"strengthY");P([m()],be.prototype,"strengthYMultiplier");P([m(q)],be.prototype,"strengthZ");P([m()],be.prototype,"strengthZMultiplier");class je{constructor(){r(this,"enabled");r(this,"attachRibbonToTransform",!1);r(this,"colorOverLifetime");r(this,"colorOverTrail");r(this,"dieWithParticles",!0);r(this,"inheritParticleColor",!0);r(this,"lifetime");r(this,"lifetimeMultiplier");r(this,"minVertexDistance",.2);r(this,"mode",0);r(this,"ratio",1);r(this,"ribbonCount",1);r(this,"shadowBias",0);r(this,"sizeAffectsLifetime",!1);r(this,"sizeAffectsWidth",!1);r(this,"splitSubEmitterRibbons",!1);r(this,"textureMode",0);r(this,"widthOverTrail");r(this,"widthOverTrailMultiplier");r(this,"worldSpace",!1)}getWidth(t,e,i,n){const s=this.widthOverTrail.evaluate(i,n);return t*=s,t}getColor(t,e,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(e);t.x*=n.r*s.r,t.y*=n.g*s.g,t.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(t.w*=n.alpha*s.alpha)}}P([m()],je.prototype,"enabled");P([m()],je.prototype,"attachRibbonToTransform");P([m(Kr)],je.prototype,"colorOverLifetime");P([m(Kr)],je.prototype,"colorOverTrail");P([m()],je.prototype,"dieWithParticles");P([m()],je.prototype,"inheritParticleColor");P([m(q)],je.prototype,"lifetime");P([m()],je.prototype,"lifetimeMultiplier");P([m()],je.prototype,"minVertexDistance");P([m()],je.prototype,"mode");P([m()],je.prototype,"ratio");P([m()],je.prototype,"ribbonCount");P([m()],je.prototype,"shadowBias");P([m()],je.prototype,"sizeAffectsLifetime");P([m()],je.prototype,"sizeAffectsWidth");P([m()],je.prototype,"splitSubEmitterRibbons");P([m()],je.prototype,"textureMode");P([m(q)],je.prototype,"widthOverTrail");P([m()],je.prototype,"widthOverTrailMultiplier");P([m()],je.prototype,"worldSpace");class ze{constructor(){r(this,"enabled");r(this,"space",0);r(this,"orbitalX");r(this,"orbitalY");r(this,"orbitalZ");r(this,"orbitalXMultiplier");r(this,"orbitalYMultiplier");r(this,"orbitalZMultiplier");r(this,"orbitalOffsetX");r(this,"orbitalOffsetY");r(this,"orbitalOffsetZ");r(this,"speedModifier");r(this,"speedModifierMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_system");r(this,"_temp",new d.Vector3);r(this,"_temp2",new d.Vector3);r(this,"_temp3",new d.Vector3);r(this,"_hasOrbital",!1);r(this,"_index",0);r(this,"_orbitalMatrix",new d.Matrix4)}update(t){this._system=t}init(t){this._index==0&&(t.debug=!0),this._index+=1,t.orbitx=this.orbitalX.evaluate(Math.random()),t.orbity=this.orbitalY.evaluate(Math.random()),t.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=t.orbitx!=0||t.orbity!=0||t.orbitz!=0}apply(t,e,i,n,s,a,l){var g;if(!this.enabled)return;const c=a/l,h=this.speedModifier.evaluate(c)*this.speedModifierMultiplier,u=this.x.evaluate(c),f=this.y.evaluate(c),p=this.z.evaluate(c);if(this._temp.set(-u,f,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((g=this._system)==null?void 0:g.worldPos)){const b=this._temp2.set(i.x,i.y,i.z),_=this.orbitalXMultiplier,v=this.orbitalYMultiplier,w=this.orbitalZMultiplier,x=h*Math.PI*2*10,O=Math.cos(x*_),E=Math.sin(x*_),M=Math.cos(x*v),R=Math.sin(x*v),F=Math.cos(x*w),D=Math.sin(x*w),A=b.x*(M*F)+b.y*(M*D)+b.z*-R,T=b.x*(E*R*F-O*D)+b.y*(E*R*D+O*F)+b.z*(E*M),G=b.x*(O*R*F+E*D)+b.y*(O*R*D-E*F)+b.z*(O*M),B=this._temp3.set(b.x-A,b.y-T,b.z-G);B.normalize(),B.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=B.x,n.y+=B.y,n.z+=B.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}P([m()],ze.prototype,"enabled");P([m()],ze.prototype,"space");P([m(q)],ze.prototype,"orbitalX");P([m(q)],ze.prototype,"orbitalY");P([m(q)],ze.prototype,"orbitalZ");P([m()],ze.prototype,"orbitalXMultiplier");P([m()],ze.prototype,"orbitalYMultiplier");P([m()],ze.prototype,"orbitalZMultiplier");P([m()],ze.prototype,"orbitalOffsetX");P([m()],ze.prototype,"orbitalOffsetY");P([m()],ze.prototype,"orbitalOffsetZ");P([m(q)],ze.prototype,"speedModifier");P([m()],ze.prototype,"speedModifierMultiplier");P([m(q)],ze.prototype,"x");P([m()],ze.prototype,"xMultiplier");P([m(q)],ze.prototype,"y");P([m()],ze.prototype,"yMultiplier");P([m(q)],ze.prototype,"z");P([m()],ze.prototype,"zMultiplier");class jt{constructor(){r(this,"animation");r(this,"enabled");r(this,"cycleCount");r(this,"frameOverTime");r(this,"frameOverTimeMultiplier");r(this,"numTilesX");r(this,"numTilesY");r(this,"startFrame");r(this,"startFrameMultiplier");r(this,"rowMode");r(this,"rowIndex");r(this,"spriteCount");r(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(t){if(!this.sampleOnceAtStart())return this.getIndex(t)}getIndex(t){const e=this.numTilesX*this.numTilesY;t=t*this.cycleCount;let i=this.frameOverTime.evaluate(t%1);return i*=this.frameOverTimeMultiplier,i*=e,i=i%e,i=Math.floor(i),i}}P([m()],jt.prototype,"animation");P([m()],jt.prototype,"enabled");P([m()],jt.prototype,"cycleCount");P([m(q)],jt.prototype,"frameOverTime");P([m()],jt.prototype,"frameOverTimeMultiplier");P([m()],jt.prototype,"numTilesX");P([m()],jt.prototype,"numTilesY");P([m(q)],jt.prototype,"startFrame");P([m()],jt.prototype,"startFrameMultiplier");P([m()],jt.prototype,"rowMode");P([m()],jt.prototype,"rowIndex");P([m()],jt.prototype,"spriteCount");P([m()],jt.prototype,"timeMode");class Cn{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e){return this.enabled?this.separateAxes?0:this.z.evaluate(t,e)*-1:0}}P([m()],Cn.prototype,"enabled");P([m()],Cn.prototype,"separateAxes");P([m(q)],Cn.prototype,"x");P([m()],Cn.prototype,"xMultiplier");P([m(q)],Cn.prototype,"y");P([m()],Cn.prototype,"yMultiplier");P([m(q)],Cn.prototype,"z");P([m()],Cn.prototype,"zMultiplier");class Ji{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e){if(!this.enabled)return 0;if(!this.separateAxes){const i=z.lerp(this.range.x,this.range.y,e);return this.z.evaluate(i)*-1}return 0}}P([m()],Ji.prototype,"enabled");P([m()],Ji.prototype,"range");P([m()],Ji.prototype,"separateAxes");P([m(q)],Ji.prototype,"x");P([m()],Ji.prototype,"xMultiplier");P([m(q)],Ji.prototype,"y");P([m()],Ji.prototype,"yMultiplier");P([m(q)],Ji.prototype,"z");P([m()],Ji.prototype,"zMultiplier");class lt{constructor(){r(this,"enabled");r(this,"dampen");r(this,"drag");r(this,"dragMultiplier");r(this,"limit");r(this,"limitMultiplier");r(this,"separateAxes");r(this,"limitX");r(this,"limitXMultiplier");r(this,"limitY");r(this,"limitYMultiplier");r(this,"limitZ");r(this,"limitZMultiplier");r(this,"multiplyDragByParticleSize",!1);r(this,"multiplyDragByParticleVelocity",!1);r(this,"space");r(this,"_temp",new d.Vector3);r(this,"_temp2",new d.Vector3)}apply(t,e,i,n,s,a,l){if(this.enabled){const c=this.limit.evaluate(s)*this.limitMultiplier;if(e.length()>c){this._temp.copy(e).normalize().multiplyScalar(c);const u=this.dampen*.5;e.x=z.lerp(e.x,this._temp.x,u),e.y=z.lerp(e.y,this._temp.y,u),e.z=z.lerp(e.z,this._temp.z,u),i.x=z.lerp(i.x,this._temp.x,u),i.y=z.lerp(i.y,this._temp.y,u),i.z=z.lerp(i.z,this._temp.z,u)}}}}P([m()],lt.prototype,"enabled");P([m()],lt.prototype,"dampen");P([m(q)],lt.prototype,"drag");P([m()],lt.prototype,"dragMultiplier");P([m(q)],lt.prototype,"limit");P([m()],lt.prototype,"limitMultiplier");P([m()],lt.prototype,"separateAxes");P([m(q)],lt.prototype,"limitX");P([m()],lt.prototype,"limitXMultiplier");P([m(q)],lt.prototype,"limitY");P([m()],lt.prototype,"limitYMultiplier");P([m(q)],lt.prototype,"limitZ");P([m()],lt.prototype,"limitZMultiplier");P([m()],lt.prototype,"multiplyDragByParticleSize");P([m()],lt.prototype,"multiplyDragByParticleVelocity");P([m()],lt.prototype,"space");const Lh=class dx{constructor(){r(this,"enabled");r(this,"curve");r(this,"curveMultiplier");r(this,"mode");r(this,"system");r(this,"_temp",new d.Vector3);r(this,"_firstUpdate",!0);r(this,"_frames",0)}clone(){var e;const t=new dx;return t.enabled=this.enabled,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new d.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new d.Vector3),this.system._iv_velocity}awake(t){this.system=t,this.reset()}reset(){this._firstUpdate=!0}update(t){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(t){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),t.x+=this._temp.x,t.y+=this._temp.y,t.z+=this._temp.z}}applyCurrent(t,e,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(e,i);this._temp.copy(this._velocity).multiplyScalar(n),t.x+=this._temp.x,t.y+=this._temp.y,t.z+=this._temp.z}}};P([m()],Lh.prototype,"enabled");P([m(q)],Lh.prototype,"curve");P([m()],Lh.prototype,"curveMultiplier");P([m()],Lh.prototype,"mode");let Ty=Lh;class gi{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e,i,n){const s=t.length(),a=z.remap(s,this.range.x,this.range.y,0,1),l=this.size.evaluate(a,i);return n.x*=l,n.y*=l,n.z*=l,n}}P([m()],gi.prototype,"enabled");P([m(d.Vector2)],gi.prototype,"range");P([m()],gi.prototype,"separateAxes");P([m(q)],gi.prototype,"size");P([m()],gi.prototype,"sizeMultiplier");P([m(q)],gi.prototype,"x");P([m()],gi.prototype,"xMultiplier");P([m(q)],gi.prototype,"y");P([m()],gi.prototype,"yMultiplier");P([m(q)],gi.prototype,"z");P([m()],gi.prototype,"zMultiplier");class _l{constructor(){r(this,"enabled");r(this,"range");r(this,"color")}evaluate(t,e,i){const n=t.length(),s=z.remap(n,this.range.x,this.range.y,0,1),a=this.color.evaluate(s,e);i.x*=a.r,i.y*=a.g,i.z*=a.b,"alpha"in a&&(i.w*=a.alpha)}}P([m()],_l.prototype,"enabled");P([m(d.Vector2)],_l.prototype,"range");P([m(Kr)],_l.prototype,"color");new d.Vector3(1,1,1);new d.Vector3(0,0,1);class Ay{constructor(t,e,i,n){r(this,"type","NeedleParticleSubEmitter");r(this,"emitterType");r(this,"emitterProbability");r(this,"q_",new d.Quaternion);r(this,"v_",new d.Vector3);r(this,"v2_",new d.Vector3);r(this,"_emitterMatrix",new ae.Matrix4);r(this,"_circularBuffer");this.system=t,this.particleSystem=e,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new ki(()=>new ae.Matrix4,s)}clone(){throw new Error("Method not implemented.")}initialize(t){t.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===Dm.Birth&&this.run(t)}update(t,e){this.run(t)}frameUpdate(t){}toJSON(){}reset(){}run(t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!t.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const e=this.system.deltaTime;if(this.emitterType===Dm.Death){let n=t.life;if(t[Ca]!==void 0&&(n=t[Ca]),!(t.age+e*1.2>=n))return;const a=this.subSystem.main.maxParticles-this.subSystem.currentParticles;t.emissionState.waitEmiting=a}const i=new ae.Matrix4;i.set(1,0,0,t.position.x,0,1,0,t.position.y,0,0,1,t.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(e,t.emissionState,i)}}var Rk=Object.defineProperty,Be=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Rk(t,e,n),n};const ro=S("debugparticles"),Ek=S("noprogressive"),Tk=S("debugprogressive");var Dm=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(Dm||{});class en extends I{constructor(){super(...arguments);r(this,"renderMode");r(this,"particleMaterial");r(this,"trailMaterial");r(this,"particleMesh");r(this,"maxParticleSize");r(this,"minParticleSize");r(this,"velocityScale");r(this,"cameraVelocityScale");r(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&j()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var i;return((i=this.particleMaterial)==null?void 0:i.transparent)??!1}getMaterial(e=!1){let i=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(i){if(i.type==="MeshStandardMaterial"){ro&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in i&&i.map&&(i.map.colorSpace=d.LinearSRGBColorSpace,i.map.premultiplyAlpha=!1);const n=new d.MeshBasicMaterial;n.copy(i),e?this.trailMaterial=n:this.particleMaterial=n}i.map&&(i.map.colorSpace=d.LinearSRGBColorSpace,i.map.premultiplyAlpha=!1),e&&i.side===d.FrontSide&&(i=i.clone(),i.side=d.BackSide,e?this.trailMaterial=i:this.particleMaterial=i)}return i&&!Ek&&i._didRequestTextureLOD===void 0&&(i._didRequestTextureLOD=0,Tk&&console.log("Load material LOD",i.name),le.NEEDLE_progressive.assignTextureLOD(i,0)),i}getMesh(e){let i=null;if(!i&&(this.particleMesh instanceof d.Mesh&&(i=this.particleMesh.geometry),i===null)){i=new d.PlaneGeometry(1,1);const s=i.attributes.uv;for(let a=0;a<s.count;a++)s.setX(a,1-s.getX(a))}return new d.Mesh(i,this.getMaterial())}}Be([m()],en.prototype,"renderMode");Be([m(d.Material)],en.prototype,"particleMaterial");Be([m(d.Material)],en.prototype,"trailMaterial");Be([m()],en.prototype,"maxParticleSize");Be([m()],en.prototype,"minParticleSize");Be([m()],en.prototype,"velocityScale");Be([m()],en.prototype,"cameraVelocityScale");Be([m()],en.prototype,"lengthScale");class Sd{constructor(t,e=1){r(this,"_curve");r(this,"_factor");r(this,"type","function");this._curve=t,this._factor=e}startGen(t){}genValue(t,e){return this._curve.evaluate(e,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Ly{constructor(t){r(this,"type","value");r(this,"system");this.system=t}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(t){}}class Ak extends Ly{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class Lk extends Ly{constructor(){super(...arguments);r(this,"_lastPosition",new d.Vector3);r(this,"_lastDistance",0)}update(){const e=Q(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const s=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let l=this._lastDistance/this.system.deltaTime*s;Number.isFinite(l)||(l=0),e+=l}const i=this.system.emission.getBurst();i>0&&(e+=i/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return z.clamp(e,0,n/this.system.deltaTime)}}class Dk extends Ly{genValue(){return this.system.isPlaying,0}}class No{constructor(t){r(this,"system");r(this,"type");this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",t&&(this.system=t)}get context(){return this.system.context}initialize(t){}update(t,e){}frameUpdate(t){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class Ik extends No{constructor(){super(...arguments);r(this,"type","NeedleTextureSheet")}update(e,i){const n=this.system.textureSheetAnimation;if(n.enabled){const s=e.age/e.life,a=n.evaluate(s);a!==void 0&&(e.uvTile=a)}}}const Db=Symbol("particleRotation");class jk extends No{constructor(){super(...arguments);r(this,"type","NeedleRotation")}initialize(e){e[Db]=Math.random()}update(e,i){if(e.rotation===void 0)return;const n=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(n,e[Db])*i:this.system.renderer.renderMode===bs.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const s=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(n,s)*i}}}const Ib=Symbol("sizeLerpFactor"),Bk=new d.Vector3;class Fk extends No{constructor(){super(...arguments);r(this,"type","NeedleSize");r(this,"_minSize",0);r(this,"_maxSize",1)}initialize(e){e[Ib]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,i){const n=e.age/e.life;let s=1;this.system.sizeOverLifetime.enabled&&(s*=this.system.sizeOverLifetime.evaluate(n,void 0,e[Ib]).x);let a=1;this.system.renderer.renderMode!==bs.Mesh&&(a=this.system.worldScale.x/this.system.cameraScale);const l=V(e.startSize).multiplyScalar(s*a);if(e.size.set(l.x,l.y,l.z),this.system.localspace){const c=ux(this.system,Bk);e.size.x*=c.x,e.size.y*=c.y,e.size.z*=c.z}}}const Ca=Symbol("particleLife"),Lp=Symbol("trailLifetime"),jb=Symbol("trailStartLength"),Dp=Symbol("trailWidthRandom");class Uk extends No{constructor(){super(...arguments);r(this,"type","NeedleTrail")}initialize(e){e instanceof ae.TrailParticle&&(e[Ca]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Lp]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Lp]),e[jb]=e.length,e[Dp]=Math.random())}update(e){var i;if((i=this.system.trails)!=null&&i.enabled&&e instanceof ae.TrailParticle){const n=e,s=e.age/e[Ca],a=e.previous.values(),l=e.previous.length;for(let c=0;c<l;c++){const u=a.next().value,f=1-c/(l-1),p=e.size;if(p.x<=0&&!this.system.trails.sizeAffectsWidth){const g=20*this.system.trails.widthOverTrail.evaluate(.5,n[Dp]);p.x=g,p.y=g,p.z=g}u.size=this.system.trails.getWidth(p.x,s,f,n[Dp]),u.color.copy(e.color),this.system.trails.getColor(u.color,s,f)}if(e.age>e[Ca]){e.velocity.set(0,0,0);const c=(e.age-e[Ca])/e[Lp];n.length=z.lerp(e[jb],0,c)}}}}const Cd=Symbol("startVelocity"),Bb=Symbol("gravityModifier"),Ip=Symbol("gravitySpeed"),Pd=Symbol("velocity lerp factor"),Im=new d.Vector3;class zk extends No{constructor(){super(...arguments);r(this,"type","NeedleVelocity");r(this,"_gravityDirection",new d.Vector3)}initialize(e){var a,l;const i=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const n=this.system.shape.getDirection(e,e.position);e.velocity.x=n.x*e.startSpeed,e.velocity.y=n.y*e.startSpeed,e.velocity.z=n.z*e.startSpeed,(a=this.system.inheritVelocity)!=null&&a.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Cd]?e[Cd].copy(e.velocity):e[Cd]=e.velocity.clone();const s=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[Bb]=s*i,e[Ip]=s*i*.5,e[Pd]=Math.random(),(l=this.system.velocityOverLifetime)==null||l.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Vc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,i){var p;const n=e[Cd],s=e[Bb];if(s!==0){const g=s*e[Ip];Im.copy(this._gravityDirection).multiplyScalar(g),e[Ip]+=i*.05,n.add(Im)}e.velocity.copy(n);const a=e.age/e.life;(p=this.system.inheritVelocity)!=null&&p.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,a,e[Pd]);const l=this.system.noise;l.enabled&&l.apply(0,e.position,e.velocity,i,e.age,e.life);const c=this.system.sizeBySpeed;c!=null&&c.enabled&&(e.size=c.evaluate(e.velocity,a,e[Pd],e.size));const h=this.system.colorBySpeed;h!=null&&h.enabled&&h.evaluate(e.velocity,e[Pd],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,i,e.age,e.life);const f=this.system.limitVelocityOverLifetime;if(f.enabled&&f.apply(e.position,n,e.velocity,e.size,a,i,1),this.system.worldspace){const g=this.system.worldScale;e.velocity.x*=g.x,e.velocity.y*=g.y,e.velocity.z*=g.z}}}const Fb=Symbol("colorLerpFactor"),Ub=new ie(1,1,1,1),Qo=new ie(1,1,1,1);class Nk extends No{constructor(){super(...arguments);r(this,"type","NeedleColor")}initialize(e){}_init(e){const i=this.system.renderer.particleMaterial;Qo.copy(this.system.main.startColor.evaluate(Math.random())),i!=null&&i.color&&(Ub.copy(i.color),Qo.multiply(Ub)),Qo.convertLinearToSRGB(),e.startColor.set(Qo.r,Qo.g,Qo.b,Qo.alpha),e.color.copy(e.startColor),e[Fb]=Math.random()}update(e,i){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const n=e.age/e.life,s=this.system.colorOverLifetime.color.evaluate(n,e[Fb]);e.color.set(s.r,s.g,s.b,"alpha"in s?s.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class $k{constructor(t){r(this,"system");r(this,"emission");r(this,"autoDestroy");r(this,"startLength");r(this,"emissionBursts");r(this,"onlyUsedByOther");r(this,"behaviors",[]);r(this,"rendererEmitterSettings",{startLength:new ae.ConstantValue(220),followLocalOrigin:!1});r(this,"flatWhiteTexture");r(this,"clonedTexture",{original:void 0,clone:void 0});this.system=t,this.emission=new Lk(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Sd(this.system.main.startLifetime)}get startSpeed(){return new Sd(this.system.main.startSpeed)}get startRotation(){return new Sd(this.system.main.startRotation)}get startSize(){return new Sd(this.system.main.startSize)}get startColor(){return new ae.ConstantColor(new ae.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new Dk(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return ae.RenderMode.Trail;switch(this.system.renderer.renderMode){case bs.Billboard:return ae.RenderMode.BillBoard;case bs.Stretch:return ae.RenderMode.StretchedBillBoard;case bs.HorizontalBillboard:return ae.RenderMode.HorizontalBillBoard;case bs.VerticalBillboard:return ae.RenderMode.VerticalBillBoard;case bs.Mesh:return ae.RenderMode.Mesh}return ae.RenderMode.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===bs.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const t=this.material;if(t&&t.map){const e=t.map;if(this.clonedTexture.original!==e||!this.clonedTexture.clone){const i=e.clone();i.premultiplyAlpha=!1,i.colorSpace=d.LinearSRGBColorSpace,this.clonedTexture.original=e,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Cg(new ie(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new Ak(this.system)}get uTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesX:void 0}get vTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesY:void 0}get renderOrder(){return 1}get blending(){var t;return((t=this.system.renderer.particleMaterial)==null?void 0:t.blending)??d.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Vc.World}}class Vk{constructor(){r(this,"burstParticleIndex",0);r(this,"burstParticleCount",0);r(this,"isBursting",!1);r(this,"travelDistance",0);r(this,"previousWorldPos");r(this,"burstIndex",0);r(this,"burstWaveIndex",0);r(this,"time",0);r(this,"waitEmiting",0)}}const Bt=class $d extends I{constructor(){super(...arguments);r(this,"_state");r(this,"colorOverLifetime");r(this,"main");r(this,"emission");r(this,"sizeOverLifetime");r(this,"shape");r(this,"noise");r(this,"trails");r(this,"velocityOverLifetime");r(this,"limitVelocityOverLifetime");r(this,"inheritVelocity");r(this,"colorBySpeed");r(this,"textureSheetAnimation");r(this,"rotationOverLifetime");r(this,"rotationBySpeed");r(this,"sizeBySpeed");r(this,"_cameraScale",1);r(this,"__worldQuaternion",new d.Quaternion);r(this,"_worldQuaternionInverted",new d.Quaternion);r(this,"_worldScale",new d.Vector3);r(this,"_worldPositionFrame",-1);r(this,"_worldPos",new d.Vector3);r(this,"_renderer");r(this,"_batchSystem");r(this,"_particleSystem");r(this,"_interface");r(this,"_container");r(this,"_time",0);r(this,"_isPlaying",!0);r(this,"_isUsedAsSubsystem",!1);r(this,"_didPreWarm",!1);r(this,"_bursts");r(this,"_subEmitterSystems");r(this,"_lastBatchesCount",-1)}play(e=!1){var i;e&&C.foreachComponent(this.gameObject,n=>{n instanceof $d&&n!==this&&n.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(i=this.emission)==null||i.reset()}pause(e=!0){e&&C.foreachComponent(this.gameObject,i=>{i instanceof $d&&i!==this&&i.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,i=!1){e&&C.foreachComponent(this.gameObject,n=>{n instanceof $d&&n!==this&&n.stop(!1,i)},!0),this._isPlaying=!1,this._time=0,i&&this.reset()}reset(){var e;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(e=this.emission)==null||e.reset())}emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new Vk),this._state.waitEmiting=e,this._state.time=0;const i=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=i}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var e;return((e=this._particleSystem)==null?void 0:e.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===Vc.World}get localspace(){return this.main.simulationSpace===Vc.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Q(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof No&&(e.system=this),ro&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const i=this._particleSystem.behaviors,n=i.indexOf(e);return n!==-1&&((j()||ro)&&console.debug("Remove custom ParticleSystem Behaviour",n,e),i.splice(n,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(e){for(let i=0;i<e.length;i++){const n=e[i];if(!(n instanceof wu)){const s=new wu;Ga(s,n),e[i]=s}}this._bursts=e}set subEmitterSystems(e){for(let i=0;i<e.length;i++){const n=e[i];if(!(n instanceof xu)){const s=new xu;Ga(s,n),e[i]=s}}ro&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const i of this._subEmitterSystems)i._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(en),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new d.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new ae.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new $k(this),this._particleSystem=new ae.ParticleSystem(this._interface),this._particleSystem.addBehavior(new Fk(this)),this._particleSystem.addBehavior(new Nk(this)),this._particleSystem.addBehavior(new Ik(this)),this._particleSystem.addBehavior(new jk(this)),this._particleSystem.addBehavior(new zk(this)),this._particleSystem.addBehavior(new Uk(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),ro&&(console.log(this),this.gameObject.add(new d.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof d.Mesh&&this._interface.renderMode==ae.RenderMode.Mesh&&le.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==ae.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){var e,i,n,s;(e=this._container)==null||e.removeFromParent(),(i=this._batchSystem)==null||i.removeFromParent(),(n=this._particleSystem)==null||n.emitter.removeFromParent(),(s=this._particleSystem)==null||s.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var e;this.main&&(this._didPreWarm===!1&&((e=this.main)==null?void 0:e.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var u;if(!((u=this.emission)!=null&&u.enabled)||this.emission.rateOverTime.getMax()<=0)return;const i=1/60,n=this.main.duration,s=this.main.startLifetime.getMax(),l=Math.min(Math.max(n,s)/Math.max(.01,this.main.simulationSpeed),1e3),c=Math.ceil(l/i),h=Date.now();ro&&console.log(`Particles ${this.name} - Prewarm for ${c} frames (${l} sec). Duration: ${n}, Lifetime: ${s}`);for(let f=0;f<c&&!(this.currentParticles>=this.maxParticles);f++){const p=Date.now()-h;if(p>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${p}`);break}this.onUpdate(),this.onSimulate(i)}}onSimulate(e){if(this._batchSystem){let i=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,i=!0),i&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const i=this._batchSystem.batches[e];i.layers.disableAll();const n=this.layer;i.layers.mask=1<<n}}onUpdate(){var s,a;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const l=Ue(e);this._cameraScale=l.x}const i=!this.worldspace,n=this.gameObject;if(_e(n,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ue(this.gameObject,this._worldScale),i&&this._container&&((s=this.gameObject)!=null&&s.parent)){const l=ux(this,Im);this._container.matrix.makeScale(l.x,l.y,l.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(a=this.inheritVelocity)==null||a.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var e;if(this._subEmitterSystems&&this._particleSystem)for(const i of this._subEmitterSystems){i.particleSystem&&(i.particleSystem.__internalAwake?i.particleSystem.__internalAwake():j()&&console.warn("SubParticleSystem serialization issue(?)",i.particleSystem,i));const n=(e=i.particleSystem)==null?void 0:e._particleSystem;if(n){i.particleSystem._isUsedAsSubsystem=!0;const s=new Ay(this,this._particleSystem,i.particleSystem,n);s.emitterType=i.type,s.emitterProbability=i.emitProbability,this._particleSystem.addBehavior(s)}else ro&&console.warn("Could not add SubParticleSystem",i,this)}}};Be([m(_f)],Bt.prototype,"colorOverLifetime");Be([m(It)],Bt.prototype,"main");Be([m($s)],Bt.prototype,"emission");Be([m(Zr)],Bt.prototype,"sizeOverLifetime");Be([m(Ey)],Bt.prototype,"shape");Be([m(be)],Bt.prototype,"noise");Be([m(je)],Bt.prototype,"trails");Be([m(ze)],Bt.prototype,"velocityOverLifetime");Be([m(lt)],Bt.prototype,"limitVelocityOverLifetime");Be([m(Ty)],Bt.prototype,"inheritVelocity");Be([m(_l)],Bt.prototype,"colorBySpeed");Be([m(jt)],Bt.prototype,"textureSheetAnimation");Be([m(Cn)],Bt.prototype,"rotationOverLifetime");Be([m(Ji)],Bt.prototype,"rotationBySpeed");Be([m(gi)],Bt.prototype,"sizeBySpeed");let Wc=Bt;class xu{constructor(){r(this,"particleSystem");r(this,"emitProbability",1);r(this,"properties");r(this,"type")}_deserialize(t,e){const i=this.particleSystem;if(i instanceof Wc)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=C.findByGuid(n,e)),ro&&!(this.particleSystem instanceof Wc)&&console.warn("Could not find particle system for sub emitter",n,e,this)}}function ux(o,t){if(t.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case Lm.Local:t=Ue(o.gameObject.parent,t),t.x=1/t.x,t.y=1/t.y,t.z=1/t.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const e="ParticleSystem scale mode "+Lm[o.main.scalingMode]+" is not supported";j()&&me(e),console.warn(e,o.name,o)}t=Ue(o.gameObject,t);break}return t}class el extends I{constructor(){super(...arguments);r(this,"_didAssignPlayerColor",!1);r(this,"tryAssignColor",()=>{const e=C.getComponentInParent(this.gameObject,yn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const i=C.getComponentInParent(this.gameObject,At);return i!=null&&i.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(i.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(ee.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ee.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Sg(.2),!this.tryAssignColor()););}assignUserColor(e){const i=el.hashCode(e),n=el.colorFromHashCode(i);if(this.gameObject.type==="Mesh"){const s=this.gameObject;this.assignColor(n,e,s)}else if(this.gameObject.children)for(const s of this.gameObject.children){const a=s;a.material&&a.material.color&&this.assignColor(n,e,a)}}assignColor(e,i,n){let s=n.material;s&&(s._playerMaterial!==i&&(s=s.clone(),s._playerMaterial=i,n.material=s),s.color=e)}static hashCode(e){var i=0,n,s;if(e.length===0)return i;for(n=0;n<e.length;n++)s=e.charCodeAt(n),i=(i<<5)-i+s,i|=0;return i}static colorFromHashCode(e){const i=(e&16711680)>>16,n=(e&65280)>>8,s=e&255;return new d.Color(i/255,n/255,s/255)}}const oc=S("debugpost");let jm=null;function Wk(o){jm=o}function fx(o){let t=o.gameObject;for(;t;){for(const e of Hu(t))if(e.isPostProcessingManager===!0)return e;t=t.parent}return null}function Gk(o){let t=fx(o);if(!t)if(jm){oc&&console.warn("Adding postprocessing manager to the scene.");const e=o.scene;t=Oi(e,jm)}else j()&&console.warn("No post processing manager found");return t}const it={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let qe=null;function Hk(o){oc==="verbose"&&console.debug("Before ordering effects",[...o]),qe||(qe=new Map,qe.set(exports.MODULES.POSTPROCESSING.MODULE.NormalPass,it.NormalPass),qe.set(exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,it.DepthDownsamplingPass),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,it.SMAA),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPass,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,it.TiltShift),qe.set(exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,it.DepthOfField),qe.set(exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,it.ChromaticAberration),qe.set(exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,it.Bloom),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,it.Bloom),qe.set(exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,it.Vignette),qe.set(exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,it.Pixelation),qe.set(exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,it.ToneMapping),qe.set(exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,it.HueSaturation),qe.set(exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect,it.BrightnessContrast)),o.sort((t,e)=>{const i=typeof t.priority=="number"?t.priority:qe.get(t.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof e.priority=="number"?e.priority:qe.get(e.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(oc&&console.warn("Unknown effect found: ",t.constructor.name,t),1):n===Number.NEGATIVE_INFINITY?(oc&&console.warn("Unknown effect found: ",e.constructor.name,e),-1):i-n}),oc==="verbose"&&console.debug("After ordering effects",[...o])}var qk=Object.defineProperty,Xk=Object.getOwnPropertyDescriptor,px=(o,t,e,i)=>{for(var n=Xk(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&qk(t,e,n),n};const Qk=S("debugpost");class U{constructor(t){r(this,"isVolumeParameter",!0);r(this,"_isInitialized",!1);r(this,"_active",!0);r(this,"_value");r(this,"_valueRaw");r(this,"_defaultValue");r(this,"valueProcessor");r(this,"onValueChanged");t!==void 0&&this.initialize(t)}get isInitialized(){return this._isInitialized}initialize(t){t!==void 0&&(this._value=t,this._defaultValue=t,this._valueRaw=t,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(t){if(this._active===t)return;this._active=t;const e=t?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(t){this.isInitialized||this.initialize(t),this.processValue(t,!1)}set defaultValue(t){this._defaultValue=t}__init(){this.processValue(this._valueRaw,!0)}processValue(t,e){if(t==null||!e&&this.testIfValueChanged(t)===!1)return;const i=this._value;Qk&&typeof i=="number"&&typeof t=="number"&&(i==null||i.toFixed(4),t==null||t.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,t=this._defaultValue,this._valueRaw=t):(this._valueRaw=t,this._active&&this.valueProcessor&&(t=this.valueProcessor(t)),this._value=t),this.onValueChanged&&this.onValueChanged(t,i,this)}testIfValueChanged(t){return this._valueRaw!==t}}px([m()],U.prototype,"overrideState");px([m()],U.prototype,"value");class Yk extends Ki{constructor(){super([U])}onSerialize(t,e){}onDeserialize(t,e){const i=e.target,n=e.path;let s;if(i&&n&&(s=i[n]),(typeof s!="object"||typeof s=="object"&&s.isVolumeParameter!==!0)&&(s=new U),typeof t=="object"&&"value"in t){const a=t.value;s.initialize(a),s.overrideState=t.overrideState}else s.value=t;return s}}new Yk;var Kk=Object.defineProperty,Zk=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Kk(t,e,n),n};const jp=S("debugpost");class Ye extends I{constructor(e=void 0){super();r(this,"order");r(this,"active",!0);r(this,"_manager",null);r(this,"_result");r(this,"_postprocessingContext",null);if(e)for(const i of Object.keys(e)){const n=e[i],s=this[i];s instanceof U?s.initialize(n):s!==void 0&&(this[i]=n)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),jp&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var e;super.onDisable(),jp&&console.warn("Disable",this.constructor.name),(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=Gk(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var i;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(i=this.onCreateEffect)==null?void 0:i.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){jp&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const i of e){const n=this[i];n instanceof U&&n.__init()}}onEditorModification(e){const i=e.propertyName;if(this[i]instanceof U){const n=e.value;return this[i].value=n,!0}}}Zk([m()],Ye.prototype,"active");var Jk=Object.defineProperty,eR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Jk(t,e,n),n};const tR=S("debugpost"),Bm={};function tn(o,t){Bm[o]=t}function iR(o){return o.__type in Bm?Bm[o.__type]:(tR&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),Ye)}class bf{constructor(){r(this,"components",[])}__init(t){var e;(e=this.components)==null||e.forEach(i=>{i.gameObject===void 0&&t.gameObject.addComponent(i),i.init()})}addEffect(t){this.components.push(t)}removeEffect(t){const e=this.components.indexOf(t);e>=0&&this.components.splice(e,1)}}eR([Br([o=>iR(o),Ye])],bf.prototype,"components");var nR=Object.defineProperty,sR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&nR(t,e,n),n};const oR=S("debugpost");class Dh extends Ye{constructor(){super(...arguments);r(this,"preset",new U(2))}get typeName(){return"Antialiasing"}onCreateEffect(){var i;const e=new exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect({preset:((i=this.preset)==null?void 0:i.value)??exports.MODULES.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:exports.MODULES.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=n=>{oR&&console.log("Antialiasing preset changed to",n),e.applyPreset(n)},e}}sR([m(U)],Dh.prototype,"preset");tn("Antialiasing",Dh);var rR=Object.defineProperty,Dy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&rR(t,e,n),n},dr;const vf=(dr=class extends Ye{constructor(){super(...arguments);r(this,"threshold",new U(.9));r(this,"intensity",new U(1));r(this,"scatter",new U(.7));r(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=dr.useSelectiveBloom),this.selectiveBloom){const i=e=new exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});i.inverted=!0}else e=new exports.MODULES.POSTPROCESSING.MODULE.BloomEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=i=>{e.intensity=i},this.threshold.onValueChanged=i=>{e.luminanceMaterial.threshold=Math.pow(i,2.2)},this.scatter.onValueChanged=i=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=i,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=d.MathUtils.lerp(.1,.9,i))},e}},r(dr,"useSelectiveBloom",!1),dr);Dy([m(U)],vf.prototype,"threshold");Dy([m(U)],vf.prototype,"intensity");Dy([m(U)],vf.prototype,"scatter");let wf=vf;tn("Bloom",wf);var aR=Object.defineProperty,lR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&aR(t,e,n),n};class Ih extends Ye{constructor(){super(...arguments);r(this,"intensity",new U(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new d.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{e.offset.x=-i,e.offset.y=i},e}}lR([m(U)],Ih.prototype,"intensity");tn("ChromaticAberration",Ih);var rc=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(rc||{});const zb=new Map;function Bp(o){switch(o){case 0:return d.LinearToneMapping;case 1:return d.ReinhardToneMapping;case 2:return d.ACESFilmicToneMapping;case 3:return d.AgXToneMapping;case 4:return d.NeutralToneMapping;default:return zb.has(o)||(zb.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),d.NeutralToneMapping}}function cR(o){switch(o){case d.LinearToneMapping:return 0;case d.ACESFilmicToneMapping:return 2;case d.AgXToneMapping:return 3;case d.NeutralToneMapping:return 1;case d.ReinhardToneMapping:return 1;default:return 0}}function Vd(o){switch(o){case d.LinearToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case d.ACESFilmicToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case d.AgXToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case d.NeutralToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case d.ReinhardToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var hR=Object.defineProperty,mx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&hR(t,e,n),n};const Fp=S("debugpost");class Ro extends Ye{constructor(){super(...arguments);r(this,"mode",new U(void 0));r(this,"exposure",new U(1));r(this,"_tonemappingEffect",null)}get typeName(){return"ToneMapping"}setMode(e){const i=rc[e];return i===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=i,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=fx(this);e&&super.onEffectEnabled(e)}onCreateEffect(){var n;if(this.mode.isInitialized==!1){const s=cR(this.context.renderer.toneMapping);Fp&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+s),this.mode.initialize(s)}(n=this._tonemappingEffect)==null||n.dispose();const e=Bp(this.mode.value),i=this._tonemappingEffect=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Vd(e)});return this.mode.onValueChanged=s=>{if(typeof s=="string")s=qv(s),i.mode=Vd(s);else{const a=Bp(s);i.mode=Vd(a)}i.name="ToneMapping ("+rc[s]+")",Fp&&console.log("[PostProcessing] ToneMapping mode changed to",rc[s],e,i.mode)},Fp&&console.log("[PostProcessing] Use ToneMapping",rc[this.mode.value],e,i.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),i}onBeforeRender(){var e;if(this._tonemappingEffect&&((e=this.postprocessingContext)!=null&&e.handler.getEffectIsActive(this._tonemappingEffect))&&(this.mode.overrideState&&(this.context.renderer.toneMapping=Bp(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const i=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=i}}}mx([m(U)],Ro.prototype,"mode");mx([m(U)],Ro.prototype,"exposure");tn("Tonemapping",Ro);var dR=Object.defineProperty,xf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&dR(t,e,n),n};class $o extends Ye{constructor(){super(...arguments);r(this,"remap",!0);r(this,"postExposure",new U(1));r(this,"contrast",new U(0));r(this,"hueShift",new U(0));r(this,"saturation",new U(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let i=1;return e>0?i=200:e<0&&(i=100),e/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){var a,l;const e=[];let i=(a=this.postprocessingContext)==null?void 0:a.components.find(c=>c instanceof Ro);i||(i=new Ro,(l=this.postprocessingContext)==null||l.components.push(i)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&i?i.exposure.value=c:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const n=new exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>n.contrast=c;const s=new exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=c=>s.hue=c,this.saturation.onValueChanged=c=>s.saturation=c,e.push(n),e.push(s),e}}xf([m(U)],$o.prototype,"postExposure");xf([m(U)],$o.prototype,"contrast");xf([m(U)],$o.prototype,"hueShift");xf([m(U)],$o.prototype,"saturation");tn("ColorAdjustments",$o);var uR=Object.defineProperty,Jr=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&uR(t,e,n),n};const fR=S("debugpost");class Pn extends Ye{constructor(){super(...arguments);r(this,"mode");r(this,"focusDistance",new U(1));r(this,"focalLength",new U(.2));r(this,"aperture",new U(20));r(this,"gaussianMaxRadius",new U);r(this,"resolutionScale",new U(1/window.devicePixelRatio));r(this,"bokehScale",new U)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300;return z.lerp(2,.01,n)};const e=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return z.lerp(1,e,n)}}onCreateEffect(){if(this.mode===0){fR&&console.warn("DepthOfField: Mode is set to Off");return}const e=new exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{e.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>e.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>e.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>e.resolution.scale=i),[e]}unapply(){}}Jr([m()],Pn.prototype,"mode");Jr([m(U)],Pn.prototype,"focusDistance");Jr([m(U)],Pn.prototype,"focalLength");Jr([m(U)],Pn.prototype,"aperture");Jr([m(U)],Pn.prototype,"gaussianMaxRadius");Jr([m(U)],Pn.prototype,"resolutionScale");Jr([m(U)],Pn.prototype,"bokehScale");tn("DepthOfField",Pn);class Gc extends Ye{constructor(e){super();r(this,"effect");this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var pR=Object.defineProperty,mR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&pR(t,e,n),n};class jh extends Ye{constructor(){super(...arguments);r(this,"granularity",new U(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=i=>{e.granularity=i},e}}mR([m(U)],jh.prototype,"granularity");tn("PixelationEffect",jh);var gR=Object.defineProperty,Bh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&gR(t,e,n),n};class Vs extends Ye{constructor(){super(...arguments);r(this,"intensity",new U(2));r(this,"falloff",new U(1));r(this,"samples",new U(9));r(this,"color",new U(new d.Color(0,0,0)));r(this,"luminanceInfluence",new U(.7));r(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof d.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const e=this.context.mainCamera,i=new exports.MODULES.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),n=new exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:i.texture,resolutionScale:.5}),s=this._ssao=new exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect(e,i.texture,{normalDepthBuffer:n.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{s.intensity=l},this.falloff.onValueChanged=l=>{s.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{s.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{s.color||(s.color=new d.Color),s.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{s.luminanceInfluence=l};const a=new Array;return a.push(i),a.push(n),a.push(s),a}}Bh([m(U)],Vs.prototype,"intensity");Bh([m(U)],Vs.prototype,"falloff");Bh([m(U)],Vs.prototype,"samples");Bh([m(U)],Vs.prototype,"color");Bh([m(U)],Vs.prototype,"luminanceInfluence");tn("ScreenSpaceAmbientOcclusion",Vs);var yR=Object.defineProperty,ea=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&yR(t,e,n),n};const _R=S("debugN8AO");var Fm=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(Fm||{});class Mn extends Ye{constructor(){super(...arguments);r(this,"gammaCorrection",!0);r(this,"aoRadius",new U(1));r(this,"falloff",new U(1));r(this,"intensity",new U(1));r(this,"color",new U(new d.Color(0,0,0)));r(this,"screenspaceRadius",!1);r(this,"quality",2);r(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(Fm[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,i=this.context.domWidth,n=this.context.domHeight,s=this._ssao=new exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,i,n);s.name="SSAO_N8";const a=Fm[this.quality];s.setQualityMode(a),s.configuration.transparencyAware=!1;const l=new d.WebGLRenderTarget(i,n);return s.configuration.beautyRenderTarget=l,s.configuration.autoRenderBeauty=!1,s.configuration.gammaCorrection=this.gammaCorrection,s.configuration.screenSpaceRadius=this.screenspaceRadius,_R&&(s.enableDebugMode(),console.log(s),setInterval(()=>{console.log("SSAO",s.lastTime)},1e3),setInterval(()=>{console.log("SSAO",s.enabled,{ssao:s,autoRenderBeauty:s.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{s.configuration.intensity=c},this.falloff.onValueChanged=c=>{s.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{s.configuration.aoRadius=c},this.color.onValueChanged=c=>{s.color||(s.color=new d.Color),s.configuration.color.copy(c)},s}}ea([Ct(),m()],Mn.prototype,"gammaCorrection");ea([m(U)],Mn.prototype,"aoRadius");ea([m(U)],Mn.prototype,"falloff");ea([m(U)],Mn.prototype,"intensity");ea([m(U)],Mn.prototype,"color");ea([Ct(),m()],Mn.prototype,"screenspaceRadius");ea([Ct(),m()],Mn.prototype,"quality");tn("ScreenSpaceAmbientOcclusionN8",Mn);var bR=Object.defineProperty,vR=Object.getOwnPropertyDescriptor,gx=(o,t,e,i)=>{for(var n=vR(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bR(t,e,n),n};class Fh extends Ye{constructor(){super(...arguments);r(this,"order",it.Sharpening);r(this,"_effect");r(this,"_amount",1);r(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(wR())),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}gx([m()],Fh.prototype,"amount");gx([m()],Fh.prototype,"radius");function wR(){const o=`
1274
+ `)}a&&s.size&&console.log(f);const y=new Set;for(const v of g){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let w=v.getPath();w.startsWith("<")&&(w=w.substring(1)),w.endsWith(">")&&(w=w.substring(0,w.length-1)),y.add({path:w,obj:v})}const b=Array.from(y).sort((v,w)=>v.path.length-w.path.length),_=new Array;for(let v=0;v<b.length;v++)for(let w=v+1;w<b.length;w++)if(b[w].path.startsWith(b[v].path)){const x=b[w],O=b[v];_.push({child:x.obj.displayName+" ("+x.path+")",parent:O.obj.displayName+" ("+O.path+")"})}_.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:_,playAnimationActions:s})}for(const f of new Set([...e,...i]))if(Array.isArray(f))for(const p of f)n.add(p.uuid);else n.add(f.uuid);_d&&console.log("All Behavior trigger sources and action targets",e,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(t,e){var i;if((i=this.behaviours)!=null&&i.length){e.beginBlock('def Scope "Behaviors"');for(const n of this.behaviours)n.writeTo(this,t.document,e);e.closeBlock()}}async onAfterSerialize(t){_d&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)typeof e.afterSerialize=="function"&&(e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,t):e.afterSerialize(this,t));for(const{clipUrl:e,filesKey:i}of this.audioClipsCopy){if(t.files[i])return;const a=await(await(await fetch(e)).blob()).arrayBuffer(),l=new Uint8Array(a);t.files[i]=l}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class py{get extensionName(){return"Physics"}onExportObject(t,e,i){const n=C.getComponents(t,ot).filter(c=>c.enabled),s=C.getComponents(t,ui).filter(c=>c.enabled&&!c.isTrigger);let a=n.length>0?n[0]:null;const l=s.length>0?s[0]:null;l&&!a&&(a=new ot,a.isKinematic=!0),a&&e.addEventListener("serialize",(c,h)=>{var u,f,p;if(a){if(c.appendLine(),c.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),a.useGravity||c.appendLine("bool gravityEnabled = 0"),c.appendLine('uniform token info:id = "RealityKit.RigidBody"'),a.isKinematic&&c.appendLine('token motionType = "Kinematic"'),c.beginBlock('def RealityKitStruct "massFrame"',"{",!0),c.appendLine(`float m_mass = ${a.mass}`),c.beginBlock('def RealityKitStruct "m_pose"',"{",!0),c.appendLine(`float3 position = (${a.centerOfMass.x}, ${a.centerOfMass.y}, ${a.centerOfMass.z})`),c.closeBlock("}"),c.closeBlock("}"),s.length>0){const g=s[0];c.beginBlock('def RealityKitStruct "material"',"{",!0);const y=g.sharedMaterial;y&&y.dynamicFriction!==void 0&&c.appendLine(`double dynamicFriction = ${(u=g.sharedMaterial)==null?void 0:u.dynamicFriction}`),y&&y.bounciness!==void 0&&c.appendLine(`double restitution = ${(f=g.sharedMaterial)==null?void 0:f.bounciness}`),y&&y.staticFriction!==void 0&&c.appendLine(`double staticFriction = ${(p=g.sharedMaterial)==null?void 0:p.staticFriction}`),c.closeBlock("}")}c.closeBlock("}")}}),l&&(e.addEventListener("serialize",(c,h)=>{var p;c.beginBlock('def RealityKitComponent "Collider"',"{",!0),c.appendLine("uint group = 1"),c.appendLine('uniform token info:id = "RealityKit.Collider"'),c.appendLine("uint mask = 4294967295");const f=l.isTrigger?"Trigger":"Default";if(c.appendLine(`token type = "${f}"`),c.beginBlock('def RealityKitStruct "Shape"',"{",!0),l instanceof al){const g=l;c.appendLine('token shapeType = "Sphere"'),c.appendLine(`float radius = ${g.radius}`)}else if(l instanceof tf){const g=l;c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(l instanceof As){const g=l;c.appendLine('token shapeType = "Capsule"'),c.appendLine(`float radius = ${g.radius}`),c.appendLine(`float height = ${g.height}`)}else if(l instanceof Io&&((p=l.sharedMesh)!=null&&p.geometry)){const g=l.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const y=l.sharedMesh.geometry.boundingBox;y&&(c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${y.max.x-y.min.x}, ${y.max.y-y.min.y}, ${y.max.z-y.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",l))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",l);c.beginBlock('def RealityKitStruct "pose"',"{",!0),c.closeBlock("}"),c.closeBlock("}"),c.closeBlock("}")}),s.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",l))}}const GO=S("debugshadowcomponents");ne.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class Qi extends I{constructor(){super(...arguments);r(this,"_shadowComponent",null);r(this,"_controlsChildLayout",!0);r(this,"_root");r(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Yt.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=C.getComponentInParent(this.gameObject,Ph)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,i){var a;if(!e)return;this.removeShadowComponent();const n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=C.getComponentInParent(n,Qi),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Si]=this,this.setShadowComponentOwner(e);let s=!1;if(((a=this.Root)==null?void 0:a.gameObject)===this.gameObject)this.gameObject.add(e);else{const l=this._parentComponent.shadowComponent;l&&(l==null||l.add(e),s=!0)}this.shadowComponent=e,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),rh&&e.add(new d.AxesHelper(.5)),this.onAfterAddedToScene(),s&&ne.__webpack_exports__update(),GO&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Si]===void 0||e[Si]===this)&&(e[Si]=this,e.children))for(const i of e.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(e,i,n){if(e&&e[Si]===i){n(e);for(const s of e.children)this.traverseOwnedShadowComponents(s,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class Ph extends Qi{awake(){super.awake()}}var HO=Object.defineProperty,qO=Object.getOwnPropertyDescriptor,Mh=(o,t,e,i)=>{for(var n=i>1?void 0:i?qO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&HO(t,e,n),n};const Op=S("debugui"),kp=S("debuguilayout");class ix{constructor(){r(this,"width");r(this,"height")}}class nx{constructor(){r(this,"x");r(this,"y");r(this,"width");r(this,"height")}}const cn=new d.Vector3,jl=new d.Matrix4,bd=new d.Quaternion,fl=class sx extends Qi{constructor(){super(...arguments);r(this,"_anchoredPosition");r(this,"sizeDelta",new d.Vector2(100,100));r(this,"pivot",new d.Vector2(.5,.5));r(this,"anchorMin",new d.Vector2(0,0));r(this,"anchorMax",new d.Vector2(1,1));r(this,"minWidth");r(this,"minHeight");r(this,"lastMatrix");r(this,"rectBlock");r(this,"_transformNeedsUpdate",!1);r(this,"_initialPosition");r(this,"_parentRectTransform");r(this,"_lastUpdateFrame",-1);r(this,"_lastAnchoring");r(this,"_createdBlocks",[]);r(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new d.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const i=this._parentRectTransform.width,n=this.anchorMax.x-this.anchorMin.x;e=i*n,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const i=this._parentRectTransform.height,n=this.anchorMax.y-this.anchorMin.y;e=i*n,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new d.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new d.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new d.Vector2),ma(this,"_anchoredPosition",()=>{this.markDirty()}),ma(this,"sizeDelta",()=>{this.markDirty()}),ma(this,"pivot",()=>{this.markDirty()}),ma(this,"anchorMin",()=>{this.markDirty()}),ma(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.rectBlock||(this.rectBlock=new d.Object3D),this.lastMatrix||(this.lastMatrix=new d.Matrix4),this._lastAnchoring||(this._lastAnchoring=new d.Vector2),this._initialPosition||(this._initialPosition=new d.Vector3),this._anchoredPosition||(this._anchoredPosition=new d.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(kp?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(kp&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){var s;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const i=this.shadowComponent;if(!i)return;this.gameObject.parent?this._parentRectTransform=C.getComponentInParent(this.gameObject.parent,sx):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,kp&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(i.rotation.y=Math.PI):(i.matrix.identity(),i.matrixAutoUpdate=!1,cn.set(0,0,0),this.applyPivot(cn),i.matrix.setPosition(cn.x,cn.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(bd.copy(this.gameObject.quaternion),bd.x*=-1,bd.z*=-1,jl.makeRotationFromQuaternion(bd),i.matrix.premultiply(jl)),cn.set(0,0,0),this.applyAnchoring(cn),(s=this.canvas)!=null&&s.screenspace?cn.z+=.1:cn.z+=.01,jl.identity(),jl.setPosition(cn.x,cn.y,cn.z),i.matrix.premultiply(jl),i.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const a of Hu(this.gameObject,Qi,n,1)){if(a===this||!a.activeAndEnabled)continue;const l=a;l.onParentRectTransformChanged&&l.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new d.Vector2);const i=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=i.x,this.gameObject.position.y+=i.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const n=this._parentRectTransform;if(n){let s=0;const a=1-this.anchorMax.y-this.anchorMin.y;s-=n.height*.5*a,e.y+=s;let l=0;const c=1-this.anchorMax.x-this.anchorMin.x;l-=n.width*.5*c,e.x+=l}}applyPivot(e){if(this.pivot&&!this.isRoot()){const i=this.pivot.x-.5;e.x-=i*this.sizeDelta.x*this.gameObject.scale.x;const n=this.pivot.y-.5;e.y-=n*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,i=1e-4){return e.width<=0&&(e.width=i),e.height<=0&&(e.height=1e-4),e}createNewBlock(e){e={...this.getBasicOptions(),...e},Op&&console.log(this.name,e);const i=new ne.__webpack_exports__Block(e);return this._createdBlocks.push(i),i}createNewText(e){Op&&console.log(e),e={...this.getBasicOptions(),...e},Op&&console.log(this.name,e);const i=new ne.__webpack_exports__Text(e);return this._createdTextBlocks.push(i),i}};Mh([m(d.Vector2)],fl.prototype,"anchoredPosition",1);Mh([m(d.Vector2)],fl.prototype,"sizeDelta",2);Mh([m(d.Vector2)],fl.prototype,"pivot",2);Mh([m(d.Vector2)],fl.prototype,"anchorMin",2);Mh([m(d.Vector2)],fl.prototype,"anchorMax",2);let wn=fl;var XO=Object.defineProperty,ox=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&XO(t,e,n),n};class pl extends I{constructor(){super(...arguments);r(this,"effectColor");r(this,"effectDistance")}}ox([m(ie)],pl.prototype,"effectColor");ox([m(d.Vector2)],pl.prototype,"effectDistance");var QO=Object.defineProperty,YO=Object.getOwnPropertyDescriptor,rx=(o,t,e,i)=>{for(var n=i>1?void 0:i?YO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QO(t,e,n),n};const vd={backgroundColor:new d.Color(1,1,1),backgroundOpacity:1,borderColor:new d.Color(1,1,1),borderOpacity:1};var Hn;const my=(Hn=class extends Qi{constructor(){super(...arguments);r(this,"_alphaFactor",1);r(this,"sRGBColor",new d.Color(1,0,1));r(this,"raycastTarget",!0);r(this,"uiObject",null);r(this,"_color",null);r(this,"_rect",null);r(this,"_stateManager",null);r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new ie(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new ie(1,1,1,1)),this._color.copy(e),this.onColorChanged())}setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),vd.backgroundColor=this.sRGBColor,vd.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(vd,this._alphaFactor),this.uiObject.set(vd),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=C.getComponent(this.gameObject,wn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var e;(e=this.uiObject)==null||e.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this==null||this.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new ne.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),ma(this,"_color",()=>HP(this,this.onColorChanged))}onEnable(){var e;super.onEnable(),this.uiObject&&((e=this.rectTransform.shadowComponent)==null||e.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const i={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(i),this.applyEffects(i),this.onCreate(i),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,i=1){var s;const n=(s=this.gameObject)==null?void 0:s.getComponent(pl);n&&(n.effectDistance&&(e.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(e.borderColor=n.effectColor,e.borderOpacity=n.effectColor.alpha*i))}async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(Hn.textureCache.has(e))e=Hn.textureCache.get(e);else if(!e.isRenderTargetTexture){const i=e.clone();i.colorSpace=d.LinearSRGBColorSpace,Hn.textureCache.set(e,i),e=i}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),le.NEEDLE_progressive.assignTextureLOD(e,0).then(i=>{i instanceof d.Texture&&(e&&Hn.textureCache.set(e,i),this.setOptions({backgroundImage:i}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},r(Hn,"textureCache",new Map),Hn);rx([m(ie)],my.prototype,"color",1);rx([m()],my.prototype,"raycastTarget",2);let Oh=my;class kh extends Oh{constructor(){super(...arguments);r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var KO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,zs=(o,t,e,i)=>{for(var n=i>1?void 0:i?ZO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&KO(t,e,n),n};const Xo=S("debugtext");var tt=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(tt||{}),ax=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(ax||{});class Dt extends Oh{constructor(){super(...arguments);r(this,"alignment",0);r(this,"verticalOverflow",0);r(this,"horizontalOverflow",0);r(this,"lineSpacing",1);r(this,"supportRichText",!1);r(this,"font");r(this,"fontStyle",0);r(this,"sRGBTextColor",new d.Color(1,0,1));r(this,"_text","");r(this,"_fontSize",12);r(this,"_textMeshUi",null);r(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var i;super.setAlphaFactor(e),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var i;this._fontSize=e,(i=this.uiObject)==null||i.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var i;const e=(i=this.uiObject)==null?void 0:i._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Xo&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Xo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const i=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Xo&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=i.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,i){var n,s,a;if(Xo&&console.log("feedText",this.uiObject,e,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||e.length===0)this.uiObject.textContent=e;else{let l=this.getNextTag(e);if(l){if(l.startIndex>0){for(let u=this.uiObject.children.length-1;u>=0;u--){const f=this.uiObject.children[u];f.isUI&&(this.uiObject.remove(f),f.clear())}const h=new ne.__webpack_exports__Inline({textContent:e.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const c=[];for(;l;){const h=this.getNextTag(e,l.endIndex),u={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(h){u.textContent=this.getText(e,l,h),this.handleTag(l,u,c);const f=new ne.__webpack_exports__Inline(u);(s=this.uiObject)==null||s.add(f)}else{u.textContent=e.substring(l.endIndex),this.handleTag(l,u,c);const f=new ne.__webpack_exports__Inline(u);(a=this.uiObject)==null||a.add(f)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let s=!1;if(this._textMeshUi)for(let a=0;a<this._textMeshUi.length;a++){if(e[a]===!0)continue;s=!0;const l=this._textMeshUi[a];l.textContent&&(du(l,n),e[a]=!0)}if(!s)break;yield}}handleTag(e,i,n){if(!e.isEndTag){if(e.type.includes("color")){const s=new Rp(e,{color:i.color});if(n.push(s),e.type.length>6){const a=parseInt("0x"+e.type.substring(7));i.color=a}else i.color=new d.Color(1,1,1)}else if(e.type=="b"){this.setFont(i,1);const s=new Rp(e,{fontWeight:700});n.push(s)}else if(e.type=="i"){this.setFont(i,2);const s=new Rp(e,{fontStyle:"italic"});n.push(s)}}}getText(e,i,n){return e.substring(i.endIndex,n.startIndex)}getNextTag(e,i=0){const n=e.indexOf("<",i),s=e.indexOf(">",n);if(n>=0&&s>=0){const a=e.substring(n+1,s);return{type:a,startIndex:n,endIndex:s+1,isEndTag:a.startsWith("/")}}return null}setFont(e,i){if(!this.font)return;const n=this.font,s=this.getFamilyNameWithCorrectSuffix(n,i);Xo&&console.log("Selected font family:"+s);let a=ne.__webpack_exports__FontLibrary.getFontFamily(s);switch(a||(a=ne.__webpack_exports__FontLibrary.addFontFamily(s)),e.fontFamily=a,i){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let l=a.getVariant(e.fontWeight,e.fontStyle);if(!l){let c=s;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=s;h!=null&&h.endsWith(".png")||(h+=".png"),l=a.addVariant(e.fontWeight,e.fontStyle,c,h),l==null||l.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,i){var u;const n=e.lastIndexOf("-");if(n<0)return e;const s=(u=e.substring(n+1))==null?void 0:u.toLowerCase();if(JO.includes(s))return Xo&&console.warn("Unsupported font style: "+s),e;const a=e.lastIndexOf("/");let l=e;a>=0&&(l=l.substring(a+1));const c=l[0]===l[0].toUpperCase(),h=e.substring(0,n);switch(Xo&&console.log("Select font: ",e,ax[i],l,c,h),i){case 0:return c?h+"-Regular":h+"-regular";case 1:return c?h+"-Bold":h+"-bold";case 2:return c?h+"-Italic":h+"-italic";case 3:return c?h+"-BoldItalic":h+"-bolditalic";default:return e}}}zs([m()],Dt.prototype,"alignment",2);zs([m()],Dt.prototype,"verticalOverflow",2);zs([m()],Dt.prototype,"horizontalOverflow",2);zs([m()],Dt.prototype,"lineSpacing",2);zs([m()],Dt.prototype,"supportRichText",2);zs([m(URL)],Dt.prototype,"font",2);zs([m()],Dt.prototype,"fontStyle",2);zs([m()],Dt.prototype,"text",1);zs([m()],Dt.prototype,"fontSize",1);class Rp{constructor(t,e){r(this,"tag");r(this,"previousValues");this.tag=t,this.previousValues=e}}const JO=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class cr{constructor(t){r(this,"id");r(this,"content","");r(this,"font",[]);r(this,"pointSize",144);r(this,"width");r(this,"height");r(this,"depth");r(this,"wrapMode");r(this,"horizontalAlignment");r(this,"verticalAlignment");r(this,"material");this.id=t}static getId(){return this.global_id++}setDepth(t){return this.depth=t,this}setPointSize(t){return this.pointSize=t,this}setHorizontalAlignment(t){return this.horizontalAlignment=t,this}setVerticalAlignment(t){return this.verticalAlignment=t,this}writeTo(t,e){var n;e.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),e.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),e.closeBlock(")"),e.beginBlock(),this.content&&e.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const i=this.font.map(s=>`"${s}"`).join(", ");e.appendLine(`string[] font = [ ${i} ]`),e.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&e.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&e.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&e.appendLine(`double depth = ${this.depth}`),this.wrapMode&&e.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&e.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&e.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&e.appendLine(`rel material:binding = </StageRoot/Materials/${rf(this.material)}>`),e.closeBlock()}}r(cr,"global_id",0);class gy{static singleLine(t,e,i){const n=new cr("text_"+cr.getId());return n.content=t,e&&(n.pointSize=e),i&&(n.depth=i),n}static multiLine(t,e,i,n,s,a){const l=new cr("text_"+cr.getId());return l.content=t,l.width=e,l.height=i,l.horizontalAlignment=n,l.verticalAlignment=s,a!==void 0&&(l.wrapMode=a),l}}const ek=new d.Matrix4().makeRotationY(Math.PI),tk=new d.Matrix4().makeScale(-1,1,-1);class pf{get extensionName(){return"text"}exportText(t,e,i){const n=C.getComponent(t,Dt);if(!n)return;const s=C.getComponent(t,wn);let a=100,l=100;s&&(a=s.width,l=s.height);const c=ek.clone();s&&c.premultiply(tk),e.setMatrix(c);const h=n.color.clone();e.material=new d.MeshStandardMaterial({color:h,emissive:h}),e.addEventListener("serialize",(u,f)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const g=gy.multiLine(p,a,l,"center","bottom","flowing");this.setTextAlignment(g,n.alignment),this.setOverflow(g,n),e.material&&(g.material=e.material),g.pointSize=this.convertToTextSize(n.fontSize),g.depth=.001,g.writeTo(void 0,u)})}convertToTextSize(t){return 1/.0502*144*t}setOverflow(t,e){e.horizontalOverflow?t.wrapMode="singleLine":t.wrapMode="flowing"}setTextAlignment(t,e){switch(e){case tt.LowerLeft:case tt.MiddleLeft:case tt.UpperLeft:t.horizontalAlignment="left";break;case tt.LowerCenter:case tt.MiddleCenter:case tt.UpperCenter:t.horizontalAlignment="center";break;case tt.LowerRight:case tt.MiddleRight:case tt.UpperRight:t.horizontalAlignment="right";break}switch(e){case tt.LowerLeft:case tt.LowerCenter:case tt.LowerRight:t.verticalAlignment="bottom";break;case tt.MiddleLeft:case tt.MiddleCenter:case tt.MiddleRight:t.verticalAlignment="middle";break;case tt.UpperLeft:case tt.UpperCenter:case tt.UpperRight:t.verticalAlignment="top";break}}}var ik=Object.defineProperty,Ke=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&ik(t,e,n),n};const Tb=S("debuguilayout");class Hr{constructor(){r(this,"left",0);r(this,"right",0);r(this,"top",0);r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ke([m()],Hr.prototype,"left");Ke([m()],Hr.prototype,"right");Ke([m()],Hr.prototype,"top");Ke([m()],Hr.prototype,"bottom");class Di extends I{constructor(){super(...arguments);r(this,"_rectTransform",null);r(this,"_needsUpdate",!1);r(this,"childAlignment",0);r(this,"reverseArrangement",!1);r(this,"spacing",0);r(this,"padding");r(this,"minWidth",0);r(this,"minHeight",0);r(this,"flexibleHeight",0);r(this,"flexibleWidth",0);r(this,"preferredHeight",0);r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Tb&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){Tb&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(wn);const e=this.gameObject.getComponentInParent(Ja);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Ja);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ke([m()],Di.prototype,"childAlignment");Ke([m()],Di.prototype,"reverseArrangement");Ke([m()],Di.prototype,"spacing");Ke([m(Hr)],Di.prototype,"padding");Ke([m()],Di.prototype,"minWidth");Ke([m()],Di.prototype,"minHeight");Ke([m()],Di.prototype,"flexibleHeight");Ke([m()],Di.prototype,"flexibleWidth");Ke([m()],Di.prototype,"preferredHeight");Ke([m()],Di.prototype,"preferredWidth");class Fo extends Di{constructor(){super(...arguments);r(this,"childControlHeight",!0);r(this,"childControlWidth",!0);r(this,"childForceExpandHeight",!1);r(this,"childForceExpandWidth",!1);r(this,"childScaleHeight",!1);r(this,"childScaleWidth",!1)}onCalculateLayout(e){var F;const i=this.primaryAxis,n=e.width;let s=n;const a=e.height;let l=a;s-=this.padding.horizontal,l-=this.padding.vertical,i==="x"?this.padding.horizontal:this.padding.vertical;const c=i==="x",h=c?"y":"x",u=c?this.childControlWidth:this.childControlHeight,f=c?this.childControlHeight:this.childControlWidth,p=c?this.childForceExpandWidth:this.childForceExpandHeight,g=c?this.childForceExpandHeight:this.childForceExpandWidth,y=c?l:s,b=c?n:a,_=.5*(c?this.childAlignment%3:Math.floor(this.childAlignment/3));let v=0;c?v+=this.padding.left:v+=this.padding.top;let w=0,x=0;for(let D=0;D<this.gameObject.children.length;D++){const A=this.gameObject.children[D],T=C.getComponent(A,wn);T!=null&&T.activeAndEnabled&&(x+=1,c?w+=T.width:w+=T.height)}let O=0;const E=this.spacing*(x-1);if(p||u){let D=0;c?D=s-=E:D=l-=E,x>0&&(O=D/x)}let M=0;M+=this.padding.left,M-=this.padding.right,_!==0&&(v=b-w,v*=_,v-=E*_,c?(v-=this.padding.right*_,v+=this.padding.left*(1-_),v<this.padding.left&&(v=this.padding.left)):(v-=this.padding.bottom*_,v+=this.padding.top*(1-_),v<this.padding.top&&(v=this.padding.top)));let R=1;for(let D=0;D<this.gameObject.children.length;D++){const A=this.gameObject.children[D],T=C.getComponent(A,wn);if(T!=null&&T.activeAndEnabled){(F=T.pivot)==null||F.set(.5,.5),T.anchorMin.set(0,1),T.anchorMax.set(0,1);const G=n*.5+M*.5;T.anchoredPosition.x!==G&&(T.anchoredPosition.x=G);const B=a*-.5;T.anchoredPosition.y!==B&&(T.anchoredPosition.y=B),g&&f&&T.sizeDelta[h]!==y&&(T.sizeDelta[h]=y),p&&u&&T.sizeDelta[i]!==O&&(T.sizeDelta[i]=O);const L=c?T.width:T.height,N=L*.5;if(v+=N,p){const Z=O*R-O*.5;Z>v&&(v=Z-O*.5+L+this.padding.left,v-=N)}let Y=v;i==="y"&&(Y=-Y),T.anchoredPosition[i]!==Y&&(T.anchoredPosition[i]=Y),v+=N,v+=this.spacing,R+=1}}}}Ke([m()],Fo.prototype,"childControlHeight");Ke([m()],Fo.prototype,"childControlWidth");Ke([m()],Fo.prototype,"childForceExpandHeight");Ke([m()],Fo.prototype,"childForceExpandWidth");Ke([m()],Fo.prototype,"childScaleHeight");Ke([m()],Fo.prototype,"childScaleWidth");class yy extends Fo{get primaryAxis(){return"y"}}class _y extends Fo{get primaryAxis(){return"x"}}class by extends Di{onCalculateLayout(){}}var nk=Object.defineProperty,sk=Object.getOwnPropertyDescriptor,as=(o,t,e,i)=>{for(var n=i>1?void 0:i?sk(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&nk(t,e,n),n},lx=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(lx||{});const Ep=S("debuguilayout"),Yi=class cx extends Ph{constructor(){super(...arguments);r(this,"_renderOnTop");r(this,"_depthWrite",!1);r(this,"_doubleSided",!0);r(this,"_castShadows",!1);r(this,"_receiveShadows",!1);r(this,"_renderMode",-1);r(this,"_rootCanvas");r(this,"_scaleFactor",1);r(this,"worldCamera");r(this,"planeDistance",-1);r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this));r(this,"previousParent",null);r(this,"_lastMatrixWorld",null);r(this,"_rectTransforms",[]);r(this,"_layoutGroups",new Map);r(this,"_receivers",[]);r(this,"onBeforeRenderRoutine",()=>{var e,i,n,s;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(i=this.context.xr)!=null&&i.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(n=this.shadowComponent)==null||n.updateMatrixWorld(!0),(s=this.shadowComponent)==null||s.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),Yt.ensureUpdateMeshUI(ne.ThreeMeshUI,this.context))});r(this,"onAfterRenderRoutine",()=>{var e,i,n,s,a;if(((e=this.context.xr)!=null&&e.isVR||(i=this.context.xr)!=null&&i.isPassThrough)&&this.screenspace){(n=this.previousParent)==null||n.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const h=this.context.mainCamera;h==null||h.add(this.gameObject)}else this.previousParent.add(this.gameObject);const l=this.context.renderer.autoClear,c=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),Yt.ensureUpdateMeshUI(ne.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=l,this.context.renderer.autoClearColor=c,this.previousParent.add(this.gameObject)}(a=this._lastMatrixWorld)==null||a.copy(this.gameObject.matrixWorld)});r(this,"_updateRenderSettingsRoutine");r(this,"_activeRenderMode",-1);r(this,"_lastWidth",-1);r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof cx||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,Ep&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new d.Matrix4,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);i!==-1&&this.context.post_render_callbacks.splice(i,1)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const i=this._rectTransforms.indexOf(e);i!==-1&&this._rectTransforms.splice(i,1)}registerLayoutGroup(e){const i=e.gameObject;this._layoutGroups.set(i,e)}unregisterLayoutGroup(e){const i=e.gameObject;this._layoutGroups.delete(i)}registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const i=this._receivers.indexOf(e);i!==-1&&this._receivers.splice(i,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await eh(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const i of this._receivers)(e=i.onBeforeCanvasRender)==null||e.call(i,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new d.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);Ep&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const i of this._rectTransforms){e&&i.markDirty();let n=this._layoutGroups.get(i.gameObject);i.isDirty&&!n&&(n=i.gameObject.getComponentInParent(Di)),(i.isDirty||n!=null&&n.isDirty)&&(Ep&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),n==null||n.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),we.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),du(this.shadowComponent,this);for(const e of C.getComponentsInChildren(this.gameObject,Qi))du(e.shadowComponent,this)}}onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let i=this.context.mainCameraComponent,n=10;switch(i&&i.nearClipPlane>0&&i.farClipPlane>0&&(n=z.lerp(i.nearClipPlane,i.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(i=this.worldCamera),this.planeDistance>0&&(n=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!i)return;const s=n+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-s,this.gameObject.quaternion.identity();const a=this.gameObject.getComponent(wn);let l=!1;a.sizeDelta.x!==this.context.domWidth&&(l=!0),a.sizeDelta.y!==this.context.domHeight&&(l=!0);const c=i.fieldOfView*Math.PI/180,h=2*Math.tan(c/2)*Math.abs(s);this.gameObject.scale.x=h/this.context.domHeight,this.gameObject.scale.y=h/this.context.domHeight,this.gameObject.scale.z=.01,l&&(a.sizeDelta.x=this.context.domWidth,a.sizeDelta.y=this.context.domHeight,a==null||a.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};as([m()],Yi.prototype,"renderOnTop",1);as([m()],Yi.prototype,"depthWrite",1);as([m()],Yi.prototype,"doubleSided",1);as([m()],Yi.prototype,"castShadows",1);as([m()],Yi.prototype,"receiveShadows",1);as([m()],Yi.prototype,"renderMode",1);as([m(Yi)],Yi.prototype,"rootCanvas",1);as([m()],Yi.prototype,"scaleFactor",1);as([m(ai)],Yi.prototype,"worldCamera",2);as([m()],Yi.prototype,"planeDistance",2);let Ja=Yi;var ok=Object.defineProperty,rk=Object.getOwnPropertyDescriptor,vy=(o,t,e,i)=>{for(var n=i>1?void 0:i?rk(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&ok(t,e,n),n};class ko extends I{constructor(){super(...arguments);r(this,"_alpha",1);r(this,"interactable",!0);r(this,"blocksRaycasts",!0);r(this,"_isDirty",!1);r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),we.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of C.getComponentsInChildren(this.gameObject,Qi,this._buffer)){const i=e;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}vy([m()],ko.prototype,"alpha",1);vy([m()],ko.prototype,"interactable",2);vy([m()],ko.prototype,"blocksRaycasts",2);class wy{get extensionName(){return"tmui"}onExportObject(t,e,i){const n=C.getComponent(t,Ja);if(n&&n.enabled&&n.renderMode===lx.WorldSpace){const s=new pf,a=C.getComponent(t,wn),l=C.getComponent(t,ko),c=new Array;if(a){if(!C.isActiveSelf(t)){const f=C.isActiveSelf(t);C.setActive(t,!0),a.onEnable(),a.updateTransform(),c.push(()=>{a.onDisable(),C.setActive(t,f)})}t.traverse(f=>{if(!C.isActiveInHierarchy(f)){const p=C.isActiveSelf(f);C.setActive(f,!0);const g=C.getComponent(f,Qi);g&&(g.onEnable(),c.push(()=>{g.onDisable()}));const y=C.getComponent(f,wn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),c.push(()=>{y.onDisable()}));const b=C.getComponent(f,Dt);b&&(b.onEnable(),c.push(()=>{b.onDisable()})),c.push(()=>{C.setActive(f,p)})}}),a.width,a.height;const h=Et.createEmpty(),u=a.shadowComponent;if(e.add(h),u){const f=u.matrix;h.setMatrix(f);const p=new Map,g=new Map;p.set(u,h),g.set(u,l?l.alpha:1),u.traverse(y=>{if(y===u)return;const b=Et.createEmpty();b.setMatrix(y.matrix);const _=y.parent,v=!!_&&typeof _.textContent=="string"&&_.textContent.length>0;let w=g.get(_)||1;const x=C.getComponent(y,ko);if(x&&(w*=x.alpha),y instanceof d.Mesh&&v){const E=y[Si];E?s.exportText(E.gameObject,b,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof d.Mesh&&!v){const E=y.geometry.clone();E.scale(1,1,-1),this.flipWindingOrder(E),b.geometry=E;const M=new d.Color,R=y.material.opacity;M.copy(y.material.color),b.material=new d.MeshBasicMaterial({color:M,opacity:R*w,map:y.material.map,transparent:!0})}p.set(y,b),g.set(y,w);const O=p.get(_);if(!O){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}O.add(b)})}}for(const h of c)h()}}flipWindingOrder(t){const e=t.index.array;for(let i=0,n=e.length/3;i<n;i++){const s=e[i*3];e[i*3]=e[i*3+2],e[i*3+2]=s}t.index.needsUpdate=!0}}const ic=S("debugusdz");function ak(o,t){var l;const e=[],i=C.getComponentsInChildren(o,xt),n=C.getComponentsInChildren(o,Tt),s=new Array,a=new Array;if(t.injectImplicitBehaviours)for(const c of i){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;const h=c.runtimeAnimatorController.activeState;if(!h||!h.motion||!h.motion.clip||((l=h.motion.clip.tracks)==null?void 0:l.length)<1||s.includes(c))continue;const u=new $c;u.animator=c,u.stateName=h.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const f=new d.Object3D;C.addComponent(f,u),a.push(f),s.push(c),o.add(f)}else for(const c of i){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;ic&&console.log(c);const h=[];for(const u of c.runtimeAnimatorController.enumerateActions()){ic&&console.log(u);const f=u.getClip();h.includes(f)||h.push(f)}e.push({root:c.gameObject,clips:h})}if(t.injectImplicitBehaviours)for(const c of n){if(!c||!c.clip||!c.enabled||!c.playAutomatically||s.includes(c))continue;const h=new $c;h.animation=c,h.stateName=c.clip.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const u=new d.Object3D;C.addComponent(u,h),a.push(u),s.push(c),o.add(u)}else for(const c of n){ic&&console.log(c);const h=[];for(const u of c.animations)h.includes(u)||h.push(u);e.push({root:c.gameObject,clips:h})}ic&&(e==null?void 0:e.length)>0&&console.log("USDZ Animation Clips without behaviours",e);for(const c of e)for(const h of c.clips)t.registerAnimation(c.root,h);return a}function lk(o,t){const e=C.getComponentsInChildren(o,qi),i=C.getComponentsInChildren(o,Mo),n=new Array,s=new Array;ic&&console.log({audioSources:e,playAudioOnClicks:i});for(const a of i){if(!a.target)continue;const l=e.indexOf(a.target);l>-1&&e.splice(l,1)}for(const a of e){if(!a||!a.clip||a.volume<=0||n.includes(a))continue;const l=new Mo;l.target=a,l.name="PlayAudioOnClick_implicitAtStart_",l.trigger="start";const c=new d.Object3D;C.addComponent(c,l),console.log("implicit PlayAudioOnStart",c,l),s.push(c),n.push(a),o.add(c)}return s}function ck(o){return new vt("DisableAtStart",wt.sceneStartTrigger(),fe.fadeAction(o,0,!1))}function Ab(o,t){const e=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(e)return e;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",t?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const a=document.createElement("img");return a.id="button",s.appendChild(a),o.domElement.shadowRoot.appendChild(i),s}var hk=Object.defineProperty,Ct=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&hk(t,e,n),n};const yi=S("debugusdz"),dk=S("debugusdzpruning");class qr{constructor(){r(this,"callToAction");r(this,"checkoutTitle");r(this,"checkoutSubtitle");r(this,"callToActionURL")}}Ct([m()],qr.prototype,"callToAction");Ct([m()],qr.prototype,"checkoutTitle");Ct([m()],qr.prototype,"checkoutSubtitle");Ct([m()],qr.prototype,"callToActionURL");var Ps;const pi=(Ps=class extends I{constructor(){super(...arguments);r(this,"objectToExport");r(this,"autoExportAnimations",!0);r(this,"autoExportAudioSources",!0);r(this,"exportFileName");r(this,"customUsdzFile");r(this,"customBranding");r(this,"anchoringType","plane");r(this,"maxTextureSize",2048);r(this,"planeAnchoringAlignment","horizontal");r(this,"interactive",!0);r(this,"physics",!0);r(this,"allowCreateQuicklookButton",!0);r(this,"quickLookCompatible",!0);r(this,"extensions",[]);r(this,"link");r(this,"button");r(this,"onClickedOpenInARElement",e=>{e.preventDefault(),this.exportAndOpen()});r(this,"_currentExportTasks",new Map);r(this,"_previousTimeScale",1);r(this,"lastCallback");r(this,"_rootSessionRootWasAppliedTo",null);r(this,"_rootPositionBeforeExport",new d.Vector3);r(this,"_rootRotationBeforeExport",new d.Quaternion);r(this,"_rootScaleBeforeExport",new d.Vector3)}start(){var e,i,n;yi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((i=(e=this.objectToExport)==null?void 0:e.children)!=null&&i.length)&&!((n=this.objectToExport)!=null&&n.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var n;const e=exports.DeviceUtilities.supportsQuickLookAR(),i=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(yi||e||i)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=Ab(this.context,e),this.link.addEventListener("message",this.lastCallback)),yi&&Ee("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement),Rc.registerExporter(this)}onDisable(){var e,i,n;(e=this.button)==null||e.remove(),(i=this.link)==null||i.removeEventListener("message",this.lastCallback),yi&&Ee("USDZ Exporter disabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.removeEventListener("click",this.onClickedOpenInARElement),Rc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var n;let e=this.exportFileName??((n=this.objectToExport)==null?void 0:n.name)??this.name;if(e+="-"+Uw(),Qn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=Ab(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return yi&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const i=await this.export(this.objectToExport);return i?(yi&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(i,e),i):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const i=this._currentExportTasks.get(e);if(i)return i;const n=this.internalExport(e);return n instanceof Promise?(this._currentExportTasks.set(e,n),n.then(s=>(this._currentExportTasks.delete(e),s)).catch(s=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",s),null))):n}async internalExport(e){oe.start("export-usdz",{onProgress:M=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:M}}))}}),oe.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),oe.report("export-usdz",{message:"Load progressive textures",autoStep:5}),oe.start("export-usdz-textures","export-usdz");const i=C.getComponentsInChildren(e,fi);for(const M of i)M&&M.enabled&&M.updateSprite(!0);const n=C.getComponentsInChildren(e,Ti),s=new Array;let a=0;for(const M of n){for(const R of M.sharedMeshes)if(R){const F=le.NEEDLE_progressive.assignMeshLOD(R,0);F instanceof Promise&&s.push(new Promise((D,A)=>{F.then(()=>{a++,oe.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:a,totalSteps:s.length}),D()}).catch(T=>A(T))}))}for(const R of M.sharedMaterials)if(R){const F=le.NEEDLE_progressive.assignTextureLOD(R,0);F instanceof Promise&&s.push(new Promise((D,A)=>{F.then(()=>{a++,oe.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:a,totalSteps:s.length}),D()}).catch(T=>A(T))}))}}yi&&Ee("Progressive Loading: "+s.length),await Promise.all(s),yi&&Ee("Progressive Loading: done"),oe.end("export-usdz-textures");const l=Qt.Global.Mask;Qt.Global.Set(Bn.AR);const c=new Ww,h=new af(this.quickLookCompatible);let u;const f=[];this.interactive&&(f.push(new fy),f.push(new Wr),globalThis.NEEDLE_USE_RAPIER&&C.getComponentsInChildren(e,ot).length>0&&(this.physics?(u=new py,f.push(u)):j()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),f.push(new pf),f.push(new wy));const p=[h,...f,...this.extensions],g={self:this,exporter:c,extensions:p,object:e};oe.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:g})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,oe.report("export-usdz","auto export animations and audio sources");const y=new Array;this.autoExportAnimations&&y.push(...ak(e,h)),p.find(M=>M.extensionName==="Audio")&&this.autoExportAudioSources&&y.push(...lk(e)),c.debug=yi,c.pruneUnusedNodes=!dk;const _=Qa.instance.objs.map(M=>M.batchedMesh);c.keepObject=M=>{let R=!0;const F=C.getComponent(M,Ti);return F&&!F.enabled&&(R=!1),R&&_.includes(M)&&(R=!1),R&&C.getComponentInParent(M,_h)&&(R=!1),R&&C.getComponentInParent(M,ss)&&(R=!1),yi&&!R&&console.log("USDZExporter: Discarding object",M),R},c.beforeWritingDocument=()=>{if(j()&&h&&u){const M=h.animatedRoots;for(const R of M){const F=C.getComponentsInChildren(R,ot).filter(A=>A.enabled),D=C.getComponents(R,ui).filter(A=>A.enabled&&!A.isTrigger);(F.length>0||D.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",R)}}};const v=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(M=>{M.visible||v.push(M)});const w=p.find(M=>M.extensionName==="Behaviour");this.interactive&&w&&v.length>0&&w.addBehavior(ck(v));let x=!0;this.quickLookCompatible&&!this.interactive&&(x=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),oe.report("export-usdz","Invoking exporter.parse");const O=await c.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:p,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:x}),E=new Blob([O],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,oe.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:g}));for(const M of y)C.destroy(M);return Qt.Global.Set(l),oe.end("export-usdz"),E}openInQuickLook(e,i){const n=e instanceof Blob?URL.createObjectURL(e):e,s=this.buildQuicklookOverlay();yi&&console.log("QuickLook Overlay",s);const a=s.callToAction?encodeURIComponent(s.callToAction):"",l=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",c=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=n+`#callToAction=${a}&checkoutTitle=${l}&checkoutSubtitle=${c}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=i+".usdz",this.link.click()}download(e,i){Ps.save(e,i)}static save(e,i){const n=document.createElement("a");n.style.display="none",document.body.appendChild(n),typeof e=="string"?n.href=e:n.href=URL.createObjectURL(e),n.download=i,n.click(),n.remove()}quicklookCallback(e){if((e==null?void 0:e.data)=="_apple_ar_quicklook_button_tapped"){yi&&me("Quicklook closed via call to action button");var i=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(i),!i.defaultPrevented){const n=new URLSearchParams(this.link.href);if(n){const s=n.get("callToActionURL");yi&&Ee("Quicklook url: "+s),s&&(Qn()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var n,s,a,l,c,h;const e={};return this.customBranding&&Object.assign(e,this.customBranding),Qn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(((n=e.callToAction)==null?void 0:n.length)||((s=e.checkoutTitle)==null?void 0:s.length)||((a=e.checkoutSubtitle)==null?void 0:a.length))&&((l=e.callToAction)!=null&&l.length||(e.callToAction="\0"),(c=e.checkoutTitle)!=null&&c.length||(e.checkoutTitle="\0"),(h=e.checkoutSubtitle)!=null&&h.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=C.findObjectOfType(ff);let i=C.getComponentInParent(this.objectToExport,is);i||(i=C.getComponentInChildren(this.objectToExport,is));let n=1,s=!1;const a=this.objectToExport;return e?n=e.arScale:i&&(n=i.arScale,s=i.invertForward),{scale:1/n,_invertForward:s,target:a,sessionRoot:(i==null?void 0:i.gameObject)??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:i,target:n,sessionRoot:s}=this.getARScaleAndTarget(),a=s==null?void 0:s.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=n,this._rootPositionBeforeExport.copy(n.position),this._rootRotationBeforeExport.copy(n.quaternion),this._rootScaleBeforeExport.copy(n.scale),n.scale.multiplyScalar(e),i&&n.quaternion.multiply(Ps.invertForwardQuaternion),n.updateMatrix(),n.updateMatrixWorld(!0),s&&a&&n.matrix.premultiply(a)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const i=Po.getOrCreate().createQuicklookButton();return i.parentNode||this.context.menu.appendChild(i),i}},r(Ps,"invertForwardMatrix",new d.Matrix4().makeRotationY(Math.PI)),r(Ps,"invertForwardQuaternion",new d.Quaternion().setFromEuler(new d.Euler(0,Math.PI,0))),Ps);Ct([m(d.Object3D)],pi.prototype,"objectToExport");Ct([m()],pi.prototype,"autoExportAnimations");Ct([m()],pi.prototype,"autoExportAudioSources");Ct([m()],pi.prototype,"exportFileName");Ct([m(URL)],pi.prototype,"customUsdzFile");Ct([m(qr)],pi.prototype,"customBranding");Ct([m()],pi.prototype,"anchoringType");Ct([m()],pi.prototype,"maxTextureSize");Ct([m()],pi.prototype,"planeAnchoringAlignment");Ct([m()],pi.prototype,"interactive");Ct([m()],pi.prototype,"physics");Ct([m()],pi.prototype,"allowCreateQuicklookButton");Ct([m()],pi.prototype,"quickLookCompatible");let Kn=pi;var uk=Object.defineProperty,fk=Object.getOwnPropertyDescriptor,xy=(o,t,e,i)=>{for(var n=fk(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&uk(t,e,n),n};class ml extends I{constructor(){super(...arguments);r(this,"_fog")}get fog(){return this._fog||(this._fog=new d.Fog(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}xy([m()],ml.prototype,"near");xy([m()],ml.prototype,"far");xy([m(d.Color)],ml.prototype,"color");var pk=Object.defineProperty,Sy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&pk(t,e,n),n};class Xr extends I{constructor(){super(...arguments);r(this,"objectBounds",!1);r(this,"color");r(this,"isGizmo",!0);r(this,"_gizmoObject",null);r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!rh||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new d.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=dg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),we.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var e;for(;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}Sy([m()],Xr.prototype,"objectBounds");Sy([m(d.Color)],Xr.prototype,"color");Sy([m()],Xr.prototype,"isGizmo");var mk=Object.defineProperty,Cy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&mk(t,e,n),n};class gl extends I{constructor(){super(...arguments);r(this,"isGizmo",!1);r(this,"color0");r(this,"color1");r(this,"gridHelper");r(this,"size");r(this,"divisions");r(this,"offset")}onEnable(){if(this.isGizmo&&!rh)return;const e=this.size,i=this.divisions;this.gridHelper||(this.gridHelper=new d.GridHelper(e,i,this.color0??new d.Color(.4,.4,.4),this.color1??new d.Color(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}Cy([m()],gl.prototype,"isGizmo");Cy([m(d.Color)],gl.prototype,"color0");Cy([m(d.Color)],gl.prototype,"color1");var gk=Object.defineProperty,Py=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&gk(t,e,n),n};class My extends I{constructor(){super(...arguments);r(this,"connectedBody");r(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(ot)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}Py([m(ot)],My.prototype,"connectedBody");class Oy extends My{createJoint(t,e){var i;(i=this.context.physics.engine)==null||i.addFixedJoint(t,e)}}class Rh extends My{constructor(){super(...arguments);r(this,"anchor");r(this,"axis")}createJoint(e,i){var n;this.axis&&this.anchor&&((n=this.context.physics.engine)==null||n.addHingeJoint(e,i,this.anchor,this.axis))}}Py([m(d.Vector3)],Rh.prototype,"anchor");Py([m(d.Vector3)],Rh.prototype,"axis");var yk=Object.defineProperty,_k=Object.getOwnPropertyDescriptor,ls=(o,t,e,i)=>{for(var n=i>1?void 0:i?_k(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&yk(t,e,n),n};function Tp(o){return o*Math.PI/180}const Lb=300,Zs=S("debuglights");class mi extends I{constructor(){super(...arguments);r(this,"type",0);r(this,"range",1);r(this,"spotAngle",1);r(this,"innerSpotAngle",1);r(this,"_color",new d.Color(16777215));r(this,"_shadowNearPlane",.1);r(this,"_shadowBias",0);r(this,"_shadowNormalBias",0);r(this,"_overrideShadowBiasSettings",!1);r(this,"_shadows",1);r(this,"lightmapBakeType",4);r(this,"_intensity",-1);r(this,"_shadowDistance");r(this,"shadowWidth");r(this,"shadowHeight");r(this,"_shadowResolution");r(this,"light");r(this,"_webXRStartedListener");r(this,"_webXREndedListener");r(this,"_webARRoot")}set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(e){var i,n;if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.camera)!==void 0)){const s=this.light.shadow.camera;s.near=e}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(e){var i,n;e!==this._shadowBias&&(this._shadowBias=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.bias)!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(e){var i,n;e!==this._shadowNormalBias&&(this._shadowNormalBias=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.normalBias)!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(e){var i;if(this._intensity=e,this.light){let n=1;if(this.context.isInXR&&this._webARRoot){const s=(i=this._webARRoot)==null?void 0:i.arScale;typeof s=="number"&&s>0&&(n/=s)}this.light.intensity=e*n}Zs&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}get shadowDistance(){const e=this.light;return e!=null&&e.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const i=this.light;if(i!=null&&i.shadow){const n=i.shadow.camera;n.far=e,n.updateProjectionMatrix()}}get shadowResolution(){const e=this.light;return e!=null&&e.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const i=this.light;i!=null&&i.shadow&&(i.shadow.mapSize.set(e,e),i.shadow.needsUpdate=!0)}get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new d.Color(this.color??16777215),Zs&&console.log(this.name,this)}onEnable(){Zs&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Zs&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),we.LateUpdate))}onDisable(){Zs&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(e){this._webARRoot=C.getComponentInParent(this.gameObject,is)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const i=new d.DirectionalLight(this.color,this.intensity*Math.PI);if(i.position.set(0,0,-Lb*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(i.target),Pr(i.target,0,0,0),this.light=i,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Zs){const l=new d.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const n=new d.SpotLight(this.color,this.intensity*Math.PI,this.range,Tp(this.spotAngle/2),1-Tp(this.innerSpotAngle/2)/Tp(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;const s=n.target;n.add(s),s.position.set(0,0,this.range),s.rotation.set(0,0,0);break;case 2:const a=new d.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=a;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Zs&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const i=this.light.shadow.camera;if(i.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?i.far=this._shadowDistance:i.far=Lb*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)i.left=-this.shadowWidth/2,i.right=this.shadowWidth/2;else{const n=this.gameObject.scale.x;i.left*=n,i.right*=n}if(this.shadowHeight!==void 0)i.top=this.shadowHeight/2,i.bottom=-this.shadowHeight/2;else{const n=this.gameObject.scale.y;i.top*=n,i.bottom*=n}this.light.shadow.needsUpdate=!0,Zs&&this.context.scene.add(new d.CameraHelper(i))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}r(mi,"allowChangingRendererShadowMapType",!0);ls([m()],mi.prototype,"type",2);ls([m(d.Color)],mi.prototype,"color",1);ls([m()],mi.prototype,"shadowNearPlane",1);ls([m()],mi.prototype,"shadowBias",1);ls([m()],mi.prototype,"shadowNormalBias",1);ls([m()],mi.prototype,"shadows",1);ls([m()],mi.prototype,"lightmapBakeType",2);ls([m()],mi.prototype,"intensity",1);ls([m()],mi.prototype,"shadowDistance",1);ls([m()],mi.prototype,"shadowResolution",1);new d.Vector3(0,0,0);var bk=Object.defineProperty,Eh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bk(t,e,n),n};const Ap=S("debuglods"),vk=S("nolods");class yl{constructor(){r(this,"screenRelativeTransitionHeight");r(this,"distance");r(this,"renderers")}}Eh([m()],yl.prototype,"screenRelativeTransitionHeight");Eh([m()],yl.prototype,"distance");Eh([m(Ti)],yl.prototype,"renderers");class wk{constructor(t){r(this,"model");this.model=t}get renderers(){return this.model.renderers}}class Th extends I{constructor(){super(...arguments);r(this,"fadeMode",0);r(this,"localReferencePoint");r(this,"lodCount",0);r(this,"size",0);r(this,"animateCrossFading",!1);r(this,"lodModels");r(this,"_lods",[]);r(this,"_settings",[]);r(this,"_lodsHandler");r(this,"_distanceFactor",1)}start(){if(Ap&&console.log("LODGROUP",this.name,this.lodModels,this),!vk&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const n of this.lodModels){const s=new wk(n);this._lods.push(s);for(const a of s.renderers)e.includes(a)||e.push(a)}this._lodsHandler=new Array;for(let n=0;n<e.length;n++){const s=new d.LOD;this._lodsHandler.push(s),this.gameObject.add(s)}const i=new d.Object3D;i.name="Cull "+this.name;for(let n=0;n<e.length;n++){const s=e[n],a=this._lodsHandler[n],l=s.gameObject;Ap&&console.log(n,l.name);for(const c of this._lods){const h=c.model.distance;let u=null;if(c.renderers.includes(s)?u=l:u=i,u.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${u.name}`);continue}Ap&&console.log("LEVEL",u.name,h),a.autoUpdate=!1,this.onAddLodLevel(a,u,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const i of this._lodsHandler){i.update(e);const n=i.getCurrentLevel(),s=i.levels[n];i.layers.mask=s.object.layers.mask}}onAddLodLevel(e,i,n){if(i===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",i.name,i);return}e.addLevel(i,n*this._distanceFactor,.01);const s={lod:e,levelIndex:e.levels.length-1,distance:n};this._settings.push(s)}distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const i of this._settings){const n=i.lod.levels[i.levelIndex];n.distance=i.distance*e}}}}Eh([m(d.Vector3)],Th.prototype,"localReferencePoint");Eh([m(yl)],Th.prototype,"lodModels");var xk=Object.defineProperty,Sk=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&xk(t,e,n),n};const wd=S("debugnestedgltf");class mf extends I{constructor(){super(...arguments);r(this,"filePath");r(this,"loadAssetInParent",!0);r(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(e){var i;(i=this.filePath)==null||i.beginListenDownload(e)}preload(){var e;(e=this.filePath)==null||e.preload()}async start(){var i,n,s,a,l;if(this._isLoadingOrDoneLoading)return;wd&&console.log(this,this.guid);const e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;const c=new xn;c.idProvider=new bt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;wd&&console.log("Load nested:",((i=this.filePath)==null?void 0:i.url)??this.filePath,this.gameObject.position);const u=await((s=(n=this.filePath)==null?void 0:n.instantiate)==null?void 0:s.call(this.filePath,c));wd&&console.log("Nested loaded:",((a=this.filePath)==null?void 0:a.url)??this.filePath,u),u&&this.loadAssetInParent!==!1&&(u.matrixAutoUpdate=!1,u.matrix.identity(),u.applyMatrix4(h),u.matrixAutoUpdate=!0,u.layers.disableAll(),u.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:u,assetReference:this.filePath}}))),wd&&console.log("Nested loading done:",((l=this.filePath)==null?void 0:l.url)??this.filePath,u)}}onDestroy(){var e;(e=this.filePath)==null||e.unload()}hash(e){let i=0;for(let n=0;n<e.length;n++)i=e.charCodeAt(n)+((i<<5)-i);return i}}Sk([m(te)],mf.prototype,"filePath");var Ck=Object.defineProperty,ky=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Ck(t,e,n),n};const Pk=S("debugnet"),gf=class Am extends I{constructor(){super(...arguments);r(this,"url",null);r(this,"urlParameterName",null);r(this,"localhost",null)}awake(){Pk&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Am.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const a=S(this.urlParameterName);a&&typeof a=="string"&&(e=a)}if(!e)return null;const n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n!=null&&n.groups?(n==null?void 0:n.groups.socket_prefix)?e:"wss://"+(n==null?void 0:n.groups.url):null}static GetUrl(e,i){let n=e;const s=Am.IsLocalNetwork()&&i;if(s&&(n=i),e!=null&&e.startsWith("/")){const a=s?n:window.location.origin;a!=null&&a.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),n=a+e}return n}static IsLocalNetwork(e=window.location.hostname){return Kt(e)}};ky([m()],gf.prototype,"url");ky([m()],gf.prototype,"urlParameterName");ky([m()],gf.prototype,"localhost");let Ry=gf;var Mk=Object.defineProperty,yf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Mk(t,e,n),n};class Qr extends I{constructor(){super(...arguments);r(this,"referenceSpace");r(this,"from");r(this,"affectPosition",!1);r(this,"affectRotation",!1);r(this,"alignLookDirection",!1);r(this,"levelLookDirection",!1);r(this,"levelPosition",!1);r(this,"positionOffset",new d.Vector3(0,0,0));r(this,"rotationOffset",new d.Vector3(0,0,0));r(this,"offset",new d.Vector3(0,0,0))}update(){if(!this.from)return;var e=Q(this.from),i=_e(this.from);this.offset.copy(this.positionOffset);const n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),e.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new d.Plane(this.gameObject.up,0),h=Q(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const u=new d.Vector3(0,0,0);c.projectPoint(e,u),e.copy(u)}this.affectPosition&&st(this.gameObject,e);const s=new d.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),a=new d.Quaternion().setFromEuler(s);this.affectRotation&&Hi(this.gameObject,i.multiply(a));const l=new d.Vector3;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}yf([m(C)],Qr.prototype,"referenceSpace");yf([m(C)],Qr.prototype,"from");yf([m(d.Vector3)],Qr.prototype,"positionOffset");yf([m(d.Vector3)],Qr.prototype,"rotationOffset");var Ok=Object.defineProperty,Uo=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Ok(t,e,n),n};class li{constructor(t=0,e=0){r(this,"time",0);r(this,"value",0);r(this,"inTangent",1/0);r(this,"inWeight");r(this,"outTangent",1/0);r(this,"outWeight");r(this,"weightedMode");this.time=t,this.value=e}}Uo([m()],li.prototype,"time");Uo([m()],li.prototype,"value");Uo([m()],li.prototype,"inTangent");Uo([m()],li.prototype,"inWeight");Uo([m()],li.prototype,"outTangent");Uo([m()],li.prototype,"outWeight");Uo([m()],li.prototype,"weightedMode");const hx=class nc{constructor(){r(this,"keys",[])}static linearFromTo(t,e,i){const n=new nc,s=new li;s.time=0,s.value=t;const a=new li;return a.time=i,a.value=e,n.keys.push(s,a),n}static constant(t){const e=new nc,i=new li;return i.time=0,i.value=t,e.keys.push(i),e}clone(){var e;const t=new nc;return t.keys=((e=this.keys)==null?void 0:e.map(i=>{const n=new li;return n.time=i.time,n.value=i.value,n.inTangent=i.inTangent,n.inWeight=i.inWeight,n.outTangent=i.outTangent,n.outWeight=i.outWeight,n.weightedMode=i.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(t){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=t)return this.keys[0].value;for(let e=0;e<this.keys.length;e++){const i=this.keys[e];if(i.time<=t)if(e+1<this.keys.length){const s=this.keys[e+1];if(s.time<t)continue;return!isFinite(i.outTangent)||!isFinite(s.inTangent)?i.value:nc.interpolateValue(t,i,s)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(t,e,i){const n=e.time,s=e.value,a=e.outTangent,l=i.time,c=i.value,h=i.inTangent,u=l-n,f=u*u,p=f*u,g=((a+h)*u-2*(c-s))/p,y=(3*(c-s)-(h+2*a)*u)/f,b=a,_=s,v=t-n,w=v*v,x=w*v;return g*x+y*w+b*v+_}};Uo([m(li)],hx.prototype,"keys");let Ah=hx;var kk=Object.defineProperty,P=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&kk(t,e,n),n};const xd=S("debugparticles");var bs=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(bs||{});class Yr{constructor(){r(this,"alphaKeys",[]);r(this,"colorKeys",[])}get duration(){return 1}evaluate(t,e){let i,n=0,s=null,a=0;for(let l=0;l<this.alphaKeys.length;l++){const c=this.alphaKeys[l];(c.time<t||!i)&&(i=c,n=l)}for(let l=0;l<this.colorKeys.length;l++){const c=this.colorKeys[l];(c.time<t||!s)&&(s=c,a=l)}if(s)if(a+1<this.colorKeys.length){const c=this.colorKeys[a+1],h=z.remap(t,s.time,c.time,0,1);e.r=z.lerp(s.color.r,c.color.r,h),e.g=z.lerp(s.color.g,c.color.g,h),e.b=z.lerp(s.color.b,c.color.b,h)}else e.r=s.color.r,e.g=s.color.g,e.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const c=this.alphaKeys[n+1],h=z.remap(t,i.time,c.time,0,1);e.alpha=z.lerp(i.alpha,c.alpha,h)}else e.alpha=i.alpha;return e}}P([m()],Yr.prototype,"alphaKeys");P([m()],Yr.prototype,"colorKeys");var Vc=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(Vc||{}),vu=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(vu||{});const Ns=class sc{constructor(){r(this,"mode","Constant");r(this,"constant");r(this,"constantMin");r(this,"constantMax");r(this,"curve");r(this,"curveMin");r(this,"curveMax");r(this,"curveMultiplier")}static constant(t){const e=new sc;return e.setConstant(t),e}static betweenTwoConstants(t,e){const i=new sc;return i.setMinMaxConstant(t,e),i}static curve(t,e=1){const i=new sc;return i.setCurve(t,e),i}setConstant(t){this.mode=0,this.constant=t}setMinMaxConstant(t,e){this.mode=3,this.constantMin=t,this.constantMax=e}setCurve(t,e=1){this.mode=1,this.curve=t,this.curveMultiplier=e}clone(){var e,i,n;const t=new sc;return t.mode=this.mode,t.constant=this.constant,t.constantMin=this.constantMin,t.constantMax=this.constantMax,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMin=(i=this.curveMin)==null?void 0:i.clone(),t.curveMax=(n=this.curveMax)==null?void 0:n.clone(),t.curveMultiplier=this.curveMultiplier,t}evaluate(t,e){const i=e===void 0?Math.random():e;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return t=z.clamp01(t),this.curve.evaluate(t)*this.curveMultiplier;case 2:case"TwoCurves":const n=t*this.curveMin.duration,s=t*this.curveMax.duration;return z.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return z.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(t)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(t){if(!t)return 0;let e=Number.MIN_VALUE;for(let i=0;i<t.keys.length;i++){const n=t.keys[i];n.value>e&&(e=n.value)}return e}};P([m()],Ns.prototype,"mode");P([m()],Ns.prototype,"constant");P([m()],Ns.prototype,"constantMin");P([m()],Ns.prototype,"constantMax");P([m(Ah)],Ns.prototype,"curve");P([m(Ah)],Ns.prototype,"curveMin");P([m(Ah)],Ns.prototype,"curveMax");P([m()],Ns.prototype,"curveMultiplier");let q=Ns;var Le;const zo=(Le=class{constructor(){r(this,"mode",0);r(this,"color");r(this,"colorMin");r(this,"colorMax");r(this,"gradient");r(this,"gradientMin");r(this,"gradientMax")}static constant(t){const e=new Le;return e.constant(t),e}static betweenTwoColors(t,e){const i=new Le;return i.betweenTwoColors(t,e),i}constant(t){return this.mode=0,this.color=t,this}betweenTwoColors(t,e){return this.mode=2,this.colorMin=t,this.colorMax=e,this}evaluate(t,e){const i=e===void 0?Math.random():e;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(t,Le._temp),Le._temp;case 2:case"TwoColors":return Le._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(t,Le._temp),this.gradientMax.evaluate(t,Le._temp2),Le._temp.lerp(Le._temp2,i);case 4:case"RandomColor":const s=Math.random();return this.gradientMin.evaluate(t,Le._temp),this.gradientMax.evaluate(t,Le._temp2),Le._temp.lerp(Le._temp2,s)}return Le._temp.set(16777215),Le._temp.alpha=1,Le._temp}},r(Le,"_temp",new ie(0,0,0,1)),r(Le,"_temp2",new ie(0,0,0,1)),Le);P([m()],zo.prototype,"mode");P([m(ie)],zo.prototype,"color");P([m(ie)],zo.prototype,"colorMin");P([m(ie)],zo.prototype,"colorMax");P([m(Yr)],zo.prototype,"gradient");P([m(Yr)],zo.prototype,"gradientMin");P([m(Yr)],zo.prototype,"gradientMax");let Kr=zo;var Lm=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(Lm||{});class It{constructor(){r(this,"cullingMode");r(this,"duration");r(this,"emitterVelocityMode");r(this,"flipRotation");r(this,"gravityModifier");r(this,"gravityModifierMultiplier");r(this,"loop");r(this,"maxParticles");r(this,"playOnAwake");r(this,"prewarm");r(this,"ringBufferLoopRange");r(this,"ringBufferMode");r(this,"scalingMode");r(this,"simulationSpace");r(this,"simulationSpeed");r(this,"startColor");r(this,"startDelay");r(this,"startDelayMultiplier");r(this,"startLifetime");r(this,"startLifetimeMultiplier");r(this,"startRotation");r(this,"startRotationMultiplier");r(this,"startRotation3D");r(this,"startRotationX");r(this,"startRotationXMultiplier");r(this,"startRotationY");r(this,"startRotationYMultiplier");r(this,"startRotationZ");r(this,"startRotationZMultiplier");r(this,"startSize");r(this,"startSize3D");r(this,"startSizeMultiplier");r(this,"startSizeX");r(this,"startSizeXMultiplier");r(this,"startSizeY");r(this,"startSizeYMultiplier");r(this,"startSizeZ");r(this,"startSizeZMultiplier");r(this,"startSpeed");r(this,"startSpeedMultiplier");r(this,"stopAction");r(this,"useUnscaledTime")}}P([m(q)],It.prototype,"gravityModifier");P([m(Kr)],It.prototype,"startColor");P([m(q)],It.prototype,"startDelay");P([m(q)],It.prototype,"startLifetime");P([m(q)],It.prototype,"startRotation");P([m(q)],It.prototype,"startRotationX");P([m(q)],It.prototype,"startRotationY");P([m(q)],It.prototype,"startRotationZ");P([m(q)],It.prototype,"startSize");P([m(q)],It.prototype,"startSizeX");P([m(q)],It.prototype,"startSizeY");P([m(q)],It.prototype,"startSizeZ");P([m(q)],It.prototype,"startSpeed");class wu{constructor(){r(this,"cycleCount");r(this,"maxCount");r(this,"minCount");r(this,"probability");r(this,"repeatInterval");r(this,"time");r(this,"count");r(this,"_performed",0)}reset(){this._performed=0}run(t){if(t<=this.time)return 0;let e=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(t>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:e=this.count.constant;break;case 3:e=z.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:e=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();e=z.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return e}}class $s{constructor(){r(this,"enabled");r(this,"bursts");r(this,"rateOverTime");r(this,"rateOverTimeMultiplier");r(this,"rateOverDistance");r(this,"rateOverDistanceMultiplier");r(this,"system")}get burstCount(){var t;return((t=this.bursts)==null?void 0:t.length)??0}reset(){var t;(t=this.bursts)==null||t.forEach(e=>e.reset())}getBurst(){let t=0;if(this.burstCount>0)for(let e=0;e<this.burstCount;e++){const i=this.bursts[e];this.system.main.loop&&i.time>=this.system.time&&i.reset(),t+=Math.round(i.run(this.system.time))}return t}}P([m()],$s.prototype,"enabled");P([m()],$s.prototype,"bursts");P([m(q)],$s.prototype,"rateOverTime");P([m()],$s.prototype,"rateOverTimeMultiplier");P([m(q)],$s.prototype,"rateOverDistance");P([m()],$s.prototype,"rateOverDistanceMultiplier");class _f{constructor(){r(this,"enabled");r(this,"color")}}P([m(Kr)],_f.prototype,"color");class Zr{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_time",0);r(this,"_temp",new d.Vector3)}evaluate(t,e,i){if(e||(e=this._temp),!this.enabled)return e.x=e.y=e.z=1,e;if(this.separateAxes)e.x=this.x.evaluate(t,i)*this.xMultiplier,e.y=this.y.evaluate(t,i)*this.yMultiplier,e.z=this.z.evaluate(t,i)*this.zMultiplier;else{const n=this.size.evaluate(t,i)*this.sizeMultiplier;e.x=n}return e}}P([m(q)],Zr.prototype,"size");P([m(q)],Zr.prototype,"x");P([m(q)],Zr.prototype,"y");P([m(q)],Zr.prototype,"z");var gn;const Ze=(gn=class{constructor(){r(this,"shapeType",5);r(this,"enabled",!0);r(this,"alignToDirection",!1);r(this,"angle",0);r(this,"arc",360);r(this,"arcSpread");r(this,"arcSpeedMultiplier");r(this,"arcMode");r(this,"boxThickness");r(this,"position");r(this,"rotation");r(this,"_rotation",new d.Euler);r(this,"scale");r(this,"radius");r(this,"radiusThickness");r(this,"sphericalDirectionAmount");r(this,"randomDirectionAmount");r(this,"randomPositionAmount");r(this,"meshShapeType");r(this,"meshRenderer");r(this,"_meshObj");r(this,"_meshGeometry");r(this,"system");r(this,"_space");r(this,"_worldSpaceMatrix",new d.Matrix4);r(this,"_worldSpaceMatrixInverse",new d.Matrix4);r(this,"_vector",new d.Vector3(0,0,0));r(this,"_temp",new d.Vector3(0,0,0));r(this,"_triangle",new d.Triangle);r(this,"_dir",new d.Vector3);r(this,"_loopTime",0);r(this,"_loopDirection",1);xd&&console.log(this)}get type(){return vu[this.shapeType]}initialize(t){this.onInitialize(t),t.position.x=this._vector.x,t.position.y=this._vector.y,t.position.z=this._vector.z}toJSON(){return this}clone(){return new gn}setMesh(t){this.meshRenderer=t,t?(this._meshObj=t.sharedMeshes[Math.floor(Math.random()*t.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(t,e){}onUpdate(t,e,i,n){this.system=t,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(t){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=z.toRadians(this.rotation.x),this._rotation.y=z.toRadians(this.rotation.y),this._rotation.z=z.toRadians(this.rotation.z),this._rotation.order="ZYX",t.applyEuler(this._rotation)),e}onInitialize(t){this._vector.set(0,0,0),t.mesh=void 0,t.mesh_geometry=void 0;const e=this._temp.copy(this.position),i=this._space===1;i&&e.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:xd&&$.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const s=this.meshRenderer;(s==null?void 0:s.destroyed)==!1&&this.setMesh(s);const a=t.mesh=this._meshObj,l=t.mesh_geometry=this._meshGeometry;if(a&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(a.matrixWorld),t.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),u=Math.random();h+u>1&&(h=1-h,u=1-u);const f=Math.floor(Math.random()*(c.count/3));let p=f*3,g=f*3+1,y=f*3+2;p=c.getX(p),g=c.getX(g),y=c.getX(y);const b=l.getAttribute("position");this._triangle.a.fromBufferAttribute(b,p),this._triangle.b.fromBufferAttribute(b,g),this._triangle.c.fromBufferAttribute(b,y),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,u).addScaledVector(this._triangle.c,1-(h+u)),this._vector.applyMatrix4(a.matrixWorld),t.mesh_normal=f}}break}break;default:this._vector.set(0,0,0),j()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",vu[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),xd&&$.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(t,e){var i;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const n=e.x,s=e.y,a=e.z;this._dir.set(n,s,a),(i=this.system)!=null&&i.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=t.mesh,c=t.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),u=t.mesh_normal;this._dir.fromBufferAttribute(h,u)}break;case 1:break;case 2:{const h=c.index;if(h){const u=t.mesh_normal,f=h.getX(u*3),p=h.getX(u*3+1),g=h.getX(u*3+2),y=c.getAttribute("position"),b=V(),_=V(),v=V();b.fromBufferAttribute(y,f),_.fromBufferAttribute(y,p),v.fromBufferAttribute(y,g),b.sub(_),v.sub(_),b.cross(v),this._dir.copy(b).multiplyScalar(-1);const w=_e(l);this._dir.applyQuaternion(w)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),xd&&($.DrawSphere(e,.01,8925952,.5,!0),$.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(t,e){if(e<=0)return;const i=gn._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=e*this.scale.x,i.y*=e*this.scale.y,i.z*=e*this.scale.z,t.add(i)}randomizeDirection(t,e){if(e===0)return;const i=gn._randomQuat,n=gn._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,e*Math.random()*Math.PI),t.applyQuaternion(i)}spherizeDirection(t,e){if(e===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),s=Math.sin(n)*Math.cos(i),a=Math.sin(n)*Math.sin(i),l=Math.cos(n),c=new d.Vector3(s,a,l);t.lerp(c,e)}randomSpherePoint(t,e,i,n,s){const a=Math.random(),l=Math.random(),c=2*Math.PI*a*(n/360),h=Math.acos(2*l-1),u=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*e,f=t.x+this.scale.x*(-u*Math.sin(h)*Math.cos(c)),p=t.y+this.scale.y*(u*Math.sin(h)*Math.sin(c)),g=t.z+this.scale.z*(u*Math.cos(h));s.x=f,s.y=p,s.z=g}randomCirclePoint(t,e,i,n,s){const a=Math.random(),l=2*Math.PI*a*(n/360),c=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*e,h=t.x+this.scale.x*c*Math.cos(l),u=t.y+this.scale.y*c*Math.sin(l),f=t.z;s.x=h,s.y=u,s.z=f}randomConePoint(t,e,i,n,s,a,l){let c=0,h=0;switch(a){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let u=2*Math.PI*c*(s/360);switch(a){case 2:case 1:u+=Math.PI+.5,u+=this._loopTime*Math.PI*2,u%=z.toRadians(s);break}const f=Math.acos(2*h-1),p=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=t.x+-p*Math.sin(f)*Math.cos(u),y=t.y+p*Math.sin(f)*Math.sin(u),b=t.z;l.x=g*this.scale.x,l.y=y*this.scale.y,l.z=b*this.scale.z}},r(gn,"_randomQuat",new d.Quaternion),r(gn,"_tempVec",new d.Vector3),gn);P([m()],Ze.prototype,"shapeType");P([m()],Ze.prototype,"enabled");P([m()],Ze.prototype,"alignToDirection");P([m()],Ze.prototype,"angle");P([m()],Ze.prototype,"arc");P([m()],Ze.prototype,"arcSpread");P([m()],Ze.prototype,"arcSpeedMultiplier");P([m()],Ze.prototype,"arcMode");P([m(d.Vector3)],Ze.prototype,"boxThickness");P([m(d.Vector3)],Ze.prototype,"position");P([m(d.Vector3)],Ze.prototype,"rotation");P([m(d.Vector3)],Ze.prototype,"scale");P([m()],Ze.prototype,"radius");P([m()],Ze.prototype,"radiusThickness");P([m()],Ze.prototype,"sphericalDirectionAmount");P([m()],Ze.prototype,"randomDirectionAmount");P([m()],Ze.prototype,"randomPositionAmount");P([m()],Ze.prototype,"meshShapeType");P([m(vh)],Ze.prototype,"meshRenderer");let Ey=Ze;class be{constructor(){r(this,"damping");r(this,"enabled");r(this,"frequency");r(this,"octaveCount");r(this,"octaveMultiplier");r(this,"octaveScale");r(this,"positionAmount");r(this,"quality");r(this,"remap");r(this,"remapEnabled");r(this,"remapMultiplier");r(this,"remapX");r(this,"remapXMultiplier");r(this,"remapY");r(this,"remapYMultiplier");r(this,"remapZ");r(this,"remapZMultiplier");r(this,"scrollSpeedMultiplier");r(this,"separateAxes");r(this,"strengthMultiplier");r(this,"strengthX");r(this,"strengthXMultiplier");r(this,"strengthY");r(this,"strengthYMultiplier");r(this,"strengthZ");r(this,"strengthZMultiplier");r(this,"_noise");r(this,"_time",0);r(this,"_temp",new d.Vector3)}update(t){this._time+=t.time.deltaTime*this.scrollSpeedMultiplier}apply(t,e,i,n,s,a){if(!this.enabled)return;this._noise||(this._noise=ae.createNoise4D(()=>0));const l=this._temp.set(e.x,e.y,e.z).multiplyScalar(this.frequency),c=this._noise(l.x,l.y,l.z,this._time),h=this._noise(l.x,l.y,l.z,this._time+1e3*this.frequency),u=this._noise(l.x,l.y,l.z,this._time+2e3*this.frequency);this._temp.set(c,h,u).normalize();const f=s/a;let p=this.positionAmount.evaluate(f);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(f)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}P([m()],be.prototype,"damping");P([m()],be.prototype,"enabled");P([m()],be.prototype,"frequency");P([m()],be.prototype,"octaveCount");P([m()],be.prototype,"octaveMultiplier");P([m()],be.prototype,"octaveScale");P([m(q)],be.prototype,"positionAmount");P([m()],be.prototype,"quality");P([m(q)],be.prototype,"remap");P([m()],be.prototype,"remapEnabled");P([m()],be.prototype,"remapMultiplier");P([m(q)],be.prototype,"remapX");P([m()],be.prototype,"remapXMultiplier");P([m(q)],be.prototype,"remapY");P([m()],be.prototype,"remapYMultiplier");P([m(q)],be.prototype,"remapZ");P([m()],be.prototype,"remapZMultiplier");P([m()],be.prototype,"scrollSpeedMultiplier");P([m()],be.prototype,"separateAxes");P([m()],be.prototype,"strengthMultiplier");P([m(q)],be.prototype,"strengthX");P([m()],be.prototype,"strengthXMultiplier");P([m(q)],be.prototype,"strengthY");P([m()],be.prototype,"strengthYMultiplier");P([m(q)],be.prototype,"strengthZ");P([m()],be.prototype,"strengthZMultiplier");class je{constructor(){r(this,"enabled");r(this,"attachRibbonToTransform",!1);r(this,"colorOverLifetime");r(this,"colorOverTrail");r(this,"dieWithParticles",!0);r(this,"inheritParticleColor",!0);r(this,"lifetime");r(this,"lifetimeMultiplier");r(this,"minVertexDistance",.2);r(this,"mode",0);r(this,"ratio",1);r(this,"ribbonCount",1);r(this,"shadowBias",0);r(this,"sizeAffectsLifetime",!1);r(this,"sizeAffectsWidth",!1);r(this,"splitSubEmitterRibbons",!1);r(this,"textureMode",0);r(this,"widthOverTrail");r(this,"widthOverTrailMultiplier");r(this,"worldSpace",!1)}getWidth(t,e,i,n){const s=this.widthOverTrail.evaluate(i,n);return t*=s,t}getColor(t,e,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(e);t.x*=n.r*s.r,t.y*=n.g*s.g,t.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(t.w*=n.alpha*s.alpha)}}P([m()],je.prototype,"enabled");P([m()],je.prototype,"attachRibbonToTransform");P([m(Kr)],je.prototype,"colorOverLifetime");P([m(Kr)],je.prototype,"colorOverTrail");P([m()],je.prototype,"dieWithParticles");P([m()],je.prototype,"inheritParticleColor");P([m(q)],je.prototype,"lifetime");P([m()],je.prototype,"lifetimeMultiplier");P([m()],je.prototype,"minVertexDistance");P([m()],je.prototype,"mode");P([m()],je.prototype,"ratio");P([m()],je.prototype,"ribbonCount");P([m()],je.prototype,"shadowBias");P([m()],je.prototype,"sizeAffectsLifetime");P([m()],je.prototype,"sizeAffectsWidth");P([m()],je.prototype,"splitSubEmitterRibbons");P([m()],je.prototype,"textureMode");P([m(q)],je.prototype,"widthOverTrail");P([m()],je.prototype,"widthOverTrailMultiplier");P([m()],je.prototype,"worldSpace");class ze{constructor(){r(this,"enabled");r(this,"space",0);r(this,"orbitalX");r(this,"orbitalY");r(this,"orbitalZ");r(this,"orbitalXMultiplier");r(this,"orbitalYMultiplier");r(this,"orbitalZMultiplier");r(this,"orbitalOffsetX");r(this,"orbitalOffsetY");r(this,"orbitalOffsetZ");r(this,"speedModifier");r(this,"speedModifierMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_system");r(this,"_temp",new d.Vector3);r(this,"_temp2",new d.Vector3);r(this,"_temp3",new d.Vector3);r(this,"_hasOrbital",!1);r(this,"_index",0);r(this,"_orbitalMatrix",new d.Matrix4)}update(t){this._system=t}init(t){this._index==0&&(t.debug=!0),this._index+=1,t.orbitx=this.orbitalX.evaluate(Math.random()),t.orbity=this.orbitalY.evaluate(Math.random()),t.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=t.orbitx!=0||t.orbity!=0||t.orbitz!=0}apply(t,e,i,n,s,a,l){var g;if(!this.enabled)return;const c=a/l,h=this.speedModifier.evaluate(c)*this.speedModifierMultiplier,u=this.x.evaluate(c),f=this.y.evaluate(c),p=this.z.evaluate(c);if(this._temp.set(-u,f,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((g=this._system)==null?void 0:g.worldPos)){const b=this._temp2.set(i.x,i.y,i.z),_=this.orbitalXMultiplier,v=this.orbitalYMultiplier,w=this.orbitalZMultiplier,x=h*Math.PI*2*10,O=Math.cos(x*_),E=Math.sin(x*_),M=Math.cos(x*v),R=Math.sin(x*v),F=Math.cos(x*w),D=Math.sin(x*w),A=b.x*(M*F)+b.y*(M*D)+b.z*-R,T=b.x*(E*R*F-O*D)+b.y*(E*R*D+O*F)+b.z*(E*M),G=b.x*(O*R*F+E*D)+b.y*(O*R*D-E*F)+b.z*(O*M),B=this._temp3.set(b.x-A,b.y-T,b.z-G);B.normalize(),B.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=B.x,n.y+=B.y,n.z+=B.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}P([m()],ze.prototype,"enabled");P([m()],ze.prototype,"space");P([m(q)],ze.prototype,"orbitalX");P([m(q)],ze.prototype,"orbitalY");P([m(q)],ze.prototype,"orbitalZ");P([m()],ze.prototype,"orbitalXMultiplier");P([m()],ze.prototype,"orbitalYMultiplier");P([m()],ze.prototype,"orbitalZMultiplier");P([m()],ze.prototype,"orbitalOffsetX");P([m()],ze.prototype,"orbitalOffsetY");P([m()],ze.prototype,"orbitalOffsetZ");P([m(q)],ze.prototype,"speedModifier");P([m()],ze.prototype,"speedModifierMultiplier");P([m(q)],ze.prototype,"x");P([m()],ze.prototype,"xMultiplier");P([m(q)],ze.prototype,"y");P([m()],ze.prototype,"yMultiplier");P([m(q)],ze.prototype,"z");P([m()],ze.prototype,"zMultiplier");class jt{constructor(){r(this,"animation");r(this,"enabled");r(this,"cycleCount");r(this,"frameOverTime");r(this,"frameOverTimeMultiplier");r(this,"numTilesX");r(this,"numTilesY");r(this,"startFrame");r(this,"startFrameMultiplier");r(this,"rowMode");r(this,"rowIndex");r(this,"spriteCount");r(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(t){if(!this.sampleOnceAtStart())return this.getIndex(t)}getIndex(t){const e=this.numTilesX*this.numTilesY;t=t*this.cycleCount;let i=this.frameOverTime.evaluate(t%1);return i*=this.frameOverTimeMultiplier,i*=e,i=i%e,i=Math.floor(i),i}}P([m()],jt.prototype,"animation");P([m()],jt.prototype,"enabled");P([m()],jt.prototype,"cycleCount");P([m(q)],jt.prototype,"frameOverTime");P([m()],jt.prototype,"frameOverTimeMultiplier");P([m()],jt.prototype,"numTilesX");P([m()],jt.prototype,"numTilesY");P([m(q)],jt.prototype,"startFrame");P([m()],jt.prototype,"startFrameMultiplier");P([m()],jt.prototype,"rowMode");P([m()],jt.prototype,"rowIndex");P([m()],jt.prototype,"spriteCount");P([m()],jt.prototype,"timeMode");class Cn{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e){return this.enabled?this.separateAxes?0:this.z.evaluate(t,e)*-1:0}}P([m()],Cn.prototype,"enabled");P([m()],Cn.prototype,"separateAxes");P([m(q)],Cn.prototype,"x");P([m()],Cn.prototype,"xMultiplier");P([m(q)],Cn.prototype,"y");P([m()],Cn.prototype,"yMultiplier");P([m(q)],Cn.prototype,"z");P([m()],Cn.prototype,"zMultiplier");class Ji{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e){if(!this.enabled)return 0;if(!this.separateAxes){const i=z.lerp(this.range.x,this.range.y,e);return this.z.evaluate(i)*-1}return 0}}P([m()],Ji.prototype,"enabled");P([m()],Ji.prototype,"range");P([m()],Ji.prototype,"separateAxes");P([m(q)],Ji.prototype,"x");P([m()],Ji.prototype,"xMultiplier");P([m(q)],Ji.prototype,"y");P([m()],Ji.prototype,"yMultiplier");P([m(q)],Ji.prototype,"z");P([m()],Ji.prototype,"zMultiplier");class lt{constructor(){r(this,"enabled");r(this,"dampen");r(this,"drag");r(this,"dragMultiplier");r(this,"limit");r(this,"limitMultiplier");r(this,"separateAxes");r(this,"limitX");r(this,"limitXMultiplier");r(this,"limitY");r(this,"limitYMultiplier");r(this,"limitZ");r(this,"limitZMultiplier");r(this,"multiplyDragByParticleSize",!1);r(this,"multiplyDragByParticleVelocity",!1);r(this,"space");r(this,"_temp",new d.Vector3);r(this,"_temp2",new d.Vector3)}apply(t,e,i,n,s,a,l){if(this.enabled){const c=this.limit.evaluate(s)*this.limitMultiplier;if(e.length()>c){this._temp.copy(e).normalize().multiplyScalar(c);const u=this.dampen*.5;e.x=z.lerp(e.x,this._temp.x,u),e.y=z.lerp(e.y,this._temp.y,u),e.z=z.lerp(e.z,this._temp.z,u),i.x=z.lerp(i.x,this._temp.x,u),i.y=z.lerp(i.y,this._temp.y,u),i.z=z.lerp(i.z,this._temp.z,u)}}}}P([m()],lt.prototype,"enabled");P([m()],lt.prototype,"dampen");P([m(q)],lt.prototype,"drag");P([m()],lt.prototype,"dragMultiplier");P([m(q)],lt.prototype,"limit");P([m()],lt.prototype,"limitMultiplier");P([m()],lt.prototype,"separateAxes");P([m(q)],lt.prototype,"limitX");P([m()],lt.prototype,"limitXMultiplier");P([m(q)],lt.prototype,"limitY");P([m()],lt.prototype,"limitYMultiplier");P([m(q)],lt.prototype,"limitZ");P([m()],lt.prototype,"limitZMultiplier");P([m()],lt.prototype,"multiplyDragByParticleSize");P([m()],lt.prototype,"multiplyDragByParticleVelocity");P([m()],lt.prototype,"space");const Lh=class dx{constructor(){r(this,"enabled");r(this,"curve");r(this,"curveMultiplier");r(this,"mode");r(this,"system");r(this,"_temp",new d.Vector3);r(this,"_firstUpdate",!0);r(this,"_frames",0)}clone(){var e;const t=new dx;return t.enabled=this.enabled,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new d.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new d.Vector3),this.system._iv_velocity}awake(t){this.system=t,this.reset()}reset(){this._firstUpdate=!0}update(t){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(t){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),t.x+=this._temp.x,t.y+=this._temp.y,t.z+=this._temp.z}}applyCurrent(t,e,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(e,i);this._temp.copy(this._velocity).multiplyScalar(n),t.x+=this._temp.x,t.y+=this._temp.y,t.z+=this._temp.z}}};P([m()],Lh.prototype,"enabled");P([m(q)],Lh.prototype,"curve");P([m()],Lh.prototype,"curveMultiplier");P([m()],Lh.prototype,"mode");let Ty=Lh;class gi{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e,i,n){const s=t.length(),a=z.remap(s,this.range.x,this.range.y,0,1),l=this.size.evaluate(a,i);return n.x*=l,n.y*=l,n.z*=l,n}}P([m()],gi.prototype,"enabled");P([m(d.Vector2)],gi.prototype,"range");P([m()],gi.prototype,"separateAxes");P([m(q)],gi.prototype,"size");P([m()],gi.prototype,"sizeMultiplier");P([m(q)],gi.prototype,"x");P([m()],gi.prototype,"xMultiplier");P([m(q)],gi.prototype,"y");P([m()],gi.prototype,"yMultiplier");P([m(q)],gi.prototype,"z");P([m()],gi.prototype,"zMultiplier");class _l{constructor(){r(this,"enabled");r(this,"range");r(this,"color")}evaluate(t,e,i){const n=t.length(),s=z.remap(n,this.range.x,this.range.y,0,1),a=this.color.evaluate(s,e);i.x*=a.r,i.y*=a.g,i.z*=a.b,"alpha"in a&&(i.w*=a.alpha)}}P([m()],_l.prototype,"enabled");P([m(d.Vector2)],_l.prototype,"range");P([m(Kr)],_l.prototype,"color");new d.Vector3(1,1,1);new d.Vector3(0,0,1);class Ay{constructor(t,e,i,n){r(this,"type","NeedleParticleSubEmitter");r(this,"emitterType");r(this,"emitterProbability");r(this,"q_",new d.Quaternion);r(this,"v_",new d.Vector3);r(this,"v2_",new d.Vector3);r(this,"_emitterMatrix",new ae.Matrix4);r(this,"_circularBuffer");this.system=t,this.particleSystem=e,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new ki(()=>new ae.Matrix4,s)}clone(){throw new Error("Method not implemented.")}initialize(t){t.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===Dm.Birth&&this.run(t)}update(t,e){this.run(t)}frameUpdate(t){}toJSON(){}reset(){}run(t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!t.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const e=this.system.deltaTime;if(this.emitterType===Dm.Death){let n=t.life;if(t[Ca]!==void 0&&(n=t[Ca]),!(t.age+e*1.2>=n))return;const a=this.subSystem.main.maxParticles-this.subSystem.currentParticles;t.emissionState.waitEmiting=a}const i=new ae.Matrix4;i.set(1,0,0,t.position.x,0,1,0,t.position.y,0,0,1,t.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(e,t.emissionState,i)}}var Rk=Object.defineProperty,Be=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Rk(t,e,n),n};const ro=S("debugparticles"),Ek=S("noprogressive"),Tk=S("debugprogressive");var Dm=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(Dm||{});class en extends I{constructor(){super(...arguments);r(this,"renderMode");r(this,"particleMaterial");r(this,"trailMaterial");r(this,"particleMesh");r(this,"maxParticleSize");r(this,"minParticleSize");r(this,"velocityScale");r(this,"cameraVelocityScale");r(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&j()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var i;return((i=this.particleMaterial)==null?void 0:i.transparent)??!1}getMaterial(e=!1){let i=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(i){if(i.type==="MeshStandardMaterial"){ro&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in i&&i.map&&(i.map.colorSpace=d.LinearSRGBColorSpace,i.map.premultiplyAlpha=!1);const n=new d.MeshBasicMaterial;n.copy(i),e?this.trailMaterial=n:this.particleMaterial=n}i.map&&(i.map.colorSpace=d.LinearSRGBColorSpace,i.map.premultiplyAlpha=!1),e&&i.side===d.FrontSide&&(i=i.clone(),i.side=d.BackSide,e?this.trailMaterial=i:this.particleMaterial=i)}return i&&!Ek&&i._didRequestTextureLOD===void 0&&(i._didRequestTextureLOD=0,Tk&&console.log("Load material LOD",i.name),le.NEEDLE_progressive.assignTextureLOD(i,0)),i}getMesh(e){let i=null;if(!i&&(this.particleMesh instanceof d.Mesh&&(i=this.particleMesh.geometry),i===null)){i=new d.PlaneGeometry(1,1);const s=i.attributes.uv;for(let a=0;a<s.count;a++)s.setX(a,1-s.getX(a))}return new d.Mesh(i,this.getMaterial())}}Be([m()],en.prototype,"renderMode");Be([m(d.Material)],en.prototype,"particleMaterial");Be([m(d.Material)],en.prototype,"trailMaterial");Be([m()],en.prototype,"maxParticleSize");Be([m()],en.prototype,"minParticleSize");Be([m()],en.prototype,"velocityScale");Be([m()],en.prototype,"cameraVelocityScale");Be([m()],en.prototype,"lengthScale");class Sd{constructor(t,e=1){r(this,"_curve");r(this,"_factor");r(this,"type","function");this._curve=t,this._factor=e}startGen(t){}genValue(t,e){return this._curve.evaluate(e,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Ly{constructor(t){r(this,"type","value");r(this,"system");this.system=t}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(t){}}class Ak extends Ly{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class Lk extends Ly{constructor(){super(...arguments);r(this,"_lastPosition",new d.Vector3);r(this,"_lastDistance",0)}update(){const e=Q(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const s=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let l=this._lastDistance/this.system.deltaTime*s;Number.isFinite(l)||(l=0),e+=l}const i=this.system.emission.getBurst();i>0&&(e+=i/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return z.clamp(e,0,n/this.system.deltaTime)}}class Dk extends Ly{genValue(){return this.system.isPlaying,0}}class No{constructor(t){r(this,"system");r(this,"type");this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",t&&(this.system=t)}get context(){return this.system.context}initialize(t){}update(t,e){}frameUpdate(t){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class Ik extends No{constructor(){super(...arguments);r(this,"type","NeedleTextureSheet")}update(e,i){const n=this.system.textureSheetAnimation;if(n.enabled){const s=e.age/e.life,a=n.evaluate(s);a!==void 0&&(e.uvTile=a)}}}const Db=Symbol("particleRotation");class jk extends No{constructor(){super(...arguments);r(this,"type","NeedleRotation")}initialize(e){e[Db]=Math.random()}update(e,i){if(e.rotation===void 0)return;const n=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(n,e[Db])*i:this.system.renderer.renderMode===bs.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const s=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(n,s)*i}}}const Ib=Symbol("sizeLerpFactor"),Bk=new d.Vector3;class Fk extends No{constructor(){super(...arguments);r(this,"type","NeedleSize");r(this,"_minSize",0);r(this,"_maxSize",1)}initialize(e){e[Ib]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,i){const n=e.age/e.life;let s=1;this.system.sizeOverLifetime.enabled&&(s*=this.system.sizeOverLifetime.evaluate(n,void 0,e[Ib]).x);let a=1;this.system.renderer.renderMode!==bs.Mesh&&(a=this.system.worldScale.x/this.system.cameraScale);const l=V(e.startSize).multiplyScalar(s*a);if(e.size.set(l.x,l.y,l.z),this.system.localspace){const c=ux(this.system,Bk);e.size.x*=c.x,e.size.y*=c.y,e.size.z*=c.z}}}const Ca=Symbol("particleLife"),Lp=Symbol("trailLifetime"),jb=Symbol("trailStartLength"),Dp=Symbol("trailWidthRandom");class Uk extends No{constructor(){super(...arguments);r(this,"type","NeedleTrail")}initialize(e){e instanceof ae.TrailParticle&&(e[Ca]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Lp]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Lp]),e[jb]=e.length,e[Dp]=Math.random())}update(e){var i;if((i=this.system.trails)!=null&&i.enabled&&e instanceof ae.TrailParticle){const n=e,s=e.age/e[Ca],a=e.previous.values(),l=e.previous.length;for(let c=0;c<l;c++){const u=a.next().value,f=1-c/(l-1),p=e.size;if(p.x<=0&&!this.system.trails.sizeAffectsWidth){const g=20*this.system.trails.widthOverTrail.evaluate(.5,n[Dp]);p.x=g,p.y=g,p.z=g}u.size=this.system.trails.getWidth(p.x,s,f,n[Dp]),u.color.copy(e.color),this.system.trails.getColor(u.color,s,f)}if(e.age>e[Ca]){e.velocity.set(0,0,0);const c=(e.age-e[Ca])/e[Lp];n.length=z.lerp(e[jb],0,c)}}}}const Cd=Symbol("startVelocity"),Bb=Symbol("gravityModifier"),Ip=Symbol("gravitySpeed"),Pd=Symbol("velocity lerp factor"),Im=new d.Vector3;class zk extends No{constructor(){super(...arguments);r(this,"type","NeedleVelocity");r(this,"_gravityDirection",new d.Vector3)}initialize(e){var a,l;const i=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const n=this.system.shape.getDirection(e,e.position);e.velocity.x=n.x*e.startSpeed,e.velocity.y=n.y*e.startSpeed,e.velocity.z=n.z*e.startSpeed,(a=this.system.inheritVelocity)!=null&&a.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Cd]?e[Cd].copy(e.velocity):e[Cd]=e.velocity.clone();const s=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[Bb]=s*i,e[Ip]=s*i*.5,e[Pd]=Math.random(),(l=this.system.velocityOverLifetime)==null||l.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Vc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,i){var p;const n=e[Cd],s=e[Bb];if(s!==0){const g=s*e[Ip];Im.copy(this._gravityDirection).multiplyScalar(g),e[Ip]+=i*.05,n.add(Im)}e.velocity.copy(n);const a=e.age/e.life;(p=this.system.inheritVelocity)!=null&&p.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,a,e[Pd]);const l=this.system.noise;l.enabled&&l.apply(0,e.position,e.velocity,i,e.age,e.life);const c=this.system.sizeBySpeed;c!=null&&c.enabled&&(e.size=c.evaluate(e.velocity,a,e[Pd],e.size));const h=this.system.colorBySpeed;h!=null&&h.enabled&&h.evaluate(e.velocity,e[Pd],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,i,e.age,e.life);const f=this.system.limitVelocityOverLifetime;if(f.enabled&&f.apply(e.position,n,e.velocity,e.size,a,i,1),this.system.worldspace){const g=this.system.worldScale;e.velocity.x*=g.x,e.velocity.y*=g.y,e.velocity.z*=g.z}}}const Fb=Symbol("colorLerpFactor"),Ub=new ie(1,1,1,1),Qo=new ie(1,1,1,1);class Nk extends No{constructor(){super(...arguments);r(this,"type","NeedleColor")}initialize(e){}_init(e){const i=this.system.renderer.particleMaterial;Qo.copy(this.system.main.startColor.evaluate(Math.random())),i!=null&&i.color&&(Ub.copy(i.color),Qo.multiply(Ub)),Qo.convertLinearToSRGB(),e.startColor.set(Qo.r,Qo.g,Qo.b,Qo.alpha),e.color.copy(e.startColor),e[Fb]=Math.random()}update(e,i){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const n=e.age/e.life,s=this.system.colorOverLifetime.color.evaluate(n,e[Fb]);e.color.set(s.r,s.g,s.b,"alpha"in s?s.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class $k{constructor(t){r(this,"system");r(this,"emission");r(this,"autoDestroy");r(this,"startLength");r(this,"emissionBursts");r(this,"onlyUsedByOther");r(this,"behaviors",[]);r(this,"rendererEmitterSettings",{startLength:new ae.ConstantValue(220),followLocalOrigin:!1});r(this,"flatWhiteTexture");r(this,"clonedTexture",{original:void 0,clone:void 0});this.system=t,this.emission=new Lk(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Sd(this.system.main.startLifetime)}get startSpeed(){return new Sd(this.system.main.startSpeed)}get startRotation(){return new Sd(this.system.main.startRotation)}get startSize(){return new Sd(this.system.main.startSize)}get startColor(){return new ae.ConstantColor(new ae.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new Dk(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return ae.RenderMode.Trail;switch(this.system.renderer.renderMode){case bs.Billboard:return ae.RenderMode.BillBoard;case bs.Stretch:return ae.RenderMode.StretchedBillBoard;case bs.HorizontalBillboard:return ae.RenderMode.HorizontalBillBoard;case bs.VerticalBillboard:return ae.RenderMode.VerticalBillBoard;case bs.Mesh:return ae.RenderMode.Mesh}return ae.RenderMode.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===bs.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const t=this.material;if(t&&t.map){const e=t.map;if(this.clonedTexture.original!==e||!this.clonedTexture.clone){const i=e.clone();i.premultiplyAlpha=!1,i.colorSpace=d.LinearSRGBColorSpace,this.clonedTexture.original=e,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Cg(new ie(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new Ak(this.system)}get uTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesX:void 0}get vTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesY:void 0}get renderOrder(){return 1}get blending(){var t;return((t=this.system.renderer.particleMaterial)==null?void 0:t.blending)??d.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Vc.World}}class Vk{constructor(){r(this,"burstParticleIndex",0);r(this,"burstParticleCount",0);r(this,"isBursting",!1);r(this,"travelDistance",0);r(this,"previousWorldPos");r(this,"burstIndex",0);r(this,"burstWaveIndex",0);r(this,"time",0);r(this,"waitEmiting",0)}}const Bt=class $d extends I{constructor(){super(...arguments);r(this,"_state");r(this,"colorOverLifetime");r(this,"main");r(this,"emission");r(this,"sizeOverLifetime");r(this,"shape");r(this,"noise");r(this,"trails");r(this,"velocityOverLifetime");r(this,"limitVelocityOverLifetime");r(this,"inheritVelocity");r(this,"colorBySpeed");r(this,"textureSheetAnimation");r(this,"rotationOverLifetime");r(this,"rotationBySpeed");r(this,"sizeBySpeed");r(this,"_cameraScale",1);r(this,"__worldQuaternion",new d.Quaternion);r(this,"_worldQuaternionInverted",new d.Quaternion);r(this,"_worldScale",new d.Vector3);r(this,"_worldPositionFrame",-1);r(this,"_worldPos",new d.Vector3);r(this,"_renderer");r(this,"_batchSystem");r(this,"_particleSystem");r(this,"_interface");r(this,"_container");r(this,"_time",0);r(this,"_isPlaying",!0);r(this,"_isUsedAsSubsystem",!1);r(this,"_didPreWarm",!1);r(this,"_bursts");r(this,"_subEmitterSystems");r(this,"_lastBatchesCount",-1)}play(e=!1){var i;e&&C.foreachComponent(this.gameObject,n=>{n instanceof $d&&n!==this&&n.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(i=this.emission)==null||i.reset()}pause(e=!0){e&&C.foreachComponent(this.gameObject,i=>{i instanceof $d&&i!==this&&i.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,i=!1){e&&C.foreachComponent(this.gameObject,n=>{n instanceof $d&&n!==this&&n.stop(!1,i)},!0),this._isPlaying=!1,this._time=0,i&&this.reset()}reset(){var e;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(e=this.emission)==null||e.reset())}emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new Vk),this._state.waitEmiting=e,this._state.time=0;const i=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=i}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var e;return((e=this._particleSystem)==null?void 0:e.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===Vc.World}get localspace(){return this.main.simulationSpace===Vc.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Q(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof No&&(e.system=this),ro&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const i=this._particleSystem.behaviors,n=i.indexOf(e);return n!==-1&&((j()||ro)&&console.debug("Remove custom ParticleSystem Behaviour",n,e),i.splice(n,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(e){for(let i=0;i<e.length;i++){const n=e[i];if(!(n instanceof wu)){const s=new wu;Ga(s,n),e[i]=s}}this._bursts=e}set subEmitterSystems(e){for(let i=0;i<e.length;i++){const n=e[i];if(!(n instanceof xu)){const s=new xu;Ga(s,n),e[i]=s}}ro&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const i of this._subEmitterSystems)i._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(en),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new d.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new ae.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new $k(this),this._particleSystem=new ae.ParticleSystem(this._interface),this._particleSystem.addBehavior(new Fk(this)),this._particleSystem.addBehavior(new Nk(this)),this._particleSystem.addBehavior(new Ik(this)),this._particleSystem.addBehavior(new jk(this)),this._particleSystem.addBehavior(new zk(this)),this._particleSystem.addBehavior(new Uk(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),ro&&(console.log(this),this.gameObject.add(new d.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof d.Mesh&&this._interface.renderMode==ae.RenderMode.Mesh&&le.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==ae.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){var e,i,n,s;(e=this._container)==null||e.removeFromParent(),(i=this._batchSystem)==null||i.removeFromParent(),(n=this._particleSystem)==null||n.emitter.removeFromParent(),(s=this._particleSystem)==null||s.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var e;this.main&&(this._didPreWarm===!1&&((e=this.main)==null?void 0:e.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var u;if(!((u=this.emission)!=null&&u.enabled)||this.emission.rateOverTime.getMax()<=0)return;const i=1/60,n=this.main.duration,s=this.main.startLifetime.getMax(),l=Math.min(Math.max(n,s)/Math.max(.01,this.main.simulationSpeed),1e3),c=Math.ceil(l/i),h=Date.now();ro&&console.log(`Particles ${this.name} - Prewarm for ${c} frames (${l} sec). Duration: ${n}, Lifetime: ${s}`);for(let f=0;f<c&&!(this.currentParticles>=this.maxParticles);f++){const p=Date.now()-h;if(p>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${p}`);break}this.onUpdate(),this.onSimulate(i)}}onSimulate(e){if(this._batchSystem){let i=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,i=!0),i&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const i=this._batchSystem.batches[e];i.layers.disableAll();const n=this.layer;i.layers.mask=1<<n}}onUpdate(){var s,a;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const l=Ue(e);this._cameraScale=l.x}const i=!this.worldspace,n=this.gameObject;if(_e(n,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ue(this.gameObject,this._worldScale),i&&this._container&&((s=this.gameObject)!=null&&s.parent)){const l=ux(this,Im);this._container.matrix.makeScale(l.x,l.y,l.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(a=this.inheritVelocity)==null||a.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var e;if(this._subEmitterSystems&&this._particleSystem)for(const i of this._subEmitterSystems){i.particleSystem&&(i.particleSystem.__internalAwake?i.particleSystem.__internalAwake():j()&&console.warn("SubParticleSystem serialization issue(?)",i.particleSystem,i));const n=(e=i.particleSystem)==null?void 0:e._particleSystem;if(n){i.particleSystem._isUsedAsSubsystem=!0;const s=new Ay(this,this._particleSystem,i.particleSystem,n);s.emitterType=i.type,s.emitterProbability=i.emitProbability,this._particleSystem.addBehavior(s)}else ro&&console.warn("Could not add SubParticleSystem",i,this)}}};Be([m(_f)],Bt.prototype,"colorOverLifetime");Be([m(It)],Bt.prototype,"main");Be([m($s)],Bt.prototype,"emission");Be([m(Zr)],Bt.prototype,"sizeOverLifetime");Be([m(Ey)],Bt.prototype,"shape");Be([m(be)],Bt.prototype,"noise");Be([m(je)],Bt.prototype,"trails");Be([m(ze)],Bt.prototype,"velocityOverLifetime");Be([m(lt)],Bt.prototype,"limitVelocityOverLifetime");Be([m(Ty)],Bt.prototype,"inheritVelocity");Be([m(_l)],Bt.prototype,"colorBySpeed");Be([m(jt)],Bt.prototype,"textureSheetAnimation");Be([m(Cn)],Bt.prototype,"rotationOverLifetime");Be([m(Ji)],Bt.prototype,"rotationBySpeed");Be([m(gi)],Bt.prototype,"sizeBySpeed");let Wc=Bt;class xu{constructor(){r(this,"particleSystem");r(this,"emitProbability",1);r(this,"properties");r(this,"type")}_deserialize(t,e){const i=this.particleSystem;if(i instanceof Wc)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=C.findByGuid(n,e)),ro&&!(this.particleSystem instanceof Wc)&&console.warn("Could not find particle system for sub emitter",n,e,this)}}function ux(o,t){if(t.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case Lm.Local:t=Ue(o.gameObject.parent,t),t.x=1/t.x,t.y=1/t.y,t.z=1/t.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const e="ParticleSystem scale mode "+Lm[o.main.scalingMode]+" is not supported";j()&&me(e),console.warn(e,o.name,o)}t=Ue(o.gameObject,t);break}return t}class el extends I{constructor(){super(...arguments);r(this,"_didAssignPlayerColor",!1);r(this,"tryAssignColor",()=>{const e=C.getComponentInParent(this.gameObject,yn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const i=C.getComponentInParent(this.gameObject,At);return i!=null&&i.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(i.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(ee.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ee.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Sg(.2),!this.tryAssignColor()););}assignUserColor(e){const i=el.hashCode(e),n=el.colorFromHashCode(i);if(this.gameObject.type==="Mesh"){const s=this.gameObject;this.assignColor(n,e,s)}else if(this.gameObject.children)for(const s of this.gameObject.children){const a=s;a.material&&a.material.color&&this.assignColor(n,e,a)}}assignColor(e,i,n){let s=n.material;s&&(s._playerMaterial!==i&&(s=s.clone(),s._playerMaterial=i,n.material=s),s.color=e)}static hashCode(e){var i=0,n,s;if(e.length===0)return i;for(n=0;n<e.length;n++)s=e.charCodeAt(n),i=(i<<5)-i+s,i|=0;return i}static colorFromHashCode(e){const i=(e&16711680)>>16,n=(e&65280)>>8,s=e&255;return new d.Color(i/255,n/255,s/255)}}const oc=S("debugpost");let jm=null;function Wk(o){jm=o}function fx(o){let t=o.gameObject;for(;t;){for(const e of Hu(t))if(e.isPostProcessingManager===!0)return e;t=t.parent}return null}function Gk(o){let t=fx(o);if(!t)if(jm){oc&&console.warn("Adding postprocessing manager to the scene.");const e=o.scene;t=Oi(e,jm)}else j()&&console.warn("No post processing manager found");return t}const it={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let qe=null;function Hk(o){oc==="verbose"&&console.debug("Before ordering effects",[...o]),qe||(qe=new Map,qe.set(exports.MODULES.POSTPROCESSING.MODULE.NormalPass,it.NormalPass),qe.set(exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,it.DepthDownsamplingPass),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,it.SMAA),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPass,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,it.TiltShift),qe.set(exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,it.DepthOfField),qe.set(exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,it.ChromaticAberration),qe.set(exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,it.Bloom),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,it.Bloom),qe.set(exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,it.Vignette),qe.set(exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,it.Pixelation),qe.set(exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,it.ToneMapping),qe.set(exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,it.HueSaturation),qe.set(exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect,it.BrightnessContrast)),o.sort((t,e)=>{const i=typeof t.priority=="number"?t.priority:qe.get(t.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof e.priority=="number"?e.priority:qe.get(e.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(oc&&console.warn("Unknown effect found: ",t.constructor.name,t),1):n===Number.NEGATIVE_INFINITY?(oc&&console.warn("Unknown effect found: ",e.constructor.name,e),-1):i-n}),oc==="verbose"&&console.debug("After ordering effects",[...o])}var qk=Object.defineProperty,Xk=Object.getOwnPropertyDescriptor,px=(o,t,e,i)=>{for(var n=Xk(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&qk(t,e,n),n};const Qk=S("debugpost");class U{constructor(t){r(this,"isVolumeParameter",!0);r(this,"_isInitialized",!1);r(this,"_active",!0);r(this,"_value");r(this,"_valueRaw");r(this,"_defaultValue");r(this,"valueProcessor");r(this,"onValueChanged");t!==void 0&&this.initialize(t)}get isInitialized(){return this._isInitialized}initialize(t){t!==void 0&&(this._value=t,this._defaultValue=t,this._valueRaw=t,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(t){if(this._active===t)return;this._active=t;const e=t?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(t){this.isInitialized||this.initialize(t),this.processValue(t,!1)}set defaultValue(t){this._defaultValue=t}__init(){this.processValue(this._valueRaw,!0)}processValue(t,e){if(t==null||!e&&this.testIfValueChanged(t)===!1)return;const i=this._value;Qk&&typeof i=="number"&&typeof t=="number"&&(i==null||i.toFixed(4),t==null||t.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,t=this._defaultValue,this._valueRaw=t):(this._valueRaw=t,this._active&&this.valueProcessor&&(t=this.valueProcessor(t)),this._value=t),this.onValueChanged&&this.onValueChanged(t,i,this)}testIfValueChanged(t){return this._valueRaw!==t}}px([m()],U.prototype,"overrideState");px([m()],U.prototype,"value");class Yk extends Ki{constructor(){super([U])}onSerialize(t,e){}onDeserialize(t,e){const i=e.target,n=e.path;let s;if(i&&n&&(s=i[n]),(typeof s!="object"||typeof s=="object"&&s.isVolumeParameter!==!0)&&(s=new U),typeof t=="object"&&"value"in t){const a=t.value;s.initialize(a),s.overrideState=t.overrideState}else s.value=t;return s}}new Yk;var Kk=Object.defineProperty,Zk=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Kk(t,e,n),n};const jp=S("debugpost");class Ye extends I{constructor(e=void 0){super();r(this,"order");r(this,"active",!0);r(this,"_manager",null);r(this,"_result");r(this,"_postprocessingContext",null);if(e)for(const i of Object.keys(e)){const n=e[i],s=this[i];s instanceof U?s.initialize(n):s!==void 0&&(this[i]=n)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),jp&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var e;super.onDisable(),jp&&console.warn("Disable",this.constructor.name),(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=Gk(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var i;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(i=this.onCreateEffect)==null?void 0:i.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){jp&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const i of e){const n=this[i];n instanceof U&&n.__init()}}onEditorModification(e){const i=e.propertyName;if(this[i]instanceof U){const n=e.value;return this[i].value=n,!0}}}Zk([m()],Ye.prototype,"active");var Jk=Object.defineProperty,eR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Jk(t,e,n),n};const tR=S("debugpost"),Bm={};function tn(o,t){Bm[o]=t}function iR(o){return o.__type in Bm?Bm[o.__type]:(tR&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),Ye)}class bf{constructor(){r(this,"components",[])}__init(t){var e;(e=this.components)==null||e.forEach(i=>{i.gameObject===void 0&&t.gameObject.addComponent(i),i.init()})}addEffect(t){this.components.push(t)}removeEffect(t){const e=this.components.indexOf(t);e>=0&&this.components.splice(e,1)}}eR([Br([o=>iR(o),Ye])],bf.prototype,"components");var nR=Object.defineProperty,sR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&nR(t,e,n),n};const oR=S("debugpost");class Dh extends Ye{constructor(){super(...arguments);r(this,"preset",new U(2))}get typeName(){return"Antialiasing"}onCreateEffect(){var i;const e=new exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect({preset:((i=this.preset)==null?void 0:i.value)??exports.MODULES.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:exports.MODULES.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=n=>{oR&&console.log("Antialiasing preset changed to",n),e.applyPreset(n)},e}}sR([m(U)],Dh.prototype,"preset");tn("Antialiasing",Dh);var rR=Object.defineProperty,Dy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&rR(t,e,n),n},dr;const vf=(dr=class extends Ye{constructor(){super(...arguments);r(this,"threshold",new U(.9));r(this,"intensity",new U(1));r(this,"scatter",new U(.7));r(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=dr.useSelectiveBloom),this.selectiveBloom){const i=e=new exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});i.inverted=!0}else e=new exports.MODULES.POSTPROCESSING.MODULE.BloomEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=i=>{e.intensity=i},this.threshold.onValueChanged=i=>{e.luminanceMaterial.threshold=Math.pow(i,2.2)},this.scatter.onValueChanged=i=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=i,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=d.MathUtils.lerp(.1,.9,i))},e}},r(dr,"useSelectiveBloom",!1),dr);Dy([m(U)],vf.prototype,"threshold");Dy([m(U)],vf.prototype,"intensity");Dy([m(U)],vf.prototype,"scatter");let wf=vf;tn("Bloom",wf);var aR=Object.defineProperty,lR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&aR(t,e,n),n};class Ih extends Ye{constructor(){super(...arguments);r(this,"intensity",new U(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new d.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{e.offset.x=-i,e.offset.y=i},e}}lR([m(U)],Ih.prototype,"intensity");tn("ChromaticAberration",Ih);var rc=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(rc||{});const zb=new Map;function Bp(o){switch(o){case 0:return d.LinearToneMapping;case 1:return d.ReinhardToneMapping;case 2:return d.ACESFilmicToneMapping;case 3:return d.AgXToneMapping;case 4:return d.NeutralToneMapping;default:return zb.has(o)||(zb.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),d.NeutralToneMapping}}function cR(o){switch(o){case d.LinearToneMapping:return 0;case d.ACESFilmicToneMapping:return 2;case d.AgXToneMapping:return 3;case d.NeutralToneMapping:return 1;case d.ReinhardToneMapping:return 1;default:return 0}}function Vd(o){switch(o){case d.LinearToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case d.ACESFilmicToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case d.AgXToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case d.NeutralToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case d.ReinhardToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var hR=Object.defineProperty,mx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&hR(t,e,n),n};const Fp=S("debugpost");class Ro extends Ye{constructor(){super(...arguments);r(this,"mode",new U(void 0));r(this,"exposure",new U(1));r(this,"_tonemappingEffect",null)}get typeName(){return"ToneMapping"}setMode(e){const i=rc[e];return i===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=i,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=fx(this);e&&super.onEffectEnabled(e)}onCreateEffect(){var n;if(this.mode.isInitialized==!1){const s=cR(this.context.renderer.toneMapping);Fp&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+s),this.mode.initialize(s)}(n=this._tonemappingEffect)==null||n.dispose();const e=Bp(this.mode.value),i=this._tonemappingEffect=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Vd(e)});return this.mode.onValueChanged=s=>{if(typeof s=="string")s=qv(s),i.mode=Vd(s);else{const a=Bp(s);i.mode=Vd(a)}i.name="ToneMapping ("+rc[s]+")",Fp&&console.log("[PostProcessing] ToneMapping mode changed to",rc[s],e,i.mode)},Fp&&console.log("[PostProcessing] Use ToneMapping",rc[this.mode.value],e,i.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),i}onBeforeRender(){var e;if(this._tonemappingEffect&&((e=this.postprocessingContext)!=null&&e.handler.getEffectIsActive(this._tonemappingEffect))&&(this.mode.overrideState&&(this.context.renderer.toneMapping=Bp(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const i=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=i}}}mx([m(U)],Ro.prototype,"mode");mx([m(U)],Ro.prototype,"exposure");tn("Tonemapping",Ro);var dR=Object.defineProperty,xf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&dR(t,e,n),n};class $o extends Ye{constructor(){super(...arguments);r(this,"remap",!0);r(this,"postExposure",new U(1));r(this,"contrast",new U(0));r(this,"hueShift",new U(0));r(this,"saturation",new U(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let i=1;return e>0?i=200:e<0&&(i=100),e/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){var a,l;const e=[];let i=(a=this.postprocessingContext)==null?void 0:a.components.find(c=>c instanceof Ro);i||(i=new Ro,(l=this.postprocessingContext)==null||l.components.push(i)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&i?i.exposure.value=c:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const n=new exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>n.contrast=c;const s=new exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=c=>s.hue=c,this.saturation.onValueChanged=c=>s.saturation=c,e.push(n),e.push(s),e}}xf([m(U)],$o.prototype,"postExposure");xf([m(U)],$o.prototype,"contrast");xf([m(U)],$o.prototype,"hueShift");xf([m(U)],$o.prototype,"saturation");tn("ColorAdjustments",$o);var uR=Object.defineProperty,Jr=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&uR(t,e,n),n};const fR=S("debugpost");class Pn extends Ye{constructor(){super(...arguments);r(this,"mode");r(this,"focusDistance",new U(1));r(this,"focalLength",new U(.2));r(this,"aperture",new U(20));r(this,"gaussianMaxRadius",new U);r(this,"resolutionScale",new U(1/window.devicePixelRatio));r(this,"bokehScale",new U)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300;return z.lerp(2,.01,n)};const e=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return z.lerp(1,e,n)}}onCreateEffect(){if(this.mode===0){fR&&console.warn("DepthOfField: Mode is set to Off");return}const e=new exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{e.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>e.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>e.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>e.resolution.scale=i),[e]}unapply(){}}Jr([m()],Pn.prototype,"mode");Jr([m(U)],Pn.prototype,"focusDistance");Jr([m(U)],Pn.prototype,"focalLength");Jr([m(U)],Pn.prototype,"aperture");Jr([m(U)],Pn.prototype,"gaussianMaxRadius");Jr([m(U)],Pn.prototype,"resolutionScale");Jr([m(U)],Pn.prototype,"bokehScale");tn("DepthOfField",Pn);class Gc extends Ye{constructor(e){super();r(this,"effect");this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var pR=Object.defineProperty,mR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&pR(t,e,n),n};class jh extends Ye{constructor(){super(...arguments);r(this,"granularity",new U(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=i=>{e.granularity=i},e}}mR([m(U)],jh.prototype,"granularity");tn("PixelationEffect",jh);var gR=Object.defineProperty,Bh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&gR(t,e,n),n};class Vs extends Ye{constructor(){super(...arguments);r(this,"intensity",new U(2));r(this,"falloff",new U(1));r(this,"samples",new U(9));r(this,"color",new U(new d.Color(0,0,0)));r(this,"luminanceInfluence",new U(.7));r(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof d.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const e=this.context.mainCamera,i=new exports.MODULES.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),n=new exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:i.texture,resolutionScale:.5}),s=this._ssao=new exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect(e,i.texture,{normalDepthBuffer:n.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{s.intensity=l},this.falloff.onValueChanged=l=>{s.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{s.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{s.color||(s.color=new d.Color),s.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{s.luminanceInfluence=l};const a=new Array;return a.push(i),a.push(n),a.push(s),a}}Bh([m(U)],Vs.prototype,"intensity");Bh([m(U)],Vs.prototype,"falloff");Bh([m(U)],Vs.prototype,"samples");Bh([m(U)],Vs.prototype,"color");Bh([m(U)],Vs.prototype,"luminanceInfluence");tn("ScreenSpaceAmbientOcclusion",Vs);var yR=Object.defineProperty,ea=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&yR(t,e,n),n};const _R=S("debugN8AO");var Fm=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(Fm||{});class Mn extends Ye{constructor(){super(...arguments);r(this,"gammaCorrection",!0);r(this,"aoRadius",new U(1));r(this,"falloff",new U(1));r(this,"intensity",new U(1));r(this,"color",new U(new d.Color(0,0,0)));r(this,"screenspaceRadius",!1);r(this,"quality",2);r(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(Fm[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,i=this.context.domWidth,n=this.context.domHeight,s=this._ssao=new exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,i,n);s.name="SSAO_N8";const a=Fm[this.quality];s.setQualityMode(a),s.configuration.transparencyAware=!1;const l=new d.WebGLRenderTarget(i,n);return s.configuration.beautyRenderTarget=l,s.configuration.autoRenderBeauty=!1,s.configuration.gammaCorrection=this.gammaCorrection,s.configuration.screenSpaceRadius=this.screenspaceRadius,_R&&(s.enableDebugMode(),console.log(s),setInterval(()=>{console.log("SSAO",s.lastTime)},1e3),setInterval(()=>{console.log("SSAO",s.enabled,{ssao:s,autoRenderBeauty:s.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{s.configuration.intensity=c},this.falloff.onValueChanged=c=>{s.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{s.configuration.aoRadius=c},this.color.onValueChanged=c=>{s.color||(s.color=new d.Color),s.configuration.color.copy(c)},s}}ea([St(),m()],Mn.prototype,"gammaCorrection");ea([m(U)],Mn.prototype,"aoRadius");ea([m(U)],Mn.prototype,"falloff");ea([m(U)],Mn.prototype,"intensity");ea([m(U)],Mn.prototype,"color");ea([St(),m()],Mn.prototype,"screenspaceRadius");ea([St(),m()],Mn.prototype,"quality");tn("ScreenSpaceAmbientOcclusionN8",Mn);var bR=Object.defineProperty,vR=Object.getOwnPropertyDescriptor,gx=(o,t,e,i)=>{for(var n=vR(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bR(t,e,n),n};class Fh extends Ye{constructor(){super(...arguments);r(this,"order",it.Sharpening);r(this,"_effect");r(this,"_amount",1);r(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(wR())),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}gx([m()],Fh.prototype,"amount");gx([m()],Fh.prototype,"radius");function wR(){const o=`
1275
1275
  void mainSupport() {
1276
1276
  vUv = uv;
1277
1277
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
@@ -1318,11 +1318,11 @@ axisFormat %s
1318
1318
  `;class e extends exports.MODULES.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",t,{vertexShader:o,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new d.Uniform$1(1)],["radius",new d.Uniform$1(1)]]),attributes:Xx.EffectAttribute.CONVOLUTION})}}return e}var xR=Object.defineProperty,bl=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&xR(t,e,n),n};class cs extends Ye{constructor(){super(...arguments);r(this,"offset",new U(0));r(this,"rotation",new U(0));r(this,"focusArea",new U(.4));r(this,"feather",new U(.3));r(this,"kernelSize",new U(2));r(this,"resolutionScale",new U(1/window.devicePixelRatio))}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=exports.MODULES.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:exports.MODULES.POSTPROCESSING.MODULE.KernelSize.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=i=>e.offset=i,this.rotation.onValueChanged=i=>e.rotation=i,this.focusArea.onValueChanged=i=>e.focusArea=i,this.feather.onValueChanged=i=>e.feather=i,this.kernelSize.onValueChanged=i=>e.blurPass.kernelSize=i,this.resolutionScale.onValueChanged=i=>e.resolution.scale=i/window.devicePixelRatio,e}}bl([m(U)],cs.prototype,"offset");bl([m(U)],cs.prototype,"rotation");bl([m(U)],cs.prototype,"focusArea");bl([m(U)],cs.prototype,"feather");bl([m(U)],cs.prototype,"kernelSize");bl([m(U)],cs.prototype,"resolutionScale");tn("TiltShiftEffect",cs);var SR=Object.defineProperty,Iy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&SR(t,e,n),n};class ta extends Ye{constructor(){super(...arguments);r(this,"color",new U({r:0,g:0,b:0,a:1}));r(this,"intensity",new U(0));r(this,"center",new U({x:.5,y:.5}))}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=i=>{e.offset=i,this.updateDarkness(e)},this.color.onValueChanged=i=>{this.updateDarkness(e)},e}updateDarkness(e){const i=this.intensity.value;e.darkness=i}}Iy([m(U)],ta.prototype,"color");Iy([m(U)],ta.prototype,"intensity");Iy([m(U)],ta.prototype,"center");tn("Vignette",ta);globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const ps=S("debugpost"),Up=Symbol("needle:postprocessing-handler"),Bl=Symbol("needle:previous-autoclear-state"),Fl=Symbol("needle:previous-tone-mapping");class jy{constructor(t){r(this,"_composer",null);r(this,"_lastVolumeComponents");r(this,"_effects",[]);r(this,"_isActive",!1);r(this,"context");r(this,"_anyPassHasDepth",!1);r(this,"_anyPassHasNormal",!1);r(this,"_hasSmaaEffect",!1);r(this,"_customInputBuffer",null);r(this,"_customInputBufferId",0);r(this,"_multisampling",0);r(this,"_menuEntry",null);r(this,"_passIndices",null);this.context=t}getEffectIsActive(t){return t?this._isActive&&this._effects.some(e=>e.effect===t):!1}get isActive(){return this._isActive}get composer(){return this._composer}apply(t){return this._isActive=!0,this.onApply(this.context,t)}unapply(t=!0){var n,s;if(ps&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const a of this._lastVolumeComponents)a.unapply();this._lastVolumeComponents.length=0}const e=this.context;e[Up]===this&&(delete e[Up],typeof e.renderer[Bl]=="boolean"&&(e.renderer.autoClear=e.renderer[Bl]),typeof e.renderer[Fl]=="number"&&(e.renderer.toneMapping=e.renderer[Fl])),(n=this._composer)==null||n.removeAllPasses(),t&&((s=this._composer)==null||s.dispose()),e.composer===this._composer&&(e.composer=null)}dispose(){this.unapply(!0);for(const t of this._effects)t.effect.dispose();this._effects.length=0,this._composer=null}async onApply(t,e){if(!e)return;await Promise.all([exports.MODULES.POSTPROCESSING.load(),exports.MODULES.POSTPROCESSING_AO.load()]),t[Up]=this,ps&&console.log("Apply Postprocessing Effects",e),this._lastVolumeComponents=[...e],this._effects.length=0;const i={handler:this,components:this._lastVolumeComponents};for(let n=0;n<this._lastVolumeComponents.length;n++){const s=this._lastVolumeComponents[n];if(s.context=t,s.apply){if(s.active){let a=function(h,u){return u?(u instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect||u instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass||console.warn(`PostprocessingEffect ${h} created neither Effect nor Pass - this might be caused by a bundler error or false import. Below you find some possible solutions:
1319
1319
  - If you create custom effect try creating it like this: 'new NEEDLE_ENGINE_MODULES.POSTPROCESSING.MODULE.Effect(...)' instead of 'new Effect(...)'`),!0):!1};if(!t.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const l=s.apply(i);if(!l)continue;const c=s.typeName||s.constructor.name;if(Array.isArray(l))for(const h of l)a(c,h)&&this._effects.push({effect:h,typeName:s.typeName,priority:s.order});else{if(!a(c,l))continue;this._effects.push({effect:l,typeName:s.typeName,priority:s.order})}}}else s.active&&me("Volume component is not a VolumeComponent: "+s.__type)}this.applyEffects(t)}get anyPassHasDepth(){return this._anyPassHasDepth}get anyPassHasNormal(){return this._anyPassHasNormal}get hasSmaaEffect(){return this._hasSmaaEffect}set multisampling(t){this._multisampling=t}get multisampling(){return this._multisampling}applyEffects(t){var u;if(this._anyPassHasDepth=!1,this._anyPassHasNormal=!1,this._hasSmaaEffect=!1,this._effects.length<=0)return;const e=t.mainCameraComponent,i=t.renderer,n=t.scene,s=e.threeCamera;if(typeof i[Bl]=="boolean"&&(i.autoClear=i[Bl]),i[Bl]=i.autoClear,typeof i[Fl]=="number"&&(i.toneMapping=i[Fl]),i[Fl]=i.toneMapping,i.toneMapping!=d.NoToneMapping&&!this._effects.find(f=>f instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect)){const f=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect;f.name=`ToneMapping (${i.toneMapping})`,f.mode=Vd(i.toneMapping),this._effects.push({typeName:"ToneMapping",effect:f,priority:it.ToneMapping})}this._composer||(this._composer=new exports.MODULES.POSTPROCESSING.MODULE.EffectComposer(i,{frameBufferType:d.HalfFloatType,stencilBuffer:!0})),t.composer&&t.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),t.composer=this._composer;const a=t.composer;a.setMainCamera(s),a.setRenderer(i),a.setMainScene(n),a.autoRenderToScreen=!0,a.multisampling=0;for(const f of a.passes)f.dispose();a.removeAllPasses();const l=new exports.MODULES.POSTPROCESSING.MODULE.RenderPass(n,s);l.name="RenderPass",l.mainScene=n,a.addPass(l);const c=l.render;(u=this._customInputBuffer)==null||u.dispose(),this._customInputBuffer=null,l.render=(f,p,g,y,b)=>{var _;p&&(p.samples=0,g&&(g.samples=0),(!this._customInputBuffer||this._customInputBuffer.width!==p.width||this._customInputBuffer.height!==p.height||this._customInputBuffer.samples!==this._multisampling||this._customInputBuffer.texture.format!==p.texture.format||this._customInputBuffer.texture.type!==d.HalfFloatType)&&((_=this._customInputBuffer)==null||_.dispose(),this._customInputBuffer=new d.WebGLRenderTarget(p.width,p.height,{format:p.texture.format,type:d.HalfFloatType,depthBuffer:p.depthBuffer,depthTexture:p.depthTexture?new d.DepthTexture(p.width,p.height):void 0,stencilBuffer:p.stencilBuffer,samples:Math.max(0,this._multisampling),minFilter:p.texture.minFilter??d.LinearFilter,magFilter:p.texture.magFilter??d.LinearFilter,generateMipmaps:p.texture.generateMipmaps}),this._customInputBufferId++,this._customInputBuffer.texture.name=`CustomInputBuffer-${this._customInputBufferId}`,this._customInputBuffer.depthTexture&&p.depthTexture&&(this._customInputBuffer.depthTexture.format=p.depthTexture.format,this._customInputBuffer.depthTexture.type=p.depthTexture.type),this._customInputBuffer.samples>0&&(this._customInputBuffer.ignoreDepthForMultisampleCopy=!1),ps&&console.warn(`[PostProcessing] Input buffer created with size ${this._customInputBuffer.width}x${this._customInputBuffer.height} and samples ${this._customInputBuffer.samples}`)),c.call(l,f,this._customInputBuffer,g,y,b),Mr.blit(this._customInputBuffer.texture,p,{renderer:f,depthTexture:this._customInputBuffer.depthTexture,depthWrite:!0,depthTest:!0}))};try{Hk(this._effects);let f=!1,p=null;for(let b=this._effects.length-1;b>=0;b--){const _=this._effects[b].effect;if(_ instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect){if(f){ps&&console.warn(`[PostProcessing] Found multiple tonemapping effects in the scene: ${_.name} and ${p==null?void 0:p.name}. Only the last one added will be used.`),this._effects.splice(b,1);continue}p=_,f=!0}}const g=[];let y=!1;for(let b=0;b<this._effects.length;b++){const v=this._effects[b].effect;if(v instanceof exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect?this._hasSmaaEffect=!0:v instanceof exports.MODULES.POSTPROCESSING.MODULE.NormalPass&&(this._anyPassHasNormal=!0),!(v instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect&&p!==v))if(v instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect){const w=v.getAttributes(),x=exports.MODULES.POSTPROCESSING.MODULE.EffectAttribute.CONVOLUTION;w&x&&(ps&&console.log("[PostProcessing] Convolution effect: "+v.name),y&&(ps&&console.log("[PostProcessing] → Merging effects ["+g.map(O=>O.name).join(", ")+"]"),this.createPassForMergeableEffects(g,a,s,n)),y=!0),g.push(v)}else v instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass?(y=!1,this.createPassForMergeableEffects(g,a,s,n),v.renderToScreen=!1,a.addPass(v)):(y=!1,this.createPassForMergeableEffects(g,a,s,n),a.addPass(v))}this.createPassForMergeableEffects(g,a,s,n)}catch(f){console.error("Error while applying postprocessing effects",f),a.passes.forEach(p=>p.dispose()),a.removeAllPasses()}let h=!1;for(let f=a.passes.length-1;f>=0;f--){const p=a.passes[f];let g=!1,y=!1;p.enabled&&(h||(g=!0,y=!0),h=!0),p.renderToScreen=y,(p==null?void 0:p.configuration)!==void 0?p.configuration.gammaCorrection=g:"autosetGamma"in p&&(p.autosetGamma=g),this._anyPassHasDepth||(this._anyPassHasDepth=p.needsDepthTexture)}ps&&console.log("[PostProcessing] Passes →",[...a.passes],`
1320
1320
  ---------------------------------
1321
- • `+a.passes.map(f=>f.name).join(`
1321
+ • `+a.passes.map(f=>f.name||f.constructor.name+"*").join(`
1322
1322
  • `)+`
1323
- `),ps&&this._onCreateEffectsDebug(this._composer,s)}createPassForMergeableEffects(t,e,i,n){if(t.length>0){const s=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(i,...t);s.name=t.map(a=>a.name).join(", "),s.mainScene=n,s.enabled=!0,s.renderToScreen=!1,e.addPass(s),t.length=0}}_onCreateEffectsDebug(t,e){if(ps==="passes"){const i=new exports.MODULES.POSTPROCESSING.MODULE.DepthEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(e,i);if(n.name="Depth Effect Pass",n.enabled=!1,t.passes.push(n),this._passIndices!==null){const a=[t.passes[0]];this._passIndices.length>0&&a.push(...this._passIndices.filter(l=>l!==0).map(l=>t.passes[l]).filter(l=>l)),a.length>0&&console.log("[PostProcessing] Passes (selected) →",a),t.passes.length=0;for(const l of a)l.enabled=!0,l.renderToScreen=!1,t.addPass(l)}const s=this.context.menu;if(s&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const a=document.createElement("select");a.multiple=!0;const l=document.createElement("option");l.innerText="Final Output",l.value="-1",a.appendChild(l);for(const c of t.passes){const h=document.createElement("option");h.innerText=c.name,h.value=`${t.passes.indexOf(c)}`,h.title=c.name,a.appendChild(h)}s.appendChild(a),this._menuEntry=a,a.addEventListener("change",()=>{const c=Array.from(a.selectedOptions).map(h=>parseInt(h.value));c.length===1&&c[0]===-1?this._passIndices=null:this._passIndices=c,this.applyEffects(this.context)})}}}}var CR=Object.defineProperty,yx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&CR(t,e,n),n};const Yo=S("debugpost");class vl extends I{constructor(){super(...arguments);r(this,"sharedProfile");r(this,"multisampling","auto");r(this,"_postprocessing");r(this,"_activeEffects",[]);r(this,"_effects",[]);r(this,"_componentEnabledTime",-1);r(this,"_multisampleAutoChangeTime",0);r(this,"_multisampleAutoDecreaseTime",0);r(this,"_lastApplyTime");r(this,"_rapidApplyCount",0);r(this,"_isDirty",!1);r(this,"_modificationQueue");r(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}addEffect(e){let i=e;return i instanceof Ye||(i=new Gc(i)),i.gameObject===void 0&&this.gameObject.addComponent(i),this._effects.includes(i)||(this._effects.push(i),this._isDirty=!0),e}removeEffect(e){var n,s,a,l;let i=-1;if(e instanceof Ye?i=this._effects.indexOf(e):i=this._effects.findIndex(c=>c instanceof Gc&&c.effect===e),i!==-1)return this._effects.splice(i,1),this._isDirty=!0,e;if(e instanceof Ye){const c=(s=(n=this.sharedProfile)==null?void 0:n.components)==null?void 0:s.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(l=(a=this.sharedProfile)==null?void 0:a.components)==null||l.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;Yo&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(this.enabled=!this.enabled,Ee("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(Yo||j())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' on your PostprocessingManager/Volume component that also has an SMAA effect.
1323
+ `),ps&&this._onCreateEffectsDebug(this._composer,s)}createPassForMergeableEffects(t,e,i,n){if(t.length>0){const s=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(i,...t);s.name=t.map(a=>a.name).join(", "),s.mainScene=n,s.enabled=!0,s.renderToScreen=!1,e.addPass(s),t.length=0}}_onCreateEffectsDebug(t,e){if(ps==="passes"){const i=new exports.MODULES.POSTPROCESSING.MODULE.DepthEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(e,i);if(n.name="Depth Effect Pass",n.enabled=!1,t.passes.push(n),this._passIndices!==null){const a=[t.passes[0]];this._passIndices.length>0&&a.push(...this._passIndices.filter(l=>l!==0).map(l=>t.passes[l]).filter(l=>l)),a.length>0&&console.log("[PostProcessing] Passes (selected) →",a),t.passes.length=0;for(const l of a)l.enabled=!0,l.renderToScreen=!1,t.addPass(l)}const s=this.context.menu;if(s&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const a=document.createElement("select");a.multiple=!0;const l=document.createElement("option");l.innerText="Final Output",l.value="-1",a.appendChild(l);for(const c of t.passes){const h=document.createElement("option");h.innerText=c.name,h.value=`${t.passes.indexOf(c)}`,h.title=c.name,a.appendChild(h)}s.appendChild(a),this._menuEntry=a,a.addEventListener("change",()=>{const c=Array.from(a.selectedOptions).map(h=>parseInt(h.value));c.length===1&&c[0]===-1?this._passIndices=null:this._passIndices=c,this.applyEffects(this.context)})}}}}var CR=Object.defineProperty,yx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&CR(t,e,n),n};const Yo=S("debugpost");class vl extends I{constructor(){super(...arguments);r(this,"sharedProfile");r(this,"multisampling","auto");r(this,"_postprocessing");r(this,"_activeEffects",[]);r(this,"_effects",[]);r(this,"_componentEnabledTime",-1);r(this,"_multisampleAutoChangeTime",0);r(this,"_multisampleAutoDecreaseTime",0);r(this,"_lastApplyTime");r(this,"_rapidApplyCount",0);r(this,"_isDirty",!1);r(this,"_modificationQueue");r(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}addEffect(e){let i=e;return i instanceof Ye||(i=new Gc(i),typeof e.order=="number"&&(i.order=e.order)),i.gameObject===void 0&&this.gameObject.addComponent(i),this._effects.includes(i)||(this._effects.push(i),this._isDirty=!0),e}removeEffect(e){var n,s,a,l;let i=-1;if(e instanceof Ye?i=this._effects.indexOf(e):i=this._effects.findIndex(c=>c instanceof Gc&&c.effect===e),i!==-1)return this._effects.splice(i,1),this._isDirty=!0,e;if(e instanceof Ye){const c=(s=(n=this.sharedProfile)==null?void 0:n.components)==null?void 0:s.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(l=(a=this.sharedProfile)==null?void 0:a.components)==null||l.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;Yo&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(this.enabled=!this.enabled,Ee("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(Yo||j())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' on your PostprocessingManager/Volume component that also has an SMAA effect.
1324
1324
 
1325
- If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const i=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let n=this._postprocessing.multisampling*.5;n=Math.floor(n),n!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=n),Yo&&console.debug(`[PostProcessing] Reduced multisampling from ${i} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let n=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;n=Math.floor(n),n!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=n),Yo&&console.debug(`[PostProcessing] Increased multisampling from ${i} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const i of e)if(i.mainCamera&&i.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,i,n;if(Yo&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),j()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const s=this.sharedProfile.components;for(const a of s)a.active&&a.enabled&&!this._activeEffects.includes(a)&&this._activeEffects.push(a)}for(const s of this._effects)s.active&&s.enabled&&!this._activeEffects.includes(s)&&this._activeEffects.push(s);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new jy(this.context)),(i=this._postprocessing.apply(this._activeEffects))==null||i.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),Yo&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):Yo&&console.warn("[PostProcessing] No composer found"))})):(n=this._postprocessing)==null||n.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var i,n;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((i=this._activeEffects)!=null&&i.length))return;const s=e.propertyName.split(".");if(s.length===3||s.length===4){const a=s[1],l=s[2];for(const c of this._activeEffects)if(((n=c.typeName)==null?void 0:n.toLowerCase())===a.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!Md.has(a)){const h=new Array;Md.set(a,h);const u=Object.keys(c);for(const f of u)c[f]instanceof U&&h.push(f)}if(Md.has(a)){const h=l.toLowerCase(),u=Md.get(a);for(const f of u)if(f.toLowerCase()===h){const p=c[f];p instanceof U&&(s.length===4&&s[3]==="active"?(p.overrideState=e.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}yx([Br(bf)],vl.prototype,"sharedProfile");yx([Br()],vl.prototype,"multisampling");const Md=new Map;Wk(vl);async function By(o){const{NeedleEngineWebComponent:t}=await Promise.resolve().then(()=>eT);t.observedAttributes.includes(o)||t.observedAttributes.push(o)}var PR=Object.defineProperty,pt=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&PR(t,e,n),n};const Ot=S("debugsceneswitcher"),MR=S("sceneswitcher:clearscene"),Wd="scene";By(Wd);const Js=Promise.resolve(!1);class Ge extends I{constructor(){super(...arguments);r(this,"autoLoadFirstScene",!0);r(this,"scenes",[]);r(this,"loadingScene");r(this,"queryParameterName","scene");r(this,"useSceneName",!0);r(this,"clamp",!0);r(this,"useHistory",!0);r(this,"useKeyboard",!0);r(this,"useSwipe",!0);r(this,"useSceneLighting",!0);r(this,"useSceneBackground",!0);r(this,"preloadNext",1);r(this,"preloadPrevious",1);r(this,"preloadConcurrent",2);r(this,"createMenuButtons",!1);r(this,"sceneLoadingStart",new ye);r(this,"sceneLoadingProgress",new ye);r(this,"sceneLoaded",new ye);r(this,"_currentIndex",-1);r(this,"_currentScene");r(this,"_engineElementOverserver");r(this,"_preloadScheduler");r(this,"_menuButtons");r(this,"onPopState",async e=>{if(!this.useHistory)return;const i=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const s=e==null?void 0:e.state;if(s&&s.startsWith(this.guid)){const a=s.substr(this.guid.length+2);Ot&&console.log("PopState",a),await this.trySelectSceneFromValue(a)}}}finally{this.useHistory=i}});r(this,"normalizedSwipeThresholdX",.1);r(this,"_didSwipe",!1);r(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const i=this.context.input.getPointerPositionDelta(e.button);if(i){const n=i.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}});r(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)});r(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const i=e.key.toLowerCase();if(!i)return;const n=parseInt(i)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(i){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}});r(this,"__lastSwitchScene");r(this,"__lastSwitchScenePromise");r(this,"_currentlyLoadingScene");r(this,"_lastLoadingScene");r(this,"_loadingScenePromise");r(this,"_isCurrentlyLoading",!1);r(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof d.Object3D?C.remove(e.asset):e instanceof d.Object3D&&C.remove(e);Ot&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Re.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Re.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Re.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const i of e)if(i.type==="attributes"&&i.attributeName===Wd){const n=this.context.domElement.getAttribute(Wd);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new OR(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Wd);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Re.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Re.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Re.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const i of this._menuButtons)i.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let i=this.context.addressables.findAssetReference(e);return i||(i=new te(e),this.context.addressables.registerAssetReference(i)),this.scenes.push(i),i}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var n,s,a;if(Ot&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(n=this.scenes)==null?void 0:n.find(c=>c.url===e);if(!l){const c=te.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(s=this.scenes)==null?void 0:s.indexOf(l);else return Js}if(!((a=this.scenes)!=null&&a.length))return Js;if(e<0){if(this.clamp)return Js;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Js;e=0}const i=this.scenes[e];return this.switchScene(i)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var n;if(!(e instanceof te)){const s=typeof e;if(s==="string")return this.select(e);if(s==="number")return this.select(e);if(e&&e instanceof d.Object3D){const a=(n=this.scenes)==null?void 0:n.indexOf(e);e=new te(e.name,void 0,e),a>=0&&(this.scenes[a]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${s}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Ot&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const i=this.tryGetSceneEventListener(e.asset);if(i!=null&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}e.hasUrl?e.unload():e.asset instanceof d.Object3D&&C.remove(e.asset)}}async __internalSwitchScene(e){var n,s,a,l,c;await this.__unloadCurrentScene();const i=this._currentIndex=((n=this.scenes)==null?void 0:n.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:i}});this.dispatchEvent(h),(s=this.sceneLoadingStart)==null||s.invoke(h.detail),await this.onStartLoading(),await e.loadAssetAsync((f,p)=>{var g;if(Ot){const y=p.loaded/p.total,b="["+"=".repeat(Math.floor(y*20))+"-".repeat(20-Math.floor(y*20))+"]";console.debug(`[SceneSwitcher] Download ${(y*100).toFixed(1)} % ${b}`,e.url)}this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const u=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:i}});if(this.dispatchEvent(u),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,u.defaultPrevented)return Ot&&console.warn("Adding loaded scene prevented:",e,u),!1;if(!e.asset)return Ot&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===i){if(Ot&&console.log("ADD",e.url),this._currentScene=e,MR){const g=((a=this.context.mainCameraComponent)==null?void 0:a.gameObject)||this.context.mainCamera;g==null||g.removeFromParent();const y=this.gameObject.removeFromParent();Ri(this.context.scene,!0,!0),this.context.scene=new d.Scene,this.context.scene.add(y),g&&this.context.scene.add(g)}if(C.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=d.EquirectangularReflectionMapping,this.context.scene.background=g):Ot&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&i>=0){let g=i.toString();if(this.useSceneName&&(e instanceof d.Object3D?g=e.name:e.url&&(g=Nb(e.url))),(l=this.queryParameterName)!=null&&l.length)Oc(this.queryParameterName,g,this.useHistory);else{const y=history.state,b=this.guid+"::"+i;y!==b&&history.pushState(b,"unused",location.href)}}const f=this.tryGetSceneEventListener(e.asset);if(f!=null&&f.sceneOpened){const g=f.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:i}});return this.dispatchEvent(p),(c=this.sceneLoaded)==null||c.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const i=this.scenes[e];if(i instanceof te)return i.preload()}return Js}tryLoadFromQueryParam(){var i;if(!((i=this.queryParameterName)!=null&&i.length))return Js;const e=S(this.queryParameterName);return typeof e=="boolean"?Js:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const i=parseInt(e);if(i>=0&&i<this.scenes.length)return this.select(i);{const n=e.toLowerCase();for(let s=0;s<this.scenes.length;s++){const a=this.scenes[s];if(!a)continue;if((a instanceof d.Object3D?a.name:Nb(a.url)).toLowerCase().includes(n))return this.select(s)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Kt()&&console.warn('Can not find scene: "'+e+'"',this),Js}async onStartLoading(){var e,i;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(n=>n!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&((i=this.loadingScene)!=null&&i.asset))){Ot&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const n=this.loadingScene.asset;C.add(n,this.gameObject);const s=this.tryGetSceneEventListener(n);if(s!=null&&s.sceneOpened){const a=s.sceneOpened(this);a instanceof Promise&&await a}}if(this._isCurrentlyLoading){const n=this.tryGetSceneEventListener(this.gameObject);if(n&&n.sceneOpened){const s=n.sceneOpened(this);s instanceof Promise&&await s}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Ot&&console.log("Remove loading scene",this.loadingScene.url);const i=this.loadingScene.asset,n=this.tryGetSceneEventListener(i);if(typeof(n==null?void 0:n.sceneClosing)=="function"){const s=n.sceneClosing();s instanceof Promise&&await s}C.remove(i)}if(!this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}}}tryGetSceneEventListener(e,i=0){if(!e)return null;const n=C.foreachComponent(e,s=>{const a=s;if(a.sceneClosing||a.sceneOpened)return a});if(i===0&&!n&&e.children.length)for(const s of e.children){const a=this.tryGetSceneEventListener(s,i+1);if(a)return a}return n||null}}pt([m()],Ge.prototype,"autoLoadFirstScene");pt([m(te)],Ge.prototype,"scenes");pt([m(te)],Ge.prototype,"loadingScene");pt([m()],Ge.prototype,"queryParameterName");pt([m()],Ge.prototype,"useSceneName");pt([m()],Ge.prototype,"clamp");pt([m()],Ge.prototype,"useHistory");pt([m()],Ge.prototype,"useKeyboard");pt([m()],Ge.prototype,"useSwipe");pt([m()],Ge.prototype,"useSceneLighting");pt([m()],Ge.prototype,"useSceneBackground");pt([m()],Ge.prototype,"preloadNext");pt([m()],Ge.prototype,"preloadPrevious");pt([m()],Ge.prototype,"preloadConcurrent");pt([m()],Ge.prototype,"createMenuButtons");pt([m(ye)],Ge.prototype,"sceneLoadingStart");pt([m(ye)],Ge.prototype,"sceneLoadingProgress");pt([m(ye)],Ge.prototype,"sceneLoaded");function Nb(o){const t=o.split("/").pop(),e=t==null?void 0:t.split(".").shift();return e!=null&&e.length?e:o}class OR{constructor(t,e=1,i=1,n=2){r(this,"maxLoadAhead");r(this,"maxLoadBehind");r(this,"maxConcurrent");r(this,"_isRunning",!1);r(this,"_switcher");r(this,"_loadTasks",[]);r(this,"_maxConcurrentLoads",1);this._switcher=t,this.maxLoadAhead=e,this.maxLoadBehind=i,this.maxConcurrent=n}begin(t){if(this._isRunning)return;Ot&&console.log("Preload begin",{delay:t}),this._isRunning=!0;let e=-10,i,n;const s=this._switcher.scenes,a=Date.now()+t,l=setInterval(()=>{if(this.allLoaded()&&(Ot&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(l);return}if(Date.now()<a||this.canLoadNewScene()===!1)return;(e===-10||e!==this._switcher.currentIndex)&&(e=this._switcher.currentIndex,n=0,i=0);const c=n%2===0;c&&(i+=1),n+=1;const h=c?this.maxLoadAhead:this.maxLoadBehind;if(i>h)return;const u=c?e+i:e-i;if(!(u<0)&&!(u<0||u>=s.length)&&!this._loadTasks.some(f=>f.index===u)){const f=s[u];Ot&&console.log("Preload scene",{roomIndex:u,searchForward:c,lastRoom:e,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},f==null?void 0:f.url),new kR(u,f,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const t of this._switcher.scenes)if(t!=null&&t.isLoaded&&t.isLoaded()===!1)return!1}return!0}}class kR{constructor(t,e,i){r(this,"index");r(this,"asset");r(this,"tasks");this.index=t,this.asset=e,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Ot&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Ot&&console.log("Preload finished: "+this.asset.url,this.index));const t=this.tasks.indexOf(this);t>=0&&this.tasks.splice(t,1)}}function RR(){return new Promise((o,t)=>{const i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),o())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function ER(o){await RR(),o()}var TR=Object.defineProperty,AR=Object.getOwnPropertyDescriptor,Ii=(o,t,e,i)=>{for(var n=i>1?void 0:i?AR(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&TR(t,e,n),n};const ct=S("debugvideo");var _x=(o=>(o[o.None=0]="None",o[o.AdjustHeight=1]="AdjustHeight",o[o.AdjustWidth=2]="AdjustWidth",o))(_x||{}),bx=(o=>(o[o.VideoClip=0]="VideoClip",o[o.Url=1]="Url",o))(bx||{}),vx=(o=>(o[o.CameraFarPlane=0]="CameraFarPlane",o[o.CameraNearPlane=1]="CameraNearPlane",o[o.RenderTexture=2]="RenderTexture",o[o.MaterialOverride=3]="MaterialOverride",o))(vx||{});class rt extends I{constructor(){super();r(this,"playOnAwake",!0);r(this,"aspectMode",0);r(this,"clip",null);r(this,"source",1);r(this,"_url",null);r(this,"renderMode");r(this,"targetMaterialProperty");r(this,"targetMaterialRenderer");r(this,"targetTexture");r(this,"time",0);r(this,"_playbackSpeed",1);r(this,"_isLooping",!1);r(this,"_muted",!1);r(this,"_audioOutputMode",2);r(this,"playInBackground",!0);r(this,"_crossOrigin","anonymous");r(this,"_videoElement",null);r(this,"_videoTexture",null);r(this,"_videoMaterial",null);r(this,"_isPlaying",!1);r(this,"wasPlaying",!1);r(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}});r(this,"_receivedInput",!1);r(this,"_overlay",null);r(this,"_targetObjects");r(this,"_updateAspectRoutineId",-1);r(this,"_hls");r(this,"onHlsAvailable",()=>{var e;ct&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),ct&&console.log("HLS: loaded",this.clip))});ER(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],S("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const n=this._url!==e;this.__didAwake?n&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&j()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){ct&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,ct&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,i;ct&&console.log("VideoPlayer.onEnable",bx[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(i=this._overlay)==null||i.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,i;if(this._videoElement||this.create(!1),!this._videoElement){ct&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((i=this._videoElement)!=null&&i.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}ct&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var s;console.log(n),ct&&console.error("Error playing video",n,"CODE="+n.code,(s=this.videoElement)==null?void 0:s.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),ct&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),ct&&console.log("STOP",this))}pause(){var e,i;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(i=this._videoElement)==null||i.pause(),ct&&console.log("PAUSE",this,this.currentTime)}create(e){let i;switch(this.source){case 0:i=this.clip;break;case 1:i=this.url,!(i!=null&&i.length)&&typeof this.clip=="string"&&(i=this.clip);break}return i?(this._videoElement||(ct&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof i=="string"?(ct&&console.log("Set Video src",i),this._videoElement.src=i):(ct&&console.log("Set Video srcObject",i),this._videoElement.srcObject=i),this._videoTexture||(this._videoTexture=new d.VideoTexture(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=d.SRGBColorSpace,e&&this.handleBeginPlaying(e),ct&&console.log("Video: handle playing done...",i,e),!0):(ct&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var i;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new LR(this.context)),this._overlay.add(this._videoTexture)}else(i=this._overlay)==null||i.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ct&&console.log("created video element",e),e}handleBeginPlaying(e){var s,a;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let i=this.gameObject;switch(this.renderMode){case 3:i=(s=this.targetMaterialRenderer)==null?void 0:s.gameObject,i||(i=(a=C.getComponent(this.gameObject,Ti))==null?void 0:a.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!i){console.error("Missing target for video material renderer",this.name,vx[this.renderMode],this);return}const n=i.material;if(n){this._targetObjects.push(i),n!==this._videoMaterial&&(this._videoMaterial=n.clone(),i.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,i=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let s;for(const a of n.getVideoTracks()){const l=a.getSettings();if(l&&l.width&&l.height){s=l.width/l.height;break}else s=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(s===void 0){for(let a=0;a<10;a++)yield;if(!this.isPlaying)break;continue}if(i===s){yield;continue}for(const a of this._targetObjects){let l=1;if(a.parent){const c=Ue(a.parent);l=c.x/c.y}switch(this.aspectMode){case 1:a.scale.y=1/s*a.scale.x*l;break;case 2:a.scale.x=s*a.scale.y*l;break}}for(let a=0;a<3;a++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(ct&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Ii([m()],rt.prototype,"playOnAwake",2);Ii([m()],rt.prototype,"aspectMode",2);Ii([m(URL)],rt.prototype,"clip",2);Ii([m()],rt.prototype,"source",2);Ii([m(URL)],rt.prototype,"url",1);Ii([m()],rt.prototype,"renderMode",2);Ii([m()],rt.prototype,"targetMaterialProperty",2);Ii([m(Ti)],rt.prototype,"targetMaterialRenderer",2);Ii([m(d.Texture)],rt.prototype,"targetTexture",2);Ii([m()],rt.prototype,"time",2);Ii([m()],rt.prototype,"playbackSpeed",1);Ii([m()],rt.prototype,"isLooping",1);Ii([m()],rt.prototype,"audioOutputMode",1);class LR{constructor(t){r(this,"context");r(this,"_videos",[]);r(this,"_screenspaceModeQuad");r(this,"_isInScreenspaceMode",!1);r(this,"_input");this.context=t,this._input=new DR(this)}get enabled(){return this._isInScreenspaceMode}set enabled(t){t?this.start():this.stop()}add(t){this._videos.indexOf(t)===-1&&this._videos.push(t)}remove(t){if(!t)return;const e=this._videos.indexOf(t);e>=0&&this._videos.splice(e,1)}start(){var n;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Lo.createPrimitive(Or.Quad,{material:new IR(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const e=this._screenspaceModeQuad;this.context.scene.add(e),this.updateScreenspaceMaterialUniforms();const i=e.material;i==null||i.reset(),(n=this._input)==null||n.enable(i)}stop(){var t;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((t=this._input)==null||t.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class DR{constructor(t){r(this,"_onResizeScreenFn");r(this,"_onKeyUpFn");r(this,"_onMouseWheelFn");r(this,"context");r(this,"overlay");r(this,"_material");r(this,"_isPinching",!1);r(this,"_lastPinch",0);this.overlay=t,this.context=t.context}enable(t){this._material=t,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(t.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const e=new d.Vector2;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const s=new d.Vector2(n.movementX,n.movementY);s.x/=this.context.domElement.clientWidth,s.y/=this.context.domElement.clientHeight,e.set(s.x,s.y),e.multiplyScalar(t.zoom/-this.context.time.deltaTime*.01),t.offset=t.offset.add(e)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(e.set(n.movementX,n.movementY),e.multiplyScalar(t.zoom*-this.context.time.deltaTime*.05),t.offset=t.offset.add(e))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const s=n.touches[0],a=n.touches[1],l=s.clientX-a.clientX,c=s.clientY-a.clientY,h=Math.sqrt(l*l+c*c);if(this._lastPinch!==0){const u=h-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=h}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class IR extends d.ShaderMaterial{constructor(e){super();r(this,"_offset",new d.Vector2);this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new d.Vector4(0,0,1,1)}},this.vertexShader=`
1325
+ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const i=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let n=this._postprocessing.multisampling*.5;n=Math.floor(n),n!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=n),Yo&&console.debug(`[PostProcessing] Reduced multisampling from ${i} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let n=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;n=Math.floor(n),n!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=n),Yo&&console.debug(`[PostProcessing] Increased multisampling from ${i} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const i of e)if(i.mainCamera&&i.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,i,n;if(Yo&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),j()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const s=this.sharedProfile.components;for(const a of s)a.active&&a.enabled&&!this._activeEffects.includes(a)&&this._activeEffects.push(a)}for(const s of this._effects)s.active&&s.enabled&&!this._activeEffects.includes(s)&&this._activeEffects.push(s);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new jy(this.context)),(i=this._postprocessing.apply(this._activeEffects))==null||i.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),Yo&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):Yo&&console.warn("[PostProcessing] No composer found"))})):(n=this._postprocessing)==null||n.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var i,n;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((i=this._activeEffects)!=null&&i.length))return;const s=e.propertyName.split(".");if(s.length===3||s.length===4){const a=s[1],l=s[2];for(const c of this._activeEffects)if(((n=c.typeName)==null?void 0:n.toLowerCase())===a.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!Md.has(a)){const h=new Array;Md.set(a,h);const u=Object.keys(c);for(const f of u)c[f]instanceof U&&h.push(f)}if(Md.has(a)){const h=l.toLowerCase(),u=Md.get(a);for(const f of u)if(f.toLowerCase()===h){const p=c[f];p instanceof U&&(s.length===4&&s[3]==="active"?(p.overrideState=e.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}yx([Br(bf)],vl.prototype,"sharedProfile");yx([Br()],vl.prototype,"multisampling");const Md=new Map;Wk(vl);async function By(o){const{NeedleEngineWebComponent:t}=await Promise.resolve().then(()=>eT);t.observedAttributes.includes(o)||t.observedAttributes.push(o)}var PR=Object.defineProperty,pt=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&PR(t,e,n),n};const Mt=S("debugsceneswitcher"),MR=S("sceneswitcher:clearscene"),Wd="scene";By(Wd);const Js=Promise.resolve(!1);class Ge extends I{constructor(){super(...arguments);r(this,"autoLoadFirstScene",!0);r(this,"scenes",[]);r(this,"loadingScene");r(this,"queryParameterName","scene");r(this,"useSceneName",!0);r(this,"clamp",!0);r(this,"useHistory",!0);r(this,"useKeyboard",!0);r(this,"useSwipe",!0);r(this,"useSceneLighting",!0);r(this,"useSceneBackground",!0);r(this,"preloadNext",1);r(this,"preloadPrevious",1);r(this,"preloadConcurrent",2);r(this,"createMenuButtons",!1);r(this,"sceneLoadingStart",new ye);r(this,"sceneLoadingProgress",new ye);r(this,"sceneLoaded",new ye);r(this,"_currentIndex",-1);r(this,"_currentScene");r(this,"_engineElementOverserver");r(this,"_preloadScheduler");r(this,"_menuButtons");r(this,"onPopState",async e=>{if(!this.useHistory)return;const i=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const s=e==null?void 0:e.state;if(s&&s.startsWith(this.guid)){const a=s.substr(this.guid.length+2);Mt&&console.log("PopState",a),await this.trySelectSceneFromValue(a)}}}finally{this.useHistory=i}});r(this,"normalizedSwipeThresholdX",.1);r(this,"_didSwipe",!1);r(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const i=this.context.input.getPointerPositionDelta(e.button);if(i){const n=i.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}});r(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)});r(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const i=e.key.toLowerCase();if(!i)return;const n=parseInt(i)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(i){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}});r(this,"__lastSwitchScene");r(this,"__lastSwitchScenePromise");r(this,"_currentlyLoadingScene");r(this,"_lastLoadingScene");r(this,"_loadingScenePromise");r(this,"_isCurrentlyLoading",!1);r(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof d.Object3D?C.remove(e.asset):e instanceof d.Object3D&&C.remove(e);Mt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Re.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Re.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Re.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const i of e)if(i.type==="attributes"&&i.attributeName===Wd){const n=this.context.domElement.getAttribute(Wd);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new OR(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Wd);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Re.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Re.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Re.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const i of this._menuButtons)i.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let i=this.context.addressables.findAssetReference(e);return i||(i=new te(e),this.context.addressables.registerAssetReference(i)),this.scenes.push(i),i}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var n,s,a;if(Mt&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(n=this.scenes)==null?void 0:n.find(c=>c.url===e);if(!l){const c=te.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(s=this.scenes)==null?void 0:s.indexOf(l);else return Js}if(!((a=this.scenes)!=null&&a.length))return Js;if(e<0){if(this.clamp)return Js;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Js;e=0}const i=this.scenes[e];return this.switchScene(i)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var n;if(!(e instanceof te)){const s=typeof e;if(s==="string")return this.select(e);if(s==="number")return this.select(e);if(e&&e instanceof d.Object3D){const a=(n=this.scenes)==null?void 0:n.indexOf(e);e=new te(e.name,void 0,e),a>=0&&(this.scenes[a]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${s}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Mt&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const i=this.tryGetSceneEventListener(e.asset);if(i!=null&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}e.hasUrl?e.unload():e.asset instanceof d.Object3D&&C.remove(e.asset)}}async __internalSwitchScene(e){var n,s,a,l,c;await this.__unloadCurrentScene();const i=this._currentIndex=((n=this.scenes)==null?void 0:n.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:i}});this.dispatchEvent(h),(s=this.sceneLoadingStart)==null||s.invoke(h.detail),await this.onStartLoading(),await e.loadAssetAsync((f,p)=>{var g;if(Mt){const y=p.loaded/p.total,b="["+"=".repeat(Math.floor(y*20))+"-".repeat(20-Math.floor(y*20))+"]";console.debug(`[SceneSwitcher] Download ${(y*100).toFixed(1)} % ${b}`,e.url)}this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const u=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:i}});if(this.dispatchEvent(u),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,u.defaultPrevented)return Mt&&console.warn("Adding loaded scene prevented:",e,u),!1;if(!e.asset)return Mt&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===i){if(Mt&&console.log("ADD",e.url),this._currentScene=e,MR){const g=((a=this.context.mainCameraComponent)==null?void 0:a.gameObject)||this.context.mainCamera;g==null||g.removeFromParent();const y=this.gameObject.removeFromParent();Ri(this.context.scene,!0,!0),this.context.scene=new d.Scene,this.context.scene.add(y),g&&this.context.scene.add(g)}if(C.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=d.EquirectangularReflectionMapping,this.context.scene.background=g):Mt&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&i>=0){let g=i.toString();if(this.useSceneName&&(e instanceof d.Object3D?g=e.name:e.url&&(g=Nb(e.url))),(l=this.queryParameterName)!=null&&l.length)Oc(this.queryParameterName,g,this.useHistory);else{const y=history.state,b=this.guid+"::"+i;y!==b&&history.pushState(b,"unused",location.href)}}const f=this.tryGetSceneEventListener(e.asset);if(f!=null&&f.sceneOpened){const g=f.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:i}});return this.dispatchEvent(p),(c=this.sceneLoaded)==null||c.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const i=this.scenes[e];if(i instanceof te)return i.preload()}return Js}tryLoadFromQueryParam(){var i;if(!((i=this.queryParameterName)!=null&&i.length))return Js;const e=S(this.queryParameterName);return typeof e=="boolean"?Js:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const i=parseInt(e);if(i>=0&&i<this.scenes.length)return this.select(i);{const n=e.toLowerCase();for(let s=0;s<this.scenes.length;s++){const a=this.scenes[s];if(!a)continue;if((a instanceof d.Object3D?a.name:Nb(a.url)).toLowerCase().includes(n))return this.select(s)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Kt()&&console.warn('Can not find scene: "'+e+'"',this),Js}async onStartLoading(){var e,i;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(n=>n!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&((i=this.loadingScene)!=null&&i.asset))){Mt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const n=this.loadingScene.asset;C.add(n,this.gameObject);const s=this.tryGetSceneEventListener(n);if(s!=null&&s.sceneOpened){const a=s.sceneOpened(this);a instanceof Promise&&await a}}if(this._isCurrentlyLoading){const n=this.tryGetSceneEventListener(this.gameObject);if(n&&n.sceneOpened){const s=n.sceneOpened(this);s instanceof Promise&&await s}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Mt&&console.log("Remove loading scene",this.loadingScene.url);const i=this.loadingScene.asset,n=this.tryGetSceneEventListener(i);if(typeof(n==null?void 0:n.sceneClosing)=="function"){const s=n.sceneClosing();s instanceof Promise&&await s}C.remove(i)}if(!this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}}}tryGetSceneEventListener(e,i=0){if(!e)return null;const n=C.foreachComponent(e,s=>{const a=s;if(a.sceneClosing||a.sceneOpened)return a});if(i===0&&!n&&e.children.length)for(const s of e.children){const a=this.tryGetSceneEventListener(s,i+1);if(a)return a}return n||null}}pt([m()],Ge.prototype,"autoLoadFirstScene");pt([m(te)],Ge.prototype,"scenes");pt([m(te)],Ge.prototype,"loadingScene");pt([m()],Ge.prototype,"queryParameterName");pt([m()],Ge.prototype,"useSceneName");pt([m()],Ge.prototype,"clamp");pt([m()],Ge.prototype,"useHistory");pt([m()],Ge.prototype,"useKeyboard");pt([m()],Ge.prototype,"useSwipe");pt([m()],Ge.prototype,"useSceneLighting");pt([m()],Ge.prototype,"useSceneBackground");pt([m()],Ge.prototype,"preloadNext");pt([m()],Ge.prototype,"preloadPrevious");pt([m()],Ge.prototype,"preloadConcurrent");pt([m()],Ge.prototype,"createMenuButtons");pt([m(ye)],Ge.prototype,"sceneLoadingStart");pt([m(ye)],Ge.prototype,"sceneLoadingProgress");pt([m(ye)],Ge.prototype,"sceneLoaded");function Nb(o){const t=o.split("/").pop(),e=t==null?void 0:t.split(".").shift();return e!=null&&e.length?e:o}class OR{constructor(t,e=1,i=1,n=2){r(this,"maxLoadAhead");r(this,"maxLoadBehind");r(this,"maxConcurrent");r(this,"_isRunning",!1);r(this,"_switcher");r(this,"_loadTasks",[]);r(this,"_maxConcurrentLoads",1);this._switcher=t,this.maxLoadAhead=e,this.maxLoadBehind=i,this.maxConcurrent=n}begin(t){if(this._isRunning)return;Mt&&console.log("Preload begin",{delay:t}),this._isRunning=!0;let e=-10,i,n;const s=this._switcher.scenes,a=Date.now()+t,l=setInterval(()=>{if(this.allLoaded()&&(Mt&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(l);return}if(Date.now()<a||this.canLoadNewScene()===!1)return;(e===-10||e!==this._switcher.currentIndex)&&(e=this._switcher.currentIndex,n=0,i=0);const c=n%2===0;c&&(i+=1),n+=1;const h=c?this.maxLoadAhead:this.maxLoadBehind;if(i>h)return;const u=c?e+i:e-i;if(!(u<0)&&!(u<0||u>=s.length)&&!this._loadTasks.some(f=>f.index===u)){const f=s[u];Mt&&console.log("Preload scene",{roomIndex:u,searchForward:c,lastRoom:e,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},f==null?void 0:f.url),new kR(u,f,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const t of this._switcher.scenes)if(t!=null&&t.isLoaded&&t.isLoaded()===!1)return!1}return!0}}class kR{constructor(t,e,i){r(this,"index");r(this,"asset");r(this,"tasks");this.index=t,this.asset=e,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Mt&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Mt&&console.log("Preload finished: "+this.asset.url,this.index));const t=this.tasks.indexOf(this);t>=0&&this.tasks.splice(t,1)}}function RR(){return new Promise((o,t)=>{const i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),o())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function ER(o){await RR(),o()}var TR=Object.defineProperty,AR=Object.getOwnPropertyDescriptor,Ii=(o,t,e,i)=>{for(var n=i>1?void 0:i?AR(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&TR(t,e,n),n};const ct=S("debugvideo");var _x=(o=>(o[o.None=0]="None",o[o.AdjustHeight=1]="AdjustHeight",o[o.AdjustWidth=2]="AdjustWidth",o))(_x||{}),bx=(o=>(o[o.VideoClip=0]="VideoClip",o[o.Url=1]="Url",o))(bx||{}),vx=(o=>(o[o.CameraFarPlane=0]="CameraFarPlane",o[o.CameraNearPlane=1]="CameraNearPlane",o[o.RenderTexture=2]="RenderTexture",o[o.MaterialOverride=3]="MaterialOverride",o))(vx||{});class rt extends I{constructor(){super();r(this,"playOnAwake",!0);r(this,"aspectMode",0);r(this,"clip",null);r(this,"source",1);r(this,"_url",null);r(this,"renderMode");r(this,"targetMaterialProperty");r(this,"targetMaterialRenderer");r(this,"targetTexture");r(this,"time",0);r(this,"_playbackSpeed",1);r(this,"_isLooping",!1);r(this,"_muted",!1);r(this,"_audioOutputMode",2);r(this,"playInBackground",!0);r(this,"_crossOrigin","anonymous");r(this,"_videoElement",null);r(this,"_videoTexture",null);r(this,"_videoMaterial",null);r(this,"_isPlaying",!1);r(this,"wasPlaying",!1);r(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}});r(this,"_receivedInput",!1);r(this,"_overlay",null);r(this,"_targetObjects");r(this,"_updateAspectRoutineId",-1);r(this,"_hls");r(this,"onHlsAvailable",()=>{var e;ct&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),ct&&console.log("HLS: loaded",this.clip))});ER(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],S("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const n=this._url!==e;this.__didAwake?n&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&j()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){ct&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,ct&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,i;ct&&console.log("VideoPlayer.onEnable",bx[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(i=this._overlay)==null||i.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,i;if(this._videoElement||this.create(!1),!this._videoElement){ct&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((i=this._videoElement)!=null&&i.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}ct&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var s;console.log(n),ct&&console.error("Error playing video",n,"CODE="+n.code,(s=this.videoElement)==null?void 0:s.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),ct&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),ct&&console.log("STOP",this))}pause(){var e,i;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(i=this._videoElement)==null||i.pause(),ct&&console.log("PAUSE",this,this.currentTime)}create(e){let i;switch(this.source){case 0:i=this.clip;break;case 1:i=this.url,!(i!=null&&i.length)&&typeof this.clip=="string"&&(i=this.clip);break}return i?(this._videoElement||(ct&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof i=="string"?(ct&&console.log("Set Video src",i),this._videoElement.src=i):(ct&&console.log("Set Video srcObject",i),this._videoElement.srcObject=i),this._videoTexture||(this._videoTexture=new d.VideoTexture(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=d.SRGBColorSpace,e&&this.handleBeginPlaying(e),ct&&console.log("Video: handle playing done...",i,e),!0):(ct&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var i;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new LR(this.context)),this._overlay.add(this._videoTexture)}else(i=this._overlay)==null||i.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ct&&console.log("created video element",e),e}handleBeginPlaying(e){var s,a;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let i=this.gameObject;switch(this.renderMode){case 3:i=(s=this.targetMaterialRenderer)==null?void 0:s.gameObject,i||(i=(a=C.getComponent(this.gameObject,Ti))==null?void 0:a.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!i){console.error("Missing target for video material renderer",this.name,vx[this.renderMode],this);return}const n=i.material;if(n){this._targetObjects.push(i),n!==this._videoMaterial&&(this._videoMaterial=n.clone(),i.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,i=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let s;for(const a of n.getVideoTracks()){const l=a.getSettings();if(l&&l.width&&l.height){s=l.width/l.height;break}else s=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(s===void 0){for(let a=0;a<10;a++)yield;if(!this.isPlaying)break;continue}if(i===s){yield;continue}for(const a of this._targetObjects){let l=1;if(a.parent){const c=Ue(a.parent);l=c.x/c.y}switch(this.aspectMode){case 1:a.scale.y=1/s*a.scale.x*l;break;case 2:a.scale.x=s*a.scale.y*l;break}}for(let a=0;a<3;a++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(ct&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Ii([m()],rt.prototype,"playOnAwake",2);Ii([m()],rt.prototype,"aspectMode",2);Ii([m(URL)],rt.prototype,"clip",2);Ii([m()],rt.prototype,"source",2);Ii([m(URL)],rt.prototype,"url",1);Ii([m()],rt.prototype,"renderMode",2);Ii([m()],rt.prototype,"targetMaterialProperty",2);Ii([m(Ti)],rt.prototype,"targetMaterialRenderer",2);Ii([m(d.Texture)],rt.prototype,"targetTexture",2);Ii([m()],rt.prototype,"time",2);Ii([m()],rt.prototype,"playbackSpeed",1);Ii([m()],rt.prototype,"isLooping",1);Ii([m()],rt.prototype,"audioOutputMode",1);class LR{constructor(t){r(this,"context");r(this,"_videos",[]);r(this,"_screenspaceModeQuad");r(this,"_isInScreenspaceMode",!1);r(this,"_input");this.context=t,this._input=new DR(this)}get enabled(){return this._isInScreenspaceMode}set enabled(t){t?this.start():this.stop()}add(t){this._videos.indexOf(t)===-1&&this._videos.push(t)}remove(t){if(!t)return;const e=this._videos.indexOf(t);e>=0&&this._videos.splice(e,1)}start(){var n;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Lo.createPrimitive(Or.Quad,{material:new IR(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const e=this._screenspaceModeQuad;this.context.scene.add(e),this.updateScreenspaceMaterialUniforms();const i=e.material;i==null||i.reset(),(n=this._input)==null||n.enable(i)}stop(){var t;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((t=this._input)==null||t.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class DR{constructor(t){r(this,"_onResizeScreenFn");r(this,"_onKeyUpFn");r(this,"_onMouseWheelFn");r(this,"context");r(this,"overlay");r(this,"_material");r(this,"_isPinching",!1);r(this,"_lastPinch",0);this.overlay=t,this.context=t.context}enable(t){this._material=t,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(t.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const e=new d.Vector2;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const s=new d.Vector2(n.movementX,n.movementY);s.x/=this.context.domElement.clientWidth,s.y/=this.context.domElement.clientHeight,e.set(s.x,s.y),e.multiplyScalar(t.zoom/-this.context.time.deltaTime*.01),t.offset=t.offset.add(e)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(e.set(n.movementX,n.movementY),e.multiplyScalar(t.zoom*-this.context.time.deltaTime*.05),t.offset=t.offset.add(e))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const s=n.touches[0],a=n.touches[1],l=s.clientX-a.clientX,c=s.clientY-a.clientY,h=Math.sqrt(l*l+c*c);if(this._lastPinch!==0){const u=h-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=h}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class IR extends d.ShaderMaterial{constructor(e){super();r(this,"_offset",new d.Vector2);this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new d.Vector4(0,0,1,1)}},this.vertexShader=`
1326
1326
  uniform sampler2D map;
1327
1327
  uniform float screenAspect;
1328
1328
  uniform vec4 offsetScale;
@@ -1386,12 +1386,12 @@ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`))
1386
1386
  // be blended onto the scene.
1387
1387
  gl_FragColor = vec4(direct, max);
1388
1388
  return;
1389
- `)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new d.ShadowMaterial;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const i=new d.MeshBasicMaterial;this.targetMesh.material=i,e=i}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}xx([m()],zh.prototype,"mode");xx([m(ie)],zh.prototype,"shadowColor");var UR=Object.defineProperty,Nh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&UR(t,e,n),n};const _t=S("debugskybox");By("background-image");By("environment-image");function $b(o,t,e,i,n){if(t==="transparent"||t!=null&&t.startsWith("rgb")||t!=null&&t.startsWith("#"))return console.warn(`Needle Engine: Invalid ${n} value (${t}). Did you mean to set background-color instead?`),null;const s=new Sf;s.allowDrop=!1,s.allowNetworking=!1,s.background=e,s.environment=i,C.addComponent(o.scene,s);const a=l=>{typeof l=="string"&&(_t&&console.log(n,"CHANGED TO",l),s.setSkybox(l))};return d0(o.domElement,n,a),s.addEventListener("destroy",()=>{_t&&console.log("Destroyed attribute remote skybox",n),u0(o.domElement,n,a)}),s.setSkybox(t)}const Su=new Array;re.registerCallback(he.ContextCreationStart,o=>{const t=o.context,e=t.domElement.getAttribute("background-image"),i=t.domElement.getAttribute("environment-image");if(e){_t&&console.log("Creating remote skybox to load "+e);const n=$b(t,e,!0,!1,"background-image");n&&Su.push(n)}if(i){_t&&console.log("Creating remote environment to load "+i);const n=$b(t,i,!1,!0,"environment-image");n&&Su.push(n)}});re.registerCallback(he.ContextCreationStart,()=>Promise.all(Su).finally(()=>{Su.length=0}));function Sx(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function Vb(o){const e=Sx().find(i=>i.src===o);return e?(_t&&console.log("Skybox: Found previously loaded texture for "+o),e.texture):null}async function zR(o){const t=await o;fg(t,!0),Se(t)}function NR(o,t){const e=Sx();for(;e.length>5;){const i=e.shift();i&&zR(i.texture)}t.then(i=>fg(i,!1)),e.push({src:o,texture:t})}const Lr=class extends I{constructor(){super(...arguments);r(this,"url");r(this,"allowDrop",!0);r(this,"background",!0);r(this,"environment",!0);r(this,"allowNetworking",!0);r(this,"_loader");r(this,"_prevUrl");r(this,"_prevLoadedEnvironment");r(this,"_prevEnvironment",null);r(this,"_prevBackground",null);r(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]);r(this,"onDragOverEvent",e=>{if(this.allowDrop&&e.dataTransfer)for(const i of e.dataTransfer.types)(i==="text/uri-list"||i==="Files")&&e.preventDefault()});r(this,"onDrop",e=>{var i,n,s,a;if(this.allowDrop&&e.dataTransfer){for(const l of e.dataTransfer.types)if(_t&&console.log(l),l==="text/uri-list"){const c=e.dataTransfer.getData(l);_t&&console.log(l,c);let h=(n=(i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(c))==null?void 0:i.groups)==null?void 0:n.name;if(h||(h=(a=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(c))==null?void 0:s.groups)==null?void 0:a.name),_t&&console.log(h),h){const u="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+h+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${u}`),e.preventDefault(),this.setSkybox(u);break}else if(this.isValidTextureType(c)){console.log("[Remote Skybox] Setting skybox from url: "+c),e.preventDefault(),this.setSkybox(c);break}else{console.warn(`[RemoteSkybox] Unknown url ${c}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const u=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:c,apply:f=>{e.preventDefault(),this.setSkybox(f)}}});this.dispatchEvent(u)}}else if(l=="Files"){const c=e.dataTransfer.files.item(0);if(_t&&console.log(l,c),!c)continue;if(!this.isValidTextureType(c.name)){console.warn(`[RemoteSkybox]: File "${c.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(Vb(c.name)===null){const h=new Blob([c]),u=URL.createObjectURL(h);e.preventDefault(),this.setSkybox(u,c.name)}else e.preventDefault(),this.setSkybox(c.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var e;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,ai.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(e=this.context.mainCameraComponent)==null||e.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):_t&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(e,i){var a;if(!this.activeAndEnabled||(e=$R(e,this.environment,this.background),!e))return!1;try{e.startsWith("/")||e.startsWith(".")?new URL(e,window.location.href):new URL(e)}catch{return _t&&console.warn("RemoteSkybox: Invalid URL",e,this.name),!1}if(i??(i=e),this.isValidTextureType(i)||console.warn("Potentially invalid skybox url",i,"on",this.name),_t&&console.log("Set remote skybox url: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.apply(),!0;(a=this._prevLoadedEnvironment)==null||a.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const n=await this.loadTexture(e,i);if(!n)return _t&&console.warn("RemoteSkybox: Failed to load texture from url",e),!1;if(!this.enabled)return _t&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==e)return _t&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=e;const s=e.lastIndexOf("/");return n.name=e.substring(s>=0?s+1:0),this._loader instanceof d.TextureLoader&&(n.colorSpace=d.SRGBColorSpace),this._prevLoadedEnvironment=n,this.apply(),!0}async loadTexture(e,i){var u,f,p,g,y;if(!e)return Promise.resolve(null);i??(i=e);const n=Vb(i);if(n){const b=await n;if(((f=(u=b.source)==null?void 0:u.data)==null?void 0:f.length)>0||(y=(g=(p=b.source)==null?void 0:p.data)==null?void 0:g.data)!=null&&y.length)return b}const s=i.endsWith(".exr"),a=i.endsWith(".hdr"),l=i.endsWith(".ktx2");if(s)this._loader instanceof H.EXRLoader||(this._loader=new H.EXRLoader);else if(a)this._loader instanceof H.RGBELoader||(this._loader=new H.RGBELoader);else if(l){if(!(this._loader instanceof H.KTX2Loader)){const{ktx2Loader:b}=le.createLoaders(this.context.renderer);this._loader=b}}else this._loader instanceof d.TextureLoader||(this._loader=new d.TextureLoader);_t&&console.log("Loading skybox: "+e);const c=this._loader.loadAsync(e);return NR(i,c),await c}apply(){var i;const e=this._prevLoadedEnvironment;e&&(e instanceof d.CubeTexture||e instanceof d.CompressedCubeTexture||(e.mapping=d.EquirectangularRefractionMapping,e.needsUpdate=!0),this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),_t&&console.log("Set remote skybox",this.url,!ai.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!ai.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((i=this.context.mainCameraComponent)==null?void 0:i.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const i of this.validTextureTypes)if(e.endsWith(i))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}};Nh([hy(Lr.prototype.urlChangedSyncField),m(URL)],Lr.prototype,"url");Nh([m()],Lr.prototype,"allowDrop");Nh([m()],Lr.prototype,"background");Nh([m()],Lr.prototype,"environment");Nh([m()],Lr.prototype,"allowNetworking");let Sf=Lr;function $R(o,t,e){const i=t&&!e;switch(o==null?void 0:o.toLowerCase()){case"studio":return i?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return i?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return i?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return i?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return o===void 0?null:o}var VR=Object.defineProperty,Cf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&VR(t,e,n),n},ur;const $h=(ur=class extends I{constructor(){super(...arguments);r(this,"target",null);r(this,"followFactor",.1);r(this,"rotateFactor",.1);r(this,"positionAxes",xa.All);r(this,"flipForward",!1);r(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const i=Q(this.target),n=this._firstUpdate||e?1:z.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&xa.X&&(s.x=z.lerp(s.x,i.x,n)),this.positionAxes&xa.Y&&(s.y=z.lerp(s.y,i.y,n)),this.positionAxes&xa.Z&&(s.z=z.lerp(s.z,i.z,n)),this.worldPosition=s}if(this.rotateFactor>0){const i=_e(this.target);this.flipForward&&i.premultiply(ur._invertForward);const n=this._firstUpdate||e?1:z.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(i,n)}this._firstUpdate=!1}}},r(ur,"_invertForward",new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI)),ur);Cf([m(d.Object3D)],$h.prototype,"target");Cf([m()],$h.prototype,"followFactor");Cf([m()],$h.prototype,"rotateFactor");Cf([m()],$h.prototype,"positionAxes");let Pf=$h;var WR=Object.defineProperty,Vh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&WR(t,e,n),n};const _c=S("debugspatialtrigger"),Wb=new d.Layers,Gb=new d.Layers;function GR(o,t){return Wb.mask=o,Gb.mask=t,Wb.test(Gb)}class Zn extends I{constructor(){super(...arguments);r(this,"triggerMask",0);r(this,"onEnter");r(this,"onStay");r(this,"onExit");r(this,"currentIntersected",[]);r(this,"lastIntersected",[])}start(){_c&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Mf.triggers)GR(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const i=this.lastIntersected[e];this.currentIntersected.indexOf(i)<0&&(this.onExitTrigger(i),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var i;_c&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(i=this.onEnter)==null||i.invoke()}onExitTrigger(e){var i;_c&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(i=this.onExit)==null||i.invoke()}onStayTrigger(e){var i;e.raiseOnStayEvent(this),(i=this.onStay)==null||i.invoke()}}Vh([m()],Zn.prototype,"triggerMask");Vh([m(ye)],Zn.prototype,"onEnter");Vh([m(ye)],Zn.prototype,"onStay");Vh([m(ye)],Zn.prototype,"onExit");var ks;const Cx=(ks=class extends I{constructor(){super(...arguments);r(this,"triggerMask");r(this,"boxHelper")}start(){_c&&console.log(this.name,this.triggerMask,this)}onEnable(){var e;ks.triggers.push(this),this.boxHelper||(this.boxHelper=C.addComponent(this.gameObject,ts),(e=this.boxHelper)==null||e.showHelper(null,_c))}onDisable(){ks.triggers.splice(ks.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onStayTrigger(this)},!1)}raiseOnExitEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onExitTrigger(this)},!1)}},r(ks,"triggers",[]),ks);Vh([m()],Cx.prototype,"triggerMask");let Mf=Cx;var HR=Object.defineProperty,qR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&HR(t,e,n),n};const Pi=S("debugspectator");class Of extends I{constructor(){super(...arguments);r(this,"cam",null);r(this,"useKeys",!0);r(this,"_mode",0);r(this,"orbit",null);r(this,"_handler");r(this,"eventSub_WebXRRequestStartEvent",null);r(this,"eventSub_WebXRStartEvent",null);r(this,"eventSub_WebXREndEvent",null);r(this,"_debug");r(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var i;return((i=this.target)==null?void 0:i.userId)===e}isFollowedBy(e){var i;return(i=this.followers)==null?void 0:i.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var i;if(this._handler){const n=(i=this._handler.currentTarget)==null?void 0:i.userId,s=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&(s==null?void 0:s.currentObject)===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),C.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,n)):this._handler.currentTarget!==e&&(this._handler.set(e),C.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,n))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,i;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((i=this.context.players.getPlayerView(this.localId))==null?void 0:i.currentObject)}awake(){if(this._debug=new YR(this.context,this),this._networking=new JR(this.context,this),this._networking.awake(),C.setActive(this.gameObject,!1),this.cam=C.getComponent(this.gameObject,ai),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new XR(this.context,this.cam,this)),this.orbit=C.getComponent(this.context.mainCamera,ge)}onDestroy(){var e,i;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(i=this._networking)==null||i.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,i=/Windows|MacOS/.test(e),n=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return i&&!n}onBeforeXR(e){this.isSupportedPlatform()&&C.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Pi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var i,n;this.context.removeCamera(this.cam),C.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(i=this._handler)==null||i.set(void 0),(n=this._handler)==null||n.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,wo.Headset),this.target=this.context.players.getPlayerView(this.localId)),Pi&&console.log("Follow self",this.target)}onAfterRender(){var u,f,p;if(!this.cam)return;const e=this.context.renderer,i=e.xr.enabled;if(!e.xr.isPresenting&&!((u=this._handler)!=null&&u.currentTarget))return;(f=this._handler)==null||f.update(this._mode);const n=e.getRenderTarget();let s=null;const a=e.state;if(!n){if(!e.state.bindFramebuffer||!a.bindXRFramebuffer)return;s=e._framebuffer,a.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const l=this.context.mainCameraComponent;if(l){const g=l.backgroundColor;g&&e.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=l.clearFlags,this.cam.nearClipPlane=l.nearClipPlane,this.cam.farClipPlane=l.farClipPlane}else e.setClearColor(new d.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const c=(p=this.cam)==null?void 0:p.threeCamera;this.context.updateAspect(c);const h=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,c),e.xr.isPresenting=h,e.xr.enabled=i,n?e.setRenderTarget(n):a.bindXRFramebuffer&&a.bindXRFramebuffer(s),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const i of At.instances)if(i.avatar&&"isLocalAvatar"in i.avatar&&"flags"in i.avatar){let n=Bn.All;this.isSpectatingSelf&&(n=e&&i.avatar.isLocalAvatar?Bn.FirstPerson:Bn.ThirdPerson);const s=i.avatar.flags;if(!s)continue;for(const a of s)a.UpdateVisible(n)}}resetAvatarFlags(){var e;for(const i of At.instances)if(i.avatar&&"flags"in i.avatar){const n=i.avatar.flags;if(!n)continue;for(const s of n)"isLocalAvatar"in i.avatar&&((e=i.avatar)!=null&&e.isLocalAvatar)?s.UpdateVisible(Bn.FirstPerson):s.UpdateVisible(Bn.ThirdPerson)}}}qR([m()],Of.prototype,"useKeys");class XR{constructor(t,e,i){r(this,"context");r(this,"cam");r(this,"spectator");r(this,"follow");r(this,"target");r(this,"view");r(this,"currentObject");this.context=t,this.cam=e,this.spectator=i}get currentTarget(){return this.view}set(t){const e=t==null?void 0:t.currentObject;if(!e){this.spectator.stopSpectating();return}e!==this.currentObject&&(this.currentObject=e,this.view=t,this.follow||(this.follow=C.addComponent(this.cam.gameObject,Pf)),this.target||(this.target=new d.Object3D),e.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Pi&&console.log("FOLLOW",e),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Pi&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var t;(t=this.target)==null||t.removeFromParent(),this.follow&&C.destroy(this.follow)}update(t){var n,s,a,l,c,h;if(((n=this.currentTarget)==null?void 0:n.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Pi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((a=this.currentTarget)==null?void 0:a.currentObject)!==this.currentObject&&(Pi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const e=this.context.mainCamera;if(e){const u=this.cam.threeCamera;(u.near!==e.near||u.far!==e.far)&&(u.near=e.near,u.far=e.far,u.updateProjectionMatrix())}const i=(l=this.follow)==null?void 0:l.target;if(!(!i||!this.follow)){switch(t){case 0:((c=this.view)==null?void 0:c.viewDevice)!==wo.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((h=this.view)==null?void 0:h.viewDevice)!==wo.Browser?i.quaternion.copy(QR):i.quaternion.identity()}}}const QR=new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI);class YR{constructor(t,e){r(this,"context");r(this,"spectator");this.context=t,this.spectator=e,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",n=>{if(!this.spectator.useKeys)return;n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Re.PointerDown,n=>{i=this.context.time.time}),this.context.input.addEventListener(Re.PointerUp,n=>{const s=this.context.time.time-i;s>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&s<.3&&this.trySelectObject()})}trySelectObject(){const t=new Ds;t.setMask(16777215);const e=this.context.physics.raycast(t);if(Pi&&console.log(...e),e!=null&&e.length)for(const i of e){if(i.distance<.2)continue;const n=i.object,s=C.getComponentInParent(n,At),a=s==null?void 0:s.connectionId;if(a){const l=this.context.players.getPlayerView(a);this.spectator.target=l,Pi&&console.log("spectate",a,s);break}}}}class KR{constructor(t,e,i){r(this,"guid");r(this,"dontSave",!0);r(this,"targetUserId");r(this,"stoppedFollowing");this.guid=t,this.targetUserId=e,this.stoppedFollowing=i}}class ZR{constructor(t,e){r(this,"guid");r(this,"userId");this.guid=t.guid,this.userId=e}}class JR{constructor(t,e){r(this,"followers",[]);r(this,"context");r(this,"spectator");r(this,"_followerEventMethod");r(this,"_requestFollowMethod");r(this,"_joinedRoomMethod");r(this,"_lastRequestFollowUser");r(this,"_enforceFollowInterval");this.context=t,this.spectator=e,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ee.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",t=>{this.spectator.useKeys&&(t.key==="f"?this.onRequestFollowMe():t.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ee.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(t,e){if(Pi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",t,e),this.context.connection.connectionId){const i=(t==null?void 0:t.userId)===void 0,n=i?e:t==null?void 0:t.userId,s=new KR(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",s)}}onRequestFollowMe(t=!1){if(Pi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const e=t?void 0:this.context.connection.connectionId,i=new ZR(this.spectator,e);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){S("followme")&&this.onRequestFollowMe()}onFollowerEvent(t){const e=t.targetUserId,i=t.guid;if(Pi&&console.log(t),e===this.context.connection.connectionId)if(t.stoppedFollowing){const n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let t=this.followers.length-1;t>=0;t--){const e=this.followers[t];this.context.connection.userIsInRoom(e)===!1&&this.followers.splice(t,1)}}onRequestFollowEvent(t){if(this._lastRequestFollowUser=t,t.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(t.userId===void 0)this.spectator.stopSpectating();else{const e=this.context.players.getPlayerView(t.userId);if(e)this.spectator.target=e;else return Pi&&console.warn("Could not find view",t.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Pi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class jn{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSyncedCameraModel(t,e){return(e||new jn).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedCameraModel(t,e){return t.setPosition(t.position()+ae.SIZE_PREFIX_LENGTH),(e||new jn).__init(t.readInt32(t.position())+t.position(),t)}userId(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}guid(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dontSave(){const t=this.bb.__offset(this.bb_pos,8);return t?!!this.bb.readInt8(this.bb_pos+t):!1}pos(t){const e=this.bb.__offset(this.bb_pos,10);return e?(t||new Sr).__init(this.bb_pos+e,this.bb):null}rot(t){const e=this.bb.__offset(this.bb_pos,12);return e?(t||new Sr).__init(this.bb_pos+e,this.bb):null}static startSyncedCameraModel(t){t.startObject(5)}static addUserId(t,e){t.addFieldOffset(0,e,0)}static addGuid(t,e){t.addFieldOffset(1,e,0)}static addDontSave(t,e){t.addFieldInt8(2,+e,0)}static addPos(t,e){t.addFieldStruct(3,e,0)}static addRot(t,e){t.addFieldStruct(4,e,0)}static endSyncedCameraModel(t){return t.endObject()}static finishSyncedCameraModelBuffer(t,e){t.finish(e)}static finishSizePrefixedSyncedCameraModelBuffer(t,e){t.finish(e,void 0,!0)}}var eE=Object.defineProperty,tE=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&eE(t,e,n),n};const Cu="SCAM";ag(Cu,jn.getRootAsSyncedCameraModel);const _i=new ae.Builder;class iE{constructor(t,e){r(this,"userId");r(this,"guid");this.guid=e,this.userId=t}send(t,e){if(t){_i.clear();const i=_i.createString(this.guid),n=_i.createString(this.userId);jn.startSyncedCameraModel(_i),jn.addGuid(_i,i),jn.addUserId(_i,n);const s=Q(t),a=Bu(t);jn.addPos(_i,Sr.createVec3(_i,s.x,s.y,s.z)),jn.addRot(_i,Sr.createVec3(_i,a.x,a.y,a.z));const l=jn.endSyncedCameraModel(_i);_i.finish(l,Cu),e.sendBinary(_i.asUint8Array())}}}var bo;const Px=(bo=class extends I{constructor(){super(...arguments);r(this,"cameraPrefab",null);r(this,"_lastWorldPosition");r(this,"_lastWorldQuaternion");r(this,"_model",null);r(this,"_needsUpdate",!0);r(this,"_lastUpdateTime",0);r(this,"remoteCams",{});r(this,"userToCamMap",{});r(this,"_camTimeoutInSeconds",10);r(this,"_receiveCallback",null)}getCameraObject(e){const i=this.userToCamMap[e];return i?this.remoteCams[i].obj:null}async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Cu,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Cu,this._receiveCallback)}update(){for(const s in this.remoteCams){const a=this.remoteCams[s],l=this.context.time.realtimeSinceStartup-a.lastUpdate;if(!a||l>this._camTimeoutInSeconds){j()&&console.log("Remote cam timeout",s),a!=null&&a.obj&&C.destroy(a.obj),delete this.remoteCams[s],a&&delete this.userToCamMap[a.userId],bo.instances.push(a),this.context.players.removePlayerView(a.userId,wo.Browser);continue}}if(this.context.isInXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new iE(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const i=Q(e),n=_e(e);(i.distanceTo(this._lastWorldPosition)>.001||n.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(i),this._lastWorldQuaternion.copy(n),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,wo.Browser))}onReceivedRemoteCameraInfoBin(e){const i=e.guid();if(!i)return;const n=e.userId();if(!n||!this.context.connection.userIsInRoom(n)||!this.cameraPrefab)return;let s=this.remoteCams[i];if(!s)if("isObject3D"in this.cameraPrefab){const h=new xn;h.context=this.context;const u=C.instantiate(this.cameraPrefab,h);s=this.remoteCams[i]={obj:u,lastUpdate:this.context.time.realtimeSinceStartup,userId:n},s.obj.visible=!0,this.gameObject.add(u),this.userToCamMap[n]=i,bo.instances.push(s);const f=C.getOrAddComponent(u,At);f.connectionId=n,f.avatar=u}else return;const a=s.obj;this.context.players.setPlayerView(n,a,wo.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,Wi.markDirty(a);const l=e.pos();l&&Pr(a,l.x(),l.y(),l.z());const c=e.rot();c&&ih(a,c.x(),c.y(),c.z())}},r(bo,"instances",[]),bo);tE([m([d.Object3D,te])],Px.prototype,"cameraPrefab");let Fy=Px;var nE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,Wo=(o,t,e,i)=>{for(var n=i>1?void 0:i?sE(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&nE(t,e,n),n};const zp="view",Np=S("debugsyncedroom");class On extends I{constructor(){super(...arguments);r(this,"roomName","");r(this,"urlParameterName","room");r(this,"joinRandomRoom");r(this,"requireRoomParameter",!1);r(this,"autoRejoin",!0);r(this,"createJoinButton",!0);r(this,"createViewOnlyButton",!1);r(this,"_lastJoinedRoom");r(this,"_roomPrefix","");r(this,"_lastPingTime",0);r(this,"_lastRoomTime",-1);r(this,"_userWantsToBeInARoom",!1);r(this,"_roomButton");r(this,"_roomButtonIconJoin");r(this,"_roomButtonIconLeave");r(this,"updateRoomButtonState",()=>{var e,i;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(i=this._roomButtonIconLeave)==null||i.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))});r(this,"_viewOnlyButton");r(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{var n;const i=this.getViewOnlyUrl();i!=null&&i.length?navigator.canShare({url:i})?(n=navigator.share({url:i}))==null||n.catch(s=>{console.warn(s)}):(navigator.clipboard.writeText(i),Ee("View only URL copied to clipboard")):me("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(bt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){const e=S(zp);return e||S(this.urlParameterName)}set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}awake(){var e;this.joinRandomRoom===void 0&&((e=this.roomName)==null?void 0:e.length)<=0&&(this.joinRandomRoom=!0),Np&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=S(zp);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const i=this.createRoomButton();this.context.menu.appendChild(i)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){var e;(e=this._roomButton)==null||e.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){var n;e===void 0&&(e=0);let i=!1;if(((n=this.urlParameterName)==null?void 0:n.length)>0){const s=S(this.urlParameterName);if(s&&(typeof s=="string"||typeof s=="number")){i=!0;const a=c0(s.toString());this.roomName=a}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!i?((Np||j())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
1389
+ `)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new d.ShadowMaterial;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const i=new d.MeshBasicMaterial;this.targetMesh.material=i,e=i}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}xx([m()],zh.prototype,"mode");xx([m(ie)],zh.prototype,"shadowColor");var UR=Object.defineProperty,Nh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&UR(t,e,n),n};const Ot=S("debugskybox");By("background-image");By("environment-image");function $b(o,t,e,i,n){if(t==="transparent"||t!=null&&t.startsWith("rgb")||t!=null&&t.startsWith("#"))return console.warn(`Needle Engine: Invalid ${n} value (${t}). Did you mean to set background-color instead?`),null;const s=new Sf;s.allowDrop=!1,s.allowNetworking=!1,s.background=e,s.environment=i,C.addComponent(o.scene,s);const a=l=>{typeof l=="string"&&(Ot&&console.log(n,"CHANGED TO",l),s.setSkybox(l))};return d0(o.domElement,n,a),s.addEventListener("destroy",()=>{Ot&&console.log("Destroyed attribute remote skybox",n),u0(o.domElement,n,a)}),s.setSkybox(t)}const Su=new Array;re.registerCallback(he.ContextCreationStart,o=>{const t=o.context,e=t.domElement.getAttribute("background-image"),i=t.domElement.getAttribute("environment-image");if(e){Ot&&console.log("Creating remote skybox to load "+e);const n=$b(t,e,!0,!1,"background-image");n&&Su.push(n)}if(i){Ot&&console.log("Creating remote environment to load "+i);const n=$b(t,i,!1,!0,"environment-image");n&&Su.push(n)}});re.registerCallback(he.ContextCreationStart,()=>Promise.all(Su).finally(()=>{Su.length=0}));function Sx(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function Vb(o){const e=Sx().find(i=>i.src===o);return e?(Ot&&console.log("Skybox: Found previously loaded texture for "+o),e.texture):null}async function zR(o){const t=await o;t&&(fg(t,!0),Se(t))}function NR(o,t){const e=Sx();for(;e.length>5;){const i=e.shift();i&&zR(i.texture)}t.then(i=>fg(i,!1)),e.push({src:o,texture:t})}const Lr=class extends I{constructor(){super(...arguments);r(this,"url");r(this,"allowDrop",!0);r(this,"background",!0);r(this,"environment",!0);r(this,"allowNetworking",!0);r(this,"_loader");r(this,"_prevUrl");r(this,"_prevLoadedEnvironment");r(this,"_prevEnvironment",null);r(this,"_prevBackground",null);r(this,"validProtocols",["file:","blob:","data:"]);r(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]);r(this,"onDragOverEvent",e=>{if(this.allowDrop&&e.dataTransfer)for(const i of e.dataTransfer.types)(i==="text/uri-list"||i==="Files")&&e.preventDefault()});r(this,"onDrop",e=>{var i,n,s,a;if(this.allowDrop&&e.dataTransfer){for(const l of e.dataTransfer.types)if(Ot&&console.log(l),l==="text/uri-list"){const c=e.dataTransfer.getData(l);Ot&&console.log(l,c);let h=(n=(i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(c))==null?void 0:i.groups)==null?void 0:n.name;if(h||(h=(a=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(c))==null?void 0:s.groups)==null?void 0:a.name),Ot&&console.log(h),h){const u="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+h+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${u}`),e.preventDefault(),this.setSkybox(u);break}else if(this.isValidTextureType(c)){console.log("[Remote Skybox] Setting skybox from url: "+c),e.preventDefault(),this.setSkybox(c);break}else{console.warn(`[RemoteSkybox] Unknown url ${c}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const u=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:c,apply:f=>{e.preventDefault(),this.setSkybox(f)}}});this.dispatchEvent(u)}}else if(l=="Files"){const c=e.dataTransfer.files.item(0);if(Ot&&console.log(l,c),!c)continue;if(!this.isValidTextureType(c.name)){console.warn(`[RemoteSkybox]: File "${c.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(Vb(c.name)===null){const h=new Blob([c]),u=URL.createObjectURL(h);e.preventDefault(),this.setSkybox(u,c.name)}else e.preventDefault(),this.setSkybox(c.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var e;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,ai.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(e=this.context.mainCameraComponent)==null||e.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):Ot&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(e,i){var a,l;if(!this.activeAndEnabled||(e=$R(e,this.environment,this.background),!e))return!1;if(i??(i=e),this.isValidTextureType(i)||console.warn('Potentially invalid skybox URL: "'+i+'" on '+(this.name||((a=this.gameObject)==null?void 0:a.name)||"context")),Ot&&console.log("Set remote skybox url: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.apply(),!0;(l=this._prevLoadedEnvironment)==null||l.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const n=await this.loadTexture(e,i);if(!n)return Ot&&console.warn("RemoteSkybox: Failed to load texture from url",e),!1;if(!this.enabled)return Ot&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==e)return Ot&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=e;const s=e.lastIndexOf("/");return n.name=e.substring(s>=0?s+1:0),this._loader instanceof d.TextureLoader&&(n.colorSpace=d.SRGBColorSpace),this._prevLoadedEnvironment=n,this.apply(),!0}async loadTexture(e,i){var u,f,p,g,y;if(!e)return Promise.resolve(null);i??(i=e);const n=Vb(i);if(n){const b=await n;if(((f=(u=b==null?void 0:b.source)==null?void 0:u.data)==null?void 0:f.length)>0||(y=(g=(p=b==null?void 0:b.source)==null?void 0:p.data)==null?void 0:g.data)!=null&&y.length)return b}const s=i.endsWith(".exr"),a=i.endsWith(".hdr"),l=i.endsWith(".ktx2");if(s)this._loader instanceof H.EXRLoader||(this._loader=new H.EXRLoader);else if(a)this._loader instanceof H.RGBELoader||(this._loader=new H.RGBELoader);else if(l){if(!(this._loader instanceof H.KTX2Loader)){const{ktx2Loader:b}=le.createLoaders(this.context.renderer);this._loader=b}}else this._loader instanceof d.TextureLoader||(this._loader=new d.TextureLoader);Ot&&console.log("Loading skybox: "+e);const c=this._loader.loadAsync(e).catch(b=>(console.warn("RemoteSkybox: Failed to load texture from url:",e),null));return NR(i,c),await c}apply(){var i;const e=this._prevLoadedEnvironment;e&&(e instanceof d.CubeTexture||e instanceof d.CompressedCubeTexture||(e.mapping=d.EquirectangularRefractionMapping,e.needsUpdate=!0),this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),Ot&&console.log("Set remote skybox",this.url,!ai.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!ai.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((i=this.context.mainCameraComponent)==null?void 0:i.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const i of this.validTextureTypes)if(e.endsWith(i))return!0;for(const i of this.validProtocols)if(e.startsWith(i))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}};Nh([hy(Lr.prototype.urlChangedSyncField),m(URL)],Lr.prototype,"url");Nh([m()],Lr.prototype,"allowDrop");Nh([m()],Lr.prototype,"background");Nh([m()],Lr.prototype,"environment");Nh([m()],Lr.prototype,"allowNetworking");let Sf=Lr;function $R(o,t,e){const i=t&&!e;switch(o==null?void 0:o.toLowerCase()){case"studio":return i?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return i?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return i?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return i?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return o===void 0?null:o}var VR=Object.defineProperty,Cf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&VR(t,e,n),n},ur;const $h=(ur=class extends I{constructor(){super(...arguments);r(this,"target",null);r(this,"followFactor",.1);r(this,"rotateFactor",.1);r(this,"positionAxes",xa.All);r(this,"flipForward",!1);r(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const i=Q(this.target),n=this._firstUpdate||e?1:z.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&xa.X&&(s.x=z.lerp(s.x,i.x,n)),this.positionAxes&xa.Y&&(s.y=z.lerp(s.y,i.y,n)),this.positionAxes&xa.Z&&(s.z=z.lerp(s.z,i.z,n)),this.worldPosition=s}if(this.rotateFactor>0){const i=_e(this.target);this.flipForward&&i.premultiply(ur._invertForward);const n=this._firstUpdate||e?1:z.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(i,n)}this._firstUpdate=!1}}},r(ur,"_invertForward",new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI)),ur);Cf([m(d.Object3D)],$h.prototype,"target");Cf([m()],$h.prototype,"followFactor");Cf([m()],$h.prototype,"rotateFactor");Cf([m()],$h.prototype,"positionAxes");let Pf=$h;var WR=Object.defineProperty,Vh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&WR(t,e,n),n};const _c=S("debugspatialtrigger"),Wb=new d.Layers,Gb=new d.Layers;function GR(o,t){return Wb.mask=o,Gb.mask=t,Wb.test(Gb)}class Zn extends I{constructor(){super(...arguments);r(this,"triggerMask",0);r(this,"onEnter");r(this,"onStay");r(this,"onExit");r(this,"currentIntersected",[]);r(this,"lastIntersected",[])}start(){_c&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Mf.triggers)GR(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const i=this.lastIntersected[e];this.currentIntersected.indexOf(i)<0&&(this.onExitTrigger(i),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var i;_c&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(i=this.onEnter)==null||i.invoke()}onExitTrigger(e){var i;_c&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(i=this.onExit)==null||i.invoke()}onStayTrigger(e){var i;e.raiseOnStayEvent(this),(i=this.onStay)==null||i.invoke()}}Vh([m()],Zn.prototype,"triggerMask");Vh([m(ye)],Zn.prototype,"onEnter");Vh([m(ye)],Zn.prototype,"onStay");Vh([m(ye)],Zn.prototype,"onExit");var ks;const Cx=(ks=class extends I{constructor(){super(...arguments);r(this,"triggerMask");r(this,"boxHelper")}start(){_c&&console.log(this.name,this.triggerMask,this)}onEnable(){var e;ks.triggers.push(this),this.boxHelper||(this.boxHelper=C.addComponent(this.gameObject,ts),(e=this.boxHelper)==null||e.showHelper(null,_c))}onDisable(){ks.triggers.splice(ks.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onStayTrigger(this)},!1)}raiseOnExitEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onExitTrigger(this)},!1)}},r(ks,"triggers",[]),ks);Vh([m()],Cx.prototype,"triggerMask");let Mf=Cx;var HR=Object.defineProperty,qR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&HR(t,e,n),n};const Pi=S("debugspectator");class Of extends I{constructor(){super(...arguments);r(this,"cam",null);r(this,"useKeys",!0);r(this,"_mode",0);r(this,"orbit",null);r(this,"_handler");r(this,"eventSub_WebXRRequestStartEvent",null);r(this,"eventSub_WebXRStartEvent",null);r(this,"eventSub_WebXREndEvent",null);r(this,"_debug");r(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var i;return((i=this.target)==null?void 0:i.userId)===e}isFollowedBy(e){var i;return(i=this.followers)==null?void 0:i.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var i;if(this._handler){const n=(i=this._handler.currentTarget)==null?void 0:i.userId,s=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&(s==null?void 0:s.currentObject)===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),C.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,n)):this._handler.currentTarget!==e&&(this._handler.set(e),C.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,n))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,i;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((i=this.context.players.getPlayerView(this.localId))==null?void 0:i.currentObject)}awake(){if(this._debug=new YR(this.context,this),this._networking=new JR(this.context,this),this._networking.awake(),C.setActive(this.gameObject,!1),this.cam=C.getComponent(this.gameObject,ai),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new XR(this.context,this.cam,this)),this.orbit=C.getComponent(this.context.mainCamera,ge)}onDestroy(){var e,i;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(i=this._networking)==null||i.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,i=/Windows|MacOS/.test(e),n=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return i&&!n}onBeforeXR(e){this.isSupportedPlatform()&&C.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Pi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var i,n;this.context.removeCamera(this.cam),C.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(i=this._handler)==null||i.set(void 0),(n=this._handler)==null||n.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,wo.Headset),this.target=this.context.players.getPlayerView(this.localId)),Pi&&console.log("Follow self",this.target)}onAfterRender(){var u,f,p;if(!this.cam)return;const e=this.context.renderer,i=e.xr.enabled;if(!e.xr.isPresenting&&!((u=this._handler)!=null&&u.currentTarget))return;(f=this._handler)==null||f.update(this._mode);const n=e.getRenderTarget();let s=null;const a=e.state;if(!n){if(!e.state.bindFramebuffer||!a.bindXRFramebuffer)return;s=e._framebuffer,a.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const l=this.context.mainCameraComponent;if(l){const g=l.backgroundColor;g&&e.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=l.clearFlags,this.cam.nearClipPlane=l.nearClipPlane,this.cam.farClipPlane=l.farClipPlane}else e.setClearColor(new d.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const c=(p=this.cam)==null?void 0:p.threeCamera;this.context.updateAspect(c);const h=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,c),e.xr.isPresenting=h,e.xr.enabled=i,n?e.setRenderTarget(n):a.bindXRFramebuffer&&a.bindXRFramebuffer(s),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const i of At.instances)if(i.avatar&&"isLocalAvatar"in i.avatar&&"flags"in i.avatar){let n=Bn.All;this.isSpectatingSelf&&(n=e&&i.avatar.isLocalAvatar?Bn.FirstPerson:Bn.ThirdPerson);const s=i.avatar.flags;if(!s)continue;for(const a of s)a.UpdateVisible(n)}}resetAvatarFlags(){var e;for(const i of At.instances)if(i.avatar&&"flags"in i.avatar){const n=i.avatar.flags;if(!n)continue;for(const s of n)"isLocalAvatar"in i.avatar&&((e=i.avatar)!=null&&e.isLocalAvatar)?s.UpdateVisible(Bn.FirstPerson):s.UpdateVisible(Bn.ThirdPerson)}}}qR([m()],Of.prototype,"useKeys");class XR{constructor(t,e,i){r(this,"context");r(this,"cam");r(this,"spectator");r(this,"follow");r(this,"target");r(this,"view");r(this,"currentObject");this.context=t,this.cam=e,this.spectator=i}get currentTarget(){return this.view}set(t){const e=t==null?void 0:t.currentObject;if(!e){this.spectator.stopSpectating();return}e!==this.currentObject&&(this.currentObject=e,this.view=t,this.follow||(this.follow=C.addComponent(this.cam.gameObject,Pf)),this.target||(this.target=new d.Object3D),e.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Pi&&console.log("FOLLOW",e),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Pi&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var t;(t=this.target)==null||t.removeFromParent(),this.follow&&C.destroy(this.follow)}update(t){var n,s,a,l,c,h;if(((n=this.currentTarget)==null?void 0:n.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Pi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((a=this.currentTarget)==null?void 0:a.currentObject)!==this.currentObject&&(Pi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const e=this.context.mainCamera;if(e){const u=this.cam.threeCamera;(u.near!==e.near||u.far!==e.far)&&(u.near=e.near,u.far=e.far,u.updateProjectionMatrix())}const i=(l=this.follow)==null?void 0:l.target;if(!(!i||!this.follow)){switch(t){case 0:((c=this.view)==null?void 0:c.viewDevice)!==wo.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((h=this.view)==null?void 0:h.viewDevice)!==wo.Browser?i.quaternion.copy(QR):i.quaternion.identity()}}}const QR=new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI);class YR{constructor(t,e){r(this,"context");r(this,"spectator");this.context=t,this.spectator=e,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",n=>{if(!this.spectator.useKeys)return;n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Re.PointerDown,n=>{i=this.context.time.time}),this.context.input.addEventListener(Re.PointerUp,n=>{const s=this.context.time.time-i;s>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&s<.3&&this.trySelectObject()})}trySelectObject(){const t=new Ds;t.setMask(16777215);const e=this.context.physics.raycast(t);if(Pi&&console.log(...e),e!=null&&e.length)for(const i of e){if(i.distance<.2)continue;const n=i.object,s=C.getComponentInParent(n,At),a=s==null?void 0:s.connectionId;if(a){const l=this.context.players.getPlayerView(a);this.spectator.target=l,Pi&&console.log("spectate",a,s);break}}}}class KR{constructor(t,e,i){r(this,"guid");r(this,"dontSave",!0);r(this,"targetUserId");r(this,"stoppedFollowing");this.guid=t,this.targetUserId=e,this.stoppedFollowing=i}}class ZR{constructor(t,e){r(this,"guid");r(this,"userId");this.guid=t.guid,this.userId=e}}class JR{constructor(t,e){r(this,"followers",[]);r(this,"context");r(this,"spectator");r(this,"_followerEventMethod");r(this,"_requestFollowMethod");r(this,"_joinedRoomMethod");r(this,"_lastRequestFollowUser");r(this,"_enforceFollowInterval");this.context=t,this.spectator=e,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ee.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",t=>{this.spectator.useKeys&&(t.key==="f"?this.onRequestFollowMe():t.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ee.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(t,e){if(Pi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",t,e),this.context.connection.connectionId){const i=(t==null?void 0:t.userId)===void 0,n=i?e:t==null?void 0:t.userId,s=new KR(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",s)}}onRequestFollowMe(t=!1){if(Pi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const e=t?void 0:this.context.connection.connectionId,i=new ZR(this.spectator,e);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){S("followme")&&this.onRequestFollowMe()}onFollowerEvent(t){const e=t.targetUserId,i=t.guid;if(Pi&&console.log(t),e===this.context.connection.connectionId)if(t.stoppedFollowing){const n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let t=this.followers.length-1;t>=0;t--){const e=this.followers[t];this.context.connection.userIsInRoom(e)===!1&&this.followers.splice(t,1)}}onRequestFollowEvent(t){if(this._lastRequestFollowUser=t,t.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(t.userId===void 0)this.spectator.stopSpectating();else{const e=this.context.players.getPlayerView(t.userId);if(e)this.spectator.target=e;else return Pi&&console.warn("Could not find view",t.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Pi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class jn{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSyncedCameraModel(t,e){return(e||new jn).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedCameraModel(t,e){return t.setPosition(t.position()+ae.SIZE_PREFIX_LENGTH),(e||new jn).__init(t.readInt32(t.position())+t.position(),t)}userId(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}guid(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dontSave(){const t=this.bb.__offset(this.bb_pos,8);return t?!!this.bb.readInt8(this.bb_pos+t):!1}pos(t){const e=this.bb.__offset(this.bb_pos,10);return e?(t||new Sr).__init(this.bb_pos+e,this.bb):null}rot(t){const e=this.bb.__offset(this.bb_pos,12);return e?(t||new Sr).__init(this.bb_pos+e,this.bb):null}static startSyncedCameraModel(t){t.startObject(5)}static addUserId(t,e){t.addFieldOffset(0,e,0)}static addGuid(t,e){t.addFieldOffset(1,e,0)}static addDontSave(t,e){t.addFieldInt8(2,+e,0)}static addPos(t,e){t.addFieldStruct(3,e,0)}static addRot(t,e){t.addFieldStruct(4,e,0)}static endSyncedCameraModel(t){return t.endObject()}static finishSyncedCameraModelBuffer(t,e){t.finish(e)}static finishSizePrefixedSyncedCameraModelBuffer(t,e){t.finish(e,void 0,!0)}}var eE=Object.defineProperty,tE=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&eE(t,e,n),n};const Cu="SCAM";ag(Cu,jn.getRootAsSyncedCameraModel);const _i=new ae.Builder;class iE{constructor(t,e){r(this,"userId");r(this,"guid");this.guid=e,this.userId=t}send(t,e){if(t){_i.clear();const i=_i.createString(this.guid),n=_i.createString(this.userId);jn.startSyncedCameraModel(_i),jn.addGuid(_i,i),jn.addUserId(_i,n);const s=Q(t),a=Bu(t);jn.addPos(_i,Sr.createVec3(_i,s.x,s.y,s.z)),jn.addRot(_i,Sr.createVec3(_i,a.x,a.y,a.z));const l=jn.endSyncedCameraModel(_i);_i.finish(l,Cu),e.sendBinary(_i.asUint8Array())}}}var bo;const Px=(bo=class extends I{constructor(){super(...arguments);r(this,"cameraPrefab",null);r(this,"_lastWorldPosition");r(this,"_lastWorldQuaternion");r(this,"_model",null);r(this,"_needsUpdate",!0);r(this,"_lastUpdateTime",0);r(this,"remoteCams",{});r(this,"userToCamMap",{});r(this,"_camTimeoutInSeconds",10);r(this,"_receiveCallback",null)}getCameraObject(e){const i=this.userToCamMap[e];return i?this.remoteCams[i].obj:null}async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Cu,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Cu,this._receiveCallback)}update(){for(const s in this.remoteCams){const a=this.remoteCams[s],l=this.context.time.realtimeSinceStartup-a.lastUpdate;if(!a||l>this._camTimeoutInSeconds){j()&&console.log("Remote cam timeout",s),a!=null&&a.obj&&C.destroy(a.obj),delete this.remoteCams[s],a&&delete this.userToCamMap[a.userId],bo.instances.push(a),this.context.players.removePlayerView(a.userId,wo.Browser);continue}}if(this.context.isInXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new iE(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const i=Q(e),n=_e(e);(i.distanceTo(this._lastWorldPosition)>.001||n.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(i),this._lastWorldQuaternion.copy(n),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,wo.Browser))}onReceivedRemoteCameraInfoBin(e){const i=e.guid();if(!i)return;const n=e.userId();if(!n||!this.context.connection.userIsInRoom(n)||!this.cameraPrefab)return;let s=this.remoteCams[i];if(!s)if("isObject3D"in this.cameraPrefab){const h=new xn;h.context=this.context;const u=C.instantiate(this.cameraPrefab,h);s=this.remoteCams[i]={obj:u,lastUpdate:this.context.time.realtimeSinceStartup,userId:n},s.obj.visible=!0,this.gameObject.add(u),this.userToCamMap[n]=i,bo.instances.push(s);const f=C.getOrAddComponent(u,At);f.connectionId=n,f.avatar=u}else return;const a=s.obj;this.context.players.setPlayerView(n,a,wo.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,Wi.markDirty(a);const l=e.pos();l&&Pr(a,l.x(),l.y(),l.z());const c=e.rot();c&&ih(a,c.x(),c.y(),c.z())}},r(bo,"instances",[]),bo);tE([m([d.Object3D,te])],Px.prototype,"cameraPrefab");let Fy=Px;var nE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,Wo=(o,t,e,i)=>{for(var n=i>1?void 0:i?sE(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&nE(t,e,n),n};const zp="view",Np=S("debugsyncedroom");class On extends I{constructor(){super(...arguments);r(this,"roomName","");r(this,"urlParameterName","room");r(this,"joinRandomRoom");r(this,"requireRoomParameter",!1);r(this,"autoRejoin",!0);r(this,"createJoinButton",!0);r(this,"createViewOnlyButton",!1);r(this,"_lastJoinedRoom");r(this,"_roomPrefix","");r(this,"_lastPingTime",0);r(this,"_lastRoomTime",-1);r(this,"_userWantsToBeInARoom",!1);r(this,"_roomButton");r(this,"_roomButtonIconJoin");r(this,"_roomButtonIconLeave");r(this,"updateRoomButtonState",()=>{var e,i;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(i=this._roomButtonIconLeave)==null||i.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))});r(this,"_viewOnlyButton");r(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{var n;const i=this.getViewOnlyUrl();i!=null&&i.length?navigator.canShare({url:i})?(n=navigator.share({url:i}))==null||n.catch(s=>{console.warn(s)}):(navigator.clipboard.writeText(i),Ee("View only URL copied to clipboard")):me("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(_t("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){const e=S(zp);return e||S(this.urlParameterName)}set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}awake(){var e;this.joinRandomRoom===void 0&&((e=this.roomName)==null?void 0:e.length)<=0&&(this.joinRandomRoom=!0),Np&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=S(zp);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const i=this.createRoomButton();this.context.menu.appendChild(i)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){var e;(e=this._roomButton)==null||e.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){var n;e===void 0&&(e=0);let i=!1;if(((n=this.urlParameterName)==null?void 0:n.length)>0){const s=S(this.urlParameterName);if(s&&(typeof s=="string"||typeof s=="number")){i=!0;const a=c0(s.toString());this.roomName=a}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!i?((Np||j())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
1390
1390
  To allow joining a room without a query parameter you can set "requireRoomParameter" to false.`),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.roomName.length<=0?(console.warn(`[SyncedRoom] Room name is not set so we can not join a networked room.
1391
1391
  Please choose one of the following options to fix this:
1392
1392
  A) Set a room name in the SyncedRoom component
1393
1393
  B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
1394
- C) Set "joinRandomRoom" to true`),!1):(Np&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):j()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,i=new URLSearchParams(e);return i.has(this.urlParameterName)&&i.delete(this.urlParameterName),i.set(zp,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+i.toString()}return null}setRandomRoomUrlParameter(){const e=Zc(),i=this.generateRoomName();S(this.urlParameterName)?e.set(this.urlParameterName,i):e.append(this.urlParameterName,i),Vm(i,e)}generateRoomName(){let e="";for(let i=0;i<6;i++)e+=Math.floor(Math.random()*10).toFixed(0);return e}createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Oc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const i=S(this.urlParameterName);(!i||i===!0)&&(this._lastJoinedRoom?Oc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=bt("group"),this._roomButtonIconLeave=bt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(ee.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(ee.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(ee.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(ee.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(ee.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(ee.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var e;this.context.connection.stopListen(ee.JoinedRoom,this.onCreateViewOnlyButton),(e=this._viewOnlyButton)==null||e.remove()}}Wo([m()],On.prototype,"roomName",2);Wo([m()],On.prototype,"urlParameterName",2);Wo([m()],On.prototype,"joinRandomRoom",2);Wo([m()],On.prototype,"requireRoomParameter",2);Wo([m()],On.prototype,"autoRejoin",2);Wo([m()],On.prototype,"createJoinButton",2);Wo([m()],On.prototype,"createViewOnlyButton",2);Wo([m()],On.prototype,"roomPrefix",1);function oE(){const o=S("testwindowcount")||0;o&&o>0&&rE(o)}function rE(o){if(S("testwindow"))return null;const t=new URL(window.location.href);Xp(t.searchParams,aM,1),Xp(t.searchParams,"testwindow",1);const e=t.toString(),i=[];window.onbeforeunload=()=>{for(const c of i)c.close()};const n=.05,s=128;let a=0,l=0;for(let c=0;c<o;c++){a*s+s*.01>=window.innerWidth&&(l+=1,a=0);const h=a*(s*(1+n))+window.screenLeft,u=l*(s*(1+n))+window.screenTop+90+60*l;a+=1;const f=window.open(e,"test window "+c,`popup=yes width=${s} height=${s} top=${u} left=${h}`);if(!f){console.warn("Failed to open window");continue}i.push(f),f.onload=()=>{f.onbeforeunload=()=>{for(let p=0;p<i.length;p++){const g=i[p];g!==f&&g.close()}i.length=0}}}return i}class Uy extends I{awake(){oE()}}class zy extends I{constructor(){super(...arguments);r(this,"transformsPerFrame",10);r(this,"interval",0);r(this,"useFlatbuffers",!0);r(this,"builder",null);r(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Bc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new Mx(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new ae.Builder(1024));const e=this.builder;for(let i=0;i<this.transformsPerFrame;i++){e.clear();const n=lw(this.context.connection.connectionId,this);this.context.connection.sendBinary(n)}}else if(this.models)for(let e=0;e<this.models.length;e++){const i=this.models[e];i.dontSave=!0,i.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,i)}}}}class Mx{constructor(t,e){r(this,"guid");r(this,"fast",!1);r(this,"position");r(this,"rotation");r(this,"velocity");r(this,"dontSave");this.guid=t,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(e,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(t,e){const i=t.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=t.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,e){const s=e.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=s.x,this.velocity.y=s.y,this.velocity.z=s.z}}}r(Mx,"temp",new d.Vector3);var aE=Object.defineProperty,kf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&aE(t,e,n),n};const lE=S("debugsignals");class Rf{constructor(){r(this,"guid")}}kf([m()],Rf.prototype,"guid");class Wh{constructor(){r(this,"signal");r(this,"reaction")}}kf([m(Rf)],Wh.prototype,"signal");kf([m(ye)],Wh.prototype,"reaction");var oi;const Ox=(oi=class extends I{constructor(){super(...arguments);r(this,"events")}static invoke(e){if(oi.receivers[e]){const i=oi.receivers[e];if(!i)return;for(const n of i)n.invoke(e)}}awake(){lE&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)oi.receivers[e.signal.guid]||(oi.receivers[e.signal.guid]=[]),oi.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(oi.receivers[e.signal.guid]){const i=oi.receivers[e.signal.guid].indexOf(this);i>=0&&oi.receivers[e.signal.guid].splice(i,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const i=typeof e=="object"?e.guid:e;for(const n of this.events)if(n.signal.guid===i)try{if(n.reaction){if(!n.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",n,this);continue}}else{console.warn("Missing reaction for signal",n,this);continue}n.reaction.invoke()}catch(s){console.error(s)}}},r(oi,"receivers",{}),oi);kf([m(Wh)],Ox.prototype,"events");let Gh=Ox;var bi=(o=>(o.Activation="ActivationTrack",o.Animation="AnimationTrack",o.Audio="AudioTrack",o.Control="ControlTrack",o.Marker="MarkerTrack",o.Signal="SignalTrack",o))(bi||{}),An=(o=>(o[o.None=0]="None",o[o.Hold=1]="Hold",o[o.Loop=2]="Loop",o[o.PingPong=3]="PingPong",o[o.Continue=4]="Continue",o))(An||{}),Ny=(o=>(o.Signal="SignalEmitter",o))(Ny||{});const Wn=S("debugtimeline");class Hh{constructor(){r(this,"director");r(this,"track")}get muted(){return this.track.muted}set muted(t){var e;t!==this.track.muted&&(this.track.muted=t,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(t=!1){var e;if((e=this.track)!=null&&e.clips)if(t)for(let i=this.track.clips.length-1;i>=0;i--)yield this.track.clips[i];else for(const i of this.track.clips)yield i}getClipTime(t,e){return e.clipIn+(t-e.start)*e.timeScale}getClipTimeNormalized(t,e){return(t-e.start)/e.duration}evaluateWeight(t,e,i,n=!0){if(e<0||e>=i.length)return 0;const s=i[e];if(n||t>=s.start&&t<=s.end){let a=1;if(s.easeInDuration>0){const l=Math.min((t-s.start)/s.easeInDuration,1);a*=l}if(s.easeOutDuration>0){const l=Math.min((s.end-t)/s.easeOutDuration,1);a*=l}return a}return 0}}class cE{constructor(t){r(this,"clip");r(this,"rootPositionOffset");r(this,"rootQuaternionOffset");r(this,"rootStartPosition");r(this,"rootEndPosition");r(this,"rootStartQuaternion");r(this,"rootEndQuaternion");const e=t.getClip();this.clip=e;const i=t.getRoot(),n=i.name+".position",s=i.name+".quaternion";Wn&&console.log(e.name,e.tracks,n);for(const a of e.tracks)if(!(a.times.length<=0)){if(a.name.endsWith(n))this.rootStartPosition=new d.Vector3().fromArray(a.values,0),this.rootEndPosition=new d.Vector3().fromArray(a.values,a.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Wn&&console.log(this.rootPositionOffset);else if(a.name.endsWith(s)&&(this.rootStartQuaternion=new d.Quaternion().fromArray(a.values,0),this.rootEndQuaternion=new d.Quaternion().fromArray(a.values,a.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Wn)){const l=new d.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",l)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Ef extends Hh{constructor(){super(...arguments);r(this,"models",[]);r(this,"trackOffset");r(this,"target");r(this,"mixer");r(this,"clips",[]);r(this,"actions",[]);r(this,"weight",1);r(this,"_actionOffsets",[]);r(this,"_didBind",!1);r(this,"_animator",null);r(this,"_useclipOffsets",!0);r(this,"_totalOffsetPosition",new d.Vector3);r(this,"_totalOffsetRotation",new d.Quaternion);r(this,"_totalOffsetPosition2",new d.Vector3);r(this,"_totalOffsetRotation2",new d.Quaternion);r(this,"_summedPos",new d.Vector3);r(this,"_tempPos",new d.Vector3);r(this,"_summedRot",new d.Quaternion);r(this,"_tempRot",new d.Quaternion);r(this,"_clipRotQuat",new d.Quaternion)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&sb(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,i){var u,f;if(((u=i.tracks)==null?void 0:u.length)<=0){console.warn("No tracks in AnimationClip",i);return}const n=i.tracks[0].name.split("."),s=n[n.length-2],a=s+".position",l=s+".quaternion";let c=!1,h=!1;for(const p of i.tracks)p.name.endsWith(a)?(c=!0,this.createPositionInterpolant(i,e,p)):p.name.endsWith(l)&&(h=!0,this.createRotationInterpolant(i,e,p));if(!c||!h){const p=(f=this.mixer)==null?void 0:f.getRoot(),g=i.tracks[0],y=g.name.lastIndexOf("."),b=g.name.substring(0,y),_=b.substring(b.lastIndexOf(".")+1),v=p.getObjectByName(_);if(v)if(c){if(!h){const w=i.tracks[0].name.substring(0,y)+".quaternion";Wn&&console.warn("Create quaternion track",_,v);const x=v.quaternion,O=new d.QuaternionKeyframeTrack(w,[0,i.duration],[x.x,x.y,x.z,x.w,x.x,x.y,x.z,x.w]);i.tracks.push(O),this.createRotationInterpolant(i,e,O)}}else{const w=b+".position";Wn&&console.warn("Create position track",_,v);const x=v.position,O=new d.VectorKeyframeTrack(w,[0,i.duration],[x.x,x.y,x.z,x.x,x.y,x.z]);i.tracks.push(O),this.createPositionInterpolant(i,e,O)}}}bind(){if(!this._didBind){this._didBind=!0,Wn&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const i=new cE(e);this._actionOffsets.push(i)}this.target&&(this._animator=C.getComponent(this.target,St)??null,this._animator&&sb(this._animator.gameObject,this,!0));for(const e of this.models){const i=e.asset,n=i.position,s=i.rotation;n&&n.x!==void 0&&(n.isVector3||(i.position=new d.Vector3(n.x,n.y,n.z)),s.isQuaternion||(i.rotation=new d.Quaternion(s.x,s.y,s.z,s.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new d.Vector3(e.x,e.y,e.z)));const i=this.trackOffset.rotation;i&&(i.isQuaternion||(this.trackOffset.rotation=new d.Quaternion(i.x,i.y,i.z,i.w)))}}evaluate(e){var c,h,u,f,p,g,y;if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let i=0,n=0,s=!1,a=!1,l=0;for(let b=0;b<this.clips.length;b++){const _=this.models[b],v=this.actions[b],w=_.asset;v.weight=0;const x=e>=_.start&&e<=_.end,O=_.preExtrapolationMode,E=_.postExtrapolationMode,M=b<this.clips.length-1?this.models[b+1]:null;let R=x,F=!1;if(!R&&!s&&_.end<e&&E!==An.None?(!M||M.start>e)&&(R=!0,s=!0):b==0&&!R&&!a&&_.start>e&&O!==An.None&&(!M||M.start<e)&&(R=!0,F=!0,a=!0),R){let D=this.weight;D*=this.evaluateWeight(e,b,this.models,R),D*=this.director.weight;let A=x;if(F)switch(O){case An.Hold:break;case An.Loop:e+=_.start,A=!0;break;default:e+=_.start,A=!0;break}let T=this.getClipTime(e,_),G=0;const B=w.duration;if(F&&O===An.Hold&&(T=0),A){if(w.loop)for(G+=Math.floor(T/(B+1e-6));T>B;)T-=B}else if(!x&&s)switch(E){case An.Hold:T=this.getClipTime(_.end,_);break;case An.Loop:T%=B;break;case An.PingPong:const Y=Math.floor(T/B)%2!==0;T%=B,Y&&(T=B-T);break}_.reversed===!0?v.time=v.getClip().duration-T:v.time=T,v.timeScale=0;const L=Math.max(0,D);if(v.weight=L,l+=L,v.clampWhenFinished=!1,v.isRunning()||v.play(),this._useclipOffsets){const N=i==0?this._totalOffsetPosition:this._totalOffsetPosition2,Y=i==0?this._totalOffsetRotation:this._totalOffsetRotation2;i<1&&(n=1-D),i+=1;const Z=this._summedPos.set(0,0,0),K=this._tempPos.set(0,0,0),de=this._summedRot.identity(),Fe=this._tempRot.identity(),mt=w.rotation;mt&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(mt,D));const kn=this._actionOffsets[b];if(kn.hasOffsets)for(let nn=0;nn<G;nn++)kn.rootPositionOffset?K.copy(kn.rootPositionOffset):K.set(0,0,0),K.applyQuaternion(de),this._clipRotQuat&&K.applyQuaternion(this._clipRotQuat),kn.rootQuaternionOffset&&(Fe.copy(kn.rootQuaternionOffset),de.multiply(Fe)),Z.add(K);this._clipRotQuat&&Y.multiply(this._clipRotQuat),Y.multiply(de),w.position&&Z.add(w.position),N.add(Z)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,n),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,n)),this.__mixerError===void 0&&(Wn||j())&&((h=(c=this._animator)==null?void 0:c.runtimeAnimatorController)!=null&&h.mixer)&&this.mixer!==((f=(u=this._animator)==null?void 0:u.runtimeAnimatorController)==null?void 0:f.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(p=this._animator)!=null&&p.runtimeAnimatorController){const b=Math.max(0,1-l);(y=(g=this._animator)==null?void 0:g.runtimeAnimatorController)==null||y.update(b)}else this.mixer.update(e)}createRotationInterpolant(e,i,n){var c;const s=n.createInterpolant.bind(n),a=new d.Quaternion;this.ensureTrackOffsets();const l=(c=this.trackOffset)==null?void 0:c.rotation;n.createInterpolant=()=>{const h=s(),u=h.evaluate.bind(h);return h.evaluate=f=>{var g;const p=u(f);if(a.set(p[0],p[1],p[2],p[3]),a.premultiply(this._totalOffsetRotation),l&&a.premultiply(l),this.director.animationCallbackReceivers)for(const y of this.director.animationCallbackReceivers)(g=y==null?void 0:y.onTimelineRotation)==null||g.call(y,this.director,this.target,f,a);return p[0]=a.x,p[1]=a.y,p[2]=a.z,p[3]=a.w,p},h}}createPositionInterpolant(e,i,n){var u,f;const s=n.createInterpolant.bind(n),a=new d.Vector3;this.ensureTrackOffsets();const l=(u=this.trackOffset)==null?void 0:u.rotation,c=(f=this.trackOffset)==null?void 0:f.position;let h;n.createInterpolant=()=>{const p=s(),g=p.evaluate.bind(p);return p.evaluate=y=>{var _,v,w;const b=g(y);if(a.set(b[0],b[1],b[2]),i.removeStartOffset&&(h===void 0?(h=null,h=(v=(_=this._actionOffsets.find(x=>x.clip===e))==null?void 0:_.rootStartPosition)==null?void 0:v.clone()):h!=null&&h.isVector3&&a.sub(h)),a.applyQuaternion(this._totalOffsetRotation),a.add(this._totalOffsetPosition),l&&a.applyQuaternion(l),c&&(a.x-=c.x,a.y+=c.y,a.z+=c.z),this.director.animationCallbackReceivers)for(const x of this.director.animationCallbackReceivers)(w=x==null?void 0:x.onTimelinePosition)==null||w.call(x,this.director,this.target,y,a);return b[0]=a.x,b[1]=a.y,b[2]=a.z,b},p}}}const hE=S("mutetimeline"),ar=class ar extends Hh{constructor(){super(...arguments);r(this,"models",[]);r(this,"listener");r(this,"audio",[]);r(this,"audioContextTimeOffset",[]);r(this,"lastTime",0);r(this,"audioSource");r(this,"_audioLoader",null);r(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const i=this.director.sourceId;return Eo(i,e)}onAllowAudioChanged(e){for(let i=0;i<this.models.length;i++){const n=this.models[i];this.audio[i].setVolume(e?n.asset.volume:0)}}addModel(e){const i=new d.Audio(this.listener);this.audio.push(i);const n=e;n._didTriggerPlay=!1,this.models.push(n)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&(e==null||e.disconnect());this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const i=this.audio[e];i!=null&&i.isPlaying&&i.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const i=this.audio[e];i!=null&&i.isPlaying&&i.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const i=this.audio[e];i!=null&&i.isPlaying&&i.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(hE||this.track.muted||this.director.speed<0)return;const i=this.director.context.application.muted,n=this._playableDirectorResumed;this._playableDirectorResumed=!1;const s=i?.1:0;for(let a=0;a<this.models.length;a++){const l=this.models[a],c=this.audio[a],h=l.asset;if((!c||!c.buffer)&&this.isInTimeRange(l,e-1,e+1)&&this.handleAudioLoading(l,c),qi.userInteractionRegistered!==!1&&!(c===null||!c.buffer))if(c.playbackRate=this.director.context.time.timeScale*this.director.speed,c.loop=h.loop,e>=l.start&&e<=l.end&&e<this.director.duration){if(!c.isPlaying||!this.director.isPlaying)(n||!l._didTriggerPlay&&this.lastTime<e)&&(l.duration*l.timeScale>.3?c.offset=l.clipIn+(e-l.start)*l.timeScale:c.offset=0,Wn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+c.offset+" - "+l.asset.clip),c.play(s),l._didTriggerPlay=!0);else{const f=l.clipIn+(e-l.start)*l.timeScale,p=c.context.currentTime-c._startedAt+c.offset;Math.abs(f-p)>.3&&(c.offset=f,c.stop(),c.play(s))}let u=h.volume;if(this.track.volume!==void 0&&(u*=this.track.volume),i&&(u=0),l.easeInDuration>0){const f=Math.min((e-l.start)/l.easeInDuration,1);u*=f}if(l.easeOutDuration>0){const f=Math.min((l.end-e)/l.easeOutDuration,1);u*=f}c.setVolume(u*this.director.weight)}else l._didTriggerPlay=!1,this.director.isPlaying&&c.isPlaying&&c.stop()}this.lastTime=e}loadAudio(e,i=0,n=0){let s=null;const a=e-n,l=e+i;for(const c of this.models)if(this.isInTimeRange(c,a,l)){const h=this.audio[this.models.indexOf(c)],u=this.handleAudioLoading(c,h);u!==null&&(s===null&&(s=[]),s.push(u))}return s!==null?Promise.all(s):null}isInTimeRange(e,i,n){return i<=e.start&&n>=e.end||i>=e.start&&i<=e.end||n>=e.start&&n<=e.end}static dispose(){ar._audioBuffers.clear()}handleAudioLoading(e,i){this._audioLoader||(this._audioLoader=new d.AudioLoader);const n=this.getAudioFilePath(e.asset.clip);if(ar._audioBuffers.get(n)){const a=ar._audioBuffers.get(n);return a.then(l=>{l&&i.setBuffer(l)}),a}Wn&&console.warn("LOAD audio track",n,this.director.sourceId);const s=new Promise((a,l)=>{this._audioLoader.load(n,c=>{i.setBuffer(c),a(c)},void 0,c=>{console.error("Error loading audio",c),a(null)})});return ar._audioBuffers.set(n,s),s}};r(ar,"_audioBuffers",new Map);let tl=ar;class Hc extends Hh{constructor(){super(...arguments);r(this,"models",[]);r(this,"didTrigger",[]);r(this,"receivers",[])}evaluate(e){var n;if(this.track.muted)return;const i=this.director.context.time.deltaTime*1.5;for(let s=0;s<this.models.length;s++){const a=this.models[s],l=this.didTrigger[s],c=a.time-e;let h=!1;if(a.retroActive)h=c<=1e-6;else{const u=Math.abs(c);(u===0||u>=1e-5&&u<i)&&(h=!0)}if(h){if(!l)if(Wn&&console.log("Trigger signal",e,a.time,a),this.didTrigger[s]=!0,((n=this.receivers)==null?void 0:n.length)<=0)Gh.invoke(a.asset);else for(const u of this.receivers)u&&u.invoke(a.asset)}else a.emitOnce||(this.didTrigger[s]=!1)}}}class Tf extends Hh{constructor(){super(...arguments);r(this,"models",[]);r(this,"timelines",[]);r(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let i=this.models.length-1;i>=0;i--){const s=this.models[i].asset;if(!s.sourceObject||typeof s.sourceObject!="object"){console.log("no source object, removing model",i,s),this.models.splice(i,1);continue}else{const a=C.getComponent(s.sourceObject,il);this.timelines.push(a),a&&s.updateDirector&&(a.playOnAwake=!1)}}}evaluate(e){var i;this._previousActiveModel=null;for(let n=0;n<this.models.length;n++){const s=this.models[n],a=s.asset;if(e>=s.start&&e<=s.end){this._previousActiveModel=s;const l=this.getClipTime(e,s);if(a.controlActivation){const c=a.sourceObject;c.visible=!0}if(a.updateDirector){const c=this.timelines[n];c&&(c.isPlaying&&c.pause(),c.time=l,c.evaluate())}}else{const l=(i=this._previousActiveModel)==null?void 0:i.asset;if(a.controlActivation){const c=a.sourceObject;(l==null?void 0:l.sourceObject)!==c&&(c.visible=!1)}}}}}var dE=Object.defineProperty,kx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&dE(t,e,n),n};const ms=S("debugtimeline");var vo;const $y=(vo=class extends I{constructor(){super(...arguments);r(this,"playableAsset");r(this,"playOnAwake");r(this,"extrapolationMode",1);r(this,"waitForAudio",!0);r(this,"_visibilityChangeEvt");r(this,"_clonedPlayableAsset",!1);r(this,"_speed",1);r(this,"_guidsMap");r(this,"_isPlaying",!1);r(this,"_internalUpdateRoutine");r(this,"_isPaused",!1);r(this,"_isStopping",!1);r(this,"_time",0);r(this,"_duration",0);r(this,"_weight",1);r(this,"_animationTracks",[]);r(this,"_audioTracks",[]);r(this,"_signalTracks",[]);r(this,"_controlTracks",[]);r(this,"_customTracks",[]);r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]);r(this,"animationCallbackReceivers",[])}static registerCreateTrack(e,i){this.createTrackFunctions[e]=i}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(ms||Kt())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}awake(){var e,i,n,s,a;ms&&console.log(this,(e=this.playableAsset)==null?void 0:e.tracks),this.rebuildGraph(),!this.isValid()&&(ms||j())&&(ms?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",(i=this.playableAsset)==null?void 0:i.tracks,"IsArray?",Array.isArray((n=this.playableAsset)==null?void 0:n.tracks),this):(a=(s=this.playableAsset)==null?void 0:s.tracks)!=null&&a.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){var e,i,n;for(const s of this._audioTracks)(e=s.onEnable)==null||e.call(s);for(const s of this._customTracks)(i=s.onEnable)==null||i.call(s);for(const s of this._animationTracks)(n=s.onEnable)==null||n.call(s);this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){var e,i,n;this.stop();for(const s of this._audioTracks)(e=s.onDisable)==null||e.call(s);for(const s of this._customTracks)(i=s.onDisable)==null||i.call(s);for(const s of this._animationTracks)(n=s.onDisable)==null||n.call(s);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var e;for(const i of this._allTracks)for(const n of i)(e=n.onDestroy)==null||e.call(n)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const i=[];for(const n of this._audioTracks){const s=n.loadAudio(this._time,1,0);s&&i.push(s)}if(i.length>0&&(await Promise.all(i),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!qi.userInteractionRegistered&&this.waitForAudio;)await Jn(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),we.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const n of this._audioTracks)n.stop();const e=this._isPaused==!0,i=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!i&&this.invokePauseChangedMethodsOnTracks(),i&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const i of e)yield i}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}resolveGuids(e){this._guidsMap=e}invokePauseChangedMethodsOnTracks(){var e;for(const i of this.forEachTrack())(e=i.onPauseChanged)==null||e.call(i)}invokeStateChangedMethodsOnTracks(){var e;for(const i of this.forEachTrack())(e=i.onStateChanged)==null||e.call(i,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let i=this._time;switch(this.extrapolationMode){case 0:this._speed>0?i=Math.min(i,this._duration):this._speed<0&&(i=Math.max(i,0)),this._time=i;break;case 1:i%=this._duration,this._time=i;break;case 2:if(i>this._duration){this.stop();return}break}const n=this._time;for(const s of this.playableAsset.tracks)if(!s.muted)switch(s.type){case bi.Activation:if(!e&&!this._isPlaying)continue;for(let a=0;a<s.outputs.length;a++){const l=s.outputs[a];if(typeof l=="object"){let c=!1;if(s.clips)for(const u of s.clips)u.start<=n&&n<=u.end&&(c=!0);const h=l;h.visible!==void 0&&h.visible!==c&&(h.visible=c,ms&&console.warn(this.name,"set ActivationTrack-"+a,h.name,c,n))}}break}if(!this._isStopping)for(const s of this._animationTracks)s.evaluate(n);for(const s of this._audioTracks)s.evaluate(n);for(const s of this._signalTracks)s.evaluate(n);for(const s of this._controlTracks)s.evaluate(n);for(const s of this._customTracks)s.evaluate(n)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Jc(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const i of this.playableAsset.tracks){for(let n=i.outputs.length-1;n>=0;n--){let s=i.outputs[n];if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const a=C.findByGuid(s,e);a===null||typeof a!="object"?(i.outputs.splice(n,1),console.warn("Failed to resolve binding",s,i.name,i.type)):(ms&&console.log("Resolved binding",s,"to",a),i.outputs[n]=a)}else if(s===null){if(i.outputs.splice(n,1),vo.createTrackFunctions[i.type])continue;i.type!==bi.Audio&&i.type!==bi.Control&&i.type!==bi.Marker&&i.type!==bi.Signal&&console.warn("Missing binding",s,i.name,i.type,this.name,this.playableAsset.name)}}if(i.type===bi.Control&&i.clips)for(let n=0;n<i.clips.length;n++){const s=i.clips[n];let a=s.asset.sourceObject;if(typeof a=="string"){this._guidsMap&&this._guidsMap[a]&&(a=this._guidsMap[a]);const l=C.findByGuid(a,e);l===null||typeof l!="object"?console.warn("Failed to resolve sourceObject binding",a,i.name,s):(ms&&console.log("Resolved binding",a,"to",l),s.asset.sourceObject=l)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const i of e.clips)i.end>this._duration&&(this._duration=i.end);if(e.markers)for(const i of e.markers)i.time>this._duration&&(this._duration=i.time+.001)}}}setupAndCreateTrackHandlers(){var i,n,s;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=C.findObjectOfType(Ms,this.context);for(const a of this.playableAsset.tracks){const l=a.type,c=vo.createTrackFunctions[l];if(c!=null){const h=c(this,a);if(typeof h.evaluate=="function"){h.director=this,h.track=a,this._customTracks.push(h);continue}}if(a.type===bi.Animation){if(!a.clips||a.clips.length<=0){ms&&console.warn("Animation track has no clips",a);continue}for(let h=a.outputs.length-1;h>=0;h--){let u=a.outputs[h];if(u instanceof d.Object3D){const p=C.getOrAddComponent(u,St);p&&(u=p)}const f=(i=u==null?void 0:u.gameObject)==null?void 0:i.animations;if(f){const p=new Ef;p.trackOffset=a.trackOffset,p.director=this,p.track=a;for(let g=0;g<a.clips.length;g++){const y=a.clips[g],b=y.asset;if(!b){console.error(`Timeline ${this.name}: clip #${g} on track "${a.name}" has no animation data`);continue}const _=b.clip;let v=_;if((typeof v=="string"||typeof v=="number")&&(v=f.find(x=>x.name===_)),ms&&console.log(b,_,"→",v),!v){console.warn("Could not find animationClip for model",y,a.name,this.name,(n=this.playableAsset)==null?void 0:n.name,f,u);continue}u instanceof St&&u.runtimeAnimatorController&&(u.__internalDidAwakeAndStart||u.initializeRuntimeAnimatorController(),u.runtimeAnimatorController.mixer||u.runtimeAnimatorController.bind(u),p.mixer=u.runtimeAnimatorController.mixer),p.mixer||(p.mixer=new d.AnimationMixer(u.gameObject),this.context.animations.registerAnimationMixer(p.mixer)),p.clips.push(v),p.mixer.uncacheAction(v),p.createHooks(y.asset,v);const w=p.mixer.clipAction(v);p.actions.push(w),p.models.push(y)}this._animationTracks.push(p)}}}else if(a.type===bi.Audio){if(!a.clips||a.clips.length<=0)continue;const h=new tl;h.director=this,h.track=a,h.audioSource=a.outputs.find(u=>u instanceof qi),this._audioTracks.push(h),e||(e=(s=this.context.mainCameraComponent)==null?void 0:s.gameObject.addComponent(Ms)),h.listener=e.listener;for(let u=0;u<a.clips.length;u++){const f=a.clips[u];h.addModel(f)}}else if(a.type===bi.Marker){const h=new Hc;if(h.director=this,h.track=a,a.markers)for(const u of a.markers)switch(u.type){case Ny.Signal:h.models.push(u),h.didTrigger.push(!1);break}if(h!==null&&h.models.length>0){const u=C.getComponent(this.gameObject,Gh);u&&(h.receivers.push(u),this._signalTracks.push(h))}}else if(a.type===bi.Signal){const h=new Hc;if(h.director=this,h.track=a,a.markers)for(const u of a.markers)h.models.push(u),h.didTrigger.push(!1);for(const u of a.outputs)h.receivers.push(u);this._signalTracks.push(h)}else if(a.type===bi.Control){const h=new Tf;if(h.director=this,h.track=a,a.clips)for(const u of a.clips)h.models.push(u);h.resolveSourceObjects(this.context),this._controlTracks.push(h)}}}setAudioTracksAllowPlaying(e){for(const i of this._audioTracks)i.onAllowAudioChanged(e)}registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const i=this.animationCallbackReceivers.indexOf(e);i!==-1&&this.animationCallbackReceivers.splice(i,1)}},r(vo,"createTrackFunctions",{}),vo);kx([m()],$y.prototype,"playOnAwake");kx([m()],$y.prototype,"extrapolationMode");let il=$y;var uE=Object.defineProperty,Af=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&uE(t,e,n),n};class ia extends I{constructor(){super(...arguments);r(this,"isGizmo",!1);r(this,"translationSnap",1);r(this,"rotationSnapAngle",15);r(this,"scaleSnap",.25);r(this,"_control");r(this,"orbit");r(this,"onControlChangedEvent",e=>{const i=this.orbit;if(i&&(i.enabled=!e.value),e.value){const n=C.getComponentInParent(this.gameObject,es);n&&n.requestOwnership()}});r(this,"windowKeyDownListener",e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}});r(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}get control(){return this._control}onEnable(){var e;if(!(this.isGizmo&&!rh)&&this.context.mainCamera&&(this._control||(this._control=new H.TransformControls(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(n=>{const s=n;if(s.layers.set(2),s){const a=s.material;a&&(a.opacity=.3)}}),this.orbit=C.getComponentInParent(this.context.mainCamera,ge)??void 0),this._control)){const i=this._control.getHelper();this.context.scene.add(i),this._control.attach(this.gameObject),(e=this._control)==null||e.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){var e,i,n;(i=(e=this._control)==null?void 0:e.getHelper())==null||i.removeFromParent(),(n=this._control)==null||n.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(d.MathUtils.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}}Af([m()],ia.prototype,"isGizmo");Af([m()],ia.prototype,"translationSnap");Af([m()],ia.prototype,"rotationSnapAngle");Af([m()],ia.prototype,"scaleSnap");var fE=Object.defineProperty,pE=Object.getOwnPropertyDescriptor,Lf=(o,t,e,i)=>{for(var n=i>1?void 0:i?pE(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&fE(t,e,n),n};class Vy{constructor(){r(this,"texture",null);r(this,"rect")}}Lf([m(d.Texture)],Vy.prototype,"texture",2);let wl=class extends kh{constructor(){super(...arguments);r(this,"_sprite");r(this,"pixelsPerUnitMultiplier",1)}set image(e){this.sprite||(this.sprite=new Vy),this.sprite.texture=e,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}isBuiltinSprite(){var i,n,s,a,l,c,h;const e=this.sprite;switch((i=e==null?void 0:e.texture)==null?void 0:i.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((s=(n=e==null?void 0:e.texture)==null?void 0:n.name)!=null&&s.length)&&((l=(a=e==null?void 0:e.texture)==null?void 0:a.image)==null?void 0:l.width)===32&&((h=(c=e==null?void 0:e.texture)==null?void 0:c.image)==null?void 0:h.height)===32}onBeforeCreate(e){var i,n;super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,((n=(i=this.sprite)==null?void 0:i.texture)==null?void 0:n.name)==="Knob"&&(e.borderRadius=999))}onAfterCreated(){var e;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((e=this.sprite)==null?void 0:e.texture))}};Lf([m(Vy)],wl.prototype,"sprite",1);Lf([m()],wl.prototype,"pixelsPerUnitMultiplier",2);class Df extends kh{constructor(){super(...arguments);r(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Lf([m(d.Texture)],Df.prototype,"mainTexture",1);var mE=Object.defineProperty,gE=Object.getOwnPropertyDescriptor,ji=(o,t,e,i)=>{for(var n=i>1?void 0:i?gE(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&mE(t,e,n),n};const Ko=S("debugbutton");class Go{constructor(){r(this,"colorMultiplier");r(this,"disabledColor");r(this,"fadeDuration");r(this,"highlightedColor");r(this,"normalColor");r(this,"pressedColor");r(this,"selectedColor")}}ji([m()],Go.prototype,"colorMultiplier",2);ji([m(ie)],Go.prototype,"disabledColor",2);ji([m()],Go.prototype,"fadeDuration",2);ji([m(ie)],Go.prototype,"highlightedColor",2);ji([m(ie)],Go.prototype,"normalColor",2);ji([m(ie)],Go.prototype,"pressedColor",2);ji([m(ie)],Go.prototype,"selectedColor",2);class yE{constructor(){r(this,"disabledTrigger");r(this,"highlightedTrigger");r(this,"normalTrigger");r(this,"pressedTrigger");r(this,"selectedTrigger")}}class Ws extends I{constructor(){super(...arguments);r(this,"onClick",new ye);r(this,"_isHovered",0);r(this,"colors");r(this,"transition");r(this,"animationTriggers");r(this,"animator");r(this,"_interactable",!0);r(this,"_requestedAnimatorTrigger");r(this,"_isInit",!1);r(this,"_image")}click(){var e;(e=this.onClick)==null||e.invoke()}onPointerEnter(e){var n,s;const i=e.event.pointerType==="mouse"&&e.button===0;i&&(this._isHovered+=1),Ko&&console.warn("Button Enter",i,this._isHovered,(n=this.animationTriggers)==null?void 0:n.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("hovered")),i&&this.context.input.setCursor("pointer"))}onPointerExit(){var e,i;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),Ko&&console.log("Button Exit",this._isHovered,(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState("normal")),this.context.input.unsetCursor("pointer")))}onPointerDown(e){var i,n;Ko&&console.log("Button Down",(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((n=this._image)==null||n.setState("pressed")))}onPointerUp(e){var i,n;Ko&&console.warn("Button Up",(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((n=this._image)==null||n.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Nu.Mouse)&&(Ko&&(console.warn("Button Click",this.onClick),Ee("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),Ko))){const i=this.gameObject.worldPosition;i.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),$.DrawLabel(i,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(e){this.interactable=e}awake(){super.awake(),Ko&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable),this.gameObject.getComponentInParent(qa)||this.gameObject.addComponent(Ku)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}*setAnimatorTriggerAtEndOfFrame(e){var i;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((i=this.animator)==null||i.setTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=C.getComponent(this.gameObject,wl),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var g,y,b,_,v;e.setInteractable(this.interactable);const i=this.getFinalColor(e.color,(g=this.colors)==null?void 0:g.normalColor),n={state:"normal",attributes:{backgroundColor:i,backgroundOpacity:i.alpha}};e.setupState(n);const s=this.getFinalColor(e.color,(y=this.colors)==null?void 0:y.highlightedColor),a={state:"hovered",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,(b=this.colors)==null?void 0:b.pressedColor),c={state:"pressed",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);const h=this.getFinalColor(e.color,(_=this.colors)==null?void 0:_.selectedColor),u={state:"selected",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(u);const f=this.getFinalColor(e.color,(v=this.colors)==null?void 0:v.disabledColor),p={state:"disabled",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(p)}getFinalColor(e,i){return i?e.clone().multiply(i).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}ji([m(ye)],Ws.prototype,"onClick",2);ji([m(Go)],Ws.prototype,"colors",2);ji([m()],Ws.prototype,"transition",2);ji([m(yE)],Ws.prototype,"animationTriggers",2);ji([m(St)],Ws.prototype,"animator",2);ji([m()],Ws.prototype,"interactable",1);var _E=Object.defineProperty,If=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&_E(t,e,n),n};const eo=S("debuginputfield");var W;const qh=(W=class extends I{constructor(){super(...arguments);r(this,"textComponent");r(this,"placeholder");r(this,"onValueChanged");r(this,"onEndEdit");r(this,"inputEventFn");r(this,"_iosEventFn")}get text(){var e;return((e=this.textComponent)==null?void 0:e.text)??""}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return W.active===this}start(){eo&&console.log(this.name,this)}onEnable(){var e;W.htmlField||(W.htmlField=document.createElement("input"),W.htmlField.style.width="0px",W.htmlField.style.height="0px",W.htmlField.style.padding="0px",W.htmlField.style.border="none",W.htmlField.style.overflow="hidden",W.htmlField.style.caretColor="transparent",W.htmlField.style.outline="none",W.htmlField.classList.add("ar"),W.htmlField.onfocus=()=>W.htmlFieldFocused=!0,W.htmlField.onblur=()=>W.htmlFieldFocused=!1,document.body.append(W.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),W.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&((e=this.textComponent)!=null&&e.text.length)&&C.setActive(this.placeholder.gameObject,!1),exports.DeviceUtilities.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){var e;(e=W.htmlField)==null||e.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){W.active===this&&W.htmlField?(W.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&C.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType==="mouse"&&e.button===0&&this.context.input.setCursor("text")}onPointerExit(e){this.context.input.unsetCursor("text")}onPointerClick(e){eo&&console.log("CLICK",e,W.active),W.activeTime=this.context.time.time,W.active!==this&&this.startCoroutine(this.activeLoop(),we.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();W.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-W.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){var e,i,n,s;if(W.active!==this&&(eo&&console.log("Select",this.name,this,W.htmlField,this.context.isInXR,this.context.arOverlayElement,(e=this.textComponent)==null?void 0:e.text,(i=W.htmlField)==null?void 0:i.value),(n=W.active)==null||n.onDeselected(),W.active=this,this.placeholder&&C.setActive(this.placeholder.gameObject,!1),W.htmlField)){if(W.htmlField.value=((s=this.textComponent)==null?void 0:s.text)||"",eo&&console.log("set input field value",W.htmlField.value),this.context.isInXR){const a=this.context.arOverlayElement;a&&a.append(W.htmlField)}this.selectInputField()}}onDeselected(){var e;W.active===this&&(W.active=null,eo&&console.log("Deselect",this.name,this),W.htmlField&&(W.htmlField.blur(),document.body.append(W.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&C.setActive(this.placeholder.gameObject,!0),W.htmlField&&((e=this.onEndEdit)==null||e.invoke(W.htmlField.value)))}update(){var e;W.active===this&&((e=this.textComponent)==null||e.markDirty())}onInput(e){var i,n;if(W.active===this){if(eo&&console.log(e.code,e,(i=W.htmlField)==null?void 0:i.value,(n=this.textComponent)==null?void 0:n.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}W.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&C.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){var e;if(this.textComponent&&W.htmlField){const i=this.textComponent.text,n=W.htmlField.value,s=this.textComponent.text!==W.htmlField.value;this.textComponent.text=W.htmlField.value,s&&(eo&&console.log("[InputField] value changed:",n,i),(e=this.onValueChanged)==null||e.invoke(n,i))}}selectInputField(){W.htmlField&&(eo&&console.log("Focus Inputfield",W.htmlFieldFocused),W.htmlField.setSelectionRange(W.htmlField.value.length,W.htmlField.value.length),exports.DeviceUtilities.isiOS()?W.htmlField.focus({preventScroll:!0}):setTimeout(()=>{var e;return(e=W.htmlField)==null?void 0:e.focus()},1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const n=e[0].object,s=Tg(n);((s==null?void 0:s.gameObject)===this.gameObject||(s==null?void 0:s.gameObject.parent)===this.gameObject)&&this.selectInputField()}},r(W,"active",null),r(W,"activeTime",-1),r(W,"htmlField",null),r(W,"htmlFieldFocused",!1),W);If([m(Dt)],qh.prototype,"textComponent");If([m(Dt)],qh.prototype,"placeholder");If([m(ye)],qh.prototype,"onValueChanged");If([m(ye)],qh.prototype,"onEndEdit");let Wy=qh;var bE=Object.defineProperty,Rx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bE(t,e,n),n};class Xh extends I{constructor(){super(...arguments);r(this,"id",null);r(this,"keepAspect",!1);r(this,"_object",null)}onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const i=new H.InteractiveGroup;i.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(i);const n=new H.HTMLMesh(e);i.add(n),n.visible=!1;const s=n.material;s.transparent=!0,setTimeout(()=>{n.visible=!0;const a=Bu(this.gameObject).clone();ih(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const l=new d.Box3;l.setFromObject(i),this.setWorldRotation(a.x,a.y,a.z);const c=l.max.x-l.min.x,h=l.max.y-l.min.y;if(this.keepAspect){const f=c/h;c>h?n.scale.set(1/c,1/h/f,1):n.scale.set(1/c*f,1/h,1)}else n.scale.set(1/c,1/h,1);const u=this.gameObject.scale;n.scale.multiply(u)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}Rx([m()],Xh.prototype,"id");Rx([m()],Xh.prototype,"keepAspect");/* @license
1394
+ C) Set "joinRandomRoom" to true`),!1):(Np&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):j()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,i=new URLSearchParams(e);return i.has(this.urlParameterName)&&i.delete(this.urlParameterName),i.set(zp,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+i.toString()}return null}setRandomRoomUrlParameter(){const e=Zc(),i=this.generateRoomName();S(this.urlParameterName)?e.set(this.urlParameterName,i):e.append(this.urlParameterName,i),Vm(i,e)}generateRoomName(){let e="";for(let i=0;i<6;i++)e+=Math.floor(Math.random()*10).toFixed(0);return e}createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Oc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const i=S(this.urlParameterName);(!i||i===!0)&&(this._lastJoinedRoom?Oc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=_t("group"),this._roomButtonIconLeave=_t("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(ee.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(ee.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(ee.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(ee.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(ee.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(ee.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var e;this.context.connection.stopListen(ee.JoinedRoom,this.onCreateViewOnlyButton),(e=this._viewOnlyButton)==null||e.remove()}}Wo([m()],On.prototype,"roomName",2);Wo([m()],On.prototype,"urlParameterName",2);Wo([m()],On.prototype,"joinRandomRoom",2);Wo([m()],On.prototype,"requireRoomParameter",2);Wo([m()],On.prototype,"autoRejoin",2);Wo([m()],On.prototype,"createJoinButton",2);Wo([m()],On.prototype,"createViewOnlyButton",2);Wo([m()],On.prototype,"roomPrefix",1);function oE(){const o=S("testwindowcount")||0;o&&o>0&&rE(o)}function rE(o){if(S("testwindow"))return null;const t=new URL(window.location.href);Xp(t.searchParams,aM,1),Xp(t.searchParams,"testwindow",1);const e=t.toString(),i=[];window.onbeforeunload=()=>{for(const c of i)c.close()};const n=.05,s=128;let a=0,l=0;for(let c=0;c<o;c++){a*s+s*.01>=window.innerWidth&&(l+=1,a=0);const h=a*(s*(1+n))+window.screenLeft,u=l*(s*(1+n))+window.screenTop+90+60*l;a+=1;const f=window.open(e,"test window "+c,`popup=yes width=${s} height=${s} top=${u} left=${h}`);if(!f){console.warn("Failed to open window");continue}i.push(f),f.onload=()=>{f.onbeforeunload=()=>{for(let p=0;p<i.length;p++){const g=i[p];g!==f&&g.close()}i.length=0}}}return i}class Uy extends I{awake(){oE()}}class zy extends I{constructor(){super(...arguments);r(this,"transformsPerFrame",10);r(this,"interval",0);r(this,"useFlatbuffers",!0);r(this,"builder",null);r(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Bc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new Mx(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new ae.Builder(1024));const e=this.builder;for(let i=0;i<this.transformsPerFrame;i++){e.clear();const n=lw(this.context.connection.connectionId,this);this.context.connection.sendBinary(n)}}else if(this.models)for(let e=0;e<this.models.length;e++){const i=this.models[e];i.dontSave=!0,i.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,i)}}}}class Mx{constructor(t,e){r(this,"guid");r(this,"fast",!1);r(this,"position");r(this,"rotation");r(this,"velocity");r(this,"dontSave");this.guid=t,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(e,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(t,e){const i=t.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=t.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,e){const s=e.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=s.x,this.velocity.y=s.y,this.velocity.z=s.z}}}r(Mx,"temp",new d.Vector3);var aE=Object.defineProperty,kf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&aE(t,e,n),n};const lE=S("debugsignals");class Rf{constructor(){r(this,"guid")}}kf([m()],Rf.prototype,"guid");class Wh{constructor(){r(this,"signal");r(this,"reaction")}}kf([m(Rf)],Wh.prototype,"signal");kf([m(ye)],Wh.prototype,"reaction");var oi;const Ox=(oi=class extends I{constructor(){super(...arguments);r(this,"events")}static invoke(e){if(oi.receivers[e]){const i=oi.receivers[e];if(!i)return;for(const n of i)n.invoke(e)}}awake(){lE&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)oi.receivers[e.signal.guid]||(oi.receivers[e.signal.guid]=[]),oi.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(oi.receivers[e.signal.guid]){const i=oi.receivers[e.signal.guid].indexOf(this);i>=0&&oi.receivers[e.signal.guid].splice(i,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const i=typeof e=="object"?e.guid:e;for(const n of this.events)if(n.signal.guid===i)try{if(n.reaction){if(!n.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",n,this);continue}}else{console.warn("Missing reaction for signal",n,this);continue}n.reaction.invoke()}catch(s){console.error(s)}}},r(oi,"receivers",{}),oi);kf([m(Wh)],Ox.prototype,"events");let Gh=Ox;var bi=(o=>(o.Activation="ActivationTrack",o.Animation="AnimationTrack",o.Audio="AudioTrack",o.Control="ControlTrack",o.Marker="MarkerTrack",o.Signal="SignalTrack",o))(bi||{}),An=(o=>(o[o.None=0]="None",o[o.Hold=1]="Hold",o[o.Loop=2]="Loop",o[o.PingPong=3]="PingPong",o[o.Continue=4]="Continue",o))(An||{}),Ny=(o=>(o.Signal="SignalEmitter",o))(Ny||{});const Wn=S("debugtimeline");class Hh{constructor(){r(this,"director");r(this,"track")}get muted(){return this.track.muted}set muted(t){var e;t!==this.track.muted&&(this.track.muted=t,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(t=!1){var e;if((e=this.track)!=null&&e.clips)if(t)for(let i=this.track.clips.length-1;i>=0;i--)yield this.track.clips[i];else for(const i of this.track.clips)yield i}getClipTime(t,e){return e.clipIn+(t-e.start)*e.timeScale}getClipTimeNormalized(t,e){return(t-e.start)/e.duration}evaluateWeight(t,e,i,n=!0){if(e<0||e>=i.length)return 0;const s=i[e];if(n||t>=s.start&&t<=s.end){let a=1;if(s.easeInDuration>0){const l=Math.min((t-s.start)/s.easeInDuration,1);a*=l}if(s.easeOutDuration>0){const l=Math.min((s.end-t)/s.easeOutDuration,1);a*=l}return a}return 0}}class cE{constructor(t){r(this,"clip");r(this,"rootPositionOffset");r(this,"rootQuaternionOffset");r(this,"rootStartPosition");r(this,"rootEndPosition");r(this,"rootStartQuaternion");r(this,"rootEndQuaternion");const e=t.getClip();this.clip=e;const i=t.getRoot(),n=i.name+".position",s=i.name+".quaternion";Wn&&console.log(e.name,e.tracks,n);for(const a of e.tracks)if(!(a.times.length<=0)){if(a.name.endsWith(n))this.rootStartPosition=new d.Vector3().fromArray(a.values,0),this.rootEndPosition=new d.Vector3().fromArray(a.values,a.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Wn&&console.log(this.rootPositionOffset);else if(a.name.endsWith(s)&&(this.rootStartQuaternion=new d.Quaternion().fromArray(a.values,0),this.rootEndQuaternion=new d.Quaternion().fromArray(a.values,a.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Wn)){const l=new d.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",l)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Ef extends Hh{constructor(){super(...arguments);r(this,"models",[]);r(this,"trackOffset");r(this,"target");r(this,"mixer");r(this,"clips",[]);r(this,"actions",[]);r(this,"weight",1);r(this,"_actionOffsets",[]);r(this,"_didBind",!1);r(this,"_animator",null);r(this,"_useclipOffsets",!0);r(this,"_totalOffsetPosition",new d.Vector3);r(this,"_totalOffsetRotation",new d.Quaternion);r(this,"_totalOffsetPosition2",new d.Vector3);r(this,"_totalOffsetRotation2",new d.Quaternion);r(this,"_summedPos",new d.Vector3);r(this,"_tempPos",new d.Vector3);r(this,"_summedRot",new d.Quaternion);r(this,"_tempRot",new d.Quaternion);r(this,"_clipRotQuat",new d.Quaternion)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&sb(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,i){var u,f;if(((u=i.tracks)==null?void 0:u.length)<=0){console.warn("No tracks in AnimationClip",i);return}const n=i.tracks[0].name.split("."),s=n[n.length-2],a=s+".position",l=s+".quaternion";let c=!1,h=!1;for(const p of i.tracks)p.name.endsWith(a)?(c=!0,this.createPositionInterpolant(i,e,p)):p.name.endsWith(l)&&(h=!0,this.createRotationInterpolant(i,e,p));if(!c||!h){const p=(f=this.mixer)==null?void 0:f.getRoot(),g=i.tracks[0],y=g.name.lastIndexOf("."),b=g.name.substring(0,y),_=b.substring(b.lastIndexOf(".")+1),v=p.getObjectByName(_);if(v)if(c){if(!h){const w=i.tracks[0].name.substring(0,y)+".quaternion";Wn&&console.warn("Create quaternion track",_,v);const x=v.quaternion,O=new d.QuaternionKeyframeTrack(w,[0,i.duration],[x.x,x.y,x.z,x.w,x.x,x.y,x.z,x.w]);i.tracks.push(O),this.createRotationInterpolant(i,e,O)}}else{const w=b+".position";Wn&&console.warn("Create position track",_,v);const x=v.position,O=new d.VectorKeyframeTrack(w,[0,i.duration],[x.x,x.y,x.z,x.x,x.y,x.z]);i.tracks.push(O),this.createPositionInterpolant(i,e,O)}}}bind(){if(!this._didBind){this._didBind=!0,Wn&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const i=new cE(e);this._actionOffsets.push(i)}this.target&&(this._animator=C.getComponent(this.target,xt)??null,this._animator&&sb(this._animator.gameObject,this,!0));for(const e of this.models){const i=e.asset,n=i.position,s=i.rotation;n&&n.x!==void 0&&(n.isVector3||(i.position=new d.Vector3(n.x,n.y,n.z)),s.isQuaternion||(i.rotation=new d.Quaternion(s.x,s.y,s.z,s.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new d.Vector3(e.x,e.y,e.z)));const i=this.trackOffset.rotation;i&&(i.isQuaternion||(this.trackOffset.rotation=new d.Quaternion(i.x,i.y,i.z,i.w)))}}evaluate(e){var c,h,u,f,p,g,y;if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let i=0,n=0,s=!1,a=!1,l=0;for(let b=0;b<this.clips.length;b++){const _=this.models[b],v=this.actions[b],w=_.asset;v.weight=0;const x=e>=_.start&&e<=_.end,O=_.preExtrapolationMode,E=_.postExtrapolationMode,M=b<this.clips.length-1?this.models[b+1]:null;let R=x,F=!1;if(!R&&!s&&_.end<e&&E!==An.None?(!M||M.start>e)&&(R=!0,s=!0):b==0&&!R&&!a&&_.start>e&&O!==An.None&&(!M||M.start<e)&&(R=!0,F=!0,a=!0),R){let D=this.weight;D*=this.evaluateWeight(e,b,this.models,R),D*=this.director.weight;let A=x;if(F)switch(O){case An.Hold:break;case An.Loop:e+=_.start,A=!0;break;default:e+=_.start,A=!0;break}let T=this.getClipTime(e,_),G=0;const B=w.duration;if(F&&O===An.Hold&&(T=0),A){if(w.loop)for(G+=Math.floor(T/(B+1e-6));T>B;)T-=B}else if(!x&&s)switch(E){case An.Hold:T=this.getClipTime(_.end,_);break;case An.Loop:T%=B;break;case An.PingPong:const Y=Math.floor(T/B)%2!==0;T%=B,Y&&(T=B-T);break}_.reversed===!0?v.time=v.getClip().duration-T:v.time=T,v.timeScale=0;const L=Math.max(0,D);if(v.weight=L,l+=L,v.clampWhenFinished=!1,v.isRunning()||v.play(),this._useclipOffsets){const N=i==0?this._totalOffsetPosition:this._totalOffsetPosition2,Y=i==0?this._totalOffsetRotation:this._totalOffsetRotation2;i<1&&(n=1-D),i+=1;const Z=this._summedPos.set(0,0,0),K=this._tempPos.set(0,0,0),de=this._summedRot.identity(),Fe=this._tempRot.identity(),mt=w.rotation;mt&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(mt,D));const kn=this._actionOffsets[b];if(kn.hasOffsets)for(let nn=0;nn<G;nn++)kn.rootPositionOffset?K.copy(kn.rootPositionOffset):K.set(0,0,0),K.applyQuaternion(de),this._clipRotQuat&&K.applyQuaternion(this._clipRotQuat),kn.rootQuaternionOffset&&(Fe.copy(kn.rootQuaternionOffset),de.multiply(Fe)),Z.add(K);this._clipRotQuat&&Y.multiply(this._clipRotQuat),Y.multiply(de),w.position&&Z.add(w.position),N.add(Z)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,n),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,n)),this.__mixerError===void 0&&(Wn||j())&&((h=(c=this._animator)==null?void 0:c.runtimeAnimatorController)!=null&&h.mixer)&&this.mixer!==((f=(u=this._animator)==null?void 0:u.runtimeAnimatorController)==null?void 0:f.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(p=this._animator)!=null&&p.runtimeAnimatorController){const b=Math.max(0,1-l);(y=(g=this._animator)==null?void 0:g.runtimeAnimatorController)==null||y.update(b)}else this.mixer.update(e)}createRotationInterpolant(e,i,n){var c;const s=n.createInterpolant.bind(n),a=new d.Quaternion;this.ensureTrackOffsets();const l=(c=this.trackOffset)==null?void 0:c.rotation;n.createInterpolant=()=>{const h=s(),u=h.evaluate.bind(h);return h.evaluate=f=>{var g;const p=u(f);if(a.set(p[0],p[1],p[2],p[3]),a.premultiply(this._totalOffsetRotation),l&&a.premultiply(l),this.director.animationCallbackReceivers)for(const y of this.director.animationCallbackReceivers)(g=y==null?void 0:y.onTimelineRotation)==null||g.call(y,this.director,this.target,f,a);return p[0]=a.x,p[1]=a.y,p[2]=a.z,p[3]=a.w,p},h}}createPositionInterpolant(e,i,n){var u,f;const s=n.createInterpolant.bind(n),a=new d.Vector3;this.ensureTrackOffsets();const l=(u=this.trackOffset)==null?void 0:u.rotation,c=(f=this.trackOffset)==null?void 0:f.position;let h;n.createInterpolant=()=>{const p=s(),g=p.evaluate.bind(p);return p.evaluate=y=>{var _,v,w;const b=g(y);if(a.set(b[0],b[1],b[2]),i.removeStartOffset&&(h===void 0?(h=null,h=(v=(_=this._actionOffsets.find(x=>x.clip===e))==null?void 0:_.rootStartPosition)==null?void 0:v.clone()):h!=null&&h.isVector3&&a.sub(h)),a.applyQuaternion(this._totalOffsetRotation),a.add(this._totalOffsetPosition),l&&a.applyQuaternion(l),c&&(a.x-=c.x,a.y+=c.y,a.z+=c.z),this.director.animationCallbackReceivers)for(const x of this.director.animationCallbackReceivers)(w=x==null?void 0:x.onTimelinePosition)==null||w.call(x,this.director,this.target,y,a);return b[0]=a.x,b[1]=a.y,b[2]=a.z,b},p}}}const hE=S("mutetimeline"),ar=class ar extends Hh{constructor(){super(...arguments);r(this,"models",[]);r(this,"listener");r(this,"audio",[]);r(this,"audioContextTimeOffset",[]);r(this,"lastTime",0);r(this,"audioSource");r(this,"_audioLoader",null);r(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const i=this.director.sourceId;return Eo(i,e)}onAllowAudioChanged(e){for(let i=0;i<this.models.length;i++){const n=this.models[i];this.audio[i].setVolume(e?n.asset.volume:0)}}addModel(e){const i=new d.Audio(this.listener);this.audio.push(i);const n=e;n._didTriggerPlay=!1,this.models.push(n)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&(e==null||e.disconnect());this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const i=this.audio[e];i!=null&&i.isPlaying&&i.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const i=this.audio[e];i!=null&&i.isPlaying&&i.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const i=this.audio[e];i!=null&&i.isPlaying&&i.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(hE||this.track.muted||this.director.speed<0)return;const i=this.director.context.application.muted,n=this._playableDirectorResumed;this._playableDirectorResumed=!1;const s=i?.1:0;for(let a=0;a<this.models.length;a++){const l=this.models[a],c=this.audio[a],h=l.asset;if((!c||!c.buffer)&&this.isInTimeRange(l,e-1,e+1)&&this.handleAudioLoading(l,c),qi.userInteractionRegistered!==!1&&!(c===null||!c.buffer))if(c.playbackRate=this.director.context.time.timeScale*this.director.speed,c.loop=h.loop,e>=l.start&&e<=l.end&&e<this.director.duration){if(!c.isPlaying||!this.director.isPlaying)(n||!l._didTriggerPlay&&this.lastTime<e)&&(l.duration*l.timeScale>.3?c.offset=l.clipIn+(e-l.start)*l.timeScale:c.offset=0,Wn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+c.offset+" - "+l.asset.clip),c.play(s),l._didTriggerPlay=!0);else{const f=l.clipIn+(e-l.start)*l.timeScale,p=c.context.currentTime-c._startedAt+c.offset;Math.abs(f-p)>.3&&(c.offset=f,c.stop(),c.play(s))}let u=h.volume;if(this.track.volume!==void 0&&(u*=this.track.volume),i&&(u=0),l.easeInDuration>0){const f=Math.min((e-l.start)/l.easeInDuration,1);u*=f}if(l.easeOutDuration>0){const f=Math.min((l.end-e)/l.easeOutDuration,1);u*=f}c.setVolume(u*this.director.weight)}else l._didTriggerPlay=!1,this.director.isPlaying&&c.isPlaying&&c.stop()}this.lastTime=e}loadAudio(e,i=0,n=0){let s=null;const a=e-n,l=e+i;for(const c of this.models)if(this.isInTimeRange(c,a,l)){const h=this.audio[this.models.indexOf(c)],u=this.handleAudioLoading(c,h);u!==null&&(s===null&&(s=[]),s.push(u))}return s!==null?Promise.all(s):null}isInTimeRange(e,i,n){return i<=e.start&&n>=e.end||i>=e.start&&i<=e.end||n>=e.start&&n<=e.end}static dispose(){ar._audioBuffers.clear()}handleAudioLoading(e,i){this._audioLoader||(this._audioLoader=new d.AudioLoader);const n=this.getAudioFilePath(e.asset.clip);if(ar._audioBuffers.get(n)){const a=ar._audioBuffers.get(n);return a.then(l=>{l&&i.setBuffer(l)}),a}Wn&&console.warn("LOAD audio track",n,this.director.sourceId);const s=new Promise((a,l)=>{this._audioLoader.load(n,c=>{i.setBuffer(c),a(c)},void 0,c=>{console.error("Error loading audio",c),a(null)})});return ar._audioBuffers.set(n,s),s}};r(ar,"_audioBuffers",new Map);let tl=ar;class Hc extends Hh{constructor(){super(...arguments);r(this,"models",[]);r(this,"didTrigger",[]);r(this,"receivers",[])}evaluate(e){var n;if(this.track.muted)return;const i=this.director.context.time.deltaTime*1.5;for(let s=0;s<this.models.length;s++){const a=this.models[s],l=this.didTrigger[s],c=a.time-e;let h=!1;if(a.retroActive)h=c<=1e-6;else{const u=Math.abs(c);(u===0||u>=1e-5&&u<i)&&(h=!0)}if(h){if(!l)if(Wn&&console.log("Trigger signal",e,a.time,a),this.didTrigger[s]=!0,((n=this.receivers)==null?void 0:n.length)<=0)Gh.invoke(a.asset);else for(const u of this.receivers)u&&u.invoke(a.asset)}else a.emitOnce||(this.didTrigger[s]=!1)}}}class Tf extends Hh{constructor(){super(...arguments);r(this,"models",[]);r(this,"timelines",[]);r(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let i=this.models.length-1;i>=0;i--){const s=this.models[i].asset;if(!s.sourceObject||typeof s.sourceObject!="object"){console.log("no source object, removing model",i,s),this.models.splice(i,1);continue}else{const a=C.getComponent(s.sourceObject,il);this.timelines.push(a),a&&s.updateDirector&&(a.playOnAwake=!1)}}}evaluate(e){var i;this._previousActiveModel=null;for(let n=0;n<this.models.length;n++){const s=this.models[n],a=s.asset;if(e>=s.start&&e<=s.end){this._previousActiveModel=s;const l=this.getClipTime(e,s);if(a.controlActivation){const c=a.sourceObject;c.visible=!0}if(a.updateDirector){const c=this.timelines[n];c&&(c.isPlaying&&c.pause(),c.time=l,c.evaluate())}}else{const l=(i=this._previousActiveModel)==null?void 0:i.asset;if(a.controlActivation){const c=a.sourceObject;(l==null?void 0:l.sourceObject)!==c&&(c.visible=!1)}}}}}var dE=Object.defineProperty,kx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&dE(t,e,n),n};const ms=S("debugtimeline");var vo;const $y=(vo=class extends I{constructor(){super(...arguments);r(this,"playableAsset");r(this,"playOnAwake");r(this,"extrapolationMode",1);r(this,"waitForAudio",!0);r(this,"_visibilityChangeEvt");r(this,"_clonedPlayableAsset",!1);r(this,"_speed",1);r(this,"_guidsMap");r(this,"_isPlaying",!1);r(this,"_internalUpdateRoutine");r(this,"_isPaused",!1);r(this,"_isStopping",!1);r(this,"_time",0);r(this,"_duration",0);r(this,"_weight",1);r(this,"_animationTracks",[]);r(this,"_audioTracks",[]);r(this,"_signalTracks",[]);r(this,"_controlTracks",[]);r(this,"_customTracks",[]);r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]);r(this,"animationCallbackReceivers",[])}static registerCreateTrack(e,i){this.createTrackFunctions[e]=i}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(ms||Kt())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}awake(){var e,i,n,s,a;ms&&console.log(this,(e=this.playableAsset)==null?void 0:e.tracks),this.rebuildGraph(),!this.isValid()&&(ms||j())&&(ms?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",(i=this.playableAsset)==null?void 0:i.tracks,"IsArray?",Array.isArray((n=this.playableAsset)==null?void 0:n.tracks),this):(a=(s=this.playableAsset)==null?void 0:s.tracks)!=null&&a.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){var e,i,n;for(const s of this._audioTracks)(e=s.onEnable)==null||e.call(s);for(const s of this._customTracks)(i=s.onEnable)==null||i.call(s);for(const s of this._animationTracks)(n=s.onEnable)==null||n.call(s);this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){var e,i,n;this.stop();for(const s of this._audioTracks)(e=s.onDisable)==null||e.call(s);for(const s of this._customTracks)(i=s.onDisable)==null||i.call(s);for(const s of this._animationTracks)(n=s.onDisable)==null||n.call(s);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var e;for(const i of this._allTracks)for(const n of i)(e=n.onDestroy)==null||e.call(n)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const i=[];for(const n of this._audioTracks){const s=n.loadAudio(this._time,1,0);s&&i.push(s)}if(i.length>0&&(await Promise.all(i),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!qi.userInteractionRegistered&&this.waitForAudio;)await Jn(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),we.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const n of this._audioTracks)n.stop();const e=this._isPaused==!0,i=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!i&&this.invokePauseChangedMethodsOnTracks(),i&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const i of e)yield i}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}resolveGuids(e){this._guidsMap=e}invokePauseChangedMethodsOnTracks(){var e;for(const i of this.forEachTrack())(e=i.onPauseChanged)==null||e.call(i)}invokeStateChangedMethodsOnTracks(){var e;for(const i of this.forEachTrack())(e=i.onStateChanged)==null||e.call(i,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let i=this._time;switch(this.extrapolationMode){case 0:this._speed>0?i=Math.min(i,this._duration):this._speed<0&&(i=Math.max(i,0)),this._time=i;break;case 1:i%=this._duration,this._time=i;break;case 2:if(i>this._duration){this.stop();return}break}const n=this._time;for(const s of this.playableAsset.tracks)if(!s.muted)switch(s.type){case bi.Activation:if(!e&&!this._isPlaying)continue;for(let a=0;a<s.outputs.length;a++){const l=s.outputs[a];if(typeof l=="object"){let c=!1;if(s.clips)for(const u of s.clips)u.start<=n&&n<=u.end&&(c=!0);const h=l;h.visible!==void 0&&h.visible!==c&&(h.visible=c,ms&&console.warn(this.name,"set ActivationTrack-"+a,h.name,c,n))}}break}if(!this._isStopping)for(const s of this._animationTracks)s.evaluate(n);for(const s of this._audioTracks)s.evaluate(n);for(const s of this._signalTracks)s.evaluate(n);for(const s of this._controlTracks)s.evaluate(n);for(const s of this._customTracks)s.evaluate(n)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Jc(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const i of this.playableAsset.tracks){for(let n=i.outputs.length-1;n>=0;n--){let s=i.outputs[n];if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const a=C.findByGuid(s,e);a===null||typeof a!="object"?(i.outputs.splice(n,1),console.warn("Failed to resolve binding",s,i.name,i.type)):(ms&&console.log("Resolved binding",s,"to",a),i.outputs[n]=a)}else if(s===null){if(i.outputs.splice(n,1),vo.createTrackFunctions[i.type])continue;i.type!==bi.Audio&&i.type!==bi.Control&&i.type!==bi.Marker&&i.type!==bi.Signal&&console.warn("Missing binding",s,i.name,i.type,this.name,this.playableAsset.name)}}if(i.type===bi.Control&&i.clips)for(let n=0;n<i.clips.length;n++){const s=i.clips[n];let a=s.asset.sourceObject;if(typeof a=="string"){this._guidsMap&&this._guidsMap[a]&&(a=this._guidsMap[a]);const l=C.findByGuid(a,e);l===null||typeof l!="object"?console.warn("Failed to resolve sourceObject binding",a,i.name,s):(ms&&console.log("Resolved binding",a,"to",l),s.asset.sourceObject=l)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const i of e.clips)i.end>this._duration&&(this._duration=i.end);if(e.markers)for(const i of e.markers)i.time>this._duration&&(this._duration=i.time+.001)}}}setupAndCreateTrackHandlers(){var i,n,s;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=C.findObjectOfType(Ms,this.context);for(const a of this.playableAsset.tracks){const l=a.type,c=vo.createTrackFunctions[l];if(c!=null){const h=c(this,a);if(typeof h.evaluate=="function"){h.director=this,h.track=a,this._customTracks.push(h);continue}}if(a.type===bi.Animation){if(!a.clips||a.clips.length<=0){ms&&console.warn("Animation track has no clips",a);continue}for(let h=a.outputs.length-1;h>=0;h--){let u=a.outputs[h];if(u instanceof d.Object3D){const p=C.getOrAddComponent(u,xt);p&&(u=p)}const f=(i=u==null?void 0:u.gameObject)==null?void 0:i.animations;if(f){const p=new Ef;p.trackOffset=a.trackOffset,p.director=this,p.track=a;for(let g=0;g<a.clips.length;g++){const y=a.clips[g],b=y.asset;if(!b){console.error(`Timeline ${this.name}: clip #${g} on track "${a.name}" has no animation data`);continue}const _=b.clip;let v=_;if((typeof v=="string"||typeof v=="number")&&(v=f.find(x=>x.name===_)),ms&&console.log(b,_,"→",v),!v){console.warn("Could not find animationClip for model",y,a.name,this.name,(n=this.playableAsset)==null?void 0:n.name,f,u);continue}u instanceof xt&&u.runtimeAnimatorController&&(u.__internalDidAwakeAndStart||u.initializeRuntimeAnimatorController(),u.runtimeAnimatorController.mixer||u.runtimeAnimatorController.bind(u),p.mixer=u.runtimeAnimatorController.mixer),p.mixer||(p.mixer=new d.AnimationMixer(u.gameObject),this.context.animations.registerAnimationMixer(p.mixer)),p.clips.push(v),p.mixer.uncacheAction(v),p.createHooks(y.asset,v);const w=p.mixer.clipAction(v);p.actions.push(w),p.models.push(y)}this._animationTracks.push(p)}}}else if(a.type===bi.Audio){if(!a.clips||a.clips.length<=0)continue;const h=new tl;h.director=this,h.track=a,h.audioSource=a.outputs.find(u=>u instanceof qi),this._audioTracks.push(h),e||(e=(s=this.context.mainCameraComponent)==null?void 0:s.gameObject.addComponent(Ms)),h.listener=e.listener;for(let u=0;u<a.clips.length;u++){const f=a.clips[u];h.addModel(f)}}else if(a.type===bi.Marker){const h=new Hc;if(h.director=this,h.track=a,a.markers)for(const u of a.markers)switch(u.type){case Ny.Signal:h.models.push(u),h.didTrigger.push(!1);break}if(h!==null&&h.models.length>0){const u=C.getComponent(this.gameObject,Gh);u&&(h.receivers.push(u),this._signalTracks.push(h))}}else if(a.type===bi.Signal){const h=new Hc;if(h.director=this,h.track=a,a.markers)for(const u of a.markers)h.models.push(u),h.didTrigger.push(!1);for(const u of a.outputs)h.receivers.push(u);this._signalTracks.push(h)}else if(a.type===bi.Control){const h=new Tf;if(h.director=this,h.track=a,a.clips)for(const u of a.clips)h.models.push(u);h.resolveSourceObjects(this.context),this._controlTracks.push(h)}}}setAudioTracksAllowPlaying(e){for(const i of this._audioTracks)i.onAllowAudioChanged(e)}registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const i=this.animationCallbackReceivers.indexOf(e);i!==-1&&this.animationCallbackReceivers.splice(i,1)}},r(vo,"createTrackFunctions",{}),vo);kx([m()],$y.prototype,"playOnAwake");kx([m()],$y.prototype,"extrapolationMode");let il=$y;var uE=Object.defineProperty,Af=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&uE(t,e,n),n};class ia extends I{constructor(){super(...arguments);r(this,"isGizmo",!1);r(this,"translationSnap",1);r(this,"rotationSnapAngle",15);r(this,"scaleSnap",.25);r(this,"_control");r(this,"orbit");r(this,"onControlChangedEvent",e=>{const i=this.orbit;if(i&&(i.enabled=!e.value),e.value){const n=C.getComponentInParent(this.gameObject,es);n&&n.requestOwnership()}});r(this,"windowKeyDownListener",e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}});r(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}get control(){return this._control}onEnable(){var e;if(!(this.isGizmo&&!rh)&&this.context.mainCamera&&(this._control||(this._control=new H.TransformControls(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(n=>{const s=n;if(s.layers.set(2),s){const a=s.material;a&&(a.opacity=.3)}}),this.orbit=C.getComponentInParent(this.context.mainCamera,ge)??void 0),this._control)){const i=this._control.getHelper();this.context.scene.add(i),this._control.attach(this.gameObject),(e=this._control)==null||e.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){var e,i,n;(i=(e=this._control)==null?void 0:e.getHelper())==null||i.removeFromParent(),(n=this._control)==null||n.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(d.MathUtils.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}}Af([m()],ia.prototype,"isGizmo");Af([m()],ia.prototype,"translationSnap");Af([m()],ia.prototype,"rotationSnapAngle");Af([m()],ia.prototype,"scaleSnap");var fE=Object.defineProperty,pE=Object.getOwnPropertyDescriptor,Lf=(o,t,e,i)=>{for(var n=i>1?void 0:i?pE(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&fE(t,e,n),n};class Vy{constructor(){r(this,"texture",null);r(this,"rect")}}Lf([m(d.Texture)],Vy.prototype,"texture",2);let wl=class extends kh{constructor(){super(...arguments);r(this,"_sprite");r(this,"pixelsPerUnitMultiplier",1)}set image(e){this.sprite||(this.sprite=new Vy),this.sprite.texture=e,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}isBuiltinSprite(){var i,n,s,a,l,c,h;const e=this.sprite;switch((i=e==null?void 0:e.texture)==null?void 0:i.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((s=(n=e==null?void 0:e.texture)==null?void 0:n.name)!=null&&s.length)&&((l=(a=e==null?void 0:e.texture)==null?void 0:a.image)==null?void 0:l.width)===32&&((h=(c=e==null?void 0:e.texture)==null?void 0:c.image)==null?void 0:h.height)===32}onBeforeCreate(e){var i,n;super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,((n=(i=this.sprite)==null?void 0:i.texture)==null?void 0:n.name)==="Knob"&&(e.borderRadius=999))}onAfterCreated(){var e;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((e=this.sprite)==null?void 0:e.texture))}};Lf([m(Vy)],wl.prototype,"sprite",1);Lf([m()],wl.prototype,"pixelsPerUnitMultiplier",2);class Df extends kh{constructor(){super(...arguments);r(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Lf([m(d.Texture)],Df.prototype,"mainTexture",1);var mE=Object.defineProperty,gE=Object.getOwnPropertyDescriptor,ji=(o,t,e,i)=>{for(var n=i>1?void 0:i?gE(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&mE(t,e,n),n};const Ko=S("debugbutton");class Go{constructor(){r(this,"colorMultiplier");r(this,"disabledColor");r(this,"fadeDuration");r(this,"highlightedColor");r(this,"normalColor");r(this,"pressedColor");r(this,"selectedColor")}}ji([m()],Go.prototype,"colorMultiplier",2);ji([m(ie)],Go.prototype,"disabledColor",2);ji([m()],Go.prototype,"fadeDuration",2);ji([m(ie)],Go.prototype,"highlightedColor",2);ji([m(ie)],Go.prototype,"normalColor",2);ji([m(ie)],Go.prototype,"pressedColor",2);ji([m(ie)],Go.prototype,"selectedColor",2);class yE{constructor(){r(this,"disabledTrigger");r(this,"highlightedTrigger");r(this,"normalTrigger");r(this,"pressedTrigger");r(this,"selectedTrigger")}}class Ws extends I{constructor(){super(...arguments);r(this,"onClick",new ye);r(this,"_isHovered",0);r(this,"colors");r(this,"transition");r(this,"animationTriggers");r(this,"animator");r(this,"_interactable",!0);r(this,"_requestedAnimatorTrigger");r(this,"_isInit",!1);r(this,"_image")}click(){var e;(e=this.onClick)==null||e.invoke()}onPointerEnter(e){var n,s;const i=e.event.pointerType==="mouse"&&e.button===0;i&&(this._isHovered+=1),Ko&&console.warn("Button Enter",i,this._isHovered,(n=this.animationTriggers)==null?void 0:n.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("hovered")),i&&this.context.input.setCursor("pointer"))}onPointerExit(){var e,i;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),Ko&&console.log("Button Exit",this._isHovered,(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState("normal")),this.context.input.unsetCursor("pointer")))}onPointerDown(e){var i,n;Ko&&console.log("Button Down",(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((n=this._image)==null||n.setState("pressed")))}onPointerUp(e){var i,n;Ko&&console.warn("Button Up",(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((n=this._image)==null||n.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Nu.Mouse)&&(Ko&&(console.warn("Button Click",this.onClick),Ee("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),Ko))){const i=this.gameObject.worldPosition;i.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),$.DrawLabel(i,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(e){this.interactable=e}awake(){super.awake(),Ko&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable),this.gameObject.getComponentInParent(qa)||this.gameObject.addComponent(Ku)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}*setAnimatorTriggerAtEndOfFrame(e){var i;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((i=this.animator)==null||i.setTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=C.getComponent(this.gameObject,wl),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var g,y,b,_,v;e.setInteractable(this.interactable);const i=this.getFinalColor(e.color,(g=this.colors)==null?void 0:g.normalColor),n={state:"normal",attributes:{backgroundColor:i,backgroundOpacity:i.alpha}};e.setupState(n);const s=this.getFinalColor(e.color,(y=this.colors)==null?void 0:y.highlightedColor),a={state:"hovered",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,(b=this.colors)==null?void 0:b.pressedColor),c={state:"pressed",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);const h=this.getFinalColor(e.color,(_=this.colors)==null?void 0:_.selectedColor),u={state:"selected",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(u);const f=this.getFinalColor(e.color,(v=this.colors)==null?void 0:v.disabledColor),p={state:"disabled",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(p)}getFinalColor(e,i){return i?e.clone().multiply(i).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}ji([m(ye)],Ws.prototype,"onClick",2);ji([m(Go)],Ws.prototype,"colors",2);ji([m()],Ws.prototype,"transition",2);ji([m(yE)],Ws.prototype,"animationTriggers",2);ji([m(xt)],Ws.prototype,"animator",2);ji([m()],Ws.prototype,"interactable",1);var _E=Object.defineProperty,If=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&_E(t,e,n),n};const eo=S("debuginputfield");var W;const qh=(W=class extends I{constructor(){super(...arguments);r(this,"textComponent");r(this,"placeholder");r(this,"onValueChanged");r(this,"onEndEdit");r(this,"inputEventFn");r(this,"_iosEventFn")}get text(){var e;return((e=this.textComponent)==null?void 0:e.text)??""}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return W.active===this}start(){eo&&console.log(this.name,this)}onEnable(){var e;W.htmlField||(W.htmlField=document.createElement("input"),W.htmlField.style.width="0px",W.htmlField.style.height="0px",W.htmlField.style.padding="0px",W.htmlField.style.border="none",W.htmlField.style.overflow="hidden",W.htmlField.style.caretColor="transparent",W.htmlField.style.outline="none",W.htmlField.classList.add("ar"),W.htmlField.onfocus=()=>W.htmlFieldFocused=!0,W.htmlField.onblur=()=>W.htmlFieldFocused=!1,document.body.append(W.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),W.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&((e=this.textComponent)!=null&&e.text.length)&&C.setActive(this.placeholder.gameObject,!1),exports.DeviceUtilities.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){var e;(e=W.htmlField)==null||e.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){W.active===this&&W.htmlField?(W.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&C.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType==="mouse"&&e.button===0&&this.context.input.setCursor("text")}onPointerExit(e){this.context.input.unsetCursor("text")}onPointerClick(e){eo&&console.log("CLICK",e,W.active),W.activeTime=this.context.time.time,W.active!==this&&this.startCoroutine(this.activeLoop(),we.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();W.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-W.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){var e,i,n,s;if(W.active!==this&&(eo&&console.log("Select",this.name,this,W.htmlField,this.context.isInXR,this.context.arOverlayElement,(e=this.textComponent)==null?void 0:e.text,(i=W.htmlField)==null?void 0:i.value),(n=W.active)==null||n.onDeselected(),W.active=this,this.placeholder&&C.setActive(this.placeholder.gameObject,!1),W.htmlField)){if(W.htmlField.value=((s=this.textComponent)==null?void 0:s.text)||"",eo&&console.log("set input field value",W.htmlField.value),this.context.isInXR){const a=this.context.arOverlayElement;a&&a.append(W.htmlField)}this.selectInputField()}}onDeselected(){var e;W.active===this&&(W.active=null,eo&&console.log("Deselect",this.name,this),W.htmlField&&(W.htmlField.blur(),document.body.append(W.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&C.setActive(this.placeholder.gameObject,!0),W.htmlField&&((e=this.onEndEdit)==null||e.invoke(W.htmlField.value)))}update(){var e;W.active===this&&((e=this.textComponent)==null||e.markDirty())}onInput(e){var i,n;if(W.active===this){if(eo&&console.log(e.code,e,(i=W.htmlField)==null?void 0:i.value,(n=this.textComponent)==null?void 0:n.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}W.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&C.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){var e;if(this.textComponent&&W.htmlField){const i=this.textComponent.text,n=W.htmlField.value,s=this.textComponent.text!==W.htmlField.value;this.textComponent.text=W.htmlField.value,s&&(eo&&console.log("[InputField] value changed:",n,i),(e=this.onValueChanged)==null||e.invoke(n,i))}}selectInputField(){W.htmlField&&(eo&&console.log("Focus Inputfield",W.htmlFieldFocused),W.htmlField.setSelectionRange(W.htmlField.value.length,W.htmlField.value.length),exports.DeviceUtilities.isiOS()?W.htmlField.focus({preventScroll:!0}):setTimeout(()=>{var e;return(e=W.htmlField)==null?void 0:e.focus()},1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const n=e[0].object,s=Tg(n);((s==null?void 0:s.gameObject)===this.gameObject||(s==null?void 0:s.gameObject.parent)===this.gameObject)&&this.selectInputField()}},r(W,"active",null),r(W,"activeTime",-1),r(W,"htmlField",null),r(W,"htmlFieldFocused",!1),W);If([m(Dt)],qh.prototype,"textComponent");If([m(Dt)],qh.prototype,"placeholder");If([m(ye)],qh.prototype,"onValueChanged");If([m(ye)],qh.prototype,"onEndEdit");let Wy=qh;var bE=Object.defineProperty,Rx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bE(t,e,n),n};class Xh extends I{constructor(){super(...arguments);r(this,"id",null);r(this,"keepAspect",!1);r(this,"_object",null)}onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const i=new H.InteractiveGroup;i.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(i);const n=new H.HTMLMesh(e);i.add(n),n.visible=!1;const s=n.material;s.transparent=!0,setTimeout(()=>{n.visible=!0;const a=Bu(this.gameObject).clone();ih(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const l=new d.Box3;l.setFromObject(i),this.setWorldRotation(a.x,a.y,a.z);const c=l.max.x-l.min.x,h=l.max.y-l.min.y;if(this.keepAspect){const f=c/h;c>h?n.scale.set(1/c,1/h/f,1):n.scale.set(1/c*f,1/h,1)}else n.scale.set(1/c,1/h,1);const u=this.gameObject.scale;n.scale.multiply(u)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}Rx([m()],Xh.prototype,"id");Rx([m()],Xh.prototype,"keepAspect");/* @license
1395
1395
  * Copyright 2021 Google LLC. All Rights Reserved.
1396
1396
  * Licensed under the Apache License, Version 2.0 (the 'License');
1397
1397
  * you may not use this file except in compliance with the License.
@@ -1404,7 +1404,7 @@ C) Set "joinRandomRoom" to true`),!1):(Np&&console.log("Join "+this.roomName),th
1404
1404
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1405
1405
  * See the License for the specific language governing permissions and
1406
1406
  * limitations under the License.
1407
- */const vE={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},wE={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]};class jf extends d.Scene{constructor(t){super(),this.position.y=-3.5;const e=new d.BoxGeometry;e.deleteAttribute("uv");const i=new d.MeshStandardMaterial({metalness:0,side:d.BackSide}),n=new d.MeshStandardMaterial({metalness:0}),s=t=="legacy"?vE:wE,a=new d.PointLight(16777215,s.topLight.intensity,28,2);a.position.set(...s.topLight.position),this.add(a);const l=new d.Mesh(e,i);l.position.set(...s.room.position),l.scale.set(...s.room.scale),this.add(l);for(const c of s.boxes){const h=new d.Mesh(e,n);h.position.set(...c.position),h.rotation.set(0,c.rotation,0),h.scale.set(...c.scale),this.add(h)}for(const c of s.lights){const h=new d.Mesh(e,this.createAreaLightMaterial(c.intensity));h.position.set(...c.position),h.scale.set(...c.scale),this.add(h)}}createAreaLightMaterial(t){const e=new d.MeshBasicMaterial;return e.color.setScalar(t),e}}var xE=Object.defineProperty,Bf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&xE(t,e,n),n},fr;const Qh=(fr=class extends I{constructor(){super(...arguments);r(this,"target");r(this,"invertForward",!1);r(this,"keepUpDirection",!0);r(this,"copyTargetRotation",!1)}onBeforeRender(){let e=this.target;if(e||(e=this.context.mainCamera),!e)return;let i=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(i=!1),th(this.gameObject,e,this.keepUpDirection,i),this.invertForward&&this.gameObject.quaternion.multiply(fr.flipYQuat)}createBehaviours(e,i,n){if(i.uuid===this.gameObject.uuid){let s=i;if(this.keepUpDirection){const l=Et.createEmptyParent(i);s=l;const c=this.invertForward?-1:1;l.setMatrix(l.getMatrix().multiply(new d.Matrix4().makeRotationZ(Math.PI/2*c))),i.setMatrix(i.getMatrix().multiply(new d.Matrix4().makeRotationZ(-Math.PI/2*c)))}const a=new wt("lookat "+this.name,xt.sceneStartTrigger(),fe.lookAtCameraAction(s,void 0,this.invertForward?Vi.back:Vi.forward,this.keepUpDirection?Vi.up:Vi.zero));e.addBehavior(a)}}},r(fr,"flipYQuat",new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI)),fr);Bf([m(d.Object3D)],Qh.prototype,"target");Bf([m()],Qh.prototype,"invertForward");Bf([m()],Qh.prototype,"keepUpDirection");Bf([m()],Qh.prototype,"copyTargetRotation");let Gy=Qh;var SE=Object.defineProperty,Hy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&SE(t,e,n),n};class xl extends I{constructor(){super(...arguments);r(this,"url");r(this,"mode",0);r(this,"clickable",!0)}async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),j()&&Ee("Open URL: "+e),this.mode){case 0:exports.DeviceUtilities.isSafari(),globalThis.open(e,"_blank");break;case 1:exports.DeviceUtilities.isSafari()&&exports.DeviceUtilities.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:exports.DeviceUtilities.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){var i;this.clickable&&!e.used&&((i=this.url)!=null&&i.length)&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(j()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}Hy([m()],xl.prototype,"url");Hy([m()],xl.prototype,"mode");Hy([m()],xl.prototype,"clickable");var CE=Object.defineProperty,Sl=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&CE(t,e,n),n};class Gs extends I{constructor(){super(...arguments);r(this,"side","none");r(this,"controller",!0);r(this,"hands",!1);r(this,"controlVisibility",!0);r(this,"useGripSpace",!1);r(this,"resetTransformAfterXRSession",!0);r(this,"_startPosition",new d.Vector3);r(this,"_startRotation",new d.Quaternion);r(this,"_startScale",new d.Vector3)}get activeAndEnabled(){return!0}onEnterXR(e){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(e){if(!this.enabled)return;const i=e.xr.getController(this.side);if(i){if(i.hand&&!this.hands){this.controlVisibility&&(this.gameObject.visible=!1);return}else if(!this.controller){this.controlVisibility&&(this.gameObject.visible=!1);return}this.controlVisibility&&(this.gameObject.visible=!0),this.useGripSpace||i.targetRayMode==="transient-pointer"?(this.gameObject.worldPosition=i.gripWorldPosition,this.gameObject.worldQuaternion=i.gripWorldQuaternion,this.gameObject.worldScale=V(i.xr.rigScale,i.xr.rigScale,i.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=i.rayWorldPosition,this.gameObject.worldQuaternion=i.rayWorldQuaternion,this.gameObject.worldScale=V(i.xr.rigScale,i.xr.rigScale,i.xr.rigScale).multiply(this._startScale))}}onLeaveXR(e){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}}Sl([m()],Gs.prototype,"side");Sl([m()],Gs.prototype,"controller");Sl([m()],Gs.prototype,"hands");Sl([m()],Gs.prototype,"controlVisibility");Sl([m()],Gs.prototype,"useGripSpace");Sl([m()],Gs.prototype,"resetTransformAfterXRSession");function Ex(o,t){const e=o.xr.getFrame();if(!e)return console.warn("No XRFrame available"),!1;const i=e.session.enabledFeatures;if(i&&!i.some(s=>s==="camera-access"))return console.error(`No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene.
1407
+ */const vE={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},wE={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]};class jf extends d.Scene{constructor(t){super(),this.position.y=-3.5;const e=new d.BoxGeometry;e.deleteAttribute("uv");const i=new d.MeshStandardMaterial({metalness:0,side:d.BackSide}),n=new d.MeshStandardMaterial({metalness:0}),s=t=="legacy"?vE:wE,a=new d.PointLight(16777215,s.topLight.intensity,28,2);a.position.set(...s.topLight.position),this.add(a);const l=new d.Mesh(e,i);l.position.set(...s.room.position),l.scale.set(...s.room.scale),this.add(l);for(const c of s.boxes){const h=new d.Mesh(e,n);h.position.set(...c.position),h.rotation.set(0,c.rotation,0),h.scale.set(...c.scale),this.add(h)}for(const c of s.lights){const h=new d.Mesh(e,this.createAreaLightMaterial(c.intensity));h.position.set(...c.position),h.scale.set(...c.scale),this.add(h)}}createAreaLightMaterial(t){const e=new d.MeshBasicMaterial;return e.color.setScalar(t),e}}var xE=Object.defineProperty,Bf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&xE(t,e,n),n},fr;const Qh=(fr=class extends I{constructor(){super(...arguments);r(this,"target");r(this,"invertForward",!1);r(this,"keepUpDirection",!0);r(this,"copyTargetRotation",!1)}onBeforeRender(){let e=this.target;if(e||(e=this.context.mainCamera),!e)return;let i=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(i=!1),th(this.gameObject,e,this.keepUpDirection,i),this.invertForward&&this.gameObject.quaternion.multiply(fr.flipYQuat)}createBehaviours(e,i,n){if(i.uuid===this.gameObject.uuid){let s=i;if(this.keepUpDirection){const l=Et.createEmptyParent(i);s=l;const c=this.invertForward?-1:1;l.setMatrix(l.getMatrix().multiply(new d.Matrix4().makeRotationZ(Math.PI/2*c))),i.setMatrix(i.getMatrix().multiply(new d.Matrix4().makeRotationZ(-Math.PI/2*c)))}const a=new vt("lookat "+this.name,wt.sceneStartTrigger(),fe.lookAtCameraAction(s,void 0,this.invertForward?Vi.back:Vi.forward,this.keepUpDirection?Vi.up:Vi.zero));e.addBehavior(a)}}},r(fr,"flipYQuat",new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI)),fr);Bf([m(d.Object3D)],Qh.prototype,"target");Bf([m()],Qh.prototype,"invertForward");Bf([m()],Qh.prototype,"keepUpDirection");Bf([m()],Qh.prototype,"copyTargetRotation");let Gy=Qh;var SE=Object.defineProperty,Hy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&SE(t,e,n),n};class xl extends I{constructor(){super(...arguments);r(this,"url");r(this,"mode",0);r(this,"clickable",!0)}async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),j()&&Ee("Open URL: "+e),this.mode){case 0:exports.DeviceUtilities.isSafari(),globalThis.open(e,"_blank");break;case 1:exports.DeviceUtilities.isSafari()&&exports.DeviceUtilities.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:exports.DeviceUtilities.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){var i;this.clickable&&!e.used&&((i=this.url)!=null&&i.length)&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(j()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}Hy([m()],xl.prototype,"url");Hy([m()],xl.prototype,"mode");Hy([m()],xl.prototype,"clickable");var CE=Object.defineProperty,Sl=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&CE(t,e,n),n};class Gs extends I{constructor(){super(...arguments);r(this,"side","none");r(this,"controller",!0);r(this,"hands",!1);r(this,"controlVisibility",!0);r(this,"useGripSpace",!1);r(this,"resetTransformAfterXRSession",!0);r(this,"_startPosition",new d.Vector3);r(this,"_startRotation",new d.Quaternion);r(this,"_startScale",new d.Vector3)}get activeAndEnabled(){return!0}onEnterXR(e){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(e){if(!this.enabled)return;const i=e.xr.getController(this.side);if(i){if(i.hand&&!this.hands){this.controlVisibility&&(this.gameObject.visible=!1);return}else if(!this.controller){this.controlVisibility&&(this.gameObject.visible=!1);return}this.controlVisibility&&(this.gameObject.visible=!0),this.useGripSpace||i.targetRayMode==="transient-pointer"?(this.gameObject.worldPosition=i.gripWorldPosition,this.gameObject.worldQuaternion=i.gripWorldQuaternion,this.gameObject.worldScale=V(i.xr.rigScale,i.xr.rigScale,i.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=i.rayWorldPosition,this.gameObject.worldQuaternion=i.rayWorldQuaternion,this.gameObject.worldScale=V(i.xr.rigScale,i.xr.rigScale,i.xr.rigScale).multiply(this._startScale))}}onLeaveXR(e){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}}Sl([m()],Gs.prototype,"side");Sl([m()],Gs.prototype,"controller");Sl([m()],Gs.prototype,"hands");Sl([m()],Gs.prototype,"controlVisibility");Sl([m()],Gs.prototype,"useGripSpace");Sl([m()],Gs.prototype,"resetTransformAfterXRSession");function Ex(o,t){const e=o.xr.getFrame();if(!e)return console.warn("No XRFrame available"),!1;const i=e.session.enabledFeatures;if(i&&!i.some(s=>s==="camera-access"))return console.error(`No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene.
1408
1408
 
1409
1409
  Example to request camera-access in global scope:
1410
1410
  NeedleXRSession.onSessionRequestStart(evt => {
@@ -1450,7 +1450,7 @@ void main() {
1450
1450
  #include <colorspace_fragment>
1451
1451
  }
1452
1452
  `;var TE=Object.defineProperty,Ho=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&TE(t,e,n),n};const Xb=S("debugimagetracking"),Ta=class Ta{constructor(t,e,i,n,s,a){r(this,"measuredSize");r(this,"state");r(this,"_position");r(this,"_rotation");r(this,"_trackingComponent");r(this,"_trackedImage");r(this,"_bitmap");r(this,"_pose");this._trackingComponent=t,this._trackedImage=e,this._bitmap=i,this.measuredSize=n,this.state=s,this._pose=a}get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}getPosition(t){return this.ensureTransformData(),t.copy(this._position),t}getQuaternion(t){return this.ensureTransformData(),t.copy(this._rotation),t}applyToObject(t,e=void 0){this.ensureTransformData();const i=t.position.distanceToSquared(this._position)/.05+t.quaternion.angleTo(this._rotation)/.05;e&&(e*=Math.max(1,i)),e===void 0||e>=1?(t.position.copy(this._position),t.quaternion.copy(this._rotation)):(e=Math.max(0,Math.min(1,e)),t.position.lerp(this._position,e),t.quaternion.slerp(this._rotation,e))}ensureTransformData(){if(!this._position){this._position=Ta._positionBuffer.get(),this._rotation=Ta._rotationBuffer.get();const t=this._pose.transform,e=J.active.convertSpace(t);this._position.copy(e==null?void 0:e.position),this._rotation.copy(e==null?void 0:e.quaternion)}}};r(Ta,"_positionBuffer",new ki(()=>new d.Vector3,20)),r(Ta,"_rotationBuffer",new ki(()=>new d.Quaternion,20));let qc=Ta;class Hs{constructor(){r(this,"image");r(this,"widthInMeters",.25);r(this,"object");r(this,"createObjectInstance",!1);r(this,"imageDoesNotMove",!1);r(this,"hideWhenTrackingIsLost",!0)}}Ho([m(URL)],Hs.prototype,"image");Ho([m()],Hs.prototype,"widthInMeters");Ho([m(te)],Hs.prototype,"object");Ho([m()],Hs.prototype,"createObjectInstance");Ho([m()],Hs.prototype,"imageDoesNotMove");Ho([m()],Hs.prototype,"hideWhenTrackingIsLost");class AE{constructor(t,e,i){r(this,"filename");r(this,"widthInMeters");r(this,"imageData");this.filename=t,this.imageData=e,this.widthInMeters=i}get extensionName(){return"image-tracking"}onAfterHierarchy(t,e){const i=exports.DeviceUtilities.getiOSVersion(),a=(i?parseInt(i.split(".")[0]):18)>=18?1:100;e.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),e.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),e.appendLine("uniform double physicalWidth = "+(this.widthInMeters*a).toFixed(8)),e.closeBlock()}onBeforeBuildDocument(t){const e=C.findObjectOfType(Xc);!e||!e.trackedImages||e.trackedImages.length>1&&(j()&&me("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported."))}onAfterSerialize(t){t.files["image_tracking/"+this.filename]=this.imageData}onExportObject(t,e,i){var s;const n=C.findObjectOfType(Xc);if(!(!n||!n.trackedImages)){for(const a of n.trackedImages)if(((s=a.object)==null?void 0:s.asset)===t){const l=C.findObjectOfType(Kn);if(!l)continue;const{scale:c,target:h}=l.getARScaleAndTarget();let u=t;const f=new d.Matrix4;if(t!==h)for(;u.parent&&u.parent!==h;)u=u.parent,f.premultiply(u.matrix);const p=f.clone().invert();e.setMatrix(p.scale(new d.Vector3(c,c,c)));break}}}}var qn;const Xy=(qn=class extends I{constructor(){super(...arguments);r(this,"trackedImages");r(this,"smooth",!0);r(this,"trackedImageIndexMap",new Map);r(this,"_supported",!0);r(this,"imageToObjectMap",new Map);r(this,"currentImages",[]);r(this,"webXRIncubationsWarning",`Image tracking is currently not supported on this device. On Chrome for Android, you can enable the <a target="_blank" href="#" onclick="() => console.log('I')">chrome://flags/#webxr-incubations</a> flag.`);r(this,"onImageTrackingUpdate",e=>{const i=J.active;if(i)for(const n of e){const s=n.model,a=n.state==="tracked";if(!s.object)continue;let l=this.imageToObjectMap.get(s);if(l===void 0)l={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(s,l),s.object.loadAssetAsync().then(c=>{if(s.createObjectInstance&&c&&(c=C.instantiate(c)),c){l.object=c;for(const h of c.getComponentsInChildren(Ti))h.setInstancingEnabled(!1);i.rig?(i.rig.gameObject.add(c),n.applyToObject(c),c.activeSelf||C.setActive(c,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(l.frames++,a&&(l.lastTrackingTime=Date.now()),s.imageDoesNotMove&&l.frames>10||!l.object)continue;i.rig&&(i.rig.gameObject.add(l.object),n.applyToObject(l.object,this.smooth?this.context.time.deltaTimeUnscaled*3:void 0),l.object.activeSelf||C.setActive(l.object,!0))}}})}get supported(){return this._supported}awake(){if(Xb&&console.log(this),!!this.trackedImages){for(const e of this.trackedImages)if(e.image&&!qn._imageElements.has(e.image)){const i=e.image;qn._imageElements.set(i,null);const n=document.createElement("img");n.src=i,n.addEventListener("load",async()=>{const s=await createImageBitmap(n);qn._imageElements.set(i,s);const a=await Qw(s);if(a){const c=await(await a.convertToBlob({type:"image/png"})).arrayBuffer(),h=C.findObjectOfType(Kn);h&&this.trackedImages&&(h.extensions.push(new AE("marker.png",new Uint8Array(c),this.trackedImages[0].widthInMeters)),h.anchoringType="image")}})}}}onBeforeXR(e,i){var n;if(this.trackedImages){i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.includes("image-tracking")||i.optionalFeatures.push("image-tracking"),i.trackedImages=[];for(const s of this.trackedImages)if((n=s.image)!=null&&n.length&&s.widthInMeters>0){const a=qn._imageElements.get(s.image);a&&(this.trackedImageIndexMap.set(i.trackedImages.length,s),i.trackedImages.push({image:a,widthInMeters:s.widthInMeters}))}}}onEnterXR(e){var i;if(this.trackedImages){for(const n of this.trackedImages)if((i=n.object)!=null&&i.asset){const s=n.object.asset;s.userData||(s.userData={});const a={visible:s.visible,parent:s.parent,matrix:s.matrix.clone()};s.userData["image-tracking"]=a}}for(const n of this.imageToObjectMap.values())n.frames=0}onLeaveXR(e){var i,n;if(!this.supported&&exports.DeviceUtilities.isAndroidDevice()&&me(this.webXRIncubationsWarning),this.trackedImages){for(const s of this.trackedImages)if((i=s.object)!=null&&i.asset){const a=s.object.asset;if(a.userData){const l=a.userData["image-tracking"];l&&(a.visible=l.visible,(n=l.parent)==null||n.add(a),a.matrix.copy(l.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale)),delete a.userData["image-tracking"]}}}}onUpdateXR(e){var s;this.currentImages.length=0;const i=e.xr.frame;if(!i)return;if("getImageTrackingResults"in i){if(((s=e.xr.session.enabledFeatures)==null?void 0:s.includes("image-tracking"))===!1)return;if(i.session&&typeof i.getImageTrackingResults=="function"){const a=i.getImageTrackingResults();if(a.length>0){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of a){const h=c.trackingState,u=c.index,f=this.trackedImageIndexMap.get(u);if(f){const p=i.getPose(c.imageSpace,l),g=new qc(this,f,c.image,c.measuredSize,h,p);this.currentImages.push(g)}else Xb&&console.warn("No tracked image for index",u)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(c){console.error(c)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,me(this.webXRIncubationsWarning);return}const n=1e3;for(const[a,l]of this.imageToObjectMap){if(!l.object||!a||a.hideWhenTrackingIsLost===!1)continue;let c=!1;for(const h of this.currentImages)if(h.model===a){const u=Date.now()-l.lastTrackingTime;if(a.imageDoesNotMove||h.state==="tracked"||u<=n){c=!0;break}}c||C.setActive(l.object,!1)}}},r(qn,"_imageElements",new Map),qn);Ho([m(Hs)],Xy.prototype,"trackedImages");Ho([m()],Xy.prototype,"smooth");let Xc=Xy;var LE=Object.defineProperty,Cl=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&LE(t,e,n),n};const Zo=S("debugplanetracking");class qs extends I{constructor(){super(...arguments);r(this,"dataTemplate");r(this,"occluder",!0);r(this,"initiateRoomCaptureIfNoData",!0);r(this,"usePlaneData",!0);r(this,"useMeshData",!0);r(this,"runInVR",!0);r(this,"bounds",new d.Box3);r(this,"center",new d.Vector3);r(this,"labelOffset",new d.Vector3);r(this,"_dataId",1);r(this,"_allPlanes",new Map);r(this,"_allMeshes",new Map);r(this,"firstTimeNoPlanesDetected",-100);r(this,"makeOccluder",(e,i,n=!1)=>{if(i){if(i instanceof Array){for(const s of i)this.makeOccluder(e,s,n);return}!n&&!i.name.toLowerCase().includes("occlu")||(i.colorWrite=!1,i.depthTest=!0,i.depthWrite=!0,i.transparent=!1,i.polygonOffset=!0,i.polygonOffsetFactor=1,i.polygonOffsetUnits=.1,e.renderOrder=-1e3)}});r(this,"_flipForwardMatrix",new d.Matrix4().makeRotationY(Math.PI));r(this,"_verticesCache",new Map)}get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(e,i){e==="immersive-vr"&&!this.runInVR||(i.optionalFeatures=i.optionalFeatures||[],this.usePlaneData&&!i.optionalFeatures.includes("plane-detection")&&i.optionalFeatures.push("plane-detection"),this.useMeshData&&!i.optionalFeatures.includes("mesh-detection")&&i.optionalFeatures.push("mesh-detection"))}onEnterXR(e){for(const i of this._allPlanes.keys())this.removeData(i,this._allPlanes);for(const i of this._allMeshes.keys())this.removeData(i,this._allMeshes)}onLeaveXR(e){for(const i of this._allPlanes.keys())this.removeData(i,this._allPlanes);for(const i of this._allMeshes.keys())this.removeData(i,this._allMeshes)}onUpdateXR(e){if(!this.runInVR&&e.xr.isVR)return;const i=e.xr.rig;if(!i){console.warn("No XR rig found, cannot parent tracked planes to it");return}const n=e.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const l=n.detectedPlanes,c=n.detectedMeshes,h=l!==void 0&&l.size>0,u=c!==void 0&&c.size>0;if(this.initiateRoomCaptureIfNoData&&(!h&&!u&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(h||u)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in n.session&&(n.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),l!==void 0&&this.processFrameData(e.xr,i.gameObject,n,l,this._allPlanes),c!==void 0&&this.processFrameData(e.xr,i.gameObject,n,c,this._allMeshes),Zo){const f=this.context.mainCameraComponent.gameObject.worldPosition;for(const p of this._allPlanes.values())!p.mesh||!p.mesh.visible||(this.bounds.makeEmpty(),p.mesh.traverse(g=>{g instanceof d.Mesh&&this.bounds.expandByObject(g)}),this.bounds.getCenter(this.center),this.labelOffset.copy(f).sub(this.center).normalize().multiplyScalar(.1),$.DrawLabel(this.center.add(this.labelOffset),(p.xrData.semanticLabel||"plane").toUpperCase()+`
1453
- `+p.xrData.lastChangedTime.toFixed(2),.02))}}removeData(e,i){const n=i.get(e);if(!n)return;i.delete(e),Zo&&console.log("Plane no longer tracked, id="+n.id),n.mesh&&(n.mesh.removeFromParent(),n.mesh.traverse(a=>{const l=a.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):Zo&&console.warn("No normals helper found for mesh",n.mesh)}),Ri(n.mesh,!0,!0));const s=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:n}});this.dispatchEvent(s)}processFrameData(e,i,n,s,a){const c=this.context.renderer.xr.getReferenceSpace();if(c){for(const h of a.keys())s.has(h)||this.removeData(h,a);for(const h of s){const u="planeSpace"in h?h.planeSpace:"meshSpace"in h?h.meshSpace:void 0;if(!u)continue;const f=n.getPose(u,c);let p;if(a.has(h)){const g=a.get(h);if(p=g.mesh,g.timestamp<h.lastChangedTime){if(g.timestamp=h.lastChangedTime,g.mesh){const b=this.createGeometry(h);if(g.mesh instanceof d.Mesh)g.mesh.geometry.dispose(),g.mesh.geometry=b,this.makeOccluder(g.mesh,g.mesh.material);else if(g.mesh instanceof d.Group)for(const _ of g.mesh.children)_ instanceof d.Mesh&&(_.geometry.dispose(),_.geometry=b,this.makeOccluder(_,_.material));if(g.collider){const _=g.mesh;g.collider.sharedMesh=_,g.collider.convex=this.checkIfContextShouldBeConvex(_,g.xrData),g.collider.onDisable(),g.collider.onEnable()}Zo&&(console.log("Plane updated, id="+g.id,g),g.mesh.traverse(_=>{if(!(_ instanceof d.Mesh))return;const v=_.userData.normalsHelper;v&&v.update()}))}const y=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:g}});this.dispatchEvent(y)}}else{if(!this.dataTemplate){const g=new d.Mesh;Zo?g.material=new d.MeshNormalMaterial:this.occluder?(g.material=new d.MeshBasicMaterial,this.makeOccluder(g,g.material,!0)):g.material=new d.MeshBasicMaterial({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new te("","",g)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const g=C.instantiate(this.dataTemplate.asset);if(g.name="xr-tracked-plane",p=g,Zm(g,!1),g instanceof d.Mesh)Se(g.geometry),g.geometry=this.createGeometry(h),this.makeOccluder(g,g.material,this.occluder&&!this.dataTemplate);else if(g instanceof d.Group)for(const _ of g.children)_ instanceof d.Mesh&&(Se(_.geometry),_.geometry=this.createGeometry(h),this.makeOccluder(_,_.material,this.occluder&&!this.dataTemplate));const y=g.getComponent(Io);if(y){const _=g;y.sharedMesh=_,y.convex=this.checkIfContextShouldBeConvex(_,h),y.onDisable(),y.onEnable()}g.matrixAutoUpdate=!1,g.matrixWorldNeedsUpdate=!0,i.add(g);const b={id:this._dataId++,xrData:h,timestamp:h.lastChangedTime,mesh:g,collider:y};a.set(h,b),Zo&&console.log("New plane detected, id="+b.id,b,{hasCollider:!!y,isGroup:g instanceof d.Group});try{const _=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:b}});this.dispatchEvent(_)}catch(_){console.error(_)}}}p&&(f?(p.visible=!0,p.matrix.fromArray(f.transform.matrix),p.matrix.premultiply(this._flipForwardMatrix)):p.visible=!1,Zo&&p.traverse(g=>{if(g instanceof d.Mesh)if(g.userData.normalsHelper)g.userData.normalsHelper.update();else{const y=new H.VertexNormalsHelper(g,.05,255);y.layers.disableAll(),y.layers.set(2),this.context.scene.add(y),g.userData.normalsHelper=y}}))}}}checkIfContextShouldBeConvex(e,i){if(!e)return!0;if(e){const n=new d.Box3;n.expandByObject(e);const s=new d.Vector3;n.getSize(s);let a=!0;return s.x>2&&s.y>2&&s.z>1.5&&(a=!1),a&&"semanticLabel"in i&&i.semanticLabel==="wall"&&(a=!0),a}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new d.BufferGeometry}createMeshGeometry(e,i){const n=e.toString()+"_"+i.toString();if(this._verticesCache.has(n))return this._verticesCache.get(n);const s=new d.BufferGeometry;s.setIndex(new d.BufferAttribute(i,1)),s.setAttribute("position",new d.BufferAttribute(e,3));const a=Array();for(let l=0;l<e.length;l+=3)a.push(e[l],e[l+2]);return s.setAttribute("uv",new d.BufferAttribute(e,3)),s.computeVertexNormals(),this._verticesCache.set(n,s),s}createPlaneGeometry(e){const i=new d.BufferGeometry,n=[],s=[];e.forEach(g=>{n.push(g.x,g.y,g.z),s.push(g.x,g.z)});const a=new d.Vector3(n[0],n[1],n[2]),l=new d.Vector3(n[3],n[4],n[5]),c=new d.Vector3(n[6],n[7],n[8]),h=new d.Vector3,u=new d.Vector3;h.subVectors(l,a),u.subVectors(c,a),h.cross(u),h.normalize();const f=[];for(let g=0;g<n.length/3;g++)f.push(h.x,h.y,h.z);const p=[];for(let g=2;g<e.length;++g)p.push(0,g-1,g);return i.setAttribute("position",new d.BufferAttribute(new Float32Array(n),3)),i.setAttribute("uv",new d.BufferAttribute(new Float32Array(s),2)),i.setAttribute("normal",new d.BufferAttribute(new Float32Array(f),3)),i.setIndex(p),i.computeBoundingBox(),i.computeBoundingSphere(),i}}Cl([m(te)],qs.prototype,"dataTemplate");Cl([m()],qs.prototype,"occluder");Cl([m()],qs.prototype,"initiateRoomCaptureIfNoData");Cl([m()],qs.prototype,"usePlaneData");Cl([m()],qs.prototype,"useMeshData");Cl([m()],qs.prototype,"runInVR");var DE=Object.defineProperty,IE=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&DE(t,e,n),n};const Qb=S("debugwebxr");class Ff extends I{constructor(){super(...arguments);r(this,"priority",0);r(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var e;(e=J.active)==null||e.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(Qb){const e=new d.Object3D;e.position.y+=.5,this.gameObject.add(e);const i=e.addNewComponent(Xr);i&&(i.isGizmo=!1);const n=new d.AxesHelper(.5);this.gameObject.add(n)}}isXRRig(){return!0}supportsXR(e){return!0}onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),Qb&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}IE([m()],Ff.prototype,"priority");class jE extends I{constructor(){super(...arguments);r(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}k.add("AlignmentConstraint",fh);k.add("Animation",Tt);k.add("Animator",St);k.add("AudioListener",Ms);k.add("AudioSource",qi);k.add("Avatar_Brain_LookAt",Uc);k.add("Avatar_MouthShapes",yh);k.add("Avatar_MustacheShake",Dg);k.add("AvatarBlink_Simple",zr);k.add("AvatarEyeLook_Rotation",jg);k.add("AxesHelper",rl);k.add("BasicIKConstraint",Fg);k.add("BoxHelperComponent",ts);k.add("Camera",ai);k.add("CharacterController",Nr);k.add("CharacterControllerInput",js);k.add("Collider",ui);k.add("SphereCollider",al);k.add("BoxCollider",tf);k.add("MeshCollider",Io);k.add("CapsuleCollider",As);k.add("ContactShadows",_h);k.add("LogStats",zg);k.add("DeleteBox",Xa);k.add("Deletable",$g);k.add("DeviceFlag",nf);k.add("DragControls",lr);k.add("DropListener",Bs);k.add("Duplicatable",Gg);k.add("EventListEvent",Yu);k.add("EventTrigger",of);k.add("GltfExportBox",Zg);k.add("GltfExport",ey);k.add("VariantAction",ny);k.add("ChangeTransformOnClick",Gr);k.add("ChangeMaterialOnClick",sy);k.add("SetActiveOnClick",oy);k.add("HideOnStart",Ya);k.add("EmphasizeOnClick",hl);k.add("PlayAudioOnClick",Mo);k.add("PlayAnimationOnClick",$c);k.add("PreliminaryAction",dl);k.add("PreliminaryTrigger",Sh);k.add("VisibilityAction",Ch);k.add("TapGestureTrigger",ay);k.add("USDZExporter",Kn);k.add("Fog",ml);k.add("BoxGizmo",Xr);k.add("GridHelper",gl);k.add("GroundProjectedEnv",ss);k.add("UsageMarker",bh);k.add("Interactable",Ng);k.add("FixedJoint",Oy);k.add("HingeJoint",Rh);k.add("Light",mi);k.add("LODGroup",Th);k.add("LookAtConstraint",Ur);k.add("NeedleMenu",rs);k.add("NestedGltf",mf);k.add("Networking",Ry);k.add("OffsetConstraint",Qr);k.add("CameraTargetReachedEvent",Fc);k.add("OrbitControls",ge);k.add("ParticleSystemRenderer",en);k.add("ParticleSystem",Wc);k.add("PlayerColor",el);k.add("Antialiasing",Dh);k.add("BloomEffect",wf);k.add("ChromaticAberration",Ih);k.add("ColorAdjustments",$o);k.add("DepthOfField",Pn);k.add("EffectWrapper",Gc);k.add("PixelationEffect",jh);k.add("ScreenSpaceAmbientOcclusion",Vs);k.add("ScreenSpaceAmbientOcclusionN8",Mn);k.add("SharpeningEffect",Fh);k.add("TiltShiftEffect",cs);k.add("ToneMappingEffect",Ro);k.add("Vignette",ta);k.add("Volume",vl);k.add("ReflectionProbe",zc);k.add("Renderer",Ti);k.add("MeshRenderer",vh);k.add("SkinnedMeshRenderer",Kg);k.add("Rigidbody",ot);k.add("SceneSwitcher",Ge);k.add("ScreenCapture",Vo);k.add("ShadowCatcher",zh);k.add("RemoteSkybox",Sf);k.add("SmoothFollow",Pf);k.add("SpatialTriggerReceiver",Zn);k.add("SpatialTrigger",Mf);k.add("SpectatorCamera",Of);k.add("SpriteRenderer",fi);k.add("SyncedCamera",Fy);k.add("SyncedRoom",On);k.add("SyncedTransform",es);k.add("TestRunner",Uy);k.add("TestSimulateUserData",zy);k.add("PlayableDirector",il);k.add("SignalReceiver",Gh);k.add("AnimationTrackHandler",Ef);k.add("AudioTrackHandler",tl);k.add("SignalTrackHandler",Hc);k.add("ControlTrackHandler",Tf);k.add("TransformGizmo",ia);k.add("BaseUIComponent",Qi);k.add("UIRootComponent",Ph);k.add("Button",Ws);k.add("Canvas",Ja);k.add("CanvasGroup",ko);k.add("EventSystem",Yt);k.add("Graphic",Oh);k.add("MaskableGraphic",kh);k.add("Image",wl);k.add("RawImage",Df);k.add("InputField",Wy);k.add("VerticalLayoutGroup",yy);k.add("HorizontalLayoutGroup",_y);k.add("GridLayoutGroup",by);k.add("Outline",pl);k.add("ObjectRaycaster",Ei);k.add("GraphicRaycaster",Ku);k.add("SpatialGrabRaycaster",Tr);k.add("RectTransform",wn);k.add("SpatialHtml",Xh);k.add("Text",Dt);k.add("EnvironmentScene",jf);k.add("LookAt",Gy);k.add("OpenURL",xl);k.add("VideoPlayer",rt);k.add("Voip",Do);k.add("Avatar",Oo);k.add("XRControllerFollow",Gs);k.add("XRControllerModel",ns);k.add("XRControllerMovement",Ai);k.add("TeleportTarget",uf);k.add("WebARCameraBackground",Yh);k.add("WebARSessionRoot",is);k.add("WebXR",ff);k.add("AvatarMarker",At);k.add("WebXRImageTracking",Xc);k.add("WebXRPlaneTracking",qs);k.add("XRRig",Ff);k.add("XRFlag",$i);k.add("PlayerSync",dy);k.add("PlayerState",yn);k.add("PresentationMode",jE);const bc=dt,BE=S("debugtypestore");BE&&console.log(k);function FE(o,t){const i=wv(o,t);return i!==void 0?i:null}const UE=new f1,$p=Symbol("deserialize-queue");async function zE(o,t,e,i=null,n){if(!e){console.debug("Can not create component instances: gltf is null");return}let s=i;typeof s=="number"&&(s=new vt(i));const a=t.indexOf("?");t=a===-1?t:t.substring(0,a);const l=new vg(e.scene);l.gltfId=t,l.context=o,l.gltf=e,l.nodeToObject=n==null?void 0:n.nodeToObjectMap,l.implementationInformation=UE;let c=o[$p];if(c||(c=o[$p]=[]),e.scenes)for(const h of e.scenes)await Nm(l,h,c);if(e.children)for(const h of e.children)await Nm(l,h,c);o.new_scripts_pre_setup_callbacks.push(()=>{const h=o[$p];if(h){for(const u of h)NE(u,l);h.length=0}if(s){const u={},f=[];zm(e,s,u,f);for(const p of e.scenes)zm(p,s,u,f);for(const p of f)p.resolveGuids(u)}})}const Um=Symbol("original-component-name"),da=new Map;function zm(o,t,e,i){if(t===null||!o)return;const n=o.guid,s=o.guid;s!=null&&s.length&&(da.has(s)||(bc&&console.log('Creating InstanceIdProvider with key "'+s+'" for object '+o.name),da.set(s,new vt(s))));const a=s&&da.get(s)||t;if(o.guid=a.generateUUID(),n&&n!=="invalid"&&(e[n]=o.guid),o&&o.userData&&o.userData.components)for(const l of o.userData.components){if(l===null)continue;const c=l.guid;c?da.has(c)||(bc&&console.log('Creating InstanceIdProvider with key "'+c+'" for component '+l[Um]),da.set(c,new vt(c))):bc&&console.warn("Can not create IdProvider: component "+l[Um]+" has no guid",l.guid);const h=da.get(c)||t,u=l.guid;l.guid=h.generateUUID(),u&&u!=="invalid"&&(e[u]=l.guid),l.resolveGuids&&i.push(l)}if(o.children)for(const l of o.children)zm(l,t,e,i)}const zl=[];async function Nm(o,t,e,i){var s,a,l,c,h;if(!t)return;const n=t.userData;if(n){const u=n.builtin_components;if(u&&u.length>0)for(const f of u)try{if(f===null)continue;const p=k.get(f.name);if(p!=null){const g=new p;g.sourceId=o.gltfId,Ga(g,f,o.implementationInformation),g.context=o.context,"guid"in f&&(g[cc]=f.guid),g[Um]=f.name,vr(t,g,!1),e.push({instance:g,compData:f,obj:t}),g.isCamera&&o.context&&o.context.mainCamera===null&&g.tag==="MainCamera"&&o.context.setCurrentCamera(g),((l=(a=(s=o.context)==null?void 0:s.physics)==null?void 0:a.engine)==null?void 0:l.isInitialized)===!1&&(g.isCollider||g.isRigidbody)&&((h=(c=o.context)==null?void 0:c.physics.engine)==null||h.initialize())}else bc&&console.debug("unknown component: "+f.name),zl.includes(f.name)||zl.push(f.name)}catch(p){console.error(f.name+" - "+p.message,p)}if(zl.length>0){const f=zl.join(", ");console.warn("unknown components: "+f),zl.length=0,Kt()&&Ee(`<strong>Unknown components in scene</strong>:
1453
+ `+p.xrData.lastChangedTime.toFixed(2),.02))}}removeData(e,i){const n=i.get(e);if(!n)return;i.delete(e),Zo&&console.log("Plane no longer tracked, id="+n.id),n.mesh&&(n.mesh.removeFromParent(),n.mesh.traverse(a=>{const l=a.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):Zo&&console.warn("No normals helper found for mesh",n.mesh)}),Ri(n.mesh,!0,!0));const s=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:n}});this.dispatchEvent(s)}processFrameData(e,i,n,s,a){const c=this.context.renderer.xr.getReferenceSpace();if(c){for(const h of a.keys())s.has(h)||this.removeData(h,a);for(const h of s){const u="planeSpace"in h?h.planeSpace:"meshSpace"in h?h.meshSpace:void 0;if(!u)continue;const f=n.getPose(u,c);let p;if(a.has(h)){const g=a.get(h);if(p=g.mesh,g.timestamp<h.lastChangedTime){if(g.timestamp=h.lastChangedTime,g.mesh){const b=this.createGeometry(h);if(g.mesh instanceof d.Mesh)g.mesh.geometry.dispose(),g.mesh.geometry=b,this.makeOccluder(g.mesh,g.mesh.material);else if(g.mesh instanceof d.Group)for(const _ of g.mesh.children)_ instanceof d.Mesh&&(_.geometry.dispose(),_.geometry=b,this.makeOccluder(_,_.material));if(g.collider){const _=g.mesh;g.collider.sharedMesh=_,g.collider.convex=this.checkIfContextShouldBeConvex(_,g.xrData),g.collider.onDisable(),g.collider.onEnable()}Zo&&(console.log("Plane updated, id="+g.id,g),g.mesh.traverse(_=>{if(!(_ instanceof d.Mesh))return;const v=_.userData.normalsHelper;v&&v.update()}))}const y=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:g}});this.dispatchEvent(y)}}else{if(!this.dataTemplate){const g=new d.Mesh;Zo?g.material=new d.MeshNormalMaterial:this.occluder?(g.material=new d.MeshBasicMaterial,this.makeOccluder(g,g.material,!0)):g.material=new d.MeshBasicMaterial({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new te("","",g)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const g=C.instantiate(this.dataTemplate.asset);if(g.name="xr-tracked-plane",p=g,Zm(g,!1),g instanceof d.Mesh)Se(g.geometry),g.geometry=this.createGeometry(h),this.makeOccluder(g,g.material,this.occluder&&!this.dataTemplate);else if(g instanceof d.Group)for(const _ of g.children)_ instanceof d.Mesh&&(Se(_.geometry),_.geometry=this.createGeometry(h),this.makeOccluder(_,_.material,this.occluder&&!this.dataTemplate));const y=g.getComponent(Io);if(y){const _=g;y.sharedMesh=_,y.convex=this.checkIfContextShouldBeConvex(_,h),y.onDisable(),y.onEnable()}g.matrixAutoUpdate=!1,g.matrixWorldNeedsUpdate=!0,i.add(g);const b={id:this._dataId++,xrData:h,timestamp:h.lastChangedTime,mesh:g,collider:y};a.set(h,b),Zo&&console.log("New plane detected, id="+b.id,b,{hasCollider:!!y,isGroup:g instanceof d.Group});try{const _=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:b}});this.dispatchEvent(_)}catch(_){console.error(_)}}}p&&(f?(p.visible=!0,p.matrix.fromArray(f.transform.matrix),p.matrix.premultiply(this._flipForwardMatrix)):p.visible=!1,Zo&&p.traverse(g=>{if(g instanceof d.Mesh)if(g.userData.normalsHelper)g.userData.normalsHelper.update();else{const y=new H.VertexNormalsHelper(g,.05,255);y.layers.disableAll(),y.layers.set(2),this.context.scene.add(y),g.userData.normalsHelper=y}}))}}}checkIfContextShouldBeConvex(e,i){if(!e)return!0;if(e){const n=new d.Box3;n.expandByObject(e);const s=new d.Vector3;n.getSize(s);let a=!0;return s.x>2&&s.y>2&&s.z>1.5&&(a=!1),a&&"semanticLabel"in i&&i.semanticLabel==="wall"&&(a=!0),a}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new d.BufferGeometry}createMeshGeometry(e,i){const n=e.toString()+"_"+i.toString();if(this._verticesCache.has(n))return this._verticesCache.get(n);const s=new d.BufferGeometry;s.setIndex(new d.BufferAttribute(i,1)),s.setAttribute("position",new d.BufferAttribute(e,3));const a=Array();for(let l=0;l<e.length;l+=3)a.push(e[l],e[l+2]);return s.setAttribute("uv",new d.BufferAttribute(e,3)),s.computeVertexNormals(),this._verticesCache.set(n,s),s}createPlaneGeometry(e){const i=new d.BufferGeometry,n=[],s=[];e.forEach(g=>{n.push(g.x,g.y,g.z),s.push(g.x,g.z)});const a=new d.Vector3(n[0],n[1],n[2]),l=new d.Vector3(n[3],n[4],n[5]),c=new d.Vector3(n[6],n[7],n[8]),h=new d.Vector3,u=new d.Vector3;h.subVectors(l,a),u.subVectors(c,a),h.cross(u),h.normalize();const f=[];for(let g=0;g<n.length/3;g++)f.push(h.x,h.y,h.z);const p=[];for(let g=2;g<e.length;++g)p.push(0,g-1,g);return i.setAttribute("position",new d.BufferAttribute(new Float32Array(n),3)),i.setAttribute("uv",new d.BufferAttribute(new Float32Array(s),2)),i.setAttribute("normal",new d.BufferAttribute(new Float32Array(f),3)),i.setIndex(p),i.computeBoundingBox(),i.computeBoundingSphere(),i}}Cl([m(te)],qs.prototype,"dataTemplate");Cl([m()],qs.prototype,"occluder");Cl([m()],qs.prototype,"initiateRoomCaptureIfNoData");Cl([m()],qs.prototype,"usePlaneData");Cl([m()],qs.prototype,"useMeshData");Cl([m()],qs.prototype,"runInVR");var DE=Object.defineProperty,IE=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&DE(t,e,n),n};const Qb=S("debugwebxr");class Ff extends I{constructor(){super(...arguments);r(this,"priority",0);r(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var e;(e=J.active)==null||e.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(Qb){const e=new d.Object3D;e.position.y+=.5,this.gameObject.add(e);const i=e.addNewComponent(Xr);i&&(i.isGizmo=!1);const n=new d.AxesHelper(.5);this.gameObject.add(n)}}isXRRig(){return!0}supportsXR(e){return!0}onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),Qb&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}IE([m()],Ff.prototype,"priority");class jE extends I{constructor(){super(...arguments);r(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}k.add("AlignmentConstraint",fh);k.add("Animation",Tt);k.add("Animator",xt);k.add("AudioListener",Ms);k.add("AudioSource",qi);k.add("Avatar_Brain_LookAt",Uc);k.add("Avatar_MouthShapes",yh);k.add("Avatar_MustacheShake",Dg);k.add("AvatarBlink_Simple",zr);k.add("AvatarEyeLook_Rotation",jg);k.add("AxesHelper",rl);k.add("BasicIKConstraint",Fg);k.add("BoxHelperComponent",ts);k.add("Camera",ai);k.add("CharacterController",Nr);k.add("CharacterControllerInput",js);k.add("Collider",ui);k.add("SphereCollider",al);k.add("BoxCollider",tf);k.add("MeshCollider",Io);k.add("CapsuleCollider",As);k.add("ContactShadows",_h);k.add("LogStats",zg);k.add("DeleteBox",Xa);k.add("Deletable",$g);k.add("DeviceFlag",nf);k.add("DragControls",lr);k.add("DropListener",Bs);k.add("Duplicatable",Gg);k.add("EventListEvent",Yu);k.add("EventTrigger",of);k.add("GltfExportBox",Zg);k.add("GltfExport",ey);k.add("VariantAction",ny);k.add("ChangeTransformOnClick",Gr);k.add("ChangeMaterialOnClick",sy);k.add("SetActiveOnClick",oy);k.add("HideOnStart",Ya);k.add("EmphasizeOnClick",hl);k.add("PlayAudioOnClick",Mo);k.add("PlayAnimationOnClick",$c);k.add("PreliminaryAction",dl);k.add("PreliminaryTrigger",Sh);k.add("VisibilityAction",Ch);k.add("TapGestureTrigger",ay);k.add("USDZExporter",Kn);k.add("Fog",ml);k.add("BoxGizmo",Xr);k.add("GridHelper",gl);k.add("GroundProjectedEnv",ss);k.add("UsageMarker",bh);k.add("Interactable",Ng);k.add("FixedJoint",Oy);k.add("HingeJoint",Rh);k.add("Light",mi);k.add("LODGroup",Th);k.add("LookAtConstraint",Ur);k.add("NeedleMenu",rs);k.add("NestedGltf",mf);k.add("Networking",Ry);k.add("OffsetConstraint",Qr);k.add("CameraTargetReachedEvent",Fc);k.add("OrbitControls",ge);k.add("ParticleSystemRenderer",en);k.add("ParticleSystem",Wc);k.add("PlayerColor",el);k.add("Antialiasing",Dh);k.add("BloomEffect",wf);k.add("ChromaticAberration",Ih);k.add("ColorAdjustments",$o);k.add("DepthOfField",Pn);k.add("EffectWrapper",Gc);k.add("PixelationEffect",jh);k.add("ScreenSpaceAmbientOcclusion",Vs);k.add("ScreenSpaceAmbientOcclusionN8",Mn);k.add("SharpeningEffect",Fh);k.add("TiltShiftEffect",cs);k.add("ToneMappingEffect",Ro);k.add("Vignette",ta);k.add("Volume",vl);k.add("ReflectionProbe",zc);k.add("Renderer",Ti);k.add("MeshRenderer",vh);k.add("SkinnedMeshRenderer",Kg);k.add("Rigidbody",ot);k.add("SceneSwitcher",Ge);k.add("ScreenCapture",Vo);k.add("ShadowCatcher",zh);k.add("RemoteSkybox",Sf);k.add("SmoothFollow",Pf);k.add("SpatialTriggerReceiver",Zn);k.add("SpatialTrigger",Mf);k.add("SpectatorCamera",Of);k.add("SpriteRenderer",fi);k.add("SyncedCamera",Fy);k.add("SyncedRoom",On);k.add("SyncedTransform",es);k.add("TestRunner",Uy);k.add("TestSimulateUserData",zy);k.add("PlayableDirector",il);k.add("SignalReceiver",Gh);k.add("AnimationTrackHandler",Ef);k.add("AudioTrackHandler",tl);k.add("SignalTrackHandler",Hc);k.add("ControlTrackHandler",Tf);k.add("TransformGizmo",ia);k.add("BaseUIComponent",Qi);k.add("UIRootComponent",Ph);k.add("Button",Ws);k.add("Canvas",Ja);k.add("CanvasGroup",ko);k.add("EventSystem",Yt);k.add("Graphic",Oh);k.add("MaskableGraphic",kh);k.add("Image",wl);k.add("RawImage",Df);k.add("InputField",Wy);k.add("VerticalLayoutGroup",yy);k.add("HorizontalLayoutGroup",_y);k.add("GridLayoutGroup",by);k.add("Outline",pl);k.add("ObjectRaycaster",Ei);k.add("GraphicRaycaster",Ku);k.add("SpatialGrabRaycaster",Tr);k.add("RectTransform",wn);k.add("SpatialHtml",Xh);k.add("Text",Dt);k.add("EnvironmentScene",jf);k.add("LookAt",Gy);k.add("OpenURL",xl);k.add("VideoPlayer",rt);k.add("Voip",Do);k.add("Avatar",Oo);k.add("XRControllerFollow",Gs);k.add("XRControllerModel",ns);k.add("XRControllerMovement",Ai);k.add("TeleportTarget",uf);k.add("WebARCameraBackground",Yh);k.add("WebARSessionRoot",is);k.add("WebXR",ff);k.add("AvatarMarker",At);k.add("WebXRImageTracking",Xc);k.add("WebXRPlaneTracking",qs);k.add("XRRig",Ff);k.add("XRFlag",$i);k.add("PlayerSync",dy);k.add("PlayerState",yn);k.add("PresentationMode",jE);const bc=dt,BE=S("debugtypestore");BE&&console.log(k);function FE(o,t){const i=wv(o,t);return i!==void 0?i:null}const UE=new f1,$p=Symbol("deserialize-queue");async function zE(o,t,e,i=null,n){if(!e){console.debug("Can not create component instances: gltf is null");return}let s=i;typeof s=="number"&&(s=new bt(i));const a=t.indexOf("?");t=a===-1?t:t.substring(0,a);const l=new vg(e.scene);l.gltfId=t,l.context=o,l.gltf=e,l.nodeToObject=n==null?void 0:n.nodeToObjectMap,l.implementationInformation=UE;let c=o[$p];if(c||(c=o[$p]=[]),e.scenes)for(const h of e.scenes)await Nm(l,h,c);if(e.children)for(const h of e.children)await Nm(l,h,c);o.new_scripts_pre_setup_callbacks.push(()=>{const h=o[$p];if(h){for(const u of h)NE(u,l);h.length=0}if(s){const u={},f=[];zm(e,s,u,f);for(const p of e.scenes)zm(p,s,u,f);for(const p of f)p.resolveGuids(u)}})}const Um=Symbol("original-component-name"),da=new Map;function zm(o,t,e,i){if(t===null||!o)return;const n=o.guid,s=o.guid;s!=null&&s.length&&(da.has(s)||(bc&&console.log('Creating InstanceIdProvider with key "'+s+'" for object '+o.name),da.set(s,new bt(s))));const a=s&&da.get(s)||t;if(o.guid=a.generateUUID(),n&&n!=="invalid"&&(e[n]=o.guid),o&&o.userData&&o.userData.components)for(const l of o.userData.components){if(l===null)continue;const c=l.guid;c?da.has(c)||(bc&&console.log('Creating InstanceIdProvider with key "'+c+'" for component '+l[Um]),da.set(c,new bt(c))):bc&&console.warn("Can not create IdProvider: component "+l[Um]+" has no guid",l.guid);const h=da.get(c)||t,u=l.guid;l.guid=h.generateUUID(),u&&u!=="invalid"&&(e[u]=l.guid),l.resolveGuids&&i.push(l)}if(o.children)for(const l of o.children)zm(l,t,e,i)}const zl=[];async function Nm(o,t,e,i){var s,a,l,c,h;if(!t)return;const n=t.userData;if(n){const u=n.builtin_components;if(u&&u.length>0)for(const f of u)try{if(f===null)continue;const p=k.get(f.name);if(p!=null){const g=new p;g.sourceId=o.gltfId,Ga(g,f,o.implementationInformation),g.context=o.context,"guid"in f&&(g[cc]=f.guid),g[Um]=f.name,vr(t,g,!1),e.push({instance:g,compData:f,obj:t}),g.isCamera&&o.context&&o.context.mainCamera===null&&g.tag==="MainCamera"&&o.context.setCurrentCamera(g),((l=(a=(s=o.context)==null?void 0:s.physics)==null?void 0:a.engine)==null?void 0:l.isInitialized)===!1&&(g.isCollider||g.isRigidbody)&&((h=(c=o.context)==null?void 0:c.physics.engine)==null||h.initialize())}else bc&&console.debug("unknown component: "+f.name),zl.includes(f.name)||zl.push(f.name)}catch(p){console.error(f.name+" - "+p.message,p)}if(zl.length>0){const f=zl.join(", ");console.warn("unknown components: "+f),zl.length=0,Kt()&&Ee(`<strong>Unknown components in scene</strong>:
1454
1454
 
1455
1455
  ${f}
1456
1456
 
@@ -1604,4 +1604,4 @@ Error:`,l),null}}updateColliderCollisionGroups(t){const e=t[zt],i=t.membership;l
1604
1604
  justify-content: center;
1605
1605
  gap: .5rem;
1606
1606
  }
1607
- `),ce(this,mr).innerHTML=ce(this,Vt).innerHTML,ce(this,mr).style.cssText="display: flex; align-items: center; justify-content: center;",ce(this,Vt).innerHTML=ce(this,mr).outerHTML,ce(this,pr).innerHTML=ce(this,Vt).outerHTML,ce(this,pr).prepend(ce(this,gr)),ru(_m,{element:ce(this,pr)}),(n=ce(this,Ua))==null||n.disconnect(),ce(this,Ua)??rn(this,Ua,new MutationObserver(()=>Ol(this,nl,Nx).call(this))),ce(this,Ua).observe(ce(this,Vt),{attributes:!0}),Hp&&console.log("Needle Button updated")},Nx=function(){ce(this,Vt)&&(ce(this,Vt).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},Kc=new WeakMap,r(Zy,"observedAttributes",["ar","vr","quicklook"]);typeof window<"u"&&!window.customElements.get(i0)&&window.customElements.define(i0,Zy);const Hl=S("debugavatar");class Jy{constructor(t,e,i,n){r(this,"root");r(this,"head");r(this,"leftHand");r(this,"rigthHand");var s;this.root=t,this.head=e,this.leftHand=i,this.rigthHand=n,(s=this.root)==null||s.traverse(a=>a.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class $x{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(t,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof e=="string"){if(i=await this.loadAvatar(t,e),!i){const s=new xn;i=C.instantiate(za(e,t.scene),s)}}else i=e;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Hl&&console.log("[Custom Avatar] valid config",e,Hl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",e,Hl?n:""),null)}async loadAvatar(t,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(Hl&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+e);let s=null;if(n.ok){const l=await n.blob();l&&(s=await l.arrayBuffer())}if(!s)return null;const a=await bn().parseSync(t,s,null,0);return(a==null?void 0:a.scene)??null}const i=new H.GLTFLoader;return Og(i,t),new Promise((n,s)=>{const a=this.avatarRegistryUrl+"/"+e;i.load(a,async l=>{await bn().createBuiltinComponents(t,a,l,null,void 0),n(l.scene)},l=>{Hl&&console.log("[Custom Avatar] "+l.loaded/l.total*100+"% loaded of "+l.total/1024+"kB")},l=>{console.error("[Custom Avatar] Error when loading: "+l),n(null)})})}cacheModel(t,e){}findAvatar(t){const e=t;let i=e;i.children.length==1&&(i=t.children[0]);let n=this.findAvatarPart(i,["head"]);const s=this.findAvatarPart(i,["left","hand"]),a=this.findAvatarPart(i,["right","hand"]);if(!n){n=e;const c=new d.Vector3;new d.Box3().setFromObject(n).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new Jy(e,n,s,a)}findAvatarPart(t,e){const i=t.name.toLowerCase();let n=!0;for(const s of e){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return t;if(t.children)for(const s of t.children){const a=this.findAvatarPart(s,e);if(a)return a}return null}handleCustomAvatarErrors(t){if(!t.ok)throw Error(t.statusText);return t}}class Vx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(t){}}class Wx{}const hT=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:fe,ActionCollection:Zw,ActionModel:xi,AlignmentConstraint:fh,Animation:Tt,AnimationCurve:Ah,AnimationExtension:af,AnimationTrackHandler:Ef,Animator:St,AnimatorController:Gi,Antialiasing:Dh,AudioExtension:Wr,AudioListener:Ms,AudioSource:qi,AudioTrackHandler:tl,Avatar:Oo,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:jg,AvatarLoader:$x,AvatarMarker:At,AvatarModel:Jy,Avatar_Brain_LookAt:Uc,Avatar_MouthShapes:yh,Avatar_MustacheShake:Dg,Avatar_POI:Ts,AxesHelper:rl,BaseUIComponent:Qi,BasicIKConstraint:Fg,BehaviorExtension:fy,BehaviorModel:wt,BloomEffect:wf,BoxCollider:tf,BoxGizmo:Xr,BoxHelperComponent:ts,Button:Ws,CallInfo:Cs,Camera:ai,CameraTargetReachedEvent:Fc,Canvas:Ja,CanvasGroup:ko,CapsuleCollider:As,ChangeMaterialOnClick:sy,ChangeTransformOnClick:Gr,CharacterController:Nr,CharacterControllerInput:js,ChromaticAberration:Ih,Collider:ui,ColorAdjustments:$o,ColorBySpeedModule:_l,ColorOverLifetimeModule:_f,ContactShadows:_h,ControlTrackHandler:Tf,CustomBranding:qr,Deletable:$g,DeleteBox:Xa,DepthOfField:Pn,DeviceFlag:nf,DocumentExtension:Vx,DragControls:lr,DropListener:Bs,Duplicatable:Gg,EffectWrapper:Gc,EmissionModule:$s,EmphasizeOnClick:hl,EnvironmentScene:jf,EventList:ye,EventListEvent:Yu,EventSystem:Yt,EventTrigger:of,FieldWithDefault:Bw,FixedJoint:Oy,Fog:ml,GltfExport:ey,GltfExportBox:Zg,Gradient:Yr,Graphic:Oh,GraphicRaycaster:Ku,GridHelper:gl,GridLayoutGroup:by,GroundProjectedEnv:ss,GroupActionModel:yo,HideOnStart:Ya,HingeJoint:Rh,HorizontalLayoutGroup:_y,Image:wl,InheritVelocityModule:Ty,InputField:Wy,InstanceHandle:Nc,InstancingHandler:Qa,Interactable:Ng,Keyframe:li,LODGroup:Th,LODModel:yl,Light:mi,LimitVelocityOverLifetimeModule:lt,LogStats:zg,LookAt:Gy,LookAtConstraint:Ur,MainModule:It,MaskableGraphic:kh,MeshCollider:Io,MeshRenderer:vh,MinMaxCurve:q,MinMaxGradient:Kr,NeedleMenu:rs,NestedGltf:mf,Networking:Ry,NoiseModule:be,ObjectRaycaster:Ei,OffsetConstraint:Qr,OpenURL:xl,OrbitControls:ge,Outline:pl,Padding:Hr,ParticleBurst:wu,ParticleSubEmitter:Ay,ParticleSystem:Wc,ParticleSystemRenderer:en,PhysicsExtension:py,PixelationEffect:jh,PlayAnimationOnClick:$c,PlayAudioOnClick:Mo,PlayableDirector:il,PlayerColor:el,PointerEventData:mh,PostProcessingHandler:jy,PreliminaryAction:dl,PreliminaryTrigger:Sh,RawImage:Df,Rect:nx,RectTransform:wn,ReflectionProbe:zc,RegisteredAnimationInfo:_o,RemoteSkybox:Sf,Renderer:Ti,RendererLightmap:_u,Rigidbody:ot,RotationBySpeedModule:Ji,RotationOverLifetimeModule:Cn,SceneSwitcher:Ge,ScreenCapture:Vo,ScreenSpaceAmbientOcclusion:Vs,ScreenSpaceAmbientOcclusionN8:Mn,SetActiveOnClick:oy,ShadowCatcher:zh,ShapeModule:Ey,SharpeningEffect:Fh,SignalAsset:Rf,SignalReceiver:Gh,SignalReceiverEvent:Wh,SignalTrackHandler:Hc,Size:ix,SizeBySpeedModule:gi,SizeOverLifetimeModule:Zr,SkinnedMeshRenderer:Kg,SmoothFollow:Pf,SpatialGrabRaycaster:Tr,SpatialHtml:Xh,SpatialTrigger:Mf,SpatialTriggerReceiver:Zn,SpectatorCamera:Of,SphereCollider:al,Sprite:Us,SpriteData:Fa,SpriteRenderer:fi,SpriteSheet:Za,SubEmitterSystem:xu,SyncedCamera:Fy,SyncedRoom:On,SyncedTransform:es,TapGestureTrigger:ay,TeleportTarget:uf,TestRunner:Uy,TestSimulateUserData:zy,Text:Dt,TextBuilder:gy,TextExtension:pf,TextureSheetAnimationModule:jt,TiltShiftEffect:cs,ToneMappingEffect:Ro,TrailModule:je,TransformData:We,TransformGizmo:ia,TriggerBuilder:xt,TriggerModel:Co,UIRaycastUtils:Eg,UIRootComponent:Ph,USDZExporter:Kn,USDZText:cr,USDZUIExtension:wy,UsageMarker:bh,VariantAction:ny,VelocityOverLifetimeModule:ze,VerticalLayoutGroup:yy,VideoPlayer:rt,Vignette:ta,VisibilityAction:Ch,Voip:Do,Volume:vl,VolumeParameter:U,VolumeProfile:bf,WebARCameraBackground:Yh,WebARSessionRoot:is,WebXR:ff,WebXRImageTracking:Xc,WebXRImageTrackingModel:Hs,WebXRPlaneTracking:qs,WebXRTrackedImage:qc,XRControllerFollow:Gs,XRControllerModel:ns,XRControllerMovement:Ai,XRFlag:$i,XRRig:Ff,XRState:Qt,__Ignore:Wx},Symbol.toStringTag,{value:"Module"})),Ou=S("debugmissingcamera");re.registerCallback(he.MissingCamera,o=>{var l,c,h;Ou&&console.warn("Creating missing camera");const t=o.context.scene,e=new d.PerspectiveCamera;e.name="Default Fallback Camera",t.add(e);const i=new ai;if(i.sourceId=((c=(l=o.files)==null?void 0:l[0])==null?void 0:c.src)??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Cr.Uninitialized;else if((h=o.context.domElement.getAttribute("background-image"))!=null&&h.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Cr.Skybox,o.context.domElement.getAttribute("background-blurriness")===null&&(o.context.scene.backgroundBlurriness=.2);else{if(i.clearFlags=Cr.SolidColor,!o.context.domElement.getAttribute("background-color")){let u="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(u="#1f1f1f"),t.background=new d.Color(u)}if(!t.environment){const u=new d.PMREMGenerator$1(o.context.renderer),f=new jf("neutral");t.environment=u.fromScene(f,.025).texture}}const s=vr(e,i,!0);e.position.x=0,e.position.y=1,e.position.z=2;const a=o.context.domElement;return(a==null?void 0:a.cameraControls)!=!1&&Gx(o.context,s),s});re.registerCallback(he.ContextCreated,o=>{if(!o.context.mainCamera){Ou&&console.log("Will not auto-fit because a default camera exists");return}const t=o.context.domElement;if((t==null?void 0:t.cameraControls)==!0){const e=v0(o.context.mainCamera);if((e==null?void 0:e.isCameraController)==!0){Ou&&console.log("Will not auto-fit because a camera controller exists");return}Gx(o.context)}});function Gx(o,t){t=t??o.mainCameraComponent;const e=t==null?void 0:t.gameObject;if(Ou&&console.log("Creating default camera controls",t==null?void 0:t.name),e){const i=ah(e,ge);i.sourceId=(t==null?void 0:t.sourceId)??"unknown";const n=o.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&(n==null?void 0:n.toLowerCase())!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const s=parseFloat(n);isNaN(s)||(i.autoRotateSpeed=s)}}else console.warn("Missing camera object, can not add orbit controls")}re.registerCallback(he.ContextCreated,o=>{const t=o.context.domElement.getAttribute("autoplay");if(t!==void 0&&(t===""||t==="true"||t==="1")&&o.files)for(const e of o.files)C.foreachComponent(e.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Tt&&n.playAutomatically||n instanceof St||n instanceof il&&n.playOnAwake===!0)return!0;if(n instanceof Tt)return n.playAutomatically=!0,!0;if(n instanceof il)return n.playOnAwake=!0,!0}},!0)!==!0&&Ha.assignAnimationsFromFile(e.file,{createAnimationComponent:(n,s)=>Oi(n,Tt)})});class dT extends ae.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Nf&&Nf.tagName.toUpperCase()==="SCRIPT"&&Nf.src||new URL("needle-engine.bundle-RNpCdQTu.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(t,e,i={}){return new Promise((n,s)=>{if(e.getAttribute("position").isInterleavedBufferAttribute||e.index&&e.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");t.onerror=h=>{s(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},t.onmessage=h=>{const{data:u}=h;if(u.error)s(new Error(u.error)),t.onmessage=null;else if(u.serialized){const{serialized:f,position:p}=u,g=ae.MeshBVH.deserialize(f,e,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(e.attributes.position.array=p,f.index)if(e.index)e.index.array=f.index;else{const b=new d.BufferAttribute(f.index,1,!1);e.setIndex(b)}y.setBoundingBox&&(e.boundingBox=g.getBoundingBox(new d.Box3)),i.onProgress&&i.onProgress(u.progress),n(g),t.onmessage=null}else i.onProgress&&i.onProgress(u.progress)};const a=e.index?e.index.array:null,l=e.attributes.position.array,c=[l];a&&c.push(a),t.postMessage({index:a,position:l,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...e.groups]}},c.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const uT=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:dT},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=nM;exports.ActionBuilder=fe;exports.ActionCollection=Zw;exports.ActionModel=xi;exports.Addressables=Bv;exports.AlignmentConstraint=fh;exports.AmbientMode=Ia;exports.Animation=Tt;exports.AnimationCurve=Ah;exports.AnimationExtension=af;exports.AnimationTrackHandler=Ef;exports.AnimationUtils=Ha;exports.Animator=St;exports.AnimatorConditionMode=oo;exports.AnimatorController=Gi;exports.AnimatorControllerParameterType=kg;exports.AnimatorStateInfo=Jl;exports.Antialiasing=Dh;exports.Application=vn;exports.AssetDatabase=ev;exports.AssetReference=te;exports.AudioExtension=Wr;exports.AudioListener=Ms;exports.AudioSource=qi;exports.AudioTrackHandler=tl;exports.Avatar=Oo;exports.AvatarBlink_Simple=zr;exports.AvatarEyeLook_Rotation=jg;exports.AvatarLoader=$x;exports.AvatarMarker=At;exports.AvatarModel=Jy;exports.Avatar_Brain_LookAt=Uc;exports.Avatar_MouthShapes=yh;exports.Avatar_MustacheShake=Dg;exports.Avatar_POI=Ts;exports.Axes=xa;exports.AxesHelper=rl;exports.BUILD_TIME=tg;exports.BaseUIComponent=Qi;exports.BasicIKConstraint=Fg;exports.BehaviorExtension=fy;exports.BehaviorModel=wt;exports.BloomEffect=wf;exports.BoxCollider=tf;exports.BoxGizmo=Xr;exports.BoxHelperComponent=ts;exports.Button=Ws;exports.ButtonsFactory=zn;exports.CallDirection=_w;exports.CallInfo=Cs;exports.Camera=ai;exports.CameraTargetReachedEvent=Fc;exports.Canvas=Ja;exports.CanvasGroup=ko;exports.CapsuleCollider=As;exports.ChangeMaterialOnClick=sy;exports.ChangeTransformOnClick=Gr;exports.CharacterController=Nr;exports.CharacterControllerInput=js;exports.ChromaticAberration=Ih;exports.CircularBuffer=ki;exports.ClearFlags=Cr;exports.ClipExtrapolation=An;exports.Collider=ui;exports.Collision=mw;exports.CollisionDetectionMode=Qu;exports.ColorAdjustments=$o;exports.ColorBySpeedModule=_l;exports.ColorOverLifetimeModule=_f;exports.Component=uP;exports.Component$1=I;exports.ComponentLifecycleEvents=sh;exports.Components=hT;exports.ConnectionEvents=X0;exports.ContactPoint=pw;exports.ContactShadows=_h;exports.Context=X;exports.ContextArgs=K1;exports.ContextEvent=he;exports.ContextRegistry=re;exports.ControlTrackHandler=Tf;exports.CustomBranding=qr;exports.CustomShader=mu;exports.DefaultReflectionMode=ou;exports.Deletable=$g;exports.DeleteBox=Xa;exports.DepthOfField=Pn;exports.DeviceFlag=nf;exports.DocumentExtension=Vx;exports.DragControls=lr;exports.DragMode=Vg;exports.DropListener=Bs;exports.Duplicatable=Gg;exports.EffectWrapper=Gc;exports.EmissionModule=$s;exports.EmphasizeOnClick=hl;exports.EngineLoadingView=Pu;exports.EnvironmentScene=jf;exports.EventList=ye;exports.EventListEvent=Yu;exports.EventSystem=Yt;exports.EventTrigger=of;exports.FieldWithDefault=Bw;exports.FileReference=Ic;exports.FileReferenceSerializer=Uv;exports.FileSpawnModel=MM;exports.File_Event=Sw;exports.FixedJoint=Oy;exports.Fog=ml;exports.FrameEvent=we;exports.GENERATOR=Fu;exports.GameObject=C;exports.Gizmos=$;exports.GltfExport=ey;exports.GltfExportBox=Zg;exports.Gradient=Yr;exports.Graphic=Oh;exports.GraphicRaycaster=Ku;exports.Graphics=Mr;exports.GridHelper=gl;exports.GridLayoutGroup=by;exports.GroundProjectedEnv=ss;exports.GroupActionModel=yo;exports.HideFlags=Zu;exports.HideOnStart=Ya;exports.HingeJoint=Rh;exports.HorizontalLayoutGroup=_y;exports.HostData=t1;exports.Image=wl;exports.ImageReference=Dc;exports.ImageReferenceSerializer=Fv;exports.InheritVelocityModule=Ty;exports.Input=$0;exports.InputEventQueue=ri;exports.InputEvents=Re;exports.InputField=Wy;exports.InstanceHandle=Nc;exports.InstancingHandler=Qa;exports.InstancingUtil=Wi;exports.InstantiateEvent=dv;exports.InstantiateIdProvider=vt;exports.InstantiateOptions=xn;exports.Interactable=Ng;exports.JoinedRoomResponse=MC;exports.KeyEventArgs=mC;exports.Keyframe=li;exports.LODGroup=Th;exports.LODModel=yl;exports.LeftRoomResponse=OC;exports.Light=mi;exports.LightData=Wv;exports.LimitVelocityOverLifetimeModule=lt;exports.LoadingElementOptions=QE;exports.LogStats=zg;exports.LogType=Mi;exports.LookAt=Gy;exports.LookAtConstraint=Ur;exports.MainModule=It;exports.MarkerType=Ny;exports.MaskableGraphic=kh;exports.Mathf=z;exports.MeshCollider=Io;exports.MeshRenderer=vh;exports.MinMaxCurve=q;exports.MinMaxGradient=Kr;exports.NEKeyboardEvent=Xl;exports.NEPointerEvent=ys;exports.NeedleButtonElement=Zy;exports.NeedleEngineWebComponent=Ky;exports.NeedleMenu=rs;exports.NeedlePatchesKey=Rd;exports.NeedleXRController=og;exports.NeedleXRSession=J;exports.NeedleXRSync=K0;exports.NeedleXRUtils=J0;exports.NestedGltf=mf;exports.NetworkConnection=Y0;exports.NetworkedStreamEvents=Nn;exports.NetworkedStreams=gh;exports.Networking=Ry;exports.NewInstanceModel=fv;exports.NoiseModule=be;exports.ObjectRaycaster=Ei;exports.ObjectUtils=Lo;exports.OffsetConstraint=Qr;exports.OneEuroFilter=Od;exports.OneEuroFilterXYZ=qm;exports.OpenURL=xl;exports.OrbitControls=ge;exports.Outline=pl;exports.OwnershipEvent=Q0;exports.OwnershipModel=cg;exports.PUBLIC_KEY=ba;exports.Padding=Hr;exports.ParticleBurst=wu;exports.ParticleSubEmitter=Ay;exports.ParticleSystem=Wc;exports.ParticleSystemBaseBehaviour=No;exports.ParticleSystemRenderer=en;exports.ParticleSystemShapeType=vu;exports.PeerHandle=ja;exports.PeerNetworking=q0;exports.Physics=Ec;exports.PhysicsExtension=py;exports.PhysicsMaterialCombine=ht;exports.PixelationEffect=jh;exports.PlayAnimationOnClick=$c;exports.PlayAudioOnClick=Mo;exports.PlayableDirector=il;exports.PlayerColor=el;exports.PlayerState=yn;exports.PlayerStateEvent=tx;exports.PlayerSync=dy;exports.PlayerView=Nv;exports.PlayerViewManager=$v;exports.PointerEventData=mh;exports.PointerType=Nu;exports.PostProcessingEffect=Ye;exports.PostProcessingEffectOrder=it;exports.PostProcessingHandler=jy;exports.PreliminaryAction=dl;exports.PreliminaryTrigger=Sh;exports.PrimitiveType=Or;exports.Progress=oe;exports.PromiseAllWithErrors=Gm;exports.PromiseErrorResult=Qp;exports.RGBAColor=ie;exports.RapierPhysics=Mu;exports.RawImage=Df;exports.RaycastOptions=Ds;exports.Rect=nx;exports.RectTransform=wn;exports.ReflectionProbe=zc;exports.RegisteredAnimationInfo=_o;exports.RemoteSkybox=Sf;exports.RenderTexture=xr;exports.RenderTextureSerializer=hw;exports.Renderer=Ti;exports.RendererData=Vv;exports.RendererLightmap=_u;exports.Rigidbody=ot;exports.RigidbodyConstraints=Ne;exports.RoomEvents=ee;exports.RotationBySpeedModule=Ji;exports.RotationOverLifetimeModule=Cn;exports.SceneLightSettings=fu;exports.SceneSwitcher=Ge;exports.ScreenCapture=Vo;exports.ScreenSpaceAmbientOcclusion=Vs;exports.ScreenSpaceAmbientOcclusionN8=Mn;exports.SendQueue=fn;exports.SerializationContext=vg;exports.SetActiveOnClick=oy;exports.ShadowCatcher=zh;exports.ShapeModule=Ey;exports.SharpeningEffect=Fh;exports.SignalAsset=Rf;exports.SignalReceiver=Gh;exports.SignalReceiverEvent=Wh;exports.SignalTrackHandler=Hc;exports.Size=ix;exports.SizeBySpeedModule=gi;exports.SizeOverLifetimeModule=Zr;exports.SkinnedMeshRenderer=Kg;exports.SmoothFollow=Pf;exports.SpatialGrabRaycaster=Tr;exports.SpatialHtml=Xh;exports.SpatialTrigger=Mf;exports.SpatialTriggerReceiver=Zn;exports.SpectatorCamera=Of;exports.SphereCollider=al;exports.SphereIntersection=ug;exports.SphereOverlapResult=gw;exports.Sprite=Us;exports.SpriteData=Fa;exports.SpriteRenderer=fi;exports.SpriteSheet=Za;exports.StateMachineBehaviour=_P;exports.StreamEndedEvent=Ag;exports.StreamReceivedEvent=yw;exports.SubEmitterSystem=xu;exports.SyncedCamera=Fy;exports.SyncedRoom=On;exports.SyncedTransform=es;exports.TapGestureTrigger=ay;exports.TeleportTarget=uf;exports.TestRunner=Uy;exports.TestSceneUtils=sT;exports.TestSimulateUserData=zy;exports.Text=Dt;exports.TextBuilder=gy;exports.TextExtension=pf;exports.TextureSheetAnimationModule=jt;exports.TiltShiftEffect=cs;exports.Time=Gv;exports.ToneMappingEffect=Ro;exports.TrackHandler=Hh;exports.TrackType=bi;exports.TrailModule=je;exports.TransformData=We;exports.TransformGizmo=ia;exports.TriggerBuilder=xt;exports.TriggerModel=Co;exports.TypeStore=k;exports.UIRaycastUtils=Eg;exports.UIRootComponent=Ph;exports.USDDocument=ty;exports.USDObject=Et;exports.USDWriter=Vw;exports.USDZExporter=Kn;exports.USDZExporter$1=Ww;exports.USDZText=cr;exports.USDZUIExtension=wy;exports.UriSerializer=dw;exports.UsageMarker=bh;exports.UserJoinedOrLeftRoomModel=kC;exports.VERSION=_n;exports.VariantAction=ny;exports.VelocityOverLifetimeModule=ze;exports.VerticalLayoutGroup=yy;exports.VideoPlayer=rt;exports.ViewDevice=wo;exports.Vignette=ta;exports.VisibilityAction=Ch;exports.Voip=Do;exports.Volume=vl;exports.VolumeParameter=U;exports.VolumeProfile=bf;exports.WaitForFrames=E1;exports.WaitForPromise=zv;exports.WaitForSeconds=Sg;exports.Watch=Rs;exports.WebARCameraBackground=Yh;exports.WebARSessionRoot=is;exports.WebXR=ff;exports.WebXRButtonFactory=Po;exports.WebXRImageTracking=Xc;exports.WebXRImageTrackingModel=Hs;exports.WebXRPlaneTracking=qs;exports.WebXRTrackedImage=qc;exports.XRControllerFollow=Gs;exports.XRControllerModel=ns;exports.XRControllerMovement=Ai;exports.XRFlag=$i;exports.XRRig=Ff;exports.XRState=Qt;exports.XRStateFlag=Bn;exports.__Ignore=Wx;exports.__internalNotifyObjectDestroyed=ov;exports.activeInHierarchyFieldName=Es;exports.addAttributeChangeCallback=d0;exports.addComponent=Oi;exports.addCustomExtensionPlugin=XM;exports.addNewComponent=vr;exports.addPatch=Uu;exports.apply=Wu;exports.applyHMRChanges=dP;exports.applyPrototypeExtensions=Pv;exports.beginListenDestroy=uv;exports.beginListenInstantiate=mv;exports.binaryIdentifierCasts=rg;exports.build_scene_functions=Y1;exports.builtinComponentKeyName=er;exports.calculateProgress01=Yy;exports.clearMessages=RS;exports.colorSerializer=IP;exports.compareAssociation=bv;exports.componentSerializer=Bd;exports.copyTexture=O0;exports.createMotion=rw;exports.debugNet=ei;exports.debugOwner=Ql;exports.decompressGpuTexture=Xw;exports.deepClone=Jc;exports.delay=Jn;exports.delayForFrames=eh;exports.deserializeObject=nu;exports.destroy=Ri;exports.destroyComponentInstance=kv;exports.determineMimeTypeFromExtension=Cw;exports.disposeObjectResources=Se;exports.disposeStream=$n;exports.editorGuidKeyName=cc;exports.enableSpatialConsole=_r;exports.euler=BP;exports.eventListSerializer=NP;exports.exportAsGLTF=aT;exports.findByGuid=xg;exports.findObjectOfType=hh;exports.findObjectsOfType=Ev;exports.findResourceUsers=pg;exports.fitObjectIntoVolume=R0;exports.foreachComponent=Rr;exports.foreachComponentEnumerator=Hu;exports.forward=WS;exports.generateQRCode=f0;exports.generateSeed=pv;exports.getBoundingBox=ci;exports.getCameraController=v0;exports.getComponent=jr;exports.getComponentInChildren=ch;exports.getComponentInParent=Lc;exports.getComponents=lh;exports.getComponentsInChildren=sl;exports.getComponentsInParent=Vu;exports.getFormattedDate=Uw;exports.getIconElement=bt;exports.getIconTexture=ym;exports.getLoader=bn;exports.getOrAddComponent=ah;exports.getParam=S;exports.getParentHierarchyPath=qS;exports.getPath=lS;exports.getPeerOptions=xC;exports.getPeerjsInstance=H0;exports.getResourceUserCount=HC;exports.getTempColor=S0;exports.getTempQuaternion=un;exports.getTempVector=V;exports.getUrlParams=Zc;exports.getVisibleInCustomShadowRendering=k0;exports.getWorldDirection=C0;exports.getWorldEuler=Ym;exports.getWorldPosition=Q;exports.getWorldQuaternion=_e;exports.getWorldRotation=Bu;exports.getWorldScale=Ue;exports.hasCommercialLicense=Yn;exports.hasIndieLicense=uh;exports.hasPointerEventComponent=cu;exports.hasProLicense=Qn;exports.hideDebugConsole=L0;exports.imageToCanvas=Qw;exports.instantiate=Er;exports.invokeLoadedImportPluginHooks=Lw;exports.invokeXRSessionEnd=N0;exports.invokeXRSessionStart=z0;exports.isActiveInHierarchy=Tv;exports.isActiveSelf=ol;exports.isAndroidDevice=pS;exports.isAnimationAction=M0;exports.isComponent=fw;exports.isDebugMode=sS;exports.isDesktop=hS;exports.isDestroyed=kr;exports.isDevEnvironment=j;exports.isDisposed=WC;exports.isExporting=oT;exports.isGLTFModel=uw;exports.isHostedOnGlitch=s0;exports.isHotReloadEnabled=wm;exports.isHotReloading=cP;exports.isIPad=uS;exports.isIconElement=Xv;exports.isLocalNetwork=Kt;exports.isMacOS=gS;exports.isMobileDevice=dS;exports.isMozillaXR=mS;exports.isQuest=bS;exports.isResourceTrackingEnabled=iv;exports.isSafari=_S;exports.isUsingInstancing=Gu;exports.isiOS=yS;exports.isiPad=fS;exports.loadAsset=VE;exports.loadSync=Qy;exports.logHierarchy=Xd;exports.lookAtInverse=jS;exports.lookAtObject=th;exports.lookAtScreenPoint=BS;exports.makeId=rS;exports.makeIdFromRandomWords=l0;exports.makeNameSafe=Xi;exports.markAsInstancedRendered=Av;exports.microphonePermissionsGranted=vS;exports.nameof=nS;exports.nameofFactory=r0;exports.objectSerializer=cw;exports.offXRSessionEnd=pC;exports.offXRSessionStart=fC;exports.onAfterRender=aP;exports.onBeforeRender=rP;exports.onClear=sP;exports.onDestroy=oP;exports.onInitialized=Jv;exports.onStart=Mg;exports.onUpdate=ew;exports.onXRSessionEnd=sg;exports.onXRSessionStart=zu;exports.parseSync=Ix;exports.placeOnSurface=E0;exports.postprocessFBXMaterials=Jm;exports.prefix=RP;exports.pushState=a0;exports.randomNumber=aS;exports.registerBinaryType=ag;exports.registerComponent=qu;exports.registerComponentExtension=Xg;exports.registerCustomEffectType=tn;exports.registerExportExtensions=Qg;exports.registerExtensions=yu;exports.registerHotReloadType=iw;exports.registerLoader=ig;exports.registerPrefabProvider=yv;exports.registerPrototypeExtensions=Mv;exports.registerType=r1;exports.relativePathPrefix=h0;exports.removeAttributeChangeCallback=u0;exports.removeComponent=wg;exports.removeCustomImportExtensionType=QM;exports.removePatch=dC;exports.resolveUrl=Eo;exports.sanitizeString=c0;exports.saveImage=Tx;exports.screenshot=ME;exports.screenshot2=qy;exports.sendDestroyed=gg;exports.serializable=m;exports.serializeObject=wv;exports.serializeable=Br;exports.setActive=uc;exports.setAllowBalloonMessages=y0;exports.setAllowOverlayMessages=PS;exports.setAutoFitEnabled=Hd;exports.setCameraController=Zp;exports.setDestroyed=Dv;exports.setDevEnvironment=tC;exports.setDisposable=fg;exports.setDontDestroy=pa;exports.setOrAddParamsToUrl=Xp;exports.setParam=oS;exports.setParamWithoutReload=Oc;exports.setPeerOptions=SC;exports.setResourceTrackingEnabled=VC;exports.setState=Vm;exports.setVisibleInCustomShadowRendering=Zm;exports.setWorldEuler=Km;exports.setWorldPosition=st;exports.setWorldPositionXYZ=Pr;exports.setWorldQuaternion=Hi;exports.setWorldQuaternionXYZW=Qm;exports.setWorldRotation=P0;exports.setWorldRotationXYZ=ih;exports.setWorldScale=Na;exports.showBalloonError=nh;exports.showBalloonMessage=Ee;exports.showBalloonWarning=me;exports.showDebugConsole=eg;exports.slerp=IS;exports.syncDestroy=oh;exports.syncField=hy;exports.syncInstantiate=yg;exports.textureToCanvas=XS;exports.tryCastBinary=W0;exports.tryDetermineMimetypeFromBinary=Mw;exports.tryDetermineMimetypeFromURL=Pw;exports.tryFindObject=za;exports.tryGetGuid=G0;exports.unregisterHotReloadType=nw;exports.unwatchWrite=Wm;exports.useForAutoFit=w0;exports.validate=Ct;exports.watchWrite=ju;
1607
+ `),ce(this,mr).innerHTML=ce(this,Vt).innerHTML,ce(this,mr).style.cssText="display: flex; align-items: center; justify-content: center;",ce(this,Vt).innerHTML=ce(this,mr).outerHTML,ce(this,pr).innerHTML=ce(this,Vt).outerHTML,ce(this,pr).prepend(ce(this,gr)),ru(_m,{element:ce(this,pr)}),(n=ce(this,Ua))==null||n.disconnect(),ce(this,Ua)??rn(this,Ua,new MutationObserver(()=>Ol(this,nl,Nx).call(this))),ce(this,Ua).observe(ce(this,Vt),{attributes:!0}),Hp&&console.log("Needle Button updated")},Nx=function(){ce(this,Vt)&&(ce(this,Vt).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},Kc=new WeakMap,r(Zy,"observedAttributes",["ar","vr","quicklook"]);typeof window<"u"&&!window.customElements.get(i0)&&window.customElements.define(i0,Zy);const Hl=S("debugavatar");class Jy{constructor(t,e,i,n){r(this,"root");r(this,"head");r(this,"leftHand");r(this,"rigthHand");var s;this.root=t,this.head=e,this.leftHand=i,this.rigthHand=n,(s=this.root)==null||s.traverse(a=>a.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class $x{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(t,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof e=="string"){if(i=await this.loadAvatar(t,e),!i){const s=new xn;i=C.instantiate(za(e,t.scene),s)}}else i=e;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Hl&&console.log("[Custom Avatar] valid config",e,Hl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",e,Hl?n:""),null)}async loadAvatar(t,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(Hl&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+e);let s=null;if(n.ok){const l=await n.blob();l&&(s=await l.arrayBuffer())}if(!s)return null;const a=await bn().parseSync(t,s,null,0);return(a==null?void 0:a.scene)??null}const i=new H.GLTFLoader;return Og(i,t),new Promise((n,s)=>{const a=this.avatarRegistryUrl+"/"+e;i.load(a,async l=>{await bn().createBuiltinComponents(t,a,l,null,void 0),n(l.scene)},l=>{Hl&&console.log("[Custom Avatar] "+l.loaded/l.total*100+"% loaded of "+l.total/1024+"kB")},l=>{console.error("[Custom Avatar] Error when loading: "+l),n(null)})})}cacheModel(t,e){}findAvatar(t){const e=t;let i=e;i.children.length==1&&(i=t.children[0]);let n=this.findAvatarPart(i,["head"]);const s=this.findAvatarPart(i,["left","hand"]),a=this.findAvatarPart(i,["right","hand"]);if(!n){n=e;const c=new d.Vector3;new d.Box3().setFromObject(n).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new Jy(e,n,s,a)}findAvatarPart(t,e){const i=t.name.toLowerCase();let n=!0;for(const s of e){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return t;if(t.children)for(const s of t.children){const a=this.findAvatarPart(s,e);if(a)return a}return null}handleCustomAvatarErrors(t){if(!t.ok)throw Error(t.statusText);return t}}class Vx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(t){}}class Wx{}const hT=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:fe,ActionCollection:Zw,ActionModel:xi,AlignmentConstraint:fh,Animation:Tt,AnimationCurve:Ah,AnimationExtension:af,AnimationTrackHandler:Ef,Animator:xt,AnimatorController:Gi,Antialiasing:Dh,AudioExtension:Wr,AudioListener:Ms,AudioSource:qi,AudioTrackHandler:tl,Avatar:Oo,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:jg,AvatarLoader:$x,AvatarMarker:At,AvatarModel:Jy,Avatar_Brain_LookAt:Uc,Avatar_MouthShapes:yh,Avatar_MustacheShake:Dg,Avatar_POI:Ts,AxesHelper:rl,BaseUIComponent:Qi,BasicIKConstraint:Fg,BehaviorExtension:fy,BehaviorModel:vt,BloomEffect:wf,BoxCollider:tf,BoxGizmo:Xr,BoxHelperComponent:ts,Button:Ws,CallInfo:Cs,Camera:ai,CameraTargetReachedEvent:Fc,Canvas:Ja,CanvasGroup:ko,CapsuleCollider:As,ChangeMaterialOnClick:sy,ChangeTransformOnClick:Gr,CharacterController:Nr,CharacterControllerInput:js,ChromaticAberration:Ih,Collider:ui,ColorAdjustments:$o,ColorBySpeedModule:_l,ColorOverLifetimeModule:_f,ContactShadows:_h,ControlTrackHandler:Tf,CustomBranding:qr,Deletable:$g,DeleteBox:Xa,DepthOfField:Pn,DeviceFlag:nf,DocumentExtension:Vx,DragControls:lr,DropListener:Bs,Duplicatable:Gg,EffectWrapper:Gc,EmissionModule:$s,EmphasizeOnClick:hl,EnvironmentScene:jf,EventList:ye,EventListEvent:Yu,EventSystem:Yt,EventTrigger:of,FieldWithDefault:Bw,FixedJoint:Oy,Fog:ml,GltfExport:ey,GltfExportBox:Zg,Gradient:Yr,Graphic:Oh,GraphicRaycaster:Ku,GridHelper:gl,GridLayoutGroup:by,GroundProjectedEnv:ss,GroupActionModel:yo,HideOnStart:Ya,HingeJoint:Rh,HorizontalLayoutGroup:_y,Image:wl,InheritVelocityModule:Ty,InputField:Wy,InstanceHandle:Nc,InstancingHandler:Qa,Interactable:Ng,Keyframe:li,LODGroup:Th,LODModel:yl,Light:mi,LimitVelocityOverLifetimeModule:lt,LogStats:zg,LookAt:Gy,LookAtConstraint:Ur,MainModule:It,MaskableGraphic:kh,MeshCollider:Io,MeshRenderer:vh,MinMaxCurve:q,MinMaxGradient:Kr,NeedleMenu:rs,NestedGltf:mf,Networking:Ry,NoiseModule:be,ObjectRaycaster:Ei,OffsetConstraint:Qr,OpenURL:xl,OrbitControls:ge,Outline:pl,Padding:Hr,ParticleBurst:wu,ParticleSubEmitter:Ay,ParticleSystem:Wc,ParticleSystemRenderer:en,PhysicsExtension:py,PixelationEffect:jh,PlayAnimationOnClick:$c,PlayAudioOnClick:Mo,PlayableDirector:il,PlayerColor:el,PointerEventData:mh,PostProcessingHandler:jy,PreliminaryAction:dl,PreliminaryTrigger:Sh,RawImage:Df,Rect:nx,RectTransform:wn,ReflectionProbe:zc,RegisteredAnimationInfo:_o,RemoteSkybox:Sf,Renderer:Ti,RendererLightmap:_u,Rigidbody:ot,RotationBySpeedModule:Ji,RotationOverLifetimeModule:Cn,SceneSwitcher:Ge,ScreenCapture:Vo,ScreenSpaceAmbientOcclusion:Vs,ScreenSpaceAmbientOcclusionN8:Mn,SetActiveOnClick:oy,ShadowCatcher:zh,ShapeModule:Ey,SharpeningEffect:Fh,SignalAsset:Rf,SignalReceiver:Gh,SignalReceiverEvent:Wh,SignalTrackHandler:Hc,Size:ix,SizeBySpeedModule:gi,SizeOverLifetimeModule:Zr,SkinnedMeshRenderer:Kg,SmoothFollow:Pf,SpatialGrabRaycaster:Tr,SpatialHtml:Xh,SpatialTrigger:Mf,SpatialTriggerReceiver:Zn,SpectatorCamera:Of,SphereCollider:al,Sprite:Us,SpriteData:Fa,SpriteRenderer:fi,SpriteSheet:Za,SubEmitterSystem:xu,SyncedCamera:Fy,SyncedRoom:On,SyncedTransform:es,TapGestureTrigger:ay,TeleportTarget:uf,TestRunner:Uy,TestSimulateUserData:zy,Text:Dt,TextBuilder:gy,TextExtension:pf,TextureSheetAnimationModule:jt,TiltShiftEffect:cs,ToneMappingEffect:Ro,TrailModule:je,TransformData:We,TransformGizmo:ia,TriggerBuilder:wt,TriggerModel:Co,UIRaycastUtils:Eg,UIRootComponent:Ph,USDZExporter:Kn,USDZText:cr,USDZUIExtension:wy,UsageMarker:bh,VariantAction:ny,VelocityOverLifetimeModule:ze,VerticalLayoutGroup:yy,VideoPlayer:rt,Vignette:ta,VisibilityAction:Ch,Voip:Do,Volume:vl,VolumeParameter:U,VolumeProfile:bf,WebARCameraBackground:Yh,WebARSessionRoot:is,WebXR:ff,WebXRImageTracking:Xc,WebXRImageTrackingModel:Hs,WebXRPlaneTracking:qs,WebXRTrackedImage:qc,XRControllerFollow:Gs,XRControllerModel:ns,XRControllerMovement:Ai,XRFlag:$i,XRRig:Ff,XRState:Qt,__Ignore:Wx},Symbol.toStringTag,{value:"Module"})),Ou=S("debugmissingcamera");re.registerCallback(he.MissingCamera,o=>{var l,c,h;Ou&&console.warn("Creating missing camera");const t=o.context.scene,e=new d.PerspectiveCamera;e.name="Default Fallback Camera",t.add(e);const i=new ai;if(i.sourceId=((c=(l=o.files)==null?void 0:l[0])==null?void 0:c.src)??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Cr.Uninitialized;else if((h=o.context.domElement.getAttribute("background-image"))!=null&&h.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Cr.Skybox,o.context.domElement.getAttribute("background-blurriness")===null&&(o.context.scene.backgroundBlurriness=.2);else{if(i.clearFlags=Cr.SolidColor,!o.context.domElement.getAttribute("background-color")){let u="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(u="#1f1f1f"),t.background=new d.Color(u)}if(!t.environment){const u=new d.PMREMGenerator$1(o.context.renderer),f=new jf("neutral");t.environment=u.fromScene(f,.025).texture}}const s=vr(e,i,!0);e.position.x=0,e.position.y=1,e.position.z=2;const a=o.context.domElement;return(a==null?void 0:a.cameraControls)!=!1&&Gx(o.context,s),s});re.registerCallback(he.ContextCreated,o=>{if(!o.context.mainCamera){Ou&&console.log("Will not auto-fit because a default camera exists");return}const t=o.context.domElement;if((t==null?void 0:t.cameraControls)==!0){const e=v0(o.context.mainCamera);if((e==null?void 0:e.isCameraController)==!0){Ou&&console.log("Will not auto-fit because a camera controller exists");return}Gx(o.context)}});function Gx(o,t){t=t??o.mainCameraComponent;const e=t==null?void 0:t.gameObject;if(Ou&&console.log("Creating default camera controls",t==null?void 0:t.name),e){const i=ah(e,ge);i.sourceId=(t==null?void 0:t.sourceId)??"unknown";const n=o.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&(n==null?void 0:n.toLowerCase())!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const s=parseFloat(n);isNaN(s)||(i.autoRotateSpeed=s)}}else console.warn("Missing camera object, can not add orbit controls")}re.registerCallback(he.ContextCreated,o=>{const t=o.context.domElement.getAttribute("autoplay");if(t!==void 0&&(t===""||t==="true"||t==="1")&&o.files)for(const e of o.files)C.foreachComponent(e.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Tt&&n.playAutomatically||n instanceof xt||n instanceof il&&n.playOnAwake===!0)return!0;if(n instanceof Tt)return n.playAutomatically=!0,!0;if(n instanceof il)return n.playOnAwake=!0,!0}},!0)!==!0&&Ha.assignAnimationsFromFile(e.file,{createAnimationComponent:(n,s)=>Oi(n,Tt)})});class dT extends ae.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Nf&&Nf.tagName.toUpperCase()==="SCRIPT"&&Nf.src||new URL("needle-engine.bundle-Dm9L7JpU.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(t,e,i={}){return new Promise((n,s)=>{if(e.getAttribute("position").isInterleavedBufferAttribute||e.index&&e.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");t.onerror=h=>{s(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},t.onmessage=h=>{const{data:u}=h;if(u.error)s(new Error(u.error)),t.onmessage=null;else if(u.serialized){const{serialized:f,position:p}=u,g=ae.MeshBVH.deserialize(f,e,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(e.attributes.position.array=p,f.index)if(e.index)e.index.array=f.index;else{const b=new d.BufferAttribute(f.index,1,!1);e.setIndex(b)}y.setBoundingBox&&(e.boundingBox=g.getBoundingBox(new d.Box3)),i.onProgress&&i.onProgress(u.progress),n(g),t.onmessage=null}else i.onProgress&&i.onProgress(u.progress)};const a=e.index?e.index.array:null,l=e.attributes.position.array,c=[l];a&&c.push(a),t.postMessage({index:a,position:l,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...e.groups]}},c.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const uT=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:dT},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=nM;exports.ActionBuilder=fe;exports.ActionCollection=Zw;exports.ActionModel=xi;exports.Addressables=Bv;exports.AlignmentConstraint=fh;exports.AmbientMode=Ia;exports.Animation=Tt;exports.AnimationCurve=Ah;exports.AnimationExtension=af;exports.AnimationTrackHandler=Ef;exports.AnimationUtils=Ha;exports.Animator=xt;exports.AnimatorConditionMode=oo;exports.AnimatorController=Gi;exports.AnimatorControllerParameterType=kg;exports.AnimatorStateInfo=Jl;exports.Antialiasing=Dh;exports.Application=vn;exports.AssetDatabase=ev;exports.AssetReference=te;exports.AudioExtension=Wr;exports.AudioListener=Ms;exports.AudioSource=qi;exports.AudioTrackHandler=tl;exports.Avatar=Oo;exports.AvatarBlink_Simple=zr;exports.AvatarEyeLook_Rotation=jg;exports.AvatarLoader=$x;exports.AvatarMarker=At;exports.AvatarModel=Jy;exports.Avatar_Brain_LookAt=Uc;exports.Avatar_MouthShapes=yh;exports.Avatar_MustacheShake=Dg;exports.Avatar_POI=Ts;exports.Axes=xa;exports.AxesHelper=rl;exports.BUILD_TIME=tg;exports.BaseUIComponent=Qi;exports.BasicIKConstraint=Fg;exports.BehaviorExtension=fy;exports.BehaviorModel=vt;exports.BloomEffect=wf;exports.BoxCollider=tf;exports.BoxGizmo=Xr;exports.BoxHelperComponent=ts;exports.Button=Ws;exports.ButtonsFactory=zn;exports.CallDirection=_w;exports.CallInfo=Cs;exports.Camera=ai;exports.CameraTargetReachedEvent=Fc;exports.Canvas=Ja;exports.CanvasGroup=ko;exports.CapsuleCollider=As;exports.ChangeMaterialOnClick=sy;exports.ChangeTransformOnClick=Gr;exports.CharacterController=Nr;exports.CharacterControllerInput=js;exports.ChromaticAberration=Ih;exports.CircularBuffer=ki;exports.ClearFlags=Cr;exports.ClipExtrapolation=An;exports.Collider=ui;exports.Collision=mw;exports.CollisionDetectionMode=Qu;exports.ColorAdjustments=$o;exports.ColorBySpeedModule=_l;exports.ColorOverLifetimeModule=_f;exports.Component=uP;exports.Component$1=I;exports.ComponentLifecycleEvents=sh;exports.Components=hT;exports.ConnectionEvents=X0;exports.ContactPoint=pw;exports.ContactShadows=_h;exports.Context=X;exports.ContextArgs=K1;exports.ContextEvent=he;exports.ContextRegistry=re;exports.ControlTrackHandler=Tf;exports.CustomBranding=qr;exports.CustomShader=mu;exports.DefaultReflectionMode=ou;exports.Deletable=$g;exports.DeleteBox=Xa;exports.DepthOfField=Pn;exports.DeviceFlag=nf;exports.DocumentExtension=Vx;exports.DragControls=lr;exports.DragMode=Vg;exports.DropListener=Bs;exports.Duplicatable=Gg;exports.EffectWrapper=Gc;exports.EmissionModule=$s;exports.EmphasizeOnClick=hl;exports.EngineLoadingView=Pu;exports.EnvironmentScene=jf;exports.EventList=ye;exports.EventListEvent=Yu;exports.EventSystem=Yt;exports.EventTrigger=of;exports.FieldWithDefault=Bw;exports.FileReference=Ic;exports.FileReferenceSerializer=Uv;exports.FileSpawnModel=MM;exports.File_Event=Sw;exports.FixedJoint=Oy;exports.Fog=ml;exports.FrameEvent=we;exports.GENERATOR=Fu;exports.GameObject=C;exports.Gizmos=$;exports.GltfExport=ey;exports.GltfExportBox=Zg;exports.Gradient=Yr;exports.Graphic=Oh;exports.GraphicRaycaster=Ku;exports.Graphics=Mr;exports.GridHelper=gl;exports.GridLayoutGroup=by;exports.GroundProjectedEnv=ss;exports.GroupActionModel=yo;exports.HideFlags=Zu;exports.HideOnStart=Ya;exports.HingeJoint=Rh;exports.HorizontalLayoutGroup=_y;exports.HostData=t1;exports.Image=wl;exports.ImageReference=Dc;exports.ImageReferenceSerializer=Fv;exports.InheritVelocityModule=Ty;exports.Input=$0;exports.InputEventQueue=ri;exports.InputEvents=Re;exports.InputField=Wy;exports.InstanceHandle=Nc;exports.InstancingHandler=Qa;exports.InstancingUtil=Wi;exports.InstantiateEvent=dv;exports.InstantiateIdProvider=bt;exports.InstantiateOptions=xn;exports.Interactable=Ng;exports.JoinedRoomResponse=MC;exports.KeyEventArgs=mC;exports.Keyframe=li;exports.LODGroup=Th;exports.LODModel=yl;exports.LeftRoomResponse=OC;exports.Light=mi;exports.LightData=Wv;exports.LimitVelocityOverLifetimeModule=lt;exports.LoadingElementOptions=QE;exports.LogStats=zg;exports.LogType=Mi;exports.LookAt=Gy;exports.LookAtConstraint=Ur;exports.MainModule=It;exports.MarkerType=Ny;exports.MaskableGraphic=kh;exports.Mathf=z;exports.MeshCollider=Io;exports.MeshRenderer=vh;exports.MinMaxCurve=q;exports.MinMaxGradient=Kr;exports.NEKeyboardEvent=Xl;exports.NEPointerEvent=ys;exports.NeedleButtonElement=Zy;exports.NeedleEngineWebComponent=Ky;exports.NeedleMenu=rs;exports.NeedlePatchesKey=Rd;exports.NeedleXRController=og;exports.NeedleXRSession=J;exports.NeedleXRSync=K0;exports.NeedleXRUtils=J0;exports.NestedGltf=mf;exports.NetworkConnection=Y0;exports.NetworkedStreamEvents=Nn;exports.NetworkedStreams=gh;exports.Networking=Ry;exports.NewInstanceModel=fv;exports.NoiseModule=be;exports.ObjectRaycaster=Ei;exports.ObjectUtils=Lo;exports.OffsetConstraint=Qr;exports.OneEuroFilter=Od;exports.OneEuroFilterXYZ=qm;exports.OpenURL=xl;exports.OrbitControls=ge;exports.Outline=pl;exports.OwnershipEvent=Q0;exports.OwnershipModel=cg;exports.PUBLIC_KEY=ba;exports.Padding=Hr;exports.ParticleBurst=wu;exports.ParticleSubEmitter=Ay;exports.ParticleSystem=Wc;exports.ParticleSystemBaseBehaviour=No;exports.ParticleSystemRenderer=en;exports.ParticleSystemShapeType=vu;exports.PeerHandle=ja;exports.PeerNetworking=q0;exports.Physics=Ec;exports.PhysicsExtension=py;exports.PhysicsMaterialCombine=ht;exports.PixelationEffect=jh;exports.PlayAnimationOnClick=$c;exports.PlayAudioOnClick=Mo;exports.PlayableDirector=il;exports.PlayerColor=el;exports.PlayerState=yn;exports.PlayerStateEvent=tx;exports.PlayerSync=dy;exports.PlayerView=Nv;exports.PlayerViewManager=$v;exports.PointerEventData=mh;exports.PointerType=Nu;exports.PostProcessingEffect=Ye;exports.PostProcessingEffectOrder=it;exports.PostProcessingHandler=jy;exports.PreliminaryAction=dl;exports.PreliminaryTrigger=Sh;exports.PrimitiveType=Or;exports.Progress=oe;exports.PromiseAllWithErrors=Gm;exports.PromiseErrorResult=Qp;exports.RGBAColor=ie;exports.RapierPhysics=Mu;exports.RawImage=Df;exports.RaycastOptions=Ds;exports.Rect=nx;exports.RectTransform=wn;exports.ReflectionProbe=zc;exports.RegisteredAnimationInfo=_o;exports.RemoteSkybox=Sf;exports.RenderTexture=xr;exports.RenderTextureSerializer=hw;exports.Renderer=Ti;exports.RendererData=Vv;exports.RendererLightmap=_u;exports.Rigidbody=ot;exports.RigidbodyConstraints=Ne;exports.RoomEvents=ee;exports.RotationBySpeedModule=Ji;exports.RotationOverLifetimeModule=Cn;exports.SceneLightSettings=fu;exports.SceneSwitcher=Ge;exports.ScreenCapture=Vo;exports.ScreenSpaceAmbientOcclusion=Vs;exports.ScreenSpaceAmbientOcclusionN8=Mn;exports.SendQueue=fn;exports.SerializationContext=vg;exports.SetActiveOnClick=oy;exports.ShadowCatcher=zh;exports.ShapeModule=Ey;exports.SharpeningEffect=Fh;exports.SignalAsset=Rf;exports.SignalReceiver=Gh;exports.SignalReceiverEvent=Wh;exports.SignalTrackHandler=Hc;exports.Size=ix;exports.SizeBySpeedModule=gi;exports.SizeOverLifetimeModule=Zr;exports.SkinnedMeshRenderer=Kg;exports.SmoothFollow=Pf;exports.SpatialGrabRaycaster=Tr;exports.SpatialHtml=Xh;exports.SpatialTrigger=Mf;exports.SpatialTriggerReceiver=Zn;exports.SpectatorCamera=Of;exports.SphereCollider=al;exports.SphereIntersection=ug;exports.SphereOverlapResult=gw;exports.Sprite=Us;exports.SpriteData=Fa;exports.SpriteRenderer=fi;exports.SpriteSheet=Za;exports.StateMachineBehaviour=_P;exports.StreamEndedEvent=Ag;exports.StreamReceivedEvent=yw;exports.SubEmitterSystem=xu;exports.SyncedCamera=Fy;exports.SyncedRoom=On;exports.SyncedTransform=es;exports.TapGestureTrigger=ay;exports.TeleportTarget=uf;exports.TestRunner=Uy;exports.TestSceneUtils=sT;exports.TestSimulateUserData=zy;exports.Text=Dt;exports.TextBuilder=gy;exports.TextExtension=pf;exports.TextureSheetAnimationModule=jt;exports.TiltShiftEffect=cs;exports.Time=Gv;exports.ToneMappingEffect=Ro;exports.TrackHandler=Hh;exports.TrackType=bi;exports.TrailModule=je;exports.TransformData=We;exports.TransformGizmo=ia;exports.TriggerBuilder=wt;exports.TriggerModel=Co;exports.TypeStore=k;exports.UIRaycastUtils=Eg;exports.UIRootComponent=Ph;exports.USDDocument=ty;exports.USDObject=Et;exports.USDWriter=Vw;exports.USDZExporter=Kn;exports.USDZExporter$1=Ww;exports.USDZText=cr;exports.USDZUIExtension=wy;exports.UriSerializer=dw;exports.UsageMarker=bh;exports.UserJoinedOrLeftRoomModel=kC;exports.VERSION=_n;exports.VariantAction=ny;exports.VelocityOverLifetimeModule=ze;exports.VerticalLayoutGroup=yy;exports.VideoPlayer=rt;exports.ViewDevice=wo;exports.Vignette=ta;exports.VisibilityAction=Ch;exports.Voip=Do;exports.Volume=vl;exports.VolumeParameter=U;exports.VolumeProfile=bf;exports.WaitForFrames=E1;exports.WaitForPromise=zv;exports.WaitForSeconds=Sg;exports.Watch=Rs;exports.WebARCameraBackground=Yh;exports.WebARSessionRoot=is;exports.WebXR=ff;exports.WebXRButtonFactory=Po;exports.WebXRImageTracking=Xc;exports.WebXRImageTrackingModel=Hs;exports.WebXRPlaneTracking=qs;exports.WebXRTrackedImage=qc;exports.XRControllerFollow=Gs;exports.XRControllerModel=ns;exports.XRControllerMovement=Ai;exports.XRFlag=$i;exports.XRRig=Ff;exports.XRState=Qt;exports.XRStateFlag=Bn;exports.__Ignore=Wx;exports.__internalNotifyObjectDestroyed=ov;exports.activeInHierarchyFieldName=Es;exports.addAttributeChangeCallback=d0;exports.addComponent=Oi;exports.addCustomExtensionPlugin=XM;exports.addNewComponent=vr;exports.addPatch=Uu;exports.apply=Wu;exports.applyHMRChanges=dP;exports.applyPrototypeExtensions=Pv;exports.beginListenDestroy=uv;exports.beginListenInstantiate=mv;exports.binaryIdentifierCasts=rg;exports.build_scene_functions=Y1;exports.builtinComponentKeyName=er;exports.calculateProgress01=Yy;exports.clearMessages=RS;exports.colorSerializer=IP;exports.compareAssociation=bv;exports.componentSerializer=Bd;exports.copyTexture=O0;exports.createMotion=rw;exports.debugNet=ei;exports.debugOwner=Ql;exports.decompressGpuTexture=Xw;exports.deepClone=Jc;exports.delay=Jn;exports.delayForFrames=eh;exports.deserializeObject=nu;exports.destroy=Ri;exports.destroyComponentInstance=kv;exports.determineMimeTypeFromExtension=Cw;exports.disposeObjectResources=Se;exports.disposeStream=$n;exports.editorGuidKeyName=cc;exports.enableSpatialConsole=_r;exports.euler=BP;exports.eventListSerializer=NP;exports.exportAsGLTF=aT;exports.findByGuid=xg;exports.findObjectOfType=hh;exports.findObjectsOfType=Ev;exports.findResourceUsers=pg;exports.fitObjectIntoVolume=R0;exports.foreachComponent=Rr;exports.foreachComponentEnumerator=Hu;exports.forward=WS;exports.generateQRCode=f0;exports.generateSeed=pv;exports.getBoundingBox=ci;exports.getCameraController=v0;exports.getComponent=jr;exports.getComponentInChildren=ch;exports.getComponentInParent=Lc;exports.getComponents=lh;exports.getComponentsInChildren=sl;exports.getComponentsInParent=Vu;exports.getFormattedDate=Uw;exports.getIconElement=_t;exports.getIconTexture=ym;exports.getLoader=bn;exports.getOrAddComponent=ah;exports.getParam=S;exports.getParentHierarchyPath=qS;exports.getPath=lS;exports.getPeerOptions=xC;exports.getPeerjsInstance=H0;exports.getResourceUserCount=HC;exports.getTempColor=S0;exports.getTempQuaternion=un;exports.getTempVector=V;exports.getUrlParams=Zc;exports.getVisibleInCustomShadowRendering=k0;exports.getWorldDirection=C0;exports.getWorldEuler=Ym;exports.getWorldPosition=Q;exports.getWorldQuaternion=_e;exports.getWorldRotation=Bu;exports.getWorldScale=Ue;exports.hasCommercialLicense=Yn;exports.hasIndieLicense=uh;exports.hasPointerEventComponent=cu;exports.hasProLicense=Qn;exports.hideDebugConsole=L0;exports.imageToCanvas=Qw;exports.instantiate=Er;exports.invokeLoadedImportPluginHooks=Lw;exports.invokeXRSessionEnd=N0;exports.invokeXRSessionStart=z0;exports.isActiveInHierarchy=Tv;exports.isActiveSelf=ol;exports.isAndroidDevice=pS;exports.isAnimationAction=M0;exports.isComponent=fw;exports.isDebugMode=sS;exports.isDesktop=hS;exports.isDestroyed=kr;exports.isDevEnvironment=j;exports.isDisposed=WC;exports.isExporting=oT;exports.isGLTFModel=uw;exports.isHostedOnGlitch=s0;exports.isHotReloadEnabled=wm;exports.isHotReloading=cP;exports.isIPad=uS;exports.isIconElement=Xv;exports.isLocalNetwork=Kt;exports.isMacOS=gS;exports.isMobileDevice=dS;exports.isMozillaXR=mS;exports.isQuest=bS;exports.isResourceTrackingEnabled=iv;exports.isSafari=_S;exports.isUsingInstancing=Gu;exports.isiOS=yS;exports.isiPad=fS;exports.loadAsset=VE;exports.loadSync=Qy;exports.logHierarchy=Xd;exports.lookAtInverse=jS;exports.lookAtObject=th;exports.lookAtScreenPoint=BS;exports.makeId=rS;exports.makeIdFromRandomWords=l0;exports.makeNameSafe=Xi;exports.markAsInstancedRendered=Av;exports.microphonePermissionsGranted=vS;exports.nameof=nS;exports.nameofFactory=r0;exports.objectSerializer=cw;exports.offXRSessionEnd=pC;exports.offXRSessionStart=fC;exports.onAfterRender=aP;exports.onBeforeRender=rP;exports.onClear=sP;exports.onDestroy=oP;exports.onInitialized=Jv;exports.onStart=Mg;exports.onUpdate=ew;exports.onXRSessionEnd=sg;exports.onXRSessionStart=zu;exports.parseSync=Ix;exports.placeOnSurface=E0;exports.postprocessFBXMaterials=Jm;exports.prefix=RP;exports.pushState=a0;exports.randomNumber=aS;exports.registerBinaryType=ag;exports.registerComponent=qu;exports.registerComponentExtension=Xg;exports.registerCustomEffectType=tn;exports.registerExportExtensions=Qg;exports.registerExtensions=yu;exports.registerHotReloadType=iw;exports.registerLoader=ig;exports.registerPrefabProvider=yv;exports.registerPrototypeExtensions=Mv;exports.registerType=r1;exports.relativePathPrefix=h0;exports.removeAttributeChangeCallback=u0;exports.removeComponent=wg;exports.removeCustomImportExtensionType=QM;exports.removePatch=dC;exports.resolveUrl=Eo;exports.sanitizeString=c0;exports.saveImage=Tx;exports.screenshot=ME;exports.screenshot2=qy;exports.sendDestroyed=gg;exports.serializable=m;exports.serializeObject=wv;exports.serializeable=Br;exports.setActive=uc;exports.setAllowBalloonMessages=y0;exports.setAllowOverlayMessages=PS;exports.setAutoFitEnabled=Hd;exports.setCameraController=Zp;exports.setDestroyed=Dv;exports.setDevEnvironment=tC;exports.setDisposable=fg;exports.setDontDestroy=pa;exports.setOrAddParamsToUrl=Xp;exports.setParam=oS;exports.setParamWithoutReload=Oc;exports.setPeerOptions=SC;exports.setResourceTrackingEnabled=VC;exports.setState=Vm;exports.setVisibleInCustomShadowRendering=Zm;exports.setWorldEuler=Km;exports.setWorldPosition=st;exports.setWorldPositionXYZ=Pr;exports.setWorldQuaternion=Hi;exports.setWorldQuaternionXYZW=Qm;exports.setWorldRotation=P0;exports.setWorldRotationXYZ=ih;exports.setWorldScale=Na;exports.showBalloonError=nh;exports.showBalloonMessage=Ee;exports.showBalloonWarning=me;exports.showDebugConsole=eg;exports.slerp=IS;exports.syncDestroy=oh;exports.syncField=hy;exports.syncInstantiate=yg;exports.textureToCanvas=XS;exports.tryCastBinary=W0;exports.tryDetermineMimetypeFromBinary=Mw;exports.tryDetermineMimetypeFromURL=Pw;exports.tryFindObject=za;exports.tryGetGuid=G0;exports.unregisterHotReloadType=nw;exports.unwatchWrite=Wm;exports.useForAutoFit=w0;exports.validate=St;exports.watchWrite=ju;