@needle-tools/engine 3.45.2-beta.1 → 3.45.2-beta.3

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.
@@ -4344,7 +4344,7 @@ Open this page to get the console: `+e.toString())}const n=aa()||ew()&&st();if((
4344
4344
  #__vconsole .vc-mask {
4345
4345
  overflow: hidden;
4346
4346
  }
4347
- `,da?.prepend(r),n===!0&&OI()<=0&&pz(),console.log("\u{1F335} Debug console has loaded")}},e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(e)}function one(){const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const r=globalThis["needle:codegen_files"];if(!r||r.length===0)return;let s=globalThis["needle:codegen_files"][0];const o=s.indexOf("?");o>-1&&(s=s.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+s,l=encodeURIComponent(a);n.fullUrl="https://viewer.needle.tools?inspect&file="+l;var c='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(c)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var r=new Array;r.push({name:"Open in new window \u2197",onClick:function(s){window.open(n.fullUrl,"_blank"),ua?.hide()}}),r.push({name:"Reload",onClick:function(s){const o=e();o&&(o.src=n.fullUrl)}}),r.push({name:"Fullscreen",onClick:function(s){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(r)}),n}function ane(){return document.querySelector("#__vconsole .vc-switch")||null}function lne(){return document.querySelector("#__vconsole")||null}const vz=te("debugdefines");zf('if(!globalThis[""3.45.2-beta.1""]) globalThis[""3.45.2-beta.1""] = "0.0.0";'),zf('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),zf('if(!globalThis[""Wed Jul 17 2024 19:33:36 GMT+0200 (Central European Summer Time)""]) globalThis[""Wed Jul 17 2024 19:33:36 GMT+0200 (Central European Summer Time)""] = "unknown";'),zf('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta.1";'),zf('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),zf('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Jul 17 2024 19:33:36 GMT+0200 (Central European Summer Time)";');const el="3.45.2-beta.1",bw="undefined",DR="Wed Jul 17 2024 19:33:36 GMT+0200 (Central European Summer Time)";vz&&console.log(`Engine version: ${el} (generator: ${bw})
4347
+ `,da?.prepend(r),n===!0&&OI()<=0&&pz(),console.log("\u{1F335} Debug console has loaded")}},e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(e)}function one(){const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const r=globalThis["needle:codegen_files"];if(!r||r.length===0)return;let s=globalThis["needle:codegen_files"][0];const o=s.indexOf("?");o>-1&&(s=s.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+s,l=encodeURIComponent(a);n.fullUrl="https://viewer.needle.tools?inspect&file="+l;var c='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(c)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var r=new Array;r.push({name:"Open in new window \u2197",onClick:function(s){window.open(n.fullUrl,"_blank"),ua?.hide()}}),r.push({name:"Reload",onClick:function(s){const o=e();o&&(o.src=n.fullUrl)}}),r.push({name:"Fullscreen",onClick:function(s){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(r)}),n}function ane(){return document.querySelector("#__vconsole .vc-switch")||null}function lne(){return document.querySelector("#__vconsole")||null}const vz=te("debugdefines");zf('if(!globalThis[""3.45.2-beta.3""]) globalThis[""3.45.2-beta.3""] = "0.0.0";'),zf('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),zf('if(!globalThis[""Thu Jul 18 2024 13:36:34 GMT+0200 (Central European Summer Time)""]) globalThis[""Thu Jul 18 2024 13:36:34 GMT+0200 (Central European Summer Time)""] = "unknown";'),zf('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta.3";'),zf('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),zf('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Jul 18 2024 13:36:34 GMT+0200 (Central European Summer Time)";');const el="3.45.2-beta.3",bw="undefined",DR="Thu Jul 18 2024 13:36:34 GMT+0200 (Central European Summer Time)";vz&&console.log(`Engine version: ${el} (generator: ${bw})
4348
4348
  Project built at ${DR}`);const $c="needle_isActiveInHierarchy",wp="builtin_components",Kv="needle_editor_guid";function zf(n){try{(0,eval)(n)}catch(e){vz&&console.error(e)}}const cne='<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>',hne=btoa(cne),une="data:image/svg+xml;base64,"+hne,dne=une,pne=`<?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(pne);const mne='<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>',fne=btoa(mne),gne="data:image/svg+xml;charset=utf-8;base64,"+fne,vne=gne,pa=te("debuglicense");let Sp="basic";pa&&console.log("License Type: "+Sp);function uu(){switch(Sp){case"pro":case"enterprise":return!0}return!1}function OR(){switch(Sp){case"indie":return!0}return!1}function eh(){return uu()||OR()}const yz=[];function yne(n){if(uu()||OR())return n(!0);yz.push(n)}function Ane(n){for(const e of yz)try{e(n)}catch{}}di.registerCallback(Ci.ContextRegistered,n=>{xne(n.context),Sne(),_ne(n.context)});let Cp,LR=!1,_w="";async function bne(){if(Cp)return Cp;if(Sp==="basic")try{const n="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+el+"&generator="+encodeURIComponent(bw),e=await fetch(n,{method:"GET"}).catch(t=>{pa&&console.error("License check failed",t)});e?.status===200?(LR=!1,pa&&console.log("License check succeeded"),Sp="pro",Ane(!0)):e?.status===403?(LR=!0,_w=await e.text()):pa&&console.log("License check failed with status "+e?.status)}catch(n){pa&&console.error("License check failed",n)}else pa&&console.log('Runtime license check is skipped because license is already applied as "'+Sp+'"')}Cp=bne();async function _ne(n){function e(){const s=document.createElement("div");s.className="needle-forbidden",s.style.cssText=`
4349
4349
  position: fixed;
4350
4350
  top: 0;
@@ -5148,7 +5148,7 @@ in script ${o}.ts
5148
5148
  *
5149
5149
  * @author Feross Aboukhadijeh <https://feross.org>
5150
5150
  * @license MIT
5151
- */var rue=function(n){return n!=null&&(w6(n)||sue(n)||!!n._isBuffer)};function w6(n){return!!n.constructor&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function sue(n){return typeof n.readFloatLE=="function"&&typeof n.slice=="function"&&w6(n.slice(0,0))}(function(){var n=nue,e=x6.utf8,t=rue,r=x6.bin,s=function(o,a){o.constructor==String?a&&a.encoding==="binary"?o=r.stringToBytes(o):o=e.stringToBytes(o):t(o)?o=Array.prototype.slice.call(o,0):!Array.isArray(o)&&o.constructor!==Uint8Array&&(o=o.toString());for(var l=n.bytesToWords(o),c=o.length*8,h=1732584193,u=-271733879,p=-1732584194,m=271733878,f=0;f<l.length;f++)l[f]=(l[f]<<8|l[f]>>>24)&16711935|(l[f]<<24|l[f]>>>8)&4278255360;l[c>>>5]|=128<<c%32,l[(c+64>>>9<<4)+14]=c;for(var g=s._ff,v=s._gg,y=s._hh,A=s._ii,f=0;f<l.length;f+=16){var _=h,b=u,x=p,E=m;h=g(h,u,p,m,l[f+0],7,-680876936),m=g(m,h,u,p,l[f+1],12,-389564586),p=g(p,m,h,u,l[f+2],17,606105819),u=g(u,p,m,h,l[f+3],22,-1044525330),h=g(h,u,p,m,l[f+4],7,-176418897),m=g(m,h,u,p,l[f+5],12,1200080426),p=g(p,m,h,u,l[f+6],17,-1473231341),u=g(u,p,m,h,l[f+7],22,-45705983),h=g(h,u,p,m,l[f+8],7,1770035416),m=g(m,h,u,p,l[f+9],12,-1958414417),p=g(p,m,h,u,l[f+10],17,-42063),u=g(u,p,m,h,l[f+11],22,-1990404162),h=g(h,u,p,m,l[f+12],7,1804603682),m=g(m,h,u,p,l[f+13],12,-40341101),p=g(p,m,h,u,l[f+14],17,-1502002290),u=g(u,p,m,h,l[f+15],22,1236535329),h=v(h,u,p,m,l[f+1],5,-165796510),m=v(m,h,u,p,l[f+6],9,-1069501632),p=v(p,m,h,u,l[f+11],14,643717713),u=v(u,p,m,h,l[f+0],20,-373897302),h=v(h,u,p,m,l[f+5],5,-701558691),m=v(m,h,u,p,l[f+10],9,38016083),p=v(p,m,h,u,l[f+15],14,-660478335),u=v(u,p,m,h,l[f+4],20,-405537848),h=v(h,u,p,m,l[f+9],5,568446438),m=v(m,h,u,p,l[f+14],9,-1019803690),p=v(p,m,h,u,l[f+3],14,-187363961),u=v(u,p,m,h,l[f+8],20,1163531501),h=v(h,u,p,m,l[f+13],5,-1444681467),m=v(m,h,u,p,l[f+2],9,-51403784),p=v(p,m,h,u,l[f+7],14,1735328473),u=v(u,p,m,h,l[f+12],20,-1926607734),h=y(h,u,p,m,l[f+5],4,-378558),m=y(m,h,u,p,l[f+8],11,-2022574463),p=y(p,m,h,u,l[f+11],16,1839030562),u=y(u,p,m,h,l[f+14],23,-35309556),h=y(h,u,p,m,l[f+1],4,-1530992060),m=y(m,h,u,p,l[f+4],11,1272893353),p=y(p,m,h,u,l[f+7],16,-155497632),u=y(u,p,m,h,l[f+10],23,-1094730640),h=y(h,u,p,m,l[f+13],4,681279174),m=y(m,h,u,p,l[f+0],11,-358537222),p=y(p,m,h,u,l[f+3],16,-722521979),u=y(u,p,m,h,l[f+6],23,76029189),h=y(h,u,p,m,l[f+9],4,-640364487),m=y(m,h,u,p,l[f+12],11,-421815835),p=y(p,m,h,u,l[f+15],16,530742520),u=y(u,p,m,h,l[f+2],23,-995338651),h=A(h,u,p,m,l[f+0],6,-198630844),m=A(m,h,u,p,l[f+7],10,1126891415),p=A(p,m,h,u,l[f+14],15,-1416354905),u=A(u,p,m,h,l[f+5],21,-57434055),h=A(h,u,p,m,l[f+12],6,1700485571),m=A(m,h,u,p,l[f+3],10,-1894986606),p=A(p,m,h,u,l[f+10],15,-1051523),u=A(u,p,m,h,l[f+1],21,-2054922799),h=A(h,u,p,m,l[f+8],6,1873313359),m=A(m,h,u,p,l[f+15],10,-30611744),p=A(p,m,h,u,l[f+6],15,-1560198380),u=A(u,p,m,h,l[f+13],21,1309151649),h=A(h,u,p,m,l[f+4],6,-145523070),m=A(m,h,u,p,l[f+11],10,-1120210379),p=A(p,m,h,u,l[f+2],15,718787259),u=A(u,p,m,h,l[f+9],21,-343485551),h=h+_>>>0,u=u+b>>>0,p=p+x>>>0,m=m+E>>>0}return n.endian([h,u,p,m])};s._ff=function(o,a,l,c,h,u,p){var m=o+(a&l|~a&c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._gg=function(o,a,l,c,h,u,p){var m=o+(a&c|l&~c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._hh=function(o,a,l,c,h,u,p){var m=o+(a^l^c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._ii=function(o,a,l,c,h,u,p){var m=o+(l^(a|~c))+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._blocksize=16,s._digestsize=16,b6.exports=function(o,a){if(o==null)throw new Error("Illegal argument "+o);var l=n.wordsToBytes(s(o,a));return a&&a.asBytes?l:a&&a.asString?r.bytesToString(l):n.bytesToHex(l)}})();var oue=b6.exports;const aue=G1(oue);class hB{constructor(e,t,r,s){d(this,"success"),d(this,"filename"),d(this,"hash"),d(this,"size"),d(this,"url"),this.success=e,this.filename=t,this.hash=r,this.size=s}}async function S6(n,e){const t=await n.arrayBuffer(),r=uB(t),s=n.name.split(".").pop(),o=r+"."+s,a=n.name.split(".").shift();console.assert(a!==void 0);const l={alias:a,filename:o},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(l)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",r),new hB(!0,o,r,n.size);console.log("begin uploading file",a,n.size);const h=new FormData;h.append("file",n);const u={};u.filesize=n.size,a&&(u.alias=a);const p=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if(p?.success===!1)return p.message!==void 0?console.error("Upload failed:",p.message):console.error("Upload failed"),null;console.assert(p.hash_sum===r,"hash sum did not match","received:",p.hash_sum,"expected:",r),p.success&&console.log("successfully uploaded",r,p.id);const m=new hB(p.success,o,r,n.size);return m.url=e,m}function uB(n){return aue(new Uint8Array(n))}async function dB(n,e,t,r,s=!1){try{const o=await fetch(r+"/download/file",{method:"POST",body:n});if(o.status!==200)return console.error("download failed",o),null;const a=await o.blob(),l=await a.arrayBuffer();s||console.assert(a.size===t,"size mismatch","expected:",t,"got:",a.size);const c=uB(l);return s||console.assert(c===e,"hash mismatch, downloaded file is invalid"),a.arrayBuffer()}catch(o){console.error(o)}return null}async function C6(n,e){var t;const r=await fetch(n),s=(t=r.body)==null?void 0:t.getReader(),o=r.headers.get("Content-Length"),a=o?parseInt(o):0;if(!s)return null;let l=0;const c=[];for(;;){const{done:p,value:m}=await s.read();if(m&&(c.push(m),l+=m.length,e.call(null,new ProgressEvent("progress",{loaded:l,total:a}))),p)break}const h=new Uint8Array(l);let u=0;for(const p of c)h.set(p,u),u+=p.length;return h}const Fu=te("debugaddressables");class E6{constructor(e){d(this,"_context"),d(this,"_assetReferences",{}),d(this,"preUpdate",()=>{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const r=this._assetReferences[t];r?.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}unregisterAssetReference(e){e.uri&&delete this._assetReferences[e.uri]}}const pB=Symbol("assetReference"),Pg=class{constructor(n,e,t=null){d(this,"_loading"),d(this,"_asset"),d(this,"_glbRoot"),d(this,"_url"),d(this,"_progressListeners",[]),d(this,"_hash"),d(this,"_hashedUri"),d(this,"_isLoadingRawBinary",!1),d(this,"_rawBinary"),this._url=n,this._hash=e,n.includes("?v=")?this._hashedUri=n:this._hashedUri=e?n+"?v="+e:n,t!==null&&(this.asset=t),jV(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(n,e){if(!e&&(e=kt.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 t=e.addressables,r=t.findAssetReference(n);if(r)return r;const s=new Pg(n,e.hash);return t.registerAssetReference(s),s}static getOrCreate(n,e,t){if(typeof n=="string"){if(!t&&(t=kt.Current,!t))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 t=n.context,n=n.sourceId;const r=cu(n,e);Fu&&console.log("GetOrCreate Addressable from",n,e,"FinalPath=",r);const s=t.addressables,o=s.findAssetReference(r);if(o)return o;const a=new Pg(r,t.hash);return s.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(n){this._asset=n}get uri(){return this._url}get url(){return this._url}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(n){return n===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Jp(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Fu&&console.log("Unload",this.asset),this.asset.scene&&Ca(this.asset.scene,!0,!0),Ca(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,kt.Current&&kt.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Fu&&console.log("Preload",this._hashedUri);const n=await C6(this._hashedUri,e=>{this.raiseProgressEvent(e)});return this._rawBinary=n?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(n){if(Fu&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(n&&this._progressListeners.push(n),this._loading!==void 0)return this._loading.then(r=>this.asset);const e=kt.Current;this._rawBinary?(this._loading=Ka().parseSync(e,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Fu&&console.log("Load async",this.uri),this._loading=Ka().loadSync(e,this._hashedUri,this.uri,null,r=>{this.raiseProgressEvent(r)}));const t=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(t),this._loading=void 0,t)return t[pB]=this,this._glbRoot&&(this._glbRoot[pB]=this),this.asset&&(this.asset[pB]=this),B1(e),t.scene!==void 0&&(this.asset=t),this.asset}async instantiate(n){return this.onInstantiate(n,!1)}async instantiateSynced(n,e=!0){return this.onInstantiate(n,!0,e)}beginListenDownload(n){this._progressListeners.indexOf(n)<0&&this._progressListeners.push(n)}endListenDownload(n){const e=this._progressListeners.indexOf(n);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(n){for(const e of this._progressListeners)e(this,n)}async onInstantiate(n,e=!1,t){const r=kt.Current,s=new Ml;if(n instanceof ye?s.parent=n:n&&(Object.assign(s,n),s.cloneAssign(n)),s.parent||(s.parent=r.scene),this.mustLoad&&await this.loadAssetAsync(),Fu&&console.log("Instantiate",this.uri,"parent:",n),this.asset){Fu&&console.log("Add to scene",this.asset);let o=Pg.currentlyInstantiating.get(this.uri);if(o!==void 0&&o>=1e4)return console.error("Recursive or too many instantiations of "+this.uri+" in the same frame ("+o+")"),null;try{if(o===void 0&&(o=0),o+=1,Pg.currentlyInstantiating.set(this.uri,o),e){s.context=r;const a=this.asset;a.guid=this.uri;const l=ek(a,s,void 0,t);if(l)return l}else{const a=Gg(this.asset,s);if(a)return a}}finally{r.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,Pg.currentlyInstantiating.set(this.uri,o)})}}else Fu&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(n){if(n&&n.scene){const e=n.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};let ti=Pg;d(ti,"currentlyInstantiating",new Map);class lue extends wa{constructor(){super([ti],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ti.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof ye){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const r=e,s=t.context,o=r.guid??r.uuid,a=s.addressables.findAssetReference(o);if(a)return a;const l=new ti(o,void 0,r);return s.addressables.registerAssetReference(l),l}return null}}new lue;const cue=Promise.resolve(null),V1=class{constructor(n){d(this,"url"),d(this,"_bitmap"),d(this,"_bitmapObject"),d(this,"loader",null),this.url=n}static getOrCreate(n){let e=V1.imageReferences.get(n);return e||(e=new V1(n),V1.imageReferences.set(n,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const n=new Image;return n.src=this.url,n}createTexture(){return this.url?(this.loader||(this.loader=new Dl),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):cue}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((n,e)=>{const t=document.createElement("img");t.addEventListener("load",()=>{this._bitmap=createImageBitmap(t).then(r=>(this._bitmapObject=r,n(r),r))}),t.addEventListener("error",r=>{console.error("Failed to load image:"+this.url,r),n(null)}),t.src=this.url}),this._bitmap)}};let Q1=V1;d(Q1,"imageReferences",new Map);class M6 extends wa{constructor(){super([Q1],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return Q1.getOrCreate(r)}}}new M6;const H1=class{constructor(n){d(this,"url"),d(this,"res"),this.url=n}static getOrCreate(n){let e=H1.cache.get(n);return e||(e=new H1(n),H1.cache.set(n,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.text())}};let W1=H1;d(W1,"cache",new Map);class T6 extends wa{constructor(){super([W1],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return W1.getOrCreate(r)}}}new T6;class hue{constructor(e){d(this,"context"),d(this,"mixers",[]),this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e)return;const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Bg{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const r of e.children)this.tryGetAnimationClipsFromObjectHierarchy(r,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations)return;for(let s=0;s<e.animations.length;s++){const o=e.animations[s];if(!(!o.tracks||o.tracks.length<=0))for(const a in o.tracks){const l=o.tracks[a],c=Xt.parseTrackName(l.name);let h=Xt.findNode(e.scene,c.nodeName);if(!h){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(h=e.scene.getObjectByProperty("uuid",p),!h)continue}let u=r(h);if(!u){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=t.createAnimationComponent(e.scene,o)}u.addClip&&u.addClip(o)}}function r(s){var o;if(!s)return null;const a=(o=s.userData)==null?void 0:o.components;if(a&&a.length>0){for(let l=0;l<a.length;l++)if(a[l].isAnimationComponent===!0)return s}return r(s.parent)}}}const kg=[];function X1(n){kg.indexOf(n)===-1&&kg.push(n)}function uue(n){const e=kg.indexOf(n);e!==-1&&kg.splice(e,1)}const Dg=[];function mB(n){Dg.indexOf(n)===-1&&Dg.push(n)}function due(n){const e=Dg.indexOf(n);e!==-1&&Dg.splice(e,1)}function I6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:n}));for(let e=0;e<kg.length;e++)kg[e](n)}function R6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:n}));for(let e=0;e<Dg.length;e++)Dg[e](n)}const wr={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function P6(n){const e=await fetch(n);if(e.ok)return e.json();throw new Error(e.statusText)}async function pue(n){if(!n)throw new Error("No basePath supplied");return await P6(`${n}/profilesList.json`)}async function mue(n,e,t=null,r=!0){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const s=await pue(e);let o;if(n.profiles.some(c=>{const h=s[c];return h&&(o={profileId:c,profilePath:`${e}/${h.path}`,deprecated:!!h.deprecated}),!!o}),!o){if(!t)throw new Error("No matching profile name found");const c=s[t];if(!c)throw new Error(`No matching profile name found and default profile "${t}" missing.`);o={profileId:t,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}}const a=await P6(o.profilePath);let l;if(r){let c;if(n.handedness==="any"?c=a.layouts[Object.keys(a.layouts)[0]]:c=a.layouts[n.handedness],!c)throw new Error(`No matching handedness, ${n.handedness}, in profile ${o.profileId}`);c.assetPath&&(l=o.profilePath.replace("profile.json",c.assetPath))}return{profile:a,assetPath:l}}const fue={xAxis:0,yAxis:0,button:0,state:wr.ComponentState.DEFAULT};function gue(n=0,e=0){let t=n,r=e;if(Math.sqrt(n*n+e*e)>1){const s=Math.atan2(e,n);t=Math.cos(s),r=Math.sin(s)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:r*.5+.5}}let vue=class{constructor(n){this.componentProperty=n.componentProperty,this.states=n.states,this.valueNodeName=n.valueNodeName,this.valueNodeProperty=n.valueNodeProperty,this.valueNodeProperty===wr.VisualResponseProperty.TRANSFORM&&(this.minNodeName=n.minNodeName,this.maxNodeName=n.maxNodeName),this.value=0,this.updateFromComponent(fue)}updateFromComponent({xAxis:n,yAxis:e,button:t,state:r}){const{normalizedXAxis:s,normalizedYAxis:o}=gue(n,e);switch(this.componentProperty){case wr.ComponentProperty.X_AXIS:this.value=this.states.includes(r)?s:.5;break;case wr.ComponentProperty.Y_AXIS:this.value=this.states.includes(r)?o:.5;break;case wr.ComponentProperty.BUTTON:this.value=this.states.includes(r)?t:0;break;case wr.ComponentProperty.STATE:this.valueNodeProperty===wr.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(r):this.value=this.states.includes(r)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},yue=class{constructor(n,e){if(!n||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=n,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const r=new vue(e.visualResponses[t]);this.visualResponses[t]=r}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:wr.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(n){if(this.values.state=wr.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&n.buttons.length>this.gamepadIndices.button){const e=n.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=wr.ComponentState.PRESSED:(e.touched||this.values.button>wr.ButtonTouchThreshold)&&(this.values.state=wr.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&n.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=n.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===wr.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&n.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=n.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===wr.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},Aue=class{constructor(n,e,t){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=n,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[n.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(r=>{const s=this.layoutDescription.components[r];this.components[r]=new yue(r,s)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const n=[];return Object.values(this.components).forEach(e=>{n.push(e.data)}),n}updateFromGamepad(){Object.values(this.components).forEach(n=>{n.updateFromGamepad(this.xrInputSource.gamepad)})}};const Js=new C,B6=new C,k6=new Ce,bue=te("debuggizmos"),Wl=8947848,Xl=class{constructor(){}static isGizmo(n){return n[gB]!==void 0}static DrawLabel(n,e,t=.05,r=0,s,o,a){var l;if(!Xl.enabled)return null;s||(s=Wl);const c=((l=wt.active)==null?void 0:l.rigScale)??1,h=En.getTextLabel(r,e,t*c,s,o);return a instanceof ye&&a.add(h),h.position.x=n.x,h.position.y=n.y,h.position.z=n.z,h}static DrawRay(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),Js.set(e.x,e.y,e.z).multiplyScalar(999999999),a.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawDirection(n,e,t=Wl,r=0,s=!0,o=1){if(!Xl.enabled)return;const a=En.getLine(r),l=a.geometry.getAttribute("position");l.setXYZ(0,n.x,n.y,n.z),e.w!==void 0?(Js.set(0,0,-o),k6.set(e.x,e.y,e.z,e.w),Js.applyQuaternion(k6)):(Js.set(e.x,e.y,e.z),Js.multiplyScalar(o)),l.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),l.needsUpdate=!0,a.material.color.set(t),a.material.depthTest=s,a.material.depthWrite=!1}static DrawLine(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),a.setXYZ(1,e.x,e.y,e.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!0);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!1);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawWireBox(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getBox(r);o.position.set(n.x,n.y,n.z),o.scale.set(e.x,e.y,e.z),o.material.color.set(t),o.material.depthTest=s,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(n,e=Wl,t=0,r=!0){if(!Xl.enabled)return;const s=En.getBox(t);s.position.copy(n.getCenter(Js)),s.scale.copy(n.getSize(Js)),s.material.color.set(e),s.material.depthTest=r,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1}static DrawArrow(n,e,t=Wl,r=0,s=!0,o=!1){if(!Xl.enabled)return;const a=En.getArrowHead(r);a.position.set(e.x,e.y,e.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).normalize());const l=Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).length()*.1;a.scale.set(l,l,l),a.material.color.set(t),a.material.depthTest=s,a.material.wireframe=o,this.DrawLine(n,e,t,r,s)}static DrawWireMesh(n){const e=En.getMesh(n.duration??0);"mesh"in n?(e.geometry=n.mesh.geometry,e.matrix.copy(n.mesh.matrixWorld)):(e.geometry=n.geometry,e.matrix.copy(n.matrix)),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1,e.material.color.set(n.color??Wl),e.material.depthTest=n.depthTest??!0,e.material.wireframe=!0}};let At=Xl;d(At,"enabled",!0),d(At,"_up",new C(0,1,0));const _ue=new qi(1,1,1);function fB(n=null){const e=new xe(n??14540253),t=new iI(_ue);return new gs(t,new Gi({color:e}))}const gB=Symbol("GizmoCache");class En{static ensureFont(){let e=Ni.FontLibrary.getFontFamily(this.familyName);if(!e){e=Ni.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Ni.update()})}}static getTextLabel(e,t,r,s,o){this.ensureFont();let a=this.textLabelCache.pop(),l=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(l=parseInt(o.substring(7),16)/255,o=o.substring(0,7),bue&&console.log(o,l)):typeof o=="object"&&o.a!==void 0&&(l=o.a);const c={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:r,color:s,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:l,textContent:t,borderRadius:.5*r,padding:.8*r,whiteSpace:"pre"};if(a)a.set(c);else{a=new fR(c);const h=this,u=a;u.setText=function(p){this.set({textContent:p}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(kt.Current,a,e,this.textLabelCache),a}static getBox(e){let t=this.boxesCache.pop();if(!t){const r=new qi(1,1,1);t=new me(r)}return this.registerTimedObject(kt.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Sn;let r=t.geometry.getAttribute("position");r||(r=new nt(new Float32Array(2*3),3),t.geometry.setAttribute("position",r))}return t.frustumCulled=!1,this.registerTimedObject(kt.Current,t,e,this.linesCache),t}static getSphere(e,t,r){let s=this.spheresCache.pop();return s||(s=new me(new ja(1,8,8))),s.scale.set(e,e,e),s.material.wireframe=r,this.registerTimedObject(kt.Current,s,t,this.spheresCache),s}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new me(new jn(0,.5,1,8))),this.registerTimedObject(kt.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new me,t.material=new $t),this.registerTimedObject(kt.Current,t,e,this.mesh),t}static registerTimedObject(e,t,r,s){const o=this.contextBeforeRenderCallbacks.get(e),a=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const l=e.pre_render_callbacks.indexOf(o);l>=0&&e.pre_render_callbacks.splice(l,1),e.pre_render_callbacks.push(o)}}else{const l=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,l),e.pre_render_callbacks.push(l)}if(a){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==a){const l=e.post_render_callbacks.indexOf(a);l>=0&&e.post_render_callbacks.splice(l,1),e.post_render_callbacks.push(a)}}else{const l=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,l),e.post_render_callbacks.push(l)}t.traverse(l=>{l.layers.disableAll(),l.layers.enable(2)}),t.renderOrder=999999,t[gB]=s,t.isGizmo=!0,this.timedObjectsBuffer.push(t),r<=0&&e.currentFrameEvent>=Hi.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(kt.Current.time.realtimeSinceStartup+r),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&Ni.update();for(let r=0;r<t.length;r++){const s=t[r];if(e.mainCamera&&s instanceof Ni.MeshUIBaseElement){if(Jp(s))continue;const o=e.isInVR,a=!1,l=!o;Hv(s,e.mainCamera,a,l)}}}static onPostRender(e,t,r){const s=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const a=t[o];s>r[o]&&(t.splice(o,1),r.splice(o,1),a.removeFromParent(),Jp(a)!=!0&&a[gB].push(a))}}}d(En,"familyName","needle-gizmos"),d(En,"linesCache",[]),d(En,"spheresCache",[]),d(En,"boxesCache",[]),d(En,"arrowHeadsCache",[]),d(En,"mesh",[]),d(En,"textLabelCache",[]),d(En,"timedObjectsBuffer",new Array),d(En,"timesBuffer",new Array),d(En,"contextPostRenderCallbacks",new Map),d(En,"contextBeforeRenderCallbacks",new Map),d(En,"tmuiNeedsUpdate",!1);const cr=te("debuginput");var q1=(n=>(n.Mouse="mouse",n.Touch="touch",n.Controller="controller",n.Hand="hand",n))(q1||{}),an=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(an||{});class mh extends PointerEvent{constructor(e,t,r){super(e,r),d(this,"deviceIndex"),d(this,"origin"),d(this,"source"),d(this,"mode"),d(this,"_ray"),d(this,"space"),d(this,"isClick",!1),d(this,"isDoubleClick",!1),d(this,"_used",!1),d(this,"_pointerid"),d(this,"_pointerType"),d(this,"_type"),d(this,"metadata",{}),d(this,"intersections",new Array),d(this,"_immediatePropagationStopped",!1),d(this,"_propagationStopped",!1),this._pointerid=r.pointerId,this._pointerType=r.pointerType,this._type=e,this.deviceIndex=r.deviceIndex,this.origin=r.origin,this.source=t,this.mode=r.mode,this._ray=r.ray,this.space=r.device}get ray(){return this._ray||(this._ray=new co(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(),cr&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Xy extends KeyboardEvent{constructor(e,t,r){super(e,r),d(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class xue{constructor(e){d(this,"key"),d(this,"keyType"),d(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var ql=(n=>(n[n.Early=-100]="Early",n[n.Default=0]="Default",n[n.Late=100]="Late",n))(ql||{});class D6{constructor(e){d(this,"_eventListeners",{}),d(this,"_doubleClickTimeThreshold",.2),d(this,"_longPressTimeThreshold",1),d(this,"_specialCursorTrigger",0),d(this,"context"),d(this,"_pointerDown",[!1]),d(this,"_pointerUp",[!1]),d(this,"_pointerClick",[!1]),d(this,"_pointerDoubleClick",[!1]),d(this,"_pointerPressed",[!1]),d(this,"_pointerPositions",[new Z]),d(this,"_pointerPositionsLastFrame",[new Z]),d(this,"_pointerPositionsDelta",[new Z]),d(this,"_pointerPositionsRC",[new Z]),d(this,"_pointerPositionDown",[new Z]),d(this,"_pointerDownTime",[]),d(this,"_pointerUpTime",[]),d(this,"_pointerUpTimestamp",[]),d(this,"_pointerIds",[]),d(this,"_pointerTypes",[""]),d(this,"_mouseWheelChanged",[!1]),d(this,"_mouseWheelDeltaY",[0]),d(this,"_pointerEvent",[]),d(this,"_pointerUsed",[]),d(this,"_pointerSpace",[]),d(this,"_pressedStack",new Map),d(this,"_htmlEventSource"),d(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),d(this,"onEndOfFrame",()=>{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}),d(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),d(this,"keysPressed",{}),d(this,"onKeyDown",t=>{if(cr&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(r&&r.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 s=new Xy("keydown",t,t);this.onDispatchEvent(s)}),d(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!0,r.frame=this.context.time.frameCount+1;const s=new Xy("keypress",t,t);this.onDispatchEvent(s)}),d(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!1,r.frame=this.context.time.frameCount+1;const s=new Xy("keyup",t,t);this.onDispatchEvent(s)}),d(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),d(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 r=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=r+t.deltaY}),d(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const r=this.getPointerId(t);cr&&rn(`pointer down #${r}, identifier:${t.pointerId}`);const s=this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),o=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:s,pressure:t.pressure});this.onDown(o)}),d(this,"onPointerMove",t=>{if(this.context.isInAR)return;let r=t.button;t.pointerType==="mouse"&&(r=this.getFirstPressedButtonForPointer(0)??0);const s=this.getPointerId(t,r);r===-1&&(r=s);const o=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),a=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:r,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:o,pressure:t.pressure});this.onMove(a)}),d(this,"onPointerCancel",t=>{this.context.isInAR||(cr&&console.log("Pointer cancel",t),this.onPointerUp(t))}),d(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const r=this.getPointerId(t),s=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),pressure:t.pressure});this.onUp(s),this._pointerIds[r]=-1,cr&&console.log("ID="+r,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),d(this,"onTouchStart",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onDown(l)}}),d(this,"onTouchMove",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onMove(l)}}),d(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),pressure:s.force});this.onUp(a),this._pointerIds[o]=-1}}),d(this,"tempNearPlaneVector",new C),d(this,"tempFarPlaneVector",new C),d(this,"tempLookMatrix",new ve),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,r){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}r?r={...r}:r={};let s=0;r?.queue!=null&&(s=r.queue);const o=this._eventListeners[e],a=o.find(l=>l.priority===s);a?a.listeners.push({callback:t,options:r}):(o.push({priority:s,listeners:[{callback:t,options:r}]}),o.sort((l,c)=>l.priority-c.priority))}removeEventListener(e,t,r){if(!this._eventListeners[e]||!t)return;const s=this._eventListeners[e];if(r?.queue!=null){const o=s.find(l=>l.priority===r.queue);if(!o)return;const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}else for(const o of s){const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}}dispatchEvent(e){var t,r,s,o;let a=!1;if(e instanceof Xy){const l=this._eventListeners[e.type];if(l)for(const c of l)for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((r=(t=u.options)==null?void 0:t.signal)!=null&&r.aborted){c.listeners.splice(h,1),h--;continue}u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}if(e instanceof mh){const l=this._eventListeners[e.type];if(l)for(const c of l){if(a)break;for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((o=(s=u.options)==null?void 0:s.signal)!=null&&o.aborted){c.listeners.splice(h,1),h--;continue}if(e.immediatePropagationStopped){a=!0,cr&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(a=!0,cr&&console.log("propagationStopped",e.type));u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}}}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)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(e,t=!0){if(e>=this._pointerUsed.length){if(e>=this._pointerIds.length)return;for(;this._pointerUsed.length<=e;)this._pointerUsed.push(!1)}this._pointerUsed[e]=t}getPointerUsed(e){return e>=this._pointerUsed.length?!1:this._pointerUsed[e]}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const r=this._pointerTypes[t];if(Array.isArray(e)){let s=!1;for(const o of e)if(r===o){s=!0;break}if(!s)continue}else if(e!==r)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let r=this._pressedStack.get(e);r||(r=[],this._pressedStack.set(e,r)),r.push(t)}onReleaseButton(e,t){const r=this._pressedStack.get(e);if(!r)return;const s=r.indexOf(t);s>=0&&r.splice(s,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyDown(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.startFrame)===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyUp(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.frame)===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyPressed(s))return!0;return!1}return(t=this.keysPressed[e])==null?void 0:t.pressed}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":cr&&rn("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":cr&&rn("Create Pointer move"),this.onMove(e);break;case"pointerup":cr&&rn("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}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 e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(t=this._htmlEventSource)==null||t.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 e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&gp()?!0:(cr&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,r){let s=this._pointerSpace[e];s||(s=new ye,this._pointerSpace[e]=s),this._pointerSpace[e]=s;const o=this.context.mainCamera;if(o){const a=this.tempNearPlaneVector.set(t,r,-1);this.convertScreenspaceToRaycastSpace(a);const l=this.tempFarPlaneVector.set(a.x,a.y,1);a.unproject(o),l.unproject(o);const c=o.worldUp||pi(0,1,0).applyQuaternion(Mi(o));this.tempLookMatrix.lookAt(l,a,c),s.position.set(a.x,a.y,a.z),s.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return s}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),r=e.clientX,s=e.clientY,o=r>=t.x&&r<=t.right&&s>=t.y&&s<=t.bottom;return cr&&!o&&console.log("Not in rect",t,r,s),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`pointerId is already pressed: ${t}`,cr?e:""),cr&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new Z);for(this._pointerPositionDown[t].set(e.clientX,e.clientY);t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,r=this.getPointerPressed(t);r===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!r||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){cr&&console.log(e.pointerType,"UP",t,"was not down");return}for(cr&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0);t>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t,this._pointerUsed,!1),this.updatePointerPosition(e),!this._pointerPositionDown[t]){cr&&Di("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const r=e.clientX-this._pointerPositionDown[t].x,s=e.clientY-this._pointerPositionDown[t].y;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(r)<5&&Math.abs(s)<5){cr&&console.log("CLICK",t),this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const o=this._pointerUpTime[t],a=this.context.time.time-o;a<this._doubleClickTimeThreshold&&a>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}this._pointerUpTime[t]=this.context.time.time,this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Z);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Z);const r=this._pointerPositionsLastFrame[t];r.copy(this._pointerPositions[t]);const s=this._pointerPositionsDelta[t];let o=e.clientX-r.x,a=e.clientY-r.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;o===0&&u.movementX!==0&&(o=u.movementX||0),a===0&&u.movementY!==0&&(a=u.movementY||0)}s.x+=o,s.y+=a,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const l=e.clientX,c=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new Z);const h=this._pointerPositionsRC[t];h.set(l,c),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(e){let t=-1;for(let r=0;r<this._pointerIds.length;r++){if(this._pointerIds[r]===e)return r;t===-1&&this._pointerIds[r]===-1&&(t=r)}return t!==-1?(this._pointerIds[t]=e,t):(cr&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,r){t[e]=r}setPointerStateT(e,t,r){return t[e]=r,r}onDispatchEvent(e){const t=kt.Current;try{kt.Current=this.context,this.dispatchEvent(e)}finally{kt.Current=t}}}const Y1=new ve().makeRotationY(Math.PI),Sa=new Ce().setFromAxisAngle(new C(0,1,0),Math.PI),wue=te("debugwebxr");class Sue{constructor(){if(d(this,"priority",-1e5),d(this,"gameObject"),this.gameObject=new ye,this.gameObject.name="Implicit XR Rig",wue){const e=fB(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const Uu=te("debugwebxr"),J1=te("debugcustomgesture"),Cue="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",Eue="generic-trigger";class vB{constructor(e,t,r){d(this,"xr"),d(this,"inputSource"),d(this,"index",0),d(this,"emitEvents",!0),d(this,"_connected",!0),d(this,"_isTracking",!1),d(this,"_hitTestSource"),d(this,"_hasSelectEvent",!1),d(this,"_handJointPoses",new Map),d(this,"_gripPosition",new C),d(this,"_gripQuaternion",new Ce),d(this,"_linearVelocity",new C),d(this,"_rayPosition",new C),d(this,"_rayQuaternion",new Ce),d(this,"_gripWorldPosition",new C),d(this,"_gripWorldQuaternion",new Ce),d(this,"_rayWorldPosition",new C),d(this,"_rayWorldQuaternion",new Ce),d(this,"_ray"),d(this,"_object"),d(this,"model",null),d(this,"_debugAxesHelper",new Po(.2)),d(this,"onPointerHits",l=>{}),d(this,"_needleGamepadButtons",{}),d(this,"_buttonMap",new Map),d(this,"_motioncontroller"),d(this,"_layout"),d(this,"getMotionController"),d(this,"_selectButtonIndex"),d(this,"_squeezeButtonIndex"),d(this,"onSelectStart",l=>{var c,h,u,p;if(this.inputSource!==l.inputSource)return;this.onUpdateFrame(l.frame),this._hasSelectEvent=!0;const m=(c=this._layout)==null?void 0:c.selectComponentId,f=(p=(u=(h=this._layout)==null?void 0:h.components[m])==null?void 0:u.gamepadIndices)==null?void 0:p.button;f!==void 0&&(this._selectButtonIndex=f),!J1&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(an.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,l))}),d(this,"onSelectEnd",l=>{J1||this.inputSource===l.inputSource&&this.emitPointerEvent(an.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,l)}),d(this,"onSequeezeStart",l=>{var c,h,u;this.inputSource===l.inputSource&&(this._squeezeButtonIndex=(u=(h=(c=this._layout)==null?void 0:c.components["xr-standard-squeeze"])==null?void 0:h.gamepadIndices)==null?void 0:u.button,this._squeezeButtonIndex!==void 0&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(an.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)))}),d(this,"onSequeezeEnd",l=>{this.inputSource===l.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(an.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)}),d(this,"states",{}),d(this,"_didMoveLastFrame",!1),d(this,"_lastPointerMovePosition",new C),d(this,"_lastPointerMoveQuaternion",new Ce),d(this,"pointerInit");var s,o,a;this.xr=e,this.inputSource=t,this.index=r,this._object=new ye,Uu&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new co,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(),this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&((a=(o=(s=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:o.call(s,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||a.then(l=>this._hitTestSource=l))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return 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.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e){var t,r;if(!this.hand||!((t=this.xr.frame)!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let s=(r=this._handJointPoses)==null?void 0:r.get(e);return s||(s=this.xr.frame.getJointPose(e,this.xr.referenceSpace),s&&this._handJointPoses.set(e,s),s)}get gripPosition(){return pi(this._gripPosition).applyMatrix4(Y1)}get gripQuaternion(){return bp(this._gripQuaternion).premultiply(Sa)}get gripLinearVelocity(){return pi(this._linearVelocity).applyQuaternion(Sa)}get rayPosition(){return pi(this._rayPosition).applyMatrix4(Y1)}get rayQuaternion(){return bp(this._rayQuaternion).premultiply(Sa)}get gripWorldPosition(){return pi(this._gripWorldPosition)}get gripWorldQuaternion(){return bp(this._gripWorldQuaternion)}get rayWorldPosition(){return pi(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPosition),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return bp(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,r=t?Mi(t):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(Sa),r&&this._rayWorldQuaternion.premultiply(r)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(pi(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;At.DrawWireSphere(this.rayWorldPosition,.02),At.DrawDirection(this.rayWorldPosition,pi(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),r=this.inputSource.profiles.join(`
5151
+ */var rue=function(n){return n!=null&&(w6(n)||sue(n)||!!n._isBuffer)};function w6(n){return!!n.constructor&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function sue(n){return typeof n.readFloatLE=="function"&&typeof n.slice=="function"&&w6(n.slice(0,0))}(function(){var n=nue,e=x6.utf8,t=rue,r=x6.bin,s=function(o,a){o.constructor==String?a&&a.encoding==="binary"?o=r.stringToBytes(o):o=e.stringToBytes(o):t(o)?o=Array.prototype.slice.call(o,0):!Array.isArray(o)&&o.constructor!==Uint8Array&&(o=o.toString());for(var l=n.bytesToWords(o),c=o.length*8,h=1732584193,u=-271733879,p=-1732584194,m=271733878,f=0;f<l.length;f++)l[f]=(l[f]<<8|l[f]>>>24)&16711935|(l[f]<<24|l[f]>>>8)&4278255360;l[c>>>5]|=128<<c%32,l[(c+64>>>9<<4)+14]=c;for(var g=s._ff,v=s._gg,y=s._hh,A=s._ii,f=0;f<l.length;f+=16){var _=h,b=u,x=p,E=m;h=g(h,u,p,m,l[f+0],7,-680876936),m=g(m,h,u,p,l[f+1],12,-389564586),p=g(p,m,h,u,l[f+2],17,606105819),u=g(u,p,m,h,l[f+3],22,-1044525330),h=g(h,u,p,m,l[f+4],7,-176418897),m=g(m,h,u,p,l[f+5],12,1200080426),p=g(p,m,h,u,l[f+6],17,-1473231341),u=g(u,p,m,h,l[f+7],22,-45705983),h=g(h,u,p,m,l[f+8],7,1770035416),m=g(m,h,u,p,l[f+9],12,-1958414417),p=g(p,m,h,u,l[f+10],17,-42063),u=g(u,p,m,h,l[f+11],22,-1990404162),h=g(h,u,p,m,l[f+12],7,1804603682),m=g(m,h,u,p,l[f+13],12,-40341101),p=g(p,m,h,u,l[f+14],17,-1502002290),u=g(u,p,m,h,l[f+15],22,1236535329),h=v(h,u,p,m,l[f+1],5,-165796510),m=v(m,h,u,p,l[f+6],9,-1069501632),p=v(p,m,h,u,l[f+11],14,643717713),u=v(u,p,m,h,l[f+0],20,-373897302),h=v(h,u,p,m,l[f+5],5,-701558691),m=v(m,h,u,p,l[f+10],9,38016083),p=v(p,m,h,u,l[f+15],14,-660478335),u=v(u,p,m,h,l[f+4],20,-405537848),h=v(h,u,p,m,l[f+9],5,568446438),m=v(m,h,u,p,l[f+14],9,-1019803690),p=v(p,m,h,u,l[f+3],14,-187363961),u=v(u,p,m,h,l[f+8],20,1163531501),h=v(h,u,p,m,l[f+13],5,-1444681467),m=v(m,h,u,p,l[f+2],9,-51403784),p=v(p,m,h,u,l[f+7],14,1735328473),u=v(u,p,m,h,l[f+12],20,-1926607734),h=y(h,u,p,m,l[f+5],4,-378558),m=y(m,h,u,p,l[f+8],11,-2022574463),p=y(p,m,h,u,l[f+11],16,1839030562),u=y(u,p,m,h,l[f+14],23,-35309556),h=y(h,u,p,m,l[f+1],4,-1530992060),m=y(m,h,u,p,l[f+4],11,1272893353),p=y(p,m,h,u,l[f+7],16,-155497632),u=y(u,p,m,h,l[f+10],23,-1094730640),h=y(h,u,p,m,l[f+13],4,681279174),m=y(m,h,u,p,l[f+0],11,-358537222),p=y(p,m,h,u,l[f+3],16,-722521979),u=y(u,p,m,h,l[f+6],23,76029189),h=y(h,u,p,m,l[f+9],4,-640364487),m=y(m,h,u,p,l[f+12],11,-421815835),p=y(p,m,h,u,l[f+15],16,530742520),u=y(u,p,m,h,l[f+2],23,-995338651),h=A(h,u,p,m,l[f+0],6,-198630844),m=A(m,h,u,p,l[f+7],10,1126891415),p=A(p,m,h,u,l[f+14],15,-1416354905),u=A(u,p,m,h,l[f+5],21,-57434055),h=A(h,u,p,m,l[f+12],6,1700485571),m=A(m,h,u,p,l[f+3],10,-1894986606),p=A(p,m,h,u,l[f+10],15,-1051523),u=A(u,p,m,h,l[f+1],21,-2054922799),h=A(h,u,p,m,l[f+8],6,1873313359),m=A(m,h,u,p,l[f+15],10,-30611744),p=A(p,m,h,u,l[f+6],15,-1560198380),u=A(u,p,m,h,l[f+13],21,1309151649),h=A(h,u,p,m,l[f+4],6,-145523070),m=A(m,h,u,p,l[f+11],10,-1120210379),p=A(p,m,h,u,l[f+2],15,718787259),u=A(u,p,m,h,l[f+9],21,-343485551),h=h+_>>>0,u=u+b>>>0,p=p+x>>>0,m=m+E>>>0}return n.endian([h,u,p,m])};s._ff=function(o,a,l,c,h,u,p){var m=o+(a&l|~a&c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._gg=function(o,a,l,c,h,u,p){var m=o+(a&c|l&~c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._hh=function(o,a,l,c,h,u,p){var m=o+(a^l^c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._ii=function(o,a,l,c,h,u,p){var m=o+(l^(a|~c))+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._blocksize=16,s._digestsize=16,b6.exports=function(o,a){if(o==null)throw new Error("Illegal argument "+o);var l=n.wordsToBytes(s(o,a));return a&&a.asBytes?l:a&&a.asString?r.bytesToString(l):n.bytesToHex(l)}})();var oue=b6.exports;const aue=G1(oue);class hB{constructor(e,t,r,s){d(this,"success"),d(this,"filename"),d(this,"hash"),d(this,"size"),d(this,"url"),this.success=e,this.filename=t,this.hash=r,this.size=s}}async function S6(n,e){const t=await n.arrayBuffer(),r=uB(t),s=n.name.split(".").pop(),o=r+"."+s,a=n.name.split(".").shift();console.assert(a!==void 0);const l={alias:a,filename:o},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(l)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",r),new hB(!0,o,r,n.size);console.log("begin uploading file",a,n.size);const h=new FormData;h.append("file",n);const u={};u.filesize=n.size,a&&(u.alias=a);const p=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if(p?.success===!1)return p.message!==void 0?console.error("Upload failed:",p.message):console.error("Upload failed"),null;console.assert(p.hash_sum===r,"hash sum did not match","received:",p.hash_sum,"expected:",r),p.success&&console.log("successfully uploaded",r,p.id);const m=new hB(p.success,o,r,n.size);return m.url=e,m}function uB(n){return aue(new Uint8Array(n))}async function dB(n,e,t,r,s=!1){try{const o=await fetch(r+"/download/file",{method:"POST",body:n});if(o.status!==200)return console.error("download failed",o),null;const a=await o.blob(),l=await a.arrayBuffer();s||console.assert(a.size===t,"size mismatch","expected:",t,"got:",a.size);const c=uB(l);return s||console.assert(c===e,"hash mismatch, downloaded file is invalid"),a.arrayBuffer()}catch(o){console.error(o)}return null}async function C6(n,e){var t;const r=await fetch(n),s=(t=r.body)==null?void 0:t.getReader(),o=r.headers.get("Content-Length"),a=o?parseInt(o):0;if(!s)return null;let l=0;const c=[];for(;;){const{done:p,value:m}=await s.read();if(m&&(c.push(m),l+=m.length,e.call(null,new ProgressEvent("progress",{loaded:l,total:a}))),p)break}const h=new Uint8Array(l);let u=0;for(const p of c)h.set(p,u),u+=p.length;return h}const Fu=te("debugaddressables");class E6{constructor(e){d(this,"_context"),d(this,"_assetReferences",{}),d(this,"preUpdate",()=>{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const r=this._assetReferences[t];r?.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}unregisterAssetReference(e){e.uri&&delete this._assetReferences[e.uri]}}const pB=Symbol("assetReference"),Pg=class{constructor(n,e,t=null){d(this,"_loading"),d(this,"_asset"),d(this,"_glbRoot"),d(this,"_url"),d(this,"_progressListeners",[]),d(this,"_hash"),d(this,"_hashedUri"),d(this,"_isLoadingRawBinary",!1),d(this,"_rawBinary"),this._url=n,this._hash=e,n.includes("?v=")?this._hashedUri=n:this._hashedUri=e?n+"?v="+e:n,t!==null&&(this.asset=t),j8(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(n,e){if(!e&&(e=kt.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 t=e.addressables,r=t.findAssetReference(n);if(r)return r;const s=new Pg(n,e.hash);return t.registerAssetReference(s),s}static getOrCreate(n,e,t){if(typeof n=="string"){if(!t&&(t=kt.Current,!t))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 t=n.context,n=n.sourceId;const r=cu(n,e);Fu&&console.log("GetOrCreate Addressable from",n,e,"FinalPath=",r);const s=t.addressables,o=s.findAssetReference(r);if(o)return o;const a=new Pg(r,t.hash);return s.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(n){this._asset=n}get uri(){return this._url}get url(){return this._url}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(n){return n===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Jp(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Fu&&console.log("Unload",this.asset),this.asset.scene&&Ca(this.asset.scene,!0,!0),Ca(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,kt.Current&&kt.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Fu&&console.log("Preload",this._hashedUri);const n=await C6(this._hashedUri,e=>{this.raiseProgressEvent(e)});return this._rawBinary=n?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(n){if(Fu&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(n&&this._progressListeners.push(n),this._loading!==void 0)return this._loading.then(r=>this.asset);const e=kt.Current;this._rawBinary?(this._loading=Ka().parseSync(e,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Fu&&console.log("Load async",this.uri),this._loading=Ka().loadSync(e,this._hashedUri,this.uri,null,r=>{this.raiseProgressEvent(r)}));const t=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(t),this._loading=void 0,t)return t[pB]=this,this._glbRoot&&(this._glbRoot[pB]=this),this.asset&&(this.asset[pB]=this),B1(e),t.scene!==void 0&&(this.asset=t),this.asset}async instantiate(n){return this.onInstantiate(n,!1)}async instantiateSynced(n,e=!0){return this.onInstantiate(n,!0,e)}beginListenDownload(n){this._progressListeners.indexOf(n)<0&&this._progressListeners.push(n)}endListenDownload(n){const e=this._progressListeners.indexOf(n);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(n){for(const e of this._progressListeners)e(this,n)}async onInstantiate(n,e=!1,t){const r=kt.Current,s=new Ml;if(n instanceof ye?s.parent=n:n&&(Object.assign(s,n),s.cloneAssign(n)),s.parent||(s.parent=r.scene),this.mustLoad&&await this.loadAssetAsync(),Fu&&console.log("Instantiate",this.uri,"parent:",n),this.asset){Fu&&console.log("Add to scene",this.asset);let o=Pg.currentlyInstantiating.get(this.uri);if(o!==void 0&&o>=1e4)return console.error("Recursive or too many instantiations of "+this.uri+" in the same frame ("+o+")"),null;try{if(o===void 0&&(o=0),o+=1,Pg.currentlyInstantiating.set(this.uri,o),e){s.context=r;const a=this.asset;a.guid=this.uri;const l=ek(a,s,void 0,t);if(l)return l}else{const a=Gg(this.asset,s);if(a)return a}}finally{r.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,Pg.currentlyInstantiating.set(this.uri,o)})}}else Fu&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(n){if(n&&n.scene){const e=n.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};let ti=Pg;d(ti,"currentlyInstantiating",new Map);class lue extends wa{constructor(){super([ti],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ti.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof ye){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const r=e,s=t.context,o=r.guid??r.uuid,a=s.addressables.findAssetReference(o);if(a)return a;const l=new ti(o,void 0,r);return s.addressables.registerAssetReference(l),l}return null}}new lue;const cue=Promise.resolve(null),V1=class{constructor(n){d(this,"url"),d(this,"_bitmap"),d(this,"_bitmapObject"),d(this,"loader",null),this.url=n}static getOrCreate(n){let e=V1.imageReferences.get(n);return e||(e=new V1(n),V1.imageReferences.set(n,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const n=new Image;return n.src=this.url,n}createTexture(){return this.url?(this.loader||(this.loader=new Dl),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):cue}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((n,e)=>{const t=document.createElement("img");t.addEventListener("load",()=>{this._bitmap=createImageBitmap(t).then(r=>(this._bitmapObject=r,n(r),r))}),t.addEventListener("error",r=>{console.error("Failed to load image:"+this.url,r),n(null)}),t.src=this.url}),this._bitmap)}};let Q1=V1;d(Q1,"imageReferences",new Map);class M6 extends wa{constructor(){super([Q1],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return Q1.getOrCreate(r)}}}new M6;const H1=class{constructor(n){d(this,"url"),d(this,"res"),this.url=n}static getOrCreate(n){let e=H1.cache.get(n);return e||(e=new H1(n),H1.cache.set(n,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.text())}};let W1=H1;d(W1,"cache",new Map);class T6 extends wa{constructor(){super([W1],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return W1.getOrCreate(r)}}}new T6;class hue{constructor(e){d(this,"context"),d(this,"mixers",[]),this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e)return;const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Bg{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const r of e.children)this.tryGetAnimationClipsFromObjectHierarchy(r,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations)return;for(let s=0;s<e.animations.length;s++){const o=e.animations[s];if(!(!o.tracks||o.tracks.length<=0))for(const a in o.tracks){const l=o.tracks[a],c=Xt.parseTrackName(l.name);let h=Xt.findNode(e.scene,c.nodeName);if(!h){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(h=e.scene.getObjectByProperty("uuid",p),!h)continue}let u=r(h);if(!u){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=t.createAnimationComponent(e.scene,o)}u.addClip&&u.addClip(o)}}function r(s){var o;if(!s)return null;const a=(o=s.userData)==null?void 0:o.components;if(a&&a.length>0){for(let l=0;l<a.length;l++)if(a[l].isAnimationComponent===!0)return s}return r(s.parent)}}}const kg=[];function X1(n){kg.indexOf(n)===-1&&kg.push(n)}function uue(n){const e=kg.indexOf(n);e!==-1&&kg.splice(e,1)}const Dg=[];function mB(n){Dg.indexOf(n)===-1&&Dg.push(n)}function due(n){const e=Dg.indexOf(n);e!==-1&&Dg.splice(e,1)}function I6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:n}));for(let e=0;e<kg.length;e++)kg[e](n)}function R6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:n}));for(let e=0;e<Dg.length;e++)Dg[e](n)}const wr={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function P6(n){const e=await fetch(n);if(e.ok)return e.json();throw new Error(e.statusText)}async function pue(n){if(!n)throw new Error("No basePath supplied");return await P6(`${n}/profilesList.json`)}async function mue(n,e,t=null,r=!0){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const s=await pue(e);let o;if(n.profiles.some(c=>{const h=s[c];return h&&(o={profileId:c,profilePath:`${e}/${h.path}`,deprecated:!!h.deprecated}),!!o}),!o){if(!t)throw new Error("No matching profile name found");const c=s[t];if(!c)throw new Error(`No matching profile name found and default profile "${t}" missing.`);o={profileId:t,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}}const a=await P6(o.profilePath);let l;if(r){let c;if(n.handedness==="any"?c=a.layouts[Object.keys(a.layouts)[0]]:c=a.layouts[n.handedness],!c)throw new Error(`No matching handedness, ${n.handedness}, in profile ${o.profileId}`);c.assetPath&&(l=o.profilePath.replace("profile.json",c.assetPath))}return{profile:a,assetPath:l}}const fue={xAxis:0,yAxis:0,button:0,state:wr.ComponentState.DEFAULT};function gue(n=0,e=0){let t=n,r=e;if(Math.sqrt(n*n+e*e)>1){const s=Math.atan2(e,n);t=Math.cos(s),r=Math.sin(s)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:r*.5+.5}}let vue=class{constructor(n){this.componentProperty=n.componentProperty,this.states=n.states,this.valueNodeName=n.valueNodeName,this.valueNodeProperty=n.valueNodeProperty,this.valueNodeProperty===wr.VisualResponseProperty.TRANSFORM&&(this.minNodeName=n.minNodeName,this.maxNodeName=n.maxNodeName),this.value=0,this.updateFromComponent(fue)}updateFromComponent({xAxis:n,yAxis:e,button:t,state:r}){const{normalizedXAxis:s,normalizedYAxis:o}=gue(n,e);switch(this.componentProperty){case wr.ComponentProperty.X_AXIS:this.value=this.states.includes(r)?s:.5;break;case wr.ComponentProperty.Y_AXIS:this.value=this.states.includes(r)?o:.5;break;case wr.ComponentProperty.BUTTON:this.value=this.states.includes(r)?t:0;break;case wr.ComponentProperty.STATE:this.valueNodeProperty===wr.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(r):this.value=this.states.includes(r)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},yue=class{constructor(n,e){if(!n||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=n,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const r=new vue(e.visualResponses[t]);this.visualResponses[t]=r}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:wr.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(n){if(this.values.state=wr.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&n.buttons.length>this.gamepadIndices.button){const e=n.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=wr.ComponentState.PRESSED:(e.touched||this.values.button>wr.ButtonTouchThreshold)&&(this.values.state=wr.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&n.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=n.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===wr.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&n.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=n.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===wr.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},Aue=class{constructor(n,e,t){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=n,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[n.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(r=>{const s=this.layoutDescription.components[r];this.components[r]=new yue(r,s)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const n=[];return Object.values(this.components).forEach(e=>{n.push(e.data)}),n}updateFromGamepad(){Object.values(this.components).forEach(n=>{n.updateFromGamepad(this.xrInputSource.gamepad)})}};const Js=new C,B6=new C,k6=new Ce,bue=te("debuggizmos"),Wl=8947848,Xl=class{constructor(){}static isGizmo(n){return n[gB]!==void 0}static DrawLabel(n,e,t=.05,r=0,s,o,a){var l;if(!Xl.enabled)return null;s||(s=Wl);const c=((l=wt.active)==null?void 0:l.rigScale)??1,h=En.getTextLabel(r,e,t*c,s,o);return a instanceof ye&&a.add(h),h.position.x=n.x,h.position.y=n.y,h.position.z=n.z,h}static DrawRay(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),Js.set(e.x,e.y,e.z).multiplyScalar(999999999),a.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawDirection(n,e,t=Wl,r=0,s=!0,o=1){if(!Xl.enabled)return;const a=En.getLine(r),l=a.geometry.getAttribute("position");l.setXYZ(0,n.x,n.y,n.z),e.w!==void 0?(Js.set(0,0,-o),k6.set(e.x,e.y,e.z,e.w),Js.applyQuaternion(k6)):(Js.set(e.x,e.y,e.z),Js.multiplyScalar(o)),l.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),l.needsUpdate=!0,a.material.color.set(t),a.material.depthTest=s,a.material.depthWrite=!1}static DrawLine(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),a.setXYZ(1,e.x,e.y,e.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!0);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!1);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawWireBox(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getBox(r);o.position.set(n.x,n.y,n.z),o.scale.set(e.x,e.y,e.z),o.material.color.set(t),o.material.depthTest=s,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(n,e=Wl,t=0,r=!0){if(!Xl.enabled)return;const s=En.getBox(t);s.position.copy(n.getCenter(Js)),s.scale.copy(n.getSize(Js)),s.material.color.set(e),s.material.depthTest=r,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1}static DrawArrow(n,e,t=Wl,r=0,s=!0,o=!1){if(!Xl.enabled)return;const a=En.getArrowHead(r);a.position.set(e.x,e.y,e.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).normalize());const l=Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).length()*.1;a.scale.set(l,l,l),a.material.color.set(t),a.material.depthTest=s,a.material.wireframe=o,this.DrawLine(n,e,t,r,s)}static DrawWireMesh(n){const e=En.getMesh(n.duration??0);"mesh"in n?(e.geometry=n.mesh.geometry,e.matrix.copy(n.mesh.matrixWorld)):(e.geometry=n.geometry,e.matrix.copy(n.matrix)),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1,e.material.color.set(n.color??Wl),e.material.depthTest=n.depthTest??!0,e.material.wireframe=!0}};let At=Xl;d(At,"enabled",!0),d(At,"_up",new C(0,1,0));const _ue=new qi(1,1,1);function fB(n=null){const e=new xe(n??14540253),t=new iI(_ue);return new gs(t,new Gi({color:e}))}const gB=Symbol("GizmoCache");class En{static ensureFont(){let e=Ni.FontLibrary.getFontFamily(this.familyName);if(!e){e=Ni.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Ni.update()})}}static getTextLabel(e,t,r,s,o){this.ensureFont();let a=this.textLabelCache.pop(),l=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(l=parseInt(o.substring(7),16)/255,o=o.substring(0,7),bue&&console.log(o,l)):typeof o=="object"&&o.a!==void 0&&(l=o.a);const c={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:r,color:s,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:l,textContent:t,borderRadius:.5*r,padding:.8*r,whiteSpace:"pre"};if(a)a.set(c);else{a=new fR(c);const h=this,u=a;u.setText=function(p){this.set({textContent:p}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(kt.Current,a,e,this.textLabelCache),a}static getBox(e){let t=this.boxesCache.pop();if(!t){const r=new qi(1,1,1);t=new me(r)}return this.registerTimedObject(kt.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Sn;let r=t.geometry.getAttribute("position");r||(r=new nt(new Float32Array(2*3),3),t.geometry.setAttribute("position",r))}return t.frustumCulled=!1,this.registerTimedObject(kt.Current,t,e,this.linesCache),t}static getSphere(e,t,r){let s=this.spheresCache.pop();return s||(s=new me(new ja(1,8,8))),s.scale.set(e,e,e),s.material.wireframe=r,this.registerTimedObject(kt.Current,s,t,this.spheresCache),s}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new me(new jn(0,.5,1,8))),this.registerTimedObject(kt.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new me,t.material=new $t),this.registerTimedObject(kt.Current,t,e,this.mesh),t}static registerTimedObject(e,t,r,s){const o=this.contextBeforeRenderCallbacks.get(e),a=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const l=e.pre_render_callbacks.indexOf(o);l>=0&&e.pre_render_callbacks.splice(l,1),e.pre_render_callbacks.push(o)}}else{const l=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,l),e.pre_render_callbacks.push(l)}if(a){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==a){const l=e.post_render_callbacks.indexOf(a);l>=0&&e.post_render_callbacks.splice(l,1),e.post_render_callbacks.push(a)}}else{const l=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,l),e.post_render_callbacks.push(l)}t.traverse(l=>{l.layers.disableAll(),l.layers.enable(2)}),t.renderOrder=999999,t[gB]=s,t.isGizmo=!0,this.timedObjectsBuffer.push(t),r<=0&&e.currentFrameEvent>=Hi.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(kt.Current.time.realtimeSinceStartup+r),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&Ni.update();for(let r=0;r<t.length;r++){const s=t[r];if(e.mainCamera&&s instanceof Ni.MeshUIBaseElement){if(Jp(s))continue;const o=e.isInVR,a=!1,l=!o;Hv(s,e.mainCamera,a,l)}}}static onPostRender(e,t,r){const s=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const a=t[o];s>r[o]&&(t.splice(o,1),r.splice(o,1),a.removeFromParent(),Jp(a)!=!0&&a[gB].push(a))}}}d(En,"familyName","needle-gizmos"),d(En,"linesCache",[]),d(En,"spheresCache",[]),d(En,"boxesCache",[]),d(En,"arrowHeadsCache",[]),d(En,"mesh",[]),d(En,"textLabelCache",[]),d(En,"timedObjectsBuffer",new Array),d(En,"timesBuffer",new Array),d(En,"contextPostRenderCallbacks",new Map),d(En,"contextBeforeRenderCallbacks",new Map),d(En,"tmuiNeedsUpdate",!1);const cr=te("debuginput");var q1=(n=>(n.Mouse="mouse",n.Touch="touch",n.Controller="controller",n.Hand="hand",n))(q1||{}),an=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(an||{});class mh extends PointerEvent{constructor(e,t,r){super(e,r),d(this,"deviceIndex"),d(this,"origin"),d(this,"source"),d(this,"mode"),d(this,"_ray"),d(this,"space"),d(this,"isClick",!1),d(this,"isDoubleClick",!1),d(this,"_used",!1),d(this,"_pointerid"),d(this,"_pointerType"),d(this,"_type"),d(this,"metadata",{}),d(this,"intersections",new Array),d(this,"_immediatePropagationStopped",!1),d(this,"_propagationStopped",!1),this._pointerid=r.pointerId,this._pointerType=r.pointerType,this._type=e,this.deviceIndex=r.deviceIndex,this.origin=r.origin,this.source=t,this.mode=r.mode,this._ray=r.ray,this.space=r.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new co(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(),cr&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Xy extends KeyboardEvent{constructor(e,t,r){super(e,r),d(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class xue{constructor(e){d(this,"key"),d(this,"keyType"),d(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var ql=(n=>(n[n.Early=-100]="Early",n[n.Default=0]="Default",n[n.Late=100]="Late",n))(ql||{});class D6{constructor(e){d(this,"_eventListeners",{}),d(this,"_doubleClickTimeThreshold",.2),d(this,"_longPressTimeThreshold",1),d(this,"_specialCursorTrigger",0),d(this,"context"),d(this,"_pointerDown",[!1]),d(this,"_pointerUp",[!1]),d(this,"_pointerClick",[!1]),d(this,"_pointerDoubleClick",[!1]),d(this,"_pointerPressed",[!1]),d(this,"_pointerPositions",[new Z]),d(this,"_pointerPositionsLastFrame",[new Z]),d(this,"_pointerPositionsDelta",[new Z]),d(this,"_pointerPositionsRC",[new Z]),d(this,"_pointerPositionDown",[new Z]),d(this,"_pointerDownTime",[]),d(this,"_pointerUpTime",[]),d(this,"_pointerUpTimestamp",[]),d(this,"_pointerIds",[]),d(this,"_pointerTypes",[""]),d(this,"_mouseWheelChanged",[!1]),d(this,"_mouseWheelDeltaY",[0]),d(this,"_pointerEvent",[]),d(this,"_pointerUsed",[]),d(this,"_pointerSpace",[]),d(this,"_pressedStack",new Map),d(this,"_htmlEventSource"),d(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),d(this,"onEndOfFrame",()=>{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}),d(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),d(this,"keysPressed",{}),d(this,"onKeyDown",t=>{if(cr&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(r&&r.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 s=new Xy("keydown",t,t);this.onDispatchEvent(s)}),d(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!0,r.frame=this.context.time.frameCount+1;const s=new Xy("keypress",t,t);this.onDispatchEvent(s)}),d(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!1,r.frame=this.context.time.frameCount+1;const s=new Xy("keyup",t,t);this.onDispatchEvent(s)}),d(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),d(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 r=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=r+t.deltaY}),d(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const r=this.getPointerId(t);cr&&rn(`pointer down #${r}, identifier:${t.pointerId}`);const s=this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),o=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:s,pressure:t.pressure});this.onDown(o)}),d(this,"onPointerMove",t=>{if(this.context.isInAR)return;let r=t.button;t.pointerType==="mouse"&&(r=this.getFirstPressedButtonForPointer(0)??0);const s=this.getPointerId(t,r);r===-1&&(r=s);const o=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),a=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:r,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:o,pressure:t.pressure});this.onMove(a)}),d(this,"onPointerCancel",t=>{this.context.isInAR||(cr&&console.log("Pointer cancel",t),this.onPointerUp(t))}),d(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const r=this.getPointerId(t),s=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),pressure:t.pressure});this.onUp(s),this._pointerIds[r]=-1,cr&&console.log("ID="+r,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),d(this,"onTouchStart",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onDown(l)}}),d(this,"onTouchMove",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onMove(l)}}),d(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),pressure:s.force});this.onUp(a),this._pointerIds[o]=-1}}),d(this,"tempNearPlaneVector",new C),d(this,"tempFarPlaneVector",new C),d(this,"tempLookMatrix",new ve),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,r){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}r?r={...r}:r={};let s=0;r?.queue!=null&&(s=r.queue);const o=this._eventListeners[e],a=o.find(l=>l.priority===s);a?a.listeners.push({callback:t,options:r}):(o.push({priority:s,listeners:[{callback:t,options:r}]}),o.sort((l,c)=>l.priority-c.priority))}removeEventListener(e,t,r){if(!this._eventListeners[e]||!t)return;const s=this._eventListeners[e];if(r?.queue!=null){const o=s.find(l=>l.priority===r.queue);if(!o)return;const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}else for(const o of s){const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}}dispatchEvent(e){var t,r,s,o;let a=!1;if(e instanceof Xy){const l=this._eventListeners[e.type];if(l)for(const c of l)for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((r=(t=u.options)==null?void 0:t.signal)!=null&&r.aborted){c.listeners.splice(h,1),h--;continue}u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}if(e instanceof mh){const l=this._eventListeners[e.type];if(l)for(const c of l){if(a)break;for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((o=(s=u.options)==null?void 0:s.signal)!=null&&o.aborted){c.listeners.splice(h,1),h--;continue}if(e.immediatePropagationStopped){a=!0,cr&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(a=!0,cr&&console.log("propagationStopped",e.type));u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}}}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)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(e,t=!0){if(e>=this._pointerUsed.length){if(e>=this._pointerIds.length)return;for(;this._pointerUsed.length<=e;)this._pointerUsed.push(!1)}this._pointerUsed[e]=t}getPointerUsed(e){return e>=this._pointerUsed.length?!1:this._pointerUsed[e]}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const r=this._pointerTypes[t];if(Array.isArray(e)){let s=!1;for(const o of e)if(r===o){s=!0;break}if(!s)continue}else if(e!==r)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let r=this._pressedStack.get(e);r||(r=[],this._pressedStack.set(e,r)),r.push(t)}onReleaseButton(e,t){const r=this._pressedStack.get(e);if(!r)return;const s=r.indexOf(t);s>=0&&r.splice(s,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyDown(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.startFrame)===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyUp(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.frame)===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyPressed(s))return!0;return!1}return(t=this.keysPressed[e])==null?void 0:t.pressed}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":cr&&rn("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":cr&&rn("Create Pointer move"),this.onMove(e);break;case"pointerup":cr&&rn("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}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 e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(t=this._htmlEventSource)==null||t.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 e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&gp()?!0:(cr&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,r){let s=this._pointerSpace[e];s||(s=new ye,this._pointerSpace[e]=s),this._pointerSpace[e]=s;const o=this.context.mainCamera;if(o){const a=this.tempNearPlaneVector.set(t,r,-1);this.convertScreenspaceToRaycastSpace(a);const l=this.tempFarPlaneVector.set(a.x,a.y,1);a.unproject(o),l.unproject(o);const c=o.worldUp||pi(0,1,0).applyQuaternion(Mi(o));this.tempLookMatrix.lookAt(l,a,c),s.position.set(a.x,a.y,a.z),s.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return s}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),r=e.clientX,s=e.clientY,o=r>=t.x&&r<=t.right&&s>=t.y&&s<=t.bottom;return cr&&!o&&console.log("Not in rect",t,r,s),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`pointerId is already pressed: ${t}`,cr?e:""),cr&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new Z);for(this._pointerPositionDown[t].set(e.clientX,e.clientY);t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,r=this.getPointerPressed(t);r===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!r||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){cr&&console.log(e.pointerType,"UP",t,"was not down");return}for(cr&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0);t>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t,this._pointerUsed,!1),this.updatePointerPosition(e),!this._pointerPositionDown[t]){cr&&Di("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const r=e.clientX-this._pointerPositionDown[t].x,s=e.clientY-this._pointerPositionDown[t].y;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(r)<5&&Math.abs(s)<5){cr&&console.log("CLICK",t),this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const o=this._pointerUpTime[t],a=this.context.time.time-o;a<this._doubleClickTimeThreshold&&a>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}this._pointerUpTime[t]=this.context.time.time,this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Z);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Z);const r=this._pointerPositionsLastFrame[t];r.copy(this._pointerPositions[t]);const s=this._pointerPositionsDelta[t];let o=e.clientX-r.x,a=e.clientY-r.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;o===0&&u.movementX!==0&&(o=u.movementX||0),a===0&&u.movementY!==0&&(a=u.movementY||0)}s.x+=o,s.y+=a,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const l=e.clientX,c=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new Z);const h=this._pointerPositionsRC[t];h.set(l,c),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(e){let t=-1;for(let r=0;r<this._pointerIds.length;r++){if(this._pointerIds[r]===e)return r;t===-1&&this._pointerIds[r]===-1&&(t=r)}return t!==-1?(this._pointerIds[t]=e,t):(cr&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,r){t[e]=r}setPointerStateT(e,t,r){return t[e]=r,r}onDispatchEvent(e){const t=kt.Current;try{kt.Current=this.context,this.dispatchEvent(e)}finally{kt.Current=t}}}const Y1=new ve().makeRotationY(Math.PI),Sa=new Ce().setFromAxisAngle(new C(0,1,0),Math.PI),wue=te("debugwebxr");class Sue{constructor(){if(d(this,"priority",-1e5),d(this,"gameObject"),this.gameObject=new ye,this.gameObject.name="Implicit XR Rig",wue){const e=fB(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const Uu=te("debugwebxr"),J1=te("debugcustomgesture"),Cue="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",Eue="generic-trigger";class vB{constructor(e,t,r){d(this,"xr"),d(this,"inputSource"),d(this,"index",0),d(this,"emitEvents",!0),d(this,"_connected",!0),d(this,"_isTracking",!1),d(this,"_hitTestSource"),d(this,"_hasSelectEvent",!1),d(this,"_handJointPoses",new Map),d(this,"_gripPosition",new C),d(this,"_gripQuaternion",new Ce),d(this,"_linearVelocity",new C),d(this,"_rayPosition",new C),d(this,"_rayQuaternion",new Ce),d(this,"_gripWorldPosition",new C),d(this,"_gripWorldQuaternion",new Ce),d(this,"_rayWorldPosition",new C),d(this,"_rayWorldQuaternion",new Ce),d(this,"_ray"),d(this,"_object"),d(this,"model",null),d(this,"_debugAxesHelper",new Po(.2)),d(this,"onPointerHits",l=>{}),d(this,"_needleGamepadButtons",{}),d(this,"_buttonMap",new Map),d(this,"_motioncontroller"),d(this,"_layout"),d(this,"getMotionController"),d(this,"_selectButtonIndex"),d(this,"_squeezeButtonIndex"),d(this,"onSelectStart",l=>{var c,h,u,p;if(this.inputSource!==l.inputSource)return;this.onUpdateFrame(l.frame),this._hasSelectEvent=!0;const m=(c=this._layout)==null?void 0:c.selectComponentId,f=(p=(u=(h=this._layout)==null?void 0:h.components[m])==null?void 0:u.gamepadIndices)==null?void 0:p.button;f!==void 0&&(this._selectButtonIndex=f),!J1&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(an.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,l))}),d(this,"onSelectEnd",l=>{J1||this.inputSource===l.inputSource&&this.emitPointerEvent(an.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,l)}),d(this,"onSequeezeStart",l=>{var c,h,u;this.inputSource===l.inputSource&&(this._squeezeButtonIndex=(u=(h=(c=this._layout)==null?void 0:c.components["xr-standard-squeeze"])==null?void 0:h.gamepadIndices)==null?void 0:u.button,this._squeezeButtonIndex!==void 0&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(an.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)))}),d(this,"onSequeezeEnd",l=>{this.inputSource===l.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(an.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)}),d(this,"states",{}),d(this,"_didMoveLastFrame",!1),d(this,"_lastPointerMovePosition",new C),d(this,"_lastPointerMoveQuaternion",new Ce),d(this,"pointerInit");var s,o,a;this.xr=e,this.inputSource=t,this.index=r,this._object=new ye,Uu&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new co,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(),this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&((a=(o=(s=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:o.call(s,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||a.then(l=>this._hitTestSource=l))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return 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.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e){var t,r;if(!this.hand||!((t=this.xr.frame)!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let s=(r=this._handJointPoses)==null?void 0:r.get(e);return s||(s=this.xr.frame.getJointPose(e,this.xr.referenceSpace),s&&this._handJointPoses.set(e,s),s)}get gripPosition(){return pi(this._gripPosition).applyMatrix4(Y1)}get gripQuaternion(){return bp(this._gripQuaternion).premultiply(Sa)}get gripLinearVelocity(){return pi(this._linearVelocity).applyQuaternion(Sa)}get rayPosition(){return pi(this._rayPosition).applyMatrix4(Y1)}get rayQuaternion(){return bp(this._rayQuaternion).premultiply(Sa)}get gripWorldPosition(){return pi(this._gripWorldPosition)}get gripWorldQuaternion(){return bp(this._gripWorldQuaternion)}get rayWorldPosition(){return pi(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPosition),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return bp(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,r=t?Mi(t):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(Sa),r&&this._rayWorldQuaternion.premultiply(r)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(pi(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;At.DrawWireSphere(this.rayWorldPosition,.02),At.DrawDirection(this.rayWorldPosition,pi(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),r=this.inputSource.profiles.join(`
5152
5152
  `);let s=`Controller[${this.index}] ${this.side}
5153
5153
  C:${this.connected?"yes":"no"} T:${this.isTracking?"yes":"no"} Hand:${this.inputSource.hand?"yes":"no"}`;this.inputSource.hand&&(s+=`
5154
5154
  Pinch: ${(e=this.getGesture("pinch"))==null?void 0:e.value.toFixed(3)}`),s+=`
@@ -5229,15 +5229,15 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
5229
5229
  isIOS:`).concat(this.isIOS,`
5230
5230
  isWebRTCSupported:`).concat(this.isWebRTCSupported(),`
5231
5231
  isBrowserSupported:`).concat(this.isBrowserSupported(),`
5232
- isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},n}()),FG={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},Hue=function(){function n(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=FG,this.browser=Zy.getBrowser(),this.browserVersion=Zy.getVersion(),this.supports=function(){var e={browser:Zy.isBrowserSupported(),webRTC:Zy.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!e.webRTC)return e;var t;try{t=new RTCPeerConnection(FG),e.audioVideo=!0;var r=void 0;try{r=t.createDataChannel("_PEERJSTEST",{ordered:!0}),e.data=!0,e.reliable=!!r.ordered;try{r.binaryType="blob",e.binaryBlob=!Zy.isIOS}catch{}}catch{}finally{r&&r.close()}}catch{}finally{t&&t.close()}return e}(),this.pack=Q6.pack,this.unpack=Q6.unpack,this._dataCount=1}return n.prototype.noop=function(){},n.prototype.validateId=function(e){return!e||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(e)},n.prototype.chunk=function(e){for(var t=[],r=e.size,s=Math.ceil(r/wi.chunkedMTU),o=0,a=0;a<r;){var l=Math.min(r,a+wi.chunkedMTU),c=e.slice(a,l),h={__peerData:this._dataCount,n:o,data:c,total:s};t.push(h),a=l,o++}return this._dataCount++,t},n.prototype.blobToArrayBuffer=function(e,t){var r=new FileReader;return r.onload=function(s){s.target&&t(s.target.result)},r.readAsArrayBuffer(e),r},n.prototype.binaryStringToArrayBuffer=function(e){for(var t=new Uint8Array(e.length),r=0;r<e.length;r++)t[r]=e.charCodeAt(r)&255;return t.buffer},n.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},n.prototype.isSecure=function(){return location.protocol==="https:"},n}(),wi=new Hue,UG={};Kl(UG,"Peer",()=>UB,n=>UB=n);var $y={},Wue=Object.prototype.hasOwnProperty,Ks="~";function eA(){}Object.create&&(eA.prototype=Object.create(null),new eA().__proto__||(Ks=!1));function Xue(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function NG(n,e,t,r,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Xue(t,r||n,s),a=Ks?Ks+e:e;return n._events[a]?n._events[a].fn?n._events[a]=[n._events[a],o]:n._events[a].push(o):(n._events[a]=o,n._eventsCount++),n}function rS(n,e){--n._eventsCount===0?n._events=new eA:delete n._events[e]}function Cs(){this._events=new eA,this._eventsCount=0}Cs.prototype.eventNames=function(){var n=[],e,t;if(this._eventsCount===0)return n;for(t in e=this._events)Wue.call(e,t)&&n.push(Ks?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},Cs.prototype.listeners=function(n){var e=Ks?Ks+n:n,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,o=new Array(s);r<s;r++)o[r]=t[r].fn;return o},Cs.prototype.listenerCount=function(n){var e=Ks?Ks+n:n,t=this._events[e];return t?t.fn?1:t.length:0},Cs.prototype.emit=function(n,e,t,r,s,o){var a=Ks?Ks+n:n;if(!this._events[a])return!1;var l=this._events[a],c=arguments.length,h,u;if(l.fn){switch(l.once&&this.removeListener(n,l.fn,void 0,!0),c){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,e),!0;case 3:return l.fn.call(l.context,e,t),!0;case 4:return l.fn.call(l.context,e,t,r),!0;case 5:return l.fn.call(l.context,e,t,r,s),!0;case 6:return l.fn.call(l.context,e,t,r,s,o),!0}for(u=1,h=new Array(c-1);u<c;u++)h[u-1]=arguments[u];l.fn.apply(l.context,h)}else{var p=l.length,m;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(n,l[u].fn,void 0,!0),c){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,e);break;case 3:l[u].fn.call(l[u].context,e,t);break;case 4:l[u].fn.call(l[u].context,e,t,r);break;default:if(!h)for(m=1,h=new Array(c-1);m<c;m++)h[m-1]=arguments[m];l[u].fn.apply(l[u].context,h)}}return!0},Cs.prototype.on=function(n,e,t){return NG(this,n,e,t,!1)},Cs.prototype.once=function(n,e,t){return NG(this,n,e,t,!0)},Cs.prototype.removeListener=function(n,e,t,r){var s=Ks?Ks+n:n;if(!this._events[s])return this;if(!e)return rS(this,s),this;var o=this._events[s];if(o.fn)o.fn===e&&(!r||o.once)&&(!t||o.context===t)&&rS(this,s);else{for(var a=0,l=[],c=o.length;a<c;a++)(o[a].fn!==e||r&&!o[a].once||t&&o[a].context!==t)&&l.push(o[a]);l.length?this._events[s]=l.length===1?l[0]:l:rS(this,s)}return this},Cs.prototype.removeAllListeners=function(n){var e;return n?(e=Ks?Ks+n:n,this._events[e]&&rS(this,e)):(this._events=new eA,this._eventsCount=0),this},Cs.prototype.off=Cs.prototype.removeListener,Cs.prototype.addListener=Cs.prototype.on,Cs.prefixed=Ks,Cs.EventEmitter=Cs,$y=Cs;var dt={};Kl(dt,"LogLevel",()=>yo,n=>yo=n),Kl(dt,"default",()=>zG,n=>zG=n);var Xp=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},qp=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},que="PeerJS: ",yo;(function(n){n[n.Disabled=0]="Disabled",n[n.Errors=1]="Errors",n[n.Warnings=2]="Warnings",n[n.All=3]="All"})(yo||(yo={}));var Yue=function(){function n(){this._logLevel=yo.Disabled}return Object.defineProperty(n.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){this._logLevel=e},enumerable:!1,configurable:!0}),n.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.All&&this._print.apply(this,qp([yo.All],Xp(e),!1))},n.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.Warnings&&this._print.apply(this,qp([yo.Warnings],Xp(e),!1))},n.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.Errors&&this._print.apply(this,qp([yo.Errors],Xp(e),!1))},n.prototype.setLogFunction=function(e){this._print=e},n.prototype._print=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var s=qp([que],Xp(t),!1);for(var o in s)s[o]instanceof Error&&(s[o]="("+s[o].name+") "+s[o].message);e>=yo.All?console.log.apply(console,qp([],Xp(s),!1)):e>=yo.Warnings?console.warn.apply(console,qp(["WARNING"],Xp(s),!1)):e>=yo.Errors&&console.error.apply(console,qp(["ERROR"],Xp(s),!1))},n}(),zG=new Yue,jG={};Kl(jG,"Socket",()=>GG,n=>GG=n);var pl;(function(n){n.Data="data",n.Media="media"})(pl||(pl={}));var Fn;(function(n){n.BrowserIncompatible="browser-incompatible",n.Disconnected="disconnected",n.InvalidID="invalid-id",n.InvalidKey="invalid-key",n.Network="network",n.PeerUnavailable="peer-unavailable",n.SslUnavailable="ssl-unavailable",n.ServerError="server-error",n.SocketError="socket-error",n.SocketClosed="socket-closed",n.UnavailableID="unavailable-id",n.WebRTC="webrtc"})(Fn||(Fn={}));var gh;(function(n){n.Binary="binary",n.BinaryUTF8="binary-utf8",n.JSON="json"})(gh||(gh={}));var vh;(function(n){n.Message="message",n.Disconnected="disconnected",n.Error="error",n.Close="close"})(vh||(vh={}));var Qr;(function(n){n.Heartbeat="HEARTBEAT",n.Candidate="CANDIDATE",n.Offer="OFFER",n.Answer="ANSWER",n.Open="OPEN",n.Error="ERROR",n.IdTaken="ID-TAKEN",n.InvalidKey="INVALID-KEY",n.Leave="LEAVE",n.Expire="EXPIRE"})(Qr||(Qr={}));var kB={};kB=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz St\xFCckler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","So\u0308ren Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var Jue=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Kue=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},Zue=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},$ue=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},GG=function(n){Jue(e,n);function e(t,r,s,o,a,l){l===void 0&&(l=5e3);var c=n.call(this)||this;c.pingInterval=l,c._disconnected=!0,c._messagesQueue=[];var h=t?"wss://":"ws://";return c._baseUrl=h+r+":"+s+o+"peerjs?key="+a,c}return e.prototype.start=function(t,r){var s=this;this._id=t;var o="".concat(this._baseUrl,"&id=").concat(t,"&token=").concat(r);this._socket||!this._disconnected||(this._socket=new WebSocket(o+"&version="+kB.version),this._disconnected=!1,this._socket.onmessage=function(a){var l;try{l=JSON.parse(a.data),dt.default.log("Server message received:",l)}catch{dt.default.log("Invalid server message",a.data);return}s.emit(vh.Message,l)},this._socket.onclose=function(a){s._disconnected||(dt.default.log("Socket closed.",a),s._cleanup(),s._disconnected=!0,s.emit(vh.Disconnected))},this._socket.onopen=function(){s._disconnected||(s._sendQueuedMessages(),dt.default.log("Socket open"),s._scheduleHeartbeat())})},e.prototype._scheduleHeartbeat=function(){var t=this;this._wsPingTimer=setTimeout(function(){t._sendHeartbeat()},this.pingInterval)},e.prototype._sendHeartbeat=function(){if(!this._wsOpen()){dt.default.log("Cannot send heartbeat, because socket closed");return}var t=JSON.stringify({type:Qr.Heartbeat});this._socket.send(t),this._scheduleHeartbeat()},e.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},e.prototype._sendQueuedMessages=function(){var t,r,s=Zue([],Kue(this._messagesQueue),!1);this._messagesQueue=[];try{for(var o=$ue(s),a=o.next();!a.done;a=o.next()){var l=a.value;this.send(l)}}catch(c){t={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}},e.prototype.send=function(t){if(!this._disconnected){if(!this._id){this._messagesQueue.push(t);return}if(!t.type){this.emit(vh.Error,"Invalid message");return}if(this._wsOpen()){var r=JSON.stringify(t);this._socket.send(r)}}},e.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},e.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},e}($y.EventEmitter),DB={};Kl(DB,"MediaConnection",()=>HG,n=>HG=n);var OB={};Kl(OB,"Negotiator",()=>VG,n=>VG=n);var sS=function(){return sS=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},sS.apply(this,arguments)},oS=function(n,e,t,r){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function l(u){try{h(r.next(u))}catch(p){a(p)}}function c(u){try{h(r.throw(u))}catch(p){a(p)}}function h(u){u.done?o(u.value):s(u.value).then(l,c)}h((r=r.apply(n,e||[])).next())})},aS=function(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,s&&(o=h[0]&2?s.return:h[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,h[1])).done)return o;switch(s=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){t.label=h[1];break}if(h[0]===6&&t.label<o[1]){t.label=o[1],o=h;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(h);break}o[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(n,t)}catch(u){h=[6,u],s=0}finally{r=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}},VG=function(){function n(e){this.connection=e}return n.prototype.startConnection=function(e){var t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===pl.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){if(this.connection.type===pl.Data){var r=this.connection,s={ordered:!!e.reliable},o=t.createDataChannel(r.label,s);r.initialize(o)}this._makeOffer()}else this.handleSDP("OFFER",e.sdp)},n.prototype._startPeerConnection=function(){dt.default.log("Creating RTCPeerConnection.");var e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e},n.prototype._setupListeners=function(e){var t=this,r=this.connection.peer,s=this.connection.connectionId,o=this.connection.type,a=this.connection.provider;dt.default.log("Listening for ICE candidates."),e.onicecandidate=function(l){!l.candidate||!l.candidate.candidate||(dt.default.log("Received ICE candidates for ".concat(r,":"),l.candidate),a.socket.send({type:Qr.Candidate,payload:{candidate:l.candidate,type:o,connectionId:s},dst:r}))},e.oniceconnectionstatechange=function(){switch(e.iceConnectionState){case"failed":dt.default.log("iceConnectionState is failed, closing connections to "+r),t.connection.emit("error",new Error("Negotiation of connection to "+r+" failed.")),t.connection.close();break;case"closed":dt.default.log("iceConnectionState is closed, closing connections to "+r),t.connection.emit("error",new Error("Connection to "+r+" closed.")),t.connection.close();break;case"disconnected":dt.default.log("iceConnectionState changed to disconnected on the connection with "+r);break;case"completed":e.onicecandidate=wi.noop;break}t.connection.emit("iceStateChanged",e.iceConnectionState)},dt.default.log("Listening for data channel"),e.ondatachannel=function(l){dt.default.log("Received data channel");var c=l.channel,h=a.getConnection(r,s);h.initialize(c)},dt.default.log("Listening for remote stream"),e.ontrack=function(l){dt.default.log("Received remote stream");var c=l.streams[0],h=a.getConnection(r,s);if(h.type===pl.Media){var u=h;t._addStreamToMediaConnection(c,u)}}},n.prototype.cleanup=function(){dt.default.log("Cleaning up PeerConnection to "+this.connection.peer);var e=this.connection.peerConnection;if(e){this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=function(){};var t=e.signalingState!=="closed",r=!1;if(this.connection.type===pl.Data){var s=this.connection,o=s.dataChannel;o&&(r=!!o.readyState&&o.readyState!=="closed")}(t||r)&&e.close()}},n.prototype._makeOffer=function(){return oS(this,void 0,Promise,function(){var e,t,r,s,o,a,l;return aS(this,function(c){switch(c.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,c.label=1;case 1:return c.trys.push([1,7,,8]),[4,e.createOffer(this.connection.options.constraints)];case 2:r=c.sent(),dt.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(r.sdp=this.connection.options.sdpTransform(r.sdp)||r.sdp),c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.setLocalDescription(r)];case 4:return c.sent(),dt.default.log("Set localDescription:",r,"for:".concat(this.connection.peer)),s={sdp:r,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:wi.browser},this.connection.type===pl.Data&&(o=this.connection,s=sS(sS({},s),{label:o.label,reliable:o.reliable,serialization:o.serialization})),t.socket.send({type:Qr.Offer,payload:s,dst:this.connection.peer}),[3,6];case 5:return a=c.sent(),a!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(Fn.WebRTC,a),dt.default.log("Failed to setLocalDescription, ",a)),[3,6];case 6:return[3,8];case 7:return l=c.sent(),t.emitError(Fn.WebRTC,l),dt.default.log("Failed to createOffer, ",l),[3,8];case 8:return[2]}})})},n.prototype._makeAnswer=function(){return oS(this,void 0,Promise,function(){var e,t,r,s,o;return aS(this,function(a){switch(a.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,a.label=1;case 1:return a.trys.push([1,7,,8]),[4,e.createAnswer()];case 2:r=a.sent(),dt.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(r.sdp=this.connection.options.sdpTransform(r.sdp)||r.sdp),a.label=3;case 3:return a.trys.push([3,5,,6]),[4,e.setLocalDescription(r)];case 4:return a.sent(),dt.default.log("Set localDescription:",r,"for:".concat(this.connection.peer)),t.socket.send({type:Qr.Answer,payload:{sdp:r,type:this.connection.type,connectionId:this.connection.connectionId,browser:wi.browser},dst:this.connection.peer}),[3,6];case 5:return s=a.sent(),t.emitError(Fn.WebRTC,s),dt.default.log("Failed to setLocalDescription, ",s),[3,6];case 6:return[3,8];case 7:return o=a.sent(),t.emitError(Fn.WebRTC,o),dt.default.log("Failed to create answer, ",o),[3,8];case 8:return[2]}})})},n.prototype.handleSDP=function(e,t){return oS(this,void 0,Promise,function(){var r,s,o,a;return aS(this,function(l){switch(l.label){case 0:t=new RTCSessionDescription(t),r=this.connection.peerConnection,s=this.connection.provider,dt.default.log("Setting remote description",t),o=this,l.label=1;case 1:return l.trys.push([1,5,,6]),[4,r.setRemoteDescription(t)];case 2:return l.sent(),dt.default.log("Set remoteDescription:".concat(e," for:").concat(this.connection.peer)),e!=="OFFER"?[3,4]:[4,o._makeAnswer()];case 3:l.sent(),l.label=4;case 4:return[3,6];case 5:return a=l.sent(),s.emitError(Fn.WebRTC,a),dt.default.log("Failed to setRemoteDescription, ",a),[3,6];case 6:return[2]}})})},n.prototype.handleCandidate=function(e){return oS(this,void 0,Promise,function(){var t,r,s,o,a,l;return aS(this,function(c){switch(c.label){case 0:dt.default.log("handleCandidate:",e),t=e.candidate,r=e.sdpMLineIndex,s=e.sdpMid,o=this.connection.peerConnection,a=this.connection.provider,c.label=1;case 1:return c.trys.push([1,3,,4]),[4,o.addIceCandidate(new RTCIceCandidate({sdpMid:s,sdpMLineIndex:r,candidate:t}))];case 2:return c.sent(),dt.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return l=c.sent(),a.emitError(Fn.WebRTC,l),dt.default.log("Failed to handleCandidate, ",l),[3,4];case 4:return[2]}})})},n.prototype._addTracksToConnection=function(e,t){if(dt.default.log("add tracks from stream ".concat(e.id," to peer connection")),!t.addTrack)return dt.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(function(r){t.addTrack(r,e)})},n.prototype._addStreamToMediaConnection=function(e,t){dt.default.log("add stream ".concat(e.id," to media connection ").concat(t.connectionId)),t.addStream(e)},n}(),LB={};Kl(LB,"BaseConnection",()=>QG,n=>QG=n);var ede=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),QG=function(n){ede(e,n);function e(t,r,s){var o=n.call(this)||this;return o.peer=t,o.provider=r,o.options=s,o._open=!1,o.metadata=s.metadata,o}return Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),e}($y.EventEmitter),tde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),lS=function(){return lS=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},lS.apply(this,arguments)},ide=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},HG=function(n){tde(e,n);function e(t,r,s){var o=n.call(this,t,r,s)||this;return o._localStream=o.options._stream,o.connectionId=o.options.connectionId||e.ID_PREFIX+wi.randomToken(),o._negotiator=new OB.Negotiator(o),o._localStream&&o._negotiator.startConnection({_stream:o._localStream,originator:!0}),o}return Object.defineProperty(e.prototype,"type",{get:function(){return pl.Media},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),e.prototype.addStream=function(t){dt.default.log("Receiving stream",t),this._remoteStream=t,n.prototype.emit.call(this,"stream",t)},e.prototype.handleMessage=function(t){var r=t.type,s=t.payload;switch(t.type){case Qr.Answer:this._negotiator.handleSDP(r,s.sdp),this._open=!0;break;case Qr.Candidate:this._negotiator.handleCandidate(s.candidate);break;default:dt.default.warn("Unrecognized message type:".concat(r," from peer:").concat(this.peer));break}},e.prototype.answer=function(t,r){var s,o;if(r===void 0&&(r={}),this._localStream){dt.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=t,r&&r.sdpTransform&&(this.options.sdpTransform=r.sdpTransform),this._negotiator.startConnection(lS(lS({},this.options._payload),{_stream:t}));var a=this.provider._getMessages(this.connectionId);try{for(var l=ide(a),c=l.next();!c.done;c=l.next()){var h=c.value;this.handleMessage(h)}}catch(u){s={error:u}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(s)throw s.error}}this._open=!0},e.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,n.prototype.emit.call(this,"close"))},e.ID_PREFIX="mc_",e}(LB.BaseConnection),FB={};Kl(FB,"DataConnection",()=>qG,n=>qG=n);var WG={};Kl(WG,"EncodingQueue",()=>XG,n=>XG=n);var nde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),XG=function(n){nde(e,n);function e(){var t=n.call(this)||this;return t.fileReader=new FileReader,t._queue=[],t._processing=!1,t.fileReader.onload=function(r){t._processing=!1,r.target&&t.emit("done",r.target.result),t.doNextTask()},t.fileReader.onerror=function(r){dt.default.error("EncodingQueue error:",r),t._processing=!1,t.destroy(),t.emit("error",r)},t}return Object.defineProperty(e.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),e.prototype.enque=function(t){this.queue.push(t),!this.processing&&this.doNextTask()},e.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},e.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},e}($y.EventEmitter),rde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),sde=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},qG=function(n){rde(e,n);function e(t,r,s){var o=n.call(this,t,r,s)||this;return o.stringify=JSON.stringify,o.parse=JSON.parse,o._buffer=[],o._bufferSize=0,o._buffering=!1,o._chunkedData={},o._encodingQueue=new WG.EncodingQueue,o.connectionId=o.options.connectionId||e.ID_PREFIX+wi.randomToken(),o.label=o.options.label||o.connectionId,o.serialization=o.options.serialization||gh.Binary,o.reliable=!!o.options.reliable,o._encodingQueue.on("done",function(a){o._bufferedSend(a)}),o._encodingQueue.on("error",function(){dt.default.error("DC#".concat(o.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),o.close()}),o._negotiator=new OB.Negotiator(o),o._negotiator.startConnection(o.options._payload||{originator:!0}),o}return Object.defineProperty(e.prototype,"type",{get:function(){return pl.Data},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),e.prototype.initialize=function(t){this._dc=t,this._configureDataChannel()},e.prototype._configureDataChannel=function(){var t=this;(!wi.supports.binaryBlob||wi.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){dt.default.log("DC#".concat(t.connectionId," dc connection success")),t._open=!0,t.emit("open")},this.dataChannel.onmessage=function(r){dt.default.log("DC#".concat(t.connectionId," dc onmessage:"),r.data),t._handleDataMessage(r)},this.dataChannel.onclose=function(){dt.default.log("DC#".concat(t.connectionId," dc closed for:"),t.peer),t.close()}},e.prototype._handleDataMessage=function(t){var r=this,s=t.data,o=s.constructor,a=this.serialization===gh.Binary||this.serialization===gh.BinaryUTF8,l=s;if(a){if(o===Blob){wi.blobToArrayBuffer(s,function(h){var u=wi.unpack(h);r.emit("data",u)});return}else if(o===ArrayBuffer)l=wi.unpack(s);else if(o===String){var c=wi.binaryStringToArrayBuffer(s);l=wi.unpack(c)}}else this.serialization===gh.JSON&&(l=this.parse(s));if(l.__peerData){this._handleChunk(l);return}n.prototype.emit.call(this,"data",l)},e.prototype._handleChunk=function(t){var r=t.__peerData,s=this._chunkedData[r]||{data:[],count:0,total:t.total};if(s.data[t.n]=t.data,s.count++,this._chunkedData[r]=s,s.total===s.count){delete this._chunkedData[r];var o=new Blob(s.data);this._handleDataMessage({data:o})}},e.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,n.prototype.emit.call(this,"close"))},e.prototype.send=function(t,r){if(!this.open){n.prototype.emit.call(this,"error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization===gh.JSON)this._bufferedSend(this.stringify(t));else if(this.serialization===gh.Binary||this.serialization===gh.BinaryUTF8){var s=wi.pack(t);if(!r&&s.size>wi.chunkedMTU){this._sendChunks(s);return}wi.supports.binaryBlob?this._bufferedSend(s):this._encodingQueue.enque(s)}else this._bufferedSend(t)},e.prototype._bufferedSend=function(t){(this._buffering||!this._trySend(t))&&(this._buffer.push(t),this._bufferSize=this._buffer.length)},e.prototype._trySend=function(t){var r=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>e.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){r._buffering=!1,r._tryBuffer()},50),!1;try{this.dataChannel.send(t)}catch(s){return dt.default.error("DC#:".concat(this.connectionId," Error when sending:"),s),this._buffering=!0,this.close(),!1}return!0},e.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var t=this._buffer[0];this._trySend(t)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},e.prototype._sendChunks=function(t){var r,s,o=wi.chunk(t);dt.default.log("DC#".concat(this.connectionId," Try to send ").concat(o.length," chunks..."));try{for(var a=sde(o),l=a.next();!l.done;l=a.next()){var c=l.value;this.send(c,!0)}}catch(h){r={error:h}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}},e.prototype.handleMessage=function(t){var r=t.payload;switch(t.type){case Qr.Answer:this._negotiator.handleSDP(t.type,r.sdp);break;case Qr.Candidate:this._negotiator.handleCandidate(r.candidate);break;default:dt.default.warn("Unrecognized message type:",t.type,"from peer:",this.peer);break}},e.ID_PREFIX="dc_",e.MAX_BUFFERED_AMOUNT=8388608,e}(LB.BaseConnection),YG={};Kl(YG,"API",()=>ZG,n=>ZG=n);var JG=function(n,e,t,r){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function l(u){try{h(r.next(u))}catch(p){a(p)}}function c(u){try{h(r.throw(u))}catch(p){a(p)}}function h(u){u.done?o(u.value):s(u.value).then(l,c)}h((r=r.apply(n,e||[])).next())})},KG=function(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,s&&(o=h[0]&2?s.return:h[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,h[1])).done)return o;switch(s=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){t.label=h[1];break}if(h[0]===6&&t.label<o[1]){t.label=o[1],o=h;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(h);break}o[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(n,t)}catch(u){h=[6,u],s=0}finally{r=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}},ZG=function(){function n(e){this._options=e}return n.prototype._buildRequest=function(e){var t=this._options.secure?"https":"http",r=this._options,s=r.host,o=r.port,a=r.path,l=r.key,c=new URL("".concat(t,"://").concat(s,":").concat(o).concat(a).concat(l,"/").concat(e));return c.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),c.searchParams.set("version",kB.version),fetch(c.href,{referrerPolicy:this._options.referrerPolicy})},n.prototype.retrieveId=function(){return JG(this,void 0,Promise,function(){var e,t,r;return KG(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(e=s.sent(),e.status!==200)throw new Error("Error. Status:".concat(e.status));return[2,e.text()];case 2:throw t=s.sent(),dt.default.error("Error retrieving ID",t),r="",this._options.path==="/"&&this._options.host!==wi.CLOUD_HOST&&(r=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+r);case 3:return[2]}})})},n.prototype.listAllPeers=function(){return JG(this,void 0,Promise,function(){var e,t,r;return KG(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(e=s.sent(),e.status!==200)throw e.status===401?(t="",this._options.host===wi.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+t)):new Error("Error. Status:".concat(e.status));return[2,e.json()];case 2:throw r=s.sent(),dt.default.error("Error retrieving list peers",r),new Error("Could not get list peers from the server."+r);case 3:return[2]}})})},n}(),ode=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),tA=function(){return tA=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},tA.apply(this,arguments)},iA=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ade=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},UB=function(n){ode(e,n);function e(t,r){var s=n.call(this)||this;s._id=null,s._lastServerId=null,s._destroyed=!1,s._disconnected=!1,s._open=!1,s._connections=new Map,s._lostMessages=new Map;var o;return t&&t.constructor==Object?r=t:t&&(o=t.toString()),r=tA({debug:0,host:wi.CLOUD_HOST,port:wi.CLOUD_PORT,path:"/",key:e.DEFAULT_KEY,token:wi.randomToken(),config:wi.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},r),s._options=r,s._options.host==="/"&&(s._options.host=window.location.hostname),s._options.path&&(s._options.path[0]!=="/"&&(s._options.path="/"+s._options.path),s._options.path[s._options.path.length-1]!=="/"&&(s._options.path+="/")),s._options.secure===void 0&&s._options.host!==wi.CLOUD_HOST?s._options.secure=wi.isSecure():s._options.host==wi.CLOUD_HOST&&(s._options.secure=!0),s._options.logFunction&&dt.default.setLogFunction(s._options.logFunction),dt.default.logLevel=s._options.debug||0,s._api=new YG.API(r),s._socket=s._createServerConnection(),!wi.supports.audioVideo&&!wi.supports.data?(s._delayedAbort(Fn.BrowserIncompatible,"The current browser does not support WebRTC"),s):o&&!wi.validateId(o)?(s._delayedAbort(Fn.InvalidID,'ID "'.concat(o,'" is invalid')),s):(o?s._initialize(o):s._api.retrieveId().then(function(a){return s._initialize(a)}).catch(function(a){return s._abort(Fn.ServerError,a)}),s)}return Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connections",{get:function(){var t,r,s=Object.create(null);try{for(var o=iA(this._connections),a=o.next();!a.done;a=o.next()){var l=ade(a.value,2),c=l[0],h=l[1];s[c]=h}}catch(u){t={error:u}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return s},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),e.prototype._createServerConnection=function(){var t=this,r=new jG.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return r.on(vh.Message,function(s){t._handleMessage(s)}),r.on(vh.Error,function(s){t._abort(Fn.SocketError,s)}),r.on(vh.Disconnected,function(){t.disconnected||(t.emitError(Fn.Network,"Lost connection to server."),t.disconnect())}),r.on(vh.Close,function(){t.disconnected||t._abort(Fn.SocketClosed,"Underlying socket is already closed.")}),r},e.prototype._initialize=function(t){this._id=t,this.socket.start(t,this._options.token)},e.prototype._handleMessage=function(t){var r,s,o=t.type,a=t.payload,l=t.src;switch(o){case Qr.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case Qr.Error:this._abort(Fn.ServerError,a.msg);break;case Qr.IdTaken:this._abort(Fn.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case Qr.InvalidKey:this._abort(Fn.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case Qr.Leave:dt.default.log("Received leave message from ".concat(l)),this._cleanupPeer(l),this._connections.delete(l);break;case Qr.Expire:this.emitError(Fn.PeerUnavailable,"Could not connect to peer ".concat(l));break;case Qr.Offer:var g=a.connectionId,v=this.getConnection(l,g);if(v&&(v.close(),dt.default.warn("Offer received for existing Connection ID:".concat(g))),a.type===pl.Media){var c=new DB.MediaConnection(l,this,{connectionId:g,_payload:a,metadata:a.metadata});v=c,this._addConnection(l,v),this.emit("call",c)}else if(a.type===pl.Data){var h=new FB.DataConnection(l,this,{connectionId:g,_payload:a,metadata:a.metadata,label:a.label,serialization:a.serialization,reliable:a.reliable});v=h,this._addConnection(l,v),this.emit("connection",h)}else{dt.default.warn("Received malformed connection type:".concat(a.type));return}var u=this._getMessages(g);try{for(var p=iA(u),m=p.next();!m.done;m=p.next()){var f=m.value;v.handleMessage(f)}}catch(y){r={error:y}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}break;default:if(!a){dt.default.warn("You received a malformed message from ".concat(l," of type ").concat(o));return}var g=a.connectionId,v=this.getConnection(l,g);v&&v.peerConnection?v.handleMessage(t):g?this._storeMessage(g,t):dt.default.warn("You received an unrecognized message:",t);break}},e.prototype._storeMessage=function(t,r){this._lostMessages.has(t)||this._lostMessages.set(t,[]),this._lostMessages.get(t).push(r)},e.prototype._getMessages=function(t){var r=this._lostMessages.get(t);return r?(this._lostMessages.delete(t),r):[]},e.prototype.connect=function(t,r){if(r===void 0&&(r={}),this.disconnected){dt.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(Fn.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var s=new FB.DataConnection(t,this,r);return this._addConnection(t,s),s},e.prototype.call=function(t,r,s){if(s===void 0&&(s={}),this.disconnected){dt.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(Fn.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!r){dt.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var o=new DB.MediaConnection(t,this,tA(tA({},s),{_stream:r}));return this._addConnection(t,o),o},e.prototype._addConnection=function(t,r){dt.default.log("add connection ".concat(r.type,":").concat(r.connectionId," to peerId:").concat(t)),this._connections.has(t)||this._connections.set(t,[]),this._connections.get(t).push(r)},e.prototype._removeConnection=function(t){var r=this._connections.get(t.peer);if(r){var s=r.indexOf(t);s!==-1&&r.splice(s,1)}this._lostMessages.delete(t.connectionId)},e.prototype.getConnection=function(t,r){var s,o,a=this._connections.get(t);if(!a)return null;try{for(var l=iA(a),c=l.next();!c.done;c=l.next()){var h=c.value;if(h.connectionId===r)return h}}catch(u){s={error:u}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(s)throw s.error}}return null},e.prototype._delayedAbort=function(t,r){var s=this;setTimeout(function(){s._abort(t,r)},0)},e.prototype._abort=function(t,r){dt.default.error("Aborting!"),this.emitError(t,r),this._lastServerId?this.disconnect():this.destroy()},e.prototype.emitError=function(t,r){dt.default.error("Error:",r);var s;typeof r=="string"?s=new Error(r):s=r,s.type=t,this.emit("error",s)},e.prototype.destroy=function(){this.destroyed||(dt.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},e.prototype._cleanup=function(){var t,r;try{for(var s=iA(this._connections.keys()),o=s.next();!o.done;o=s.next()){var a=o.value;this._cleanupPeer(a),this._connections.delete(a)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}this.socket.removeAllListeners()},e.prototype._cleanupPeer=function(t){var r,s,o=this._connections.get(t);if(o)try{for(var a=iA(o),l=a.next();!l.done;l=a.next()){var c=l.value;c.close()}}catch(h){r={error:h}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}},e.prototype.disconnect=function(){if(!this.disconnected){var t=this.id;dt.default.log("Disconnect peer with ID:".concat(t)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=t,this._id=null,this.emit("disconnected",t)}},e.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)dt.default.log("Attempting reconnection to server with ID ".concat(this._lastServerId)),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)dt.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},e.prototype.listAllPeers=function(t){var r=this;t===void 0&&(t=function(s){}),this._api.listAllPeers().then(function(s){return t(s)}).catch(function(s){return r._abort(Fn.ServerError,s)})},e.DEFAULT_KEY="peerjs",e}($y.EventEmitter),NB=UG.Peer;const lde=Object.freeze(Object.defineProperty({__proto__:null,get Peer(){return UB},default:NB,util:wi},Symbol.toStringTag,{value:"Module"}));let zB;function cde(){return zB}function hde(n){zB=n}function $G(n,e){return e||(e={}),e={...zB,...e},n?new NB(n,e):new NB(e)}async function eV(){const n=await Promise.resolve().then(()=>lde);return console.log(n),n.default===void 0?n:n.default}class tV{constructor(){d(this,"_host"),d(this,"_client"),d(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}async trySetupHost(e){const t=await eV(),r=new t(e);r.on("error",s=>{console.error(s),this._host=void 0,this.trySetupClient(e)}),r.on("open",s=>{this._host=new dde(r)})}async trySetupClient(e){const t=await eV();this._client=new t,this._client.on("error",r=>{console.error("Client error",r)}),this._client.on("open",r=>{console.log("client connected",r),this._clientData=this._client.connect(e,{metadata:{id:r}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",s=>{console.log("<<",s)})})}}class ude{constructor(e){d(this,"_peer"),this._peer=e}}class dde extends ude{constructor(e){var t;super(e),d(this,"_connections",[]),console.log("I AM THE HOST"),(t=this._peer)==null||t.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(r=>{var s;return(s=r.metadata)==null?void 0:s.id}).filter(r=>r!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const r=this._peer.connections[t];if(r)if(Array.isArray(r))for(const s of r)s&&s.send(e);else console.warn(r)}}}}const iV="https://urls.needle.tools/default-networking-backend/index";let Gu="wss://needle-tiny-starter.glitch.me/socket";const Zs=!!te("debugnet"),nA=!!(Zs||te("debugowner")),nV=te("debugnetbin");var rV=(n=>(n.ConnectionInfo="connection-start-info",n))(rV||{}),Vt=(n=>(n.Join="join-room",n.Leave="leave-room",n.JoinedRoom="joined-room",n.LeftRoom="left-room",n.UserJoinedRoom="user-joined-room",n.UserLeftRoom="user-left-room",n.RoomStateSent="room-state-sent",n))(Vt||{});class pde{constructor(){d(this,"room"),d(this,"viewId"),d(this,"allowEditing"),d(this,"inRoom")}}class mde{constructor(){d(this,"room")}}class fde{constructor(){d(this,"userId")}}var sV=(n=>(n.RequestHasOwner="request-has-owner",n.ResponseHasOwner="response-has-owner",n.RequestIsOwner="request-is-owner",n.ResponseIsOwner="response-is-owner",n.RequestOwnership="request-ownership",n.GainedOwnership="gained-ownership",n.RemoveOwnership="remove-ownership",n.LostOwnership="lost-ownership",n.GainedOwnershipBroadcast="gained-ownership-broadcast",n.LostOwnershipBroadcast="lost-ownership-broadcast",n))(sV||{});class jB{constructor(e,t){d(this,"guid"),d(this,"connection"),d(this,"_hasOwnership",!1),d(this,"_isOwned"),d(this,"_gainSubscription"),d(this,"_lostSubscription"),d(this,"_hasOwnerResponse"),d(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(nA&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let r=0;const s=()=>{if(r++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):s()},100)};s()})}requestOwnership(){return nA&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(nA&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(nA&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class oV{constructor(e){d(this,"context"),d(this,"_peer",null),d(this,"_usersInRoomCopy",[]),d(this,"_defaultMessagesBuffer",[]),d(this,"_defaultMessagesBufferArray",[]),d(this,"netWebSocketUrlProvider"),d(this,"_listeners",{}),d(this,"_listenersBinary",{}),d(this,"connected",!1),d(this,"channelId"),d(this,"_connectionId",null),d(this,"_ws"),d(this,"_waitingForSocket",{}),d(this,"_isInRoom",!1),d(this,"_currentRoomName",null),d(this,"_currentRoomViewId",null),d(this,"_currentRoomAllowEditing",!0),d(this,"_currentInRoom",[]),d(this,"_state",{}),d(this,"_currentDelay",-1),d(this,"_connectingToWebsocketPromise",null),this.context=e}get peer(){return this._peer||(this._peer=new tV),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Zs}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var e;return((e=this._ws)==null?void 0:e.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.connect(),Zs&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},dl.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,r=dl.Queued){if(t===null&&(t={}),r===dl.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,r)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){var t;nV&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),(t=this._ws)==null||t.send(e)}sendBufferedMessagesNow(){var e;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const t=Object.keys(this._defaultMessagesBuffer).length;for(const s in this._defaultMessagesBuffer){const o=this._defaultMessagesBuffer[s];if(t<=1){this.sendWithWebsocket(o.key,o.value,dl.Immediate);break}const a=this.toMessage(o.key,o.value);this._defaultMessagesBufferArray.push(a)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Zs&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const r=JSON.stringify(this._defaultMessagesBufferArray);(e=this._ws)==null||e.send(r)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const r=this._listeners[e].indexOf(t);r>=0&&this._listeners[e].splice(r,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const r=this._listenersBinary[e].indexOf(t);r>=0&&this._listenersBinary[e].splice(r,1)}registerProvider(e){this.netWebSocketUrlProvider=e}async connect(){var e;if(this.connected)return Promise.resolve(!0);Zs&&console.log("connecting");const t=(e=this.netWebSocketUrlProvider)==null?void 0:e.getWebsocketUrl();return t?Gu=t:kU()&&(Gu="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var e;(e=this._ws)==null||e.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{var r,s;let o=!1;const a=p=>{o||(o=!0,e(p))};if(Gu===void 0&&(console.log("Fetch default backend url: "+iV),Gu=await(await fetch(iV)).text()),Gu===void 0){a(!1);return}console.log(`\u22A1 Connecting to networking backend on
5232
+ isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},n}()),FG={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},Hue=function(){function n(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=FG,this.browser=Zy.getBrowser(),this.browserVersion=Zy.getVersion(),this.supports=function(){var e={browser:Zy.isBrowserSupported(),webRTC:Zy.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!e.webRTC)return e;var t;try{t=new RTCPeerConnection(FG),e.audioVideo=!0;var r=void 0;try{r=t.createDataChannel("_PEERJSTEST",{ordered:!0}),e.data=!0,e.reliable=!!r.ordered;try{r.binaryType="blob",e.binaryBlob=!Zy.isIOS}catch{}}catch{}finally{r&&r.close()}}catch{}finally{t&&t.close()}return e}(),this.pack=Q6.pack,this.unpack=Q6.unpack,this._dataCount=1}return n.prototype.noop=function(){},n.prototype.validateId=function(e){return!e||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(e)},n.prototype.chunk=function(e){for(var t=[],r=e.size,s=Math.ceil(r/wi.chunkedMTU),o=0,a=0;a<r;){var l=Math.min(r,a+wi.chunkedMTU),c=e.slice(a,l),h={__peerData:this._dataCount,n:o,data:c,total:s};t.push(h),a=l,o++}return this._dataCount++,t},n.prototype.blobToArrayBuffer=function(e,t){var r=new FileReader;return r.onload=function(s){s.target&&t(s.target.result)},r.readAsArrayBuffer(e),r},n.prototype.binaryStringToArrayBuffer=function(e){for(var t=new Uint8Array(e.length),r=0;r<e.length;r++)t[r]=e.charCodeAt(r)&255;return t.buffer},n.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},n.prototype.isSecure=function(){return location.protocol==="https:"},n}(),wi=new Hue,UG={};Kl(UG,"Peer",()=>UB,n=>UB=n);var $y={},Wue=Object.prototype.hasOwnProperty,Ks="~";function eA(){}Object.create&&(eA.prototype=Object.create(null),new eA().__proto__||(Ks=!1));function Xue(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function NG(n,e,t,r,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Xue(t,r||n,s),a=Ks?Ks+e:e;return n._events[a]?n._events[a].fn?n._events[a]=[n._events[a],o]:n._events[a].push(o):(n._events[a]=o,n._eventsCount++),n}function rS(n,e){--n._eventsCount===0?n._events=new eA:delete n._events[e]}function Cs(){this._events=new eA,this._eventsCount=0}Cs.prototype.eventNames=function(){var n=[],e,t;if(this._eventsCount===0)return n;for(t in e=this._events)Wue.call(e,t)&&n.push(Ks?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},Cs.prototype.listeners=function(n){var e=Ks?Ks+n:n,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,o=new Array(s);r<s;r++)o[r]=t[r].fn;return o},Cs.prototype.listenerCount=function(n){var e=Ks?Ks+n:n,t=this._events[e];return t?t.fn?1:t.length:0},Cs.prototype.emit=function(n,e,t,r,s,o){var a=Ks?Ks+n:n;if(!this._events[a])return!1;var l=this._events[a],c=arguments.length,h,u;if(l.fn){switch(l.once&&this.removeListener(n,l.fn,void 0,!0),c){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,e),!0;case 3:return l.fn.call(l.context,e,t),!0;case 4:return l.fn.call(l.context,e,t,r),!0;case 5:return l.fn.call(l.context,e,t,r,s),!0;case 6:return l.fn.call(l.context,e,t,r,s,o),!0}for(u=1,h=new Array(c-1);u<c;u++)h[u-1]=arguments[u];l.fn.apply(l.context,h)}else{var p=l.length,m;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(n,l[u].fn,void 0,!0),c){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,e);break;case 3:l[u].fn.call(l[u].context,e,t);break;case 4:l[u].fn.call(l[u].context,e,t,r);break;default:if(!h)for(m=1,h=new Array(c-1);m<c;m++)h[m-1]=arguments[m];l[u].fn.apply(l[u].context,h)}}return!0},Cs.prototype.on=function(n,e,t){return NG(this,n,e,t,!1)},Cs.prototype.once=function(n,e,t){return NG(this,n,e,t,!0)},Cs.prototype.removeListener=function(n,e,t,r){var s=Ks?Ks+n:n;if(!this._events[s])return this;if(!e)return rS(this,s),this;var o=this._events[s];if(o.fn)o.fn===e&&(!r||o.once)&&(!t||o.context===t)&&rS(this,s);else{for(var a=0,l=[],c=o.length;a<c;a++)(o[a].fn!==e||r&&!o[a].once||t&&o[a].context!==t)&&l.push(o[a]);l.length?this._events[s]=l.length===1?l[0]:l:rS(this,s)}return this},Cs.prototype.removeAllListeners=function(n){var e;return n?(e=Ks?Ks+n:n,this._events[e]&&rS(this,e)):(this._events=new eA,this._eventsCount=0),this},Cs.prototype.off=Cs.prototype.removeListener,Cs.prototype.addListener=Cs.prototype.on,Cs.prefixed=Ks,Cs.EventEmitter=Cs,$y=Cs;var dt={};Kl(dt,"LogLevel",()=>yo,n=>yo=n),Kl(dt,"default",()=>zG,n=>zG=n);var Xp=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},qp=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},que="PeerJS: ",yo;(function(n){n[n.Disabled=0]="Disabled",n[n.Errors=1]="Errors",n[n.Warnings=2]="Warnings",n[n.All=3]="All"})(yo||(yo={}));var Yue=function(){function n(){this._logLevel=yo.Disabled}return Object.defineProperty(n.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){this._logLevel=e},enumerable:!1,configurable:!0}),n.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.All&&this._print.apply(this,qp([yo.All],Xp(e),!1))},n.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.Warnings&&this._print.apply(this,qp([yo.Warnings],Xp(e),!1))},n.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.Errors&&this._print.apply(this,qp([yo.Errors],Xp(e),!1))},n.prototype.setLogFunction=function(e){this._print=e},n.prototype._print=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var s=qp([que],Xp(t),!1);for(var o in s)s[o]instanceof Error&&(s[o]="("+s[o].name+") "+s[o].message);e>=yo.All?console.log.apply(console,qp([],Xp(s),!1)):e>=yo.Warnings?console.warn.apply(console,qp(["WARNING"],Xp(s),!1)):e>=yo.Errors&&console.error.apply(console,qp(["ERROR"],Xp(s),!1))},n}(),zG=new Yue,jG={};Kl(jG,"Socket",()=>GG,n=>GG=n);var pl;(function(n){n.Data="data",n.Media="media"})(pl||(pl={}));var Fn;(function(n){n.BrowserIncompatible="browser-incompatible",n.Disconnected="disconnected",n.InvalidID="invalid-id",n.InvalidKey="invalid-key",n.Network="network",n.PeerUnavailable="peer-unavailable",n.SslUnavailable="ssl-unavailable",n.ServerError="server-error",n.SocketError="socket-error",n.SocketClosed="socket-closed",n.UnavailableID="unavailable-id",n.WebRTC="webrtc"})(Fn||(Fn={}));var gh;(function(n){n.Binary="binary",n.BinaryUTF8="binary-utf8",n.JSON="json"})(gh||(gh={}));var vh;(function(n){n.Message="message",n.Disconnected="disconnected",n.Error="error",n.Close="close"})(vh||(vh={}));var Qr;(function(n){n.Heartbeat="HEARTBEAT",n.Candidate="CANDIDATE",n.Offer="OFFER",n.Answer="ANSWER",n.Open="OPEN",n.Error="ERROR",n.IdTaken="ID-TAKEN",n.InvalidKey="INVALID-KEY",n.Leave="LEAVE",n.Expire="EXPIRE"})(Qr||(Qr={}));var kB={};kB=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz St\xFCckler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","So\u0308ren Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var Jue=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Kue=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},Zue=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},$ue=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},GG=function(n){Jue(e,n);function e(t,r,s,o,a,l){l===void 0&&(l=5e3);var c=n.call(this)||this;c.pingInterval=l,c._disconnected=!0,c._messagesQueue=[];var h=t?"wss://":"ws://";return c._baseUrl=h+r+":"+s+o+"peerjs?key="+a,c}return e.prototype.start=function(t,r){var s=this;this._id=t;var o="".concat(this._baseUrl,"&id=").concat(t,"&token=").concat(r);this._socket||!this._disconnected||(this._socket=new WebSocket(o+"&version="+kB.version),this._disconnected=!1,this._socket.onmessage=function(a){var l;try{l=JSON.parse(a.data),dt.default.log("Server message received:",l)}catch{dt.default.log("Invalid server message",a.data);return}s.emit(vh.Message,l)},this._socket.onclose=function(a){s._disconnected||(dt.default.log("Socket closed.",a),s._cleanup(),s._disconnected=!0,s.emit(vh.Disconnected))},this._socket.onopen=function(){s._disconnected||(s._sendQueuedMessages(),dt.default.log("Socket open"),s._scheduleHeartbeat())})},e.prototype._scheduleHeartbeat=function(){var t=this;this._wsPingTimer=setTimeout(function(){t._sendHeartbeat()},this.pingInterval)},e.prototype._sendHeartbeat=function(){if(!this._wsOpen()){dt.default.log("Cannot send heartbeat, because socket closed");return}var t=JSON.stringify({type:Qr.Heartbeat});this._socket.send(t),this._scheduleHeartbeat()},e.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},e.prototype._sendQueuedMessages=function(){var t,r,s=Zue([],Kue(this._messagesQueue),!1);this._messagesQueue=[];try{for(var o=$ue(s),a=o.next();!a.done;a=o.next()){var l=a.value;this.send(l)}}catch(c){t={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}},e.prototype.send=function(t){if(!this._disconnected){if(!this._id){this._messagesQueue.push(t);return}if(!t.type){this.emit(vh.Error,"Invalid message");return}if(this._wsOpen()){var r=JSON.stringify(t);this._socket.send(r)}}},e.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},e.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},e}($y.EventEmitter),DB={};Kl(DB,"MediaConnection",()=>HG,n=>HG=n);var OB={};Kl(OB,"Negotiator",()=>VG,n=>VG=n);var sS=function(){return sS=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},sS.apply(this,arguments)},oS=function(n,e,t,r){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function l(u){try{h(r.next(u))}catch(p){a(p)}}function c(u){try{h(r.throw(u))}catch(p){a(p)}}function h(u){u.done?o(u.value):s(u.value).then(l,c)}h((r=r.apply(n,e||[])).next())})},aS=function(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,s&&(o=h[0]&2?s.return:h[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,h[1])).done)return o;switch(s=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){t.label=h[1];break}if(h[0]===6&&t.label<o[1]){t.label=o[1],o=h;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(h);break}o[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(n,t)}catch(u){h=[6,u],s=0}finally{r=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}},VG=function(){function n(e){this.connection=e}return n.prototype.startConnection=function(e){var t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===pl.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){if(this.connection.type===pl.Data){var r=this.connection,s={ordered:!!e.reliable},o=t.createDataChannel(r.label,s);r.initialize(o)}this._makeOffer()}else this.handleSDP("OFFER",e.sdp)},n.prototype._startPeerConnection=function(){dt.default.log("Creating RTCPeerConnection.");var e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e},n.prototype._setupListeners=function(e){var t=this,r=this.connection.peer,s=this.connection.connectionId,o=this.connection.type,a=this.connection.provider;dt.default.log("Listening for ICE candidates."),e.onicecandidate=function(l){!l.candidate||!l.candidate.candidate||(dt.default.log("Received ICE candidates for ".concat(r,":"),l.candidate),a.socket.send({type:Qr.Candidate,payload:{candidate:l.candidate,type:o,connectionId:s},dst:r}))},e.oniceconnectionstatechange=function(){switch(e.iceConnectionState){case"failed":dt.default.log("iceConnectionState is failed, closing connections to "+r),t.connection.emit("error",new Error("Negotiation of connection to "+r+" failed.")),t.connection.close();break;case"closed":dt.default.log("iceConnectionState is closed, closing connections to "+r),t.connection.emit("error",new Error("Connection to "+r+" closed.")),t.connection.close();break;case"disconnected":dt.default.log("iceConnectionState changed to disconnected on the connection with "+r);break;case"completed":e.onicecandidate=wi.noop;break}t.connection.emit("iceStateChanged",e.iceConnectionState)},dt.default.log("Listening for data channel"),e.ondatachannel=function(l){dt.default.log("Received data channel");var c=l.channel,h=a.getConnection(r,s);h.initialize(c)},dt.default.log("Listening for remote stream"),e.ontrack=function(l){dt.default.log("Received remote stream");var c=l.streams[0],h=a.getConnection(r,s);if(h.type===pl.Media){var u=h;t._addStreamToMediaConnection(c,u)}}},n.prototype.cleanup=function(){dt.default.log("Cleaning up PeerConnection to "+this.connection.peer);var e=this.connection.peerConnection;if(e){this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=function(){};var t=e.signalingState!=="closed",r=!1;if(this.connection.type===pl.Data){var s=this.connection,o=s.dataChannel;o&&(r=!!o.readyState&&o.readyState!=="closed")}(t||r)&&e.close()}},n.prototype._makeOffer=function(){return oS(this,void 0,Promise,function(){var e,t,r,s,o,a,l;return aS(this,function(c){switch(c.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,c.label=1;case 1:return c.trys.push([1,7,,8]),[4,e.createOffer(this.connection.options.constraints)];case 2:r=c.sent(),dt.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(r.sdp=this.connection.options.sdpTransform(r.sdp)||r.sdp),c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.setLocalDescription(r)];case 4:return c.sent(),dt.default.log("Set localDescription:",r,"for:".concat(this.connection.peer)),s={sdp:r,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:wi.browser},this.connection.type===pl.Data&&(o=this.connection,s=sS(sS({},s),{label:o.label,reliable:o.reliable,serialization:o.serialization})),t.socket.send({type:Qr.Offer,payload:s,dst:this.connection.peer}),[3,6];case 5:return a=c.sent(),a!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(Fn.WebRTC,a),dt.default.log("Failed to setLocalDescription, ",a)),[3,6];case 6:return[3,8];case 7:return l=c.sent(),t.emitError(Fn.WebRTC,l),dt.default.log("Failed to createOffer, ",l),[3,8];case 8:return[2]}})})},n.prototype._makeAnswer=function(){return oS(this,void 0,Promise,function(){var e,t,r,s,o;return aS(this,function(a){switch(a.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,a.label=1;case 1:return a.trys.push([1,7,,8]),[4,e.createAnswer()];case 2:r=a.sent(),dt.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(r.sdp=this.connection.options.sdpTransform(r.sdp)||r.sdp),a.label=3;case 3:return a.trys.push([3,5,,6]),[4,e.setLocalDescription(r)];case 4:return a.sent(),dt.default.log("Set localDescription:",r,"for:".concat(this.connection.peer)),t.socket.send({type:Qr.Answer,payload:{sdp:r,type:this.connection.type,connectionId:this.connection.connectionId,browser:wi.browser},dst:this.connection.peer}),[3,6];case 5:return s=a.sent(),t.emitError(Fn.WebRTC,s),dt.default.log("Failed to setLocalDescription, ",s),[3,6];case 6:return[3,8];case 7:return o=a.sent(),t.emitError(Fn.WebRTC,o),dt.default.log("Failed to create answer, ",o),[3,8];case 8:return[2]}})})},n.prototype.handleSDP=function(e,t){return oS(this,void 0,Promise,function(){var r,s,o,a;return aS(this,function(l){switch(l.label){case 0:t=new RTCSessionDescription(t),r=this.connection.peerConnection,s=this.connection.provider,dt.default.log("Setting remote description",t),o=this,l.label=1;case 1:return l.trys.push([1,5,,6]),[4,r.setRemoteDescription(t)];case 2:return l.sent(),dt.default.log("Set remoteDescription:".concat(e," for:").concat(this.connection.peer)),e!=="OFFER"?[3,4]:[4,o._makeAnswer()];case 3:l.sent(),l.label=4;case 4:return[3,6];case 5:return a=l.sent(),s.emitError(Fn.WebRTC,a),dt.default.log("Failed to setRemoteDescription, ",a),[3,6];case 6:return[2]}})})},n.prototype.handleCandidate=function(e){return oS(this,void 0,Promise,function(){var t,r,s,o,a,l;return aS(this,function(c){switch(c.label){case 0:dt.default.log("handleCandidate:",e),t=e.candidate,r=e.sdpMLineIndex,s=e.sdpMid,o=this.connection.peerConnection,a=this.connection.provider,c.label=1;case 1:return c.trys.push([1,3,,4]),[4,o.addIceCandidate(new RTCIceCandidate({sdpMid:s,sdpMLineIndex:r,candidate:t}))];case 2:return c.sent(),dt.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return l=c.sent(),a.emitError(Fn.WebRTC,l),dt.default.log("Failed to handleCandidate, ",l),[3,4];case 4:return[2]}})})},n.prototype._addTracksToConnection=function(e,t){if(dt.default.log("add tracks from stream ".concat(e.id," to peer connection")),!t.addTrack)return dt.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(function(r){t.addTrack(r,e)})},n.prototype._addStreamToMediaConnection=function(e,t){dt.default.log("add stream ".concat(e.id," to media connection ").concat(t.connectionId)),t.addStream(e)},n}(),LB={};Kl(LB,"BaseConnection",()=>QG,n=>QG=n);var ede=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),QG=function(n){ede(e,n);function e(t,r,s){var o=n.call(this)||this;return o.peer=t,o.provider=r,o.options=s,o._open=!1,o.metadata=s.metadata,o}return Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),e}($y.EventEmitter),tde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),lS=function(){return lS=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},lS.apply(this,arguments)},ide=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},HG=function(n){tde(e,n);function e(t,r,s){var o=n.call(this,t,r,s)||this;return o._localStream=o.options._stream,o.connectionId=o.options.connectionId||e.ID_PREFIX+wi.randomToken(),o._negotiator=new OB.Negotiator(o),o._localStream&&o._negotiator.startConnection({_stream:o._localStream,originator:!0}),o}return Object.defineProperty(e.prototype,"type",{get:function(){return pl.Media},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),e.prototype.addStream=function(t){dt.default.log("Receiving stream",t),this._remoteStream=t,n.prototype.emit.call(this,"stream",t)},e.prototype.handleMessage=function(t){var r=t.type,s=t.payload;switch(t.type){case Qr.Answer:this._negotiator.handleSDP(r,s.sdp),this._open=!0;break;case Qr.Candidate:this._negotiator.handleCandidate(s.candidate);break;default:dt.default.warn("Unrecognized message type:".concat(r," from peer:").concat(this.peer));break}},e.prototype.answer=function(t,r){var s,o;if(r===void 0&&(r={}),this._localStream){dt.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=t,r&&r.sdpTransform&&(this.options.sdpTransform=r.sdpTransform),this._negotiator.startConnection(lS(lS({},this.options._payload),{_stream:t}));var a=this.provider._getMessages(this.connectionId);try{for(var l=ide(a),c=l.next();!c.done;c=l.next()){var h=c.value;this.handleMessage(h)}}catch(u){s={error:u}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(s)throw s.error}}this._open=!0},e.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,n.prototype.emit.call(this,"close"))},e.ID_PREFIX="mc_",e}(LB.BaseConnection),FB={};Kl(FB,"DataConnection",()=>qG,n=>qG=n);var WG={};Kl(WG,"EncodingQueue",()=>XG,n=>XG=n);var nde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),XG=function(n){nde(e,n);function e(){var t=n.call(this)||this;return t.fileReader=new FileReader,t._queue=[],t._processing=!1,t.fileReader.onload=function(r){t._processing=!1,r.target&&t.emit("done",r.target.result),t.doNextTask()},t.fileReader.onerror=function(r){dt.default.error("EncodingQueue error:",r),t._processing=!1,t.destroy(),t.emit("error",r)},t}return Object.defineProperty(e.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),e.prototype.enque=function(t){this.queue.push(t),!this.processing&&this.doNextTask()},e.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},e.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},e}($y.EventEmitter),rde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),sde=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},qG=function(n){rde(e,n);function e(t,r,s){var o=n.call(this,t,r,s)||this;return o.stringify=JSON.stringify,o.parse=JSON.parse,o._buffer=[],o._bufferSize=0,o._buffering=!1,o._chunkedData={},o._encodingQueue=new WG.EncodingQueue,o.connectionId=o.options.connectionId||e.ID_PREFIX+wi.randomToken(),o.label=o.options.label||o.connectionId,o.serialization=o.options.serialization||gh.Binary,o.reliable=!!o.options.reliable,o._encodingQueue.on("done",function(a){o._bufferedSend(a)}),o._encodingQueue.on("error",function(){dt.default.error("DC#".concat(o.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),o.close()}),o._negotiator=new OB.Negotiator(o),o._negotiator.startConnection(o.options._payload||{originator:!0}),o}return Object.defineProperty(e.prototype,"type",{get:function(){return pl.Data},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),e.prototype.initialize=function(t){this._dc=t,this._configureDataChannel()},e.prototype._configureDataChannel=function(){var t=this;(!wi.supports.binaryBlob||wi.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){dt.default.log("DC#".concat(t.connectionId," dc connection success")),t._open=!0,t.emit("open")},this.dataChannel.onmessage=function(r){dt.default.log("DC#".concat(t.connectionId," dc onmessage:"),r.data),t._handleDataMessage(r)},this.dataChannel.onclose=function(){dt.default.log("DC#".concat(t.connectionId," dc closed for:"),t.peer),t.close()}},e.prototype._handleDataMessage=function(t){var r=this,s=t.data,o=s.constructor,a=this.serialization===gh.Binary||this.serialization===gh.BinaryUTF8,l=s;if(a){if(o===Blob){wi.blobToArrayBuffer(s,function(h){var u=wi.unpack(h);r.emit("data",u)});return}else if(o===ArrayBuffer)l=wi.unpack(s);else if(o===String){var c=wi.binaryStringToArrayBuffer(s);l=wi.unpack(c)}}else this.serialization===gh.JSON&&(l=this.parse(s));if(l.__peerData){this._handleChunk(l);return}n.prototype.emit.call(this,"data",l)},e.prototype._handleChunk=function(t){var r=t.__peerData,s=this._chunkedData[r]||{data:[],count:0,total:t.total};if(s.data[t.n]=t.data,s.count++,this._chunkedData[r]=s,s.total===s.count){delete this._chunkedData[r];var o=new Blob(s.data);this._handleDataMessage({data:o})}},e.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,n.prototype.emit.call(this,"close"))},e.prototype.send=function(t,r){if(!this.open){n.prototype.emit.call(this,"error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization===gh.JSON)this._bufferedSend(this.stringify(t));else if(this.serialization===gh.Binary||this.serialization===gh.BinaryUTF8){var s=wi.pack(t);if(!r&&s.size>wi.chunkedMTU){this._sendChunks(s);return}wi.supports.binaryBlob?this._bufferedSend(s):this._encodingQueue.enque(s)}else this._bufferedSend(t)},e.prototype._bufferedSend=function(t){(this._buffering||!this._trySend(t))&&(this._buffer.push(t),this._bufferSize=this._buffer.length)},e.prototype._trySend=function(t){var r=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>e.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){r._buffering=!1,r._tryBuffer()},50),!1;try{this.dataChannel.send(t)}catch(s){return dt.default.error("DC#:".concat(this.connectionId," Error when sending:"),s),this._buffering=!0,this.close(),!1}return!0},e.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var t=this._buffer[0];this._trySend(t)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},e.prototype._sendChunks=function(t){var r,s,o=wi.chunk(t);dt.default.log("DC#".concat(this.connectionId," Try to send ").concat(o.length," chunks..."));try{for(var a=sde(o),l=a.next();!l.done;l=a.next()){var c=l.value;this.send(c,!0)}}catch(h){r={error:h}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}},e.prototype.handleMessage=function(t){var r=t.payload;switch(t.type){case Qr.Answer:this._negotiator.handleSDP(t.type,r.sdp);break;case Qr.Candidate:this._negotiator.handleCandidate(r.candidate);break;default:dt.default.warn("Unrecognized message type:",t.type,"from peer:",this.peer);break}},e.ID_PREFIX="dc_",e.MAX_BUFFERED_AMOUNT=8388608,e}(LB.BaseConnection),YG={};Kl(YG,"API",()=>ZG,n=>ZG=n);var JG=function(n,e,t,r){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function l(u){try{h(r.next(u))}catch(p){a(p)}}function c(u){try{h(r.throw(u))}catch(p){a(p)}}function h(u){u.done?o(u.value):s(u.value).then(l,c)}h((r=r.apply(n,e||[])).next())})},KG=function(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,s&&(o=h[0]&2?s.return:h[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,h[1])).done)return o;switch(s=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){t.label=h[1];break}if(h[0]===6&&t.label<o[1]){t.label=o[1],o=h;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(h);break}o[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(n,t)}catch(u){h=[6,u],s=0}finally{r=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}},ZG=function(){function n(e){this._options=e}return n.prototype._buildRequest=function(e){var t=this._options.secure?"https":"http",r=this._options,s=r.host,o=r.port,a=r.path,l=r.key,c=new URL("".concat(t,"://").concat(s,":").concat(o).concat(a).concat(l,"/").concat(e));return c.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),c.searchParams.set("version",kB.version),fetch(c.href,{referrerPolicy:this._options.referrerPolicy})},n.prototype.retrieveId=function(){return JG(this,void 0,Promise,function(){var e,t,r;return KG(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(e=s.sent(),e.status!==200)throw new Error("Error. Status:".concat(e.status));return[2,e.text()];case 2:throw t=s.sent(),dt.default.error("Error retrieving ID",t),r="",this._options.path==="/"&&this._options.host!==wi.CLOUD_HOST&&(r=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+r);case 3:return[2]}})})},n.prototype.listAllPeers=function(){return JG(this,void 0,Promise,function(){var e,t,r;return KG(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(e=s.sent(),e.status!==200)throw e.status===401?(t="",this._options.host===wi.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+t)):new Error("Error. Status:".concat(e.status));return[2,e.json()];case 2:throw r=s.sent(),dt.default.error("Error retrieving list peers",r),new Error("Could not get list peers from the server."+r);case 3:return[2]}})})},n}(),ode=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),tA=function(){return tA=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},tA.apply(this,arguments)},iA=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ade=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},UB=function(n){ode(e,n);function e(t,r){var s=n.call(this)||this;s._id=null,s._lastServerId=null,s._destroyed=!1,s._disconnected=!1,s._open=!1,s._connections=new Map,s._lostMessages=new Map;var o;return t&&t.constructor==Object?r=t:t&&(o=t.toString()),r=tA({debug:0,host:wi.CLOUD_HOST,port:wi.CLOUD_PORT,path:"/",key:e.DEFAULT_KEY,token:wi.randomToken(),config:wi.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},r),s._options=r,s._options.host==="/"&&(s._options.host=window.location.hostname),s._options.path&&(s._options.path[0]!=="/"&&(s._options.path="/"+s._options.path),s._options.path[s._options.path.length-1]!=="/"&&(s._options.path+="/")),s._options.secure===void 0&&s._options.host!==wi.CLOUD_HOST?s._options.secure=wi.isSecure():s._options.host==wi.CLOUD_HOST&&(s._options.secure=!0),s._options.logFunction&&dt.default.setLogFunction(s._options.logFunction),dt.default.logLevel=s._options.debug||0,s._api=new YG.API(r),s._socket=s._createServerConnection(),!wi.supports.audioVideo&&!wi.supports.data?(s._delayedAbort(Fn.BrowserIncompatible,"The current browser does not support WebRTC"),s):o&&!wi.validateId(o)?(s._delayedAbort(Fn.InvalidID,'ID "'.concat(o,'" is invalid')),s):(o?s._initialize(o):s._api.retrieveId().then(function(a){return s._initialize(a)}).catch(function(a){return s._abort(Fn.ServerError,a)}),s)}return Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connections",{get:function(){var t,r,s=Object.create(null);try{for(var o=iA(this._connections),a=o.next();!a.done;a=o.next()){var l=ade(a.value,2),c=l[0],h=l[1];s[c]=h}}catch(u){t={error:u}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return s},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),e.prototype._createServerConnection=function(){var t=this,r=new jG.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return r.on(vh.Message,function(s){t._handleMessage(s)}),r.on(vh.Error,function(s){t._abort(Fn.SocketError,s)}),r.on(vh.Disconnected,function(){t.disconnected||(t.emitError(Fn.Network,"Lost connection to server."),t.disconnect())}),r.on(vh.Close,function(){t.disconnected||t._abort(Fn.SocketClosed,"Underlying socket is already closed.")}),r},e.prototype._initialize=function(t){this._id=t,this.socket.start(t,this._options.token)},e.prototype._handleMessage=function(t){var r,s,o=t.type,a=t.payload,l=t.src;switch(o){case Qr.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case Qr.Error:this._abort(Fn.ServerError,a.msg);break;case Qr.IdTaken:this._abort(Fn.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case Qr.InvalidKey:this._abort(Fn.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case Qr.Leave:dt.default.log("Received leave message from ".concat(l)),this._cleanupPeer(l),this._connections.delete(l);break;case Qr.Expire:this.emitError(Fn.PeerUnavailable,"Could not connect to peer ".concat(l));break;case Qr.Offer:var g=a.connectionId,v=this.getConnection(l,g);if(v&&(v.close(),dt.default.warn("Offer received for existing Connection ID:".concat(g))),a.type===pl.Media){var c=new DB.MediaConnection(l,this,{connectionId:g,_payload:a,metadata:a.metadata});v=c,this._addConnection(l,v),this.emit("call",c)}else if(a.type===pl.Data){var h=new FB.DataConnection(l,this,{connectionId:g,_payload:a,metadata:a.metadata,label:a.label,serialization:a.serialization,reliable:a.reliable});v=h,this._addConnection(l,v),this.emit("connection",h)}else{dt.default.warn("Received malformed connection type:".concat(a.type));return}var u=this._getMessages(g);try{for(var p=iA(u),m=p.next();!m.done;m=p.next()){var f=m.value;v.handleMessage(f)}}catch(y){r={error:y}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}break;default:if(!a){dt.default.warn("You received a malformed message from ".concat(l," of type ").concat(o));return}var g=a.connectionId,v=this.getConnection(l,g);v&&v.peerConnection?v.handleMessage(t):g?this._storeMessage(g,t):dt.default.warn("You received an unrecognized message:",t);break}},e.prototype._storeMessage=function(t,r){this._lostMessages.has(t)||this._lostMessages.set(t,[]),this._lostMessages.get(t).push(r)},e.prototype._getMessages=function(t){var r=this._lostMessages.get(t);return r?(this._lostMessages.delete(t),r):[]},e.prototype.connect=function(t,r){if(r===void 0&&(r={}),this.disconnected){dt.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(Fn.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var s=new FB.DataConnection(t,this,r);return this._addConnection(t,s),s},e.prototype.call=function(t,r,s){if(s===void 0&&(s={}),this.disconnected){dt.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(Fn.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!r){dt.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var o=new DB.MediaConnection(t,this,tA(tA({},s),{_stream:r}));return this._addConnection(t,o),o},e.prototype._addConnection=function(t,r){dt.default.log("add connection ".concat(r.type,":").concat(r.connectionId," to peerId:").concat(t)),this._connections.has(t)||this._connections.set(t,[]),this._connections.get(t).push(r)},e.prototype._removeConnection=function(t){var r=this._connections.get(t.peer);if(r){var s=r.indexOf(t);s!==-1&&r.splice(s,1)}this._lostMessages.delete(t.connectionId)},e.prototype.getConnection=function(t,r){var s,o,a=this._connections.get(t);if(!a)return null;try{for(var l=iA(a),c=l.next();!c.done;c=l.next()){var h=c.value;if(h.connectionId===r)return h}}catch(u){s={error:u}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(s)throw s.error}}return null},e.prototype._delayedAbort=function(t,r){var s=this;setTimeout(function(){s._abort(t,r)},0)},e.prototype._abort=function(t,r){dt.default.error("Aborting!"),this.emitError(t,r),this._lastServerId?this.disconnect():this.destroy()},e.prototype.emitError=function(t,r){dt.default.error("Error:",r);var s;typeof r=="string"?s=new Error(r):s=r,s.type=t,this.emit("error",s)},e.prototype.destroy=function(){this.destroyed||(dt.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},e.prototype._cleanup=function(){var t,r;try{for(var s=iA(this._connections.keys()),o=s.next();!o.done;o=s.next()){var a=o.value;this._cleanupPeer(a),this._connections.delete(a)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}this.socket.removeAllListeners()},e.prototype._cleanupPeer=function(t){var r,s,o=this._connections.get(t);if(o)try{for(var a=iA(o),l=a.next();!l.done;l=a.next()){var c=l.value;c.close()}}catch(h){r={error:h}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}},e.prototype.disconnect=function(){if(!this.disconnected){var t=this.id;dt.default.log("Disconnect peer with ID:".concat(t)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=t,this._id=null,this.emit("disconnected",t)}},e.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)dt.default.log("Attempting reconnection to server with ID ".concat(this._lastServerId)),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)dt.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},e.prototype.listAllPeers=function(t){var r=this;t===void 0&&(t=function(s){}),this._api.listAllPeers().then(function(s){return t(s)}).catch(function(s){return r._abort(Fn.ServerError,s)})},e.DEFAULT_KEY="peerjs",e}($y.EventEmitter),NB=UG.Peer;const lde=Object.freeze(Object.defineProperty({__proto__:null,get Peer(){return UB},default:NB,util:wi},Symbol.toStringTag,{value:"Module"}));let zB;function cde(){return zB}function hde(n){zB=n}function $G(n,e){return e||(e={}),e={...zB,...e},n?new NB(n,e):new NB(e)}async function e8(){const n=await Promise.resolve().then(()=>lde);return console.log(n),n.default===void 0?n:n.default}class t8{constructor(){d(this,"_host"),d(this,"_client"),d(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}async trySetupHost(e){const t=await e8(),r=new t(e);r.on("error",s=>{console.error(s),this._host=void 0,this.trySetupClient(e)}),r.on("open",s=>{this._host=new dde(r)})}async trySetupClient(e){const t=await e8();this._client=new t,this._client.on("error",r=>{console.error("Client error",r)}),this._client.on("open",r=>{console.log("client connected",r),this._clientData=this._client.connect(e,{metadata:{id:r}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",s=>{console.log("<<",s)})})}}class ude{constructor(e){d(this,"_peer"),this._peer=e}}class dde extends ude{constructor(e){var t;super(e),d(this,"_connections",[]),console.log("I AM THE HOST"),(t=this._peer)==null||t.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(r=>{var s;return(s=r.metadata)==null?void 0:s.id}).filter(r=>r!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const r=this._peer.connections[t];if(r)if(Array.isArray(r))for(const s of r)s&&s.send(e);else console.warn(r)}}}}const i8="https://urls.needle.tools/default-networking-backend/index";let Gu="wss://needle-tiny-starter.glitch.me/socket";const Zs=!!te("debugnet"),nA=!!(Zs||te("debugowner")),n8=te("debugnetbin");var r8=(n=>(n.ConnectionInfo="connection-start-info",n))(r8||{}),Vt=(n=>(n.Join="join-room",n.Leave="leave-room",n.JoinedRoom="joined-room",n.LeftRoom="left-room",n.UserJoinedRoom="user-joined-room",n.UserLeftRoom="user-left-room",n.RoomStateSent="room-state-sent",n))(Vt||{});class pde{constructor(){d(this,"room"),d(this,"viewId"),d(this,"allowEditing"),d(this,"inRoom")}}class mde{constructor(){d(this,"room")}}class fde{constructor(){d(this,"userId")}}var s8=(n=>(n.RequestHasOwner="request-has-owner",n.ResponseHasOwner="response-has-owner",n.RequestIsOwner="request-is-owner",n.ResponseIsOwner="response-is-owner",n.RequestOwnership="request-ownership",n.GainedOwnership="gained-ownership",n.RemoveOwnership="remove-ownership",n.LostOwnership="lost-ownership",n.GainedOwnershipBroadcast="gained-ownership-broadcast",n.LostOwnershipBroadcast="lost-ownership-broadcast",n))(s8||{});class jB{constructor(e,t){d(this,"guid"),d(this,"connection"),d(this,"_hasOwnership",!1),d(this,"_isOwned"),d(this,"_gainSubscription"),d(this,"_lostSubscription"),d(this,"_hasOwnerResponse"),d(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(nA&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let r=0;const s=()=>{if(r++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):s()},100)};s()})}requestOwnership(){return nA&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(nA&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(nA&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class o8{constructor(e){d(this,"context"),d(this,"_peer",null),d(this,"_usersInRoomCopy",[]),d(this,"_defaultMessagesBuffer",[]),d(this,"_defaultMessagesBufferArray",[]),d(this,"netWebSocketUrlProvider"),d(this,"_listeners",{}),d(this,"_listenersBinary",{}),d(this,"connected",!1),d(this,"channelId"),d(this,"_connectionId",null),d(this,"_ws"),d(this,"_waitingForSocket",{}),d(this,"_isInRoom",!1),d(this,"_currentRoomName",null),d(this,"_currentRoomViewId",null),d(this,"_currentRoomAllowEditing",!0),d(this,"_currentInRoom",[]),d(this,"_state",{}),d(this,"_currentDelay",-1),d(this,"_connectingToWebsocketPromise",null),this.context=e}get peer(){return this._peer||(this._peer=new t8),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Zs}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var e;return((e=this._ws)==null?void 0:e.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.connect(),Zs&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},dl.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,r=dl.Queued){if(t===null&&(t={}),r===dl.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,r)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){var t;n8&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),(t=this._ws)==null||t.send(e)}sendBufferedMessagesNow(){var e;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const t=Object.keys(this._defaultMessagesBuffer).length;for(const s in this._defaultMessagesBuffer){const o=this._defaultMessagesBuffer[s];if(t<=1){this.sendWithWebsocket(o.key,o.value,dl.Immediate);break}const a=this.toMessage(o.key,o.value);this._defaultMessagesBufferArray.push(a)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Zs&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const r=JSON.stringify(this._defaultMessagesBufferArray);(e=this._ws)==null||e.send(r)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const r=this._listeners[e].indexOf(t);r>=0&&this._listeners[e].splice(r,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const r=this._listenersBinary[e].indexOf(t);r>=0&&this._listenersBinary[e].splice(r,1)}registerProvider(e){this.netWebSocketUrlProvider=e}async connect(){var e;if(this.connected)return Promise.resolve(!0);Zs&&console.log("connecting");const t=(e=this.netWebSocketUrlProvider)==null?void 0:e.getWebsocketUrl();return t?Gu=t:kU()&&(Gu="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var e;(e=this._ws)==null||e.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{var r,s;let o=!1;const a=p=>{o||(o=!0,e(p))};if(Gu===void 0&&(console.log("Fetch default backend url: "+i8),Gu=await(await fetch(i8)).text()),Gu===void 0){a(!1);return}console.log(`\u22A1 Connecting to networking backend on
5233
5233
  `+Gu);const l=await Promise.resolve().then(()=>K_e),c=((r=l.default)==null?void 0:r.WebsocketBuilder)??l.WebsocketBuilder,h=((s=l.default)==null?void 0:s.ExponentialBackoff)??l.ExponentialBackoff,u=new c(Gu).withMaxRetries(3).withBackoff(new h(2e3,2)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=u,this.connected=!0,console.log(`\u229E Connected to networking backend
5234
- `+Gu),a(!0),this.onSendQueued(dl.OnConnection)}).onClose(p=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,a(!1)}).onError(p=>{console.error("\u22A0 Websocket error"),a(!1)}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();u.addEventListener(l.WebsocketEvent.message,(p,m)=>{this.onMessage(p,m)})})}onMessage(e,t){const r=t.data;try{if(typeof r!="string"){r.size&&this.handleIncomingBinaryMessage(r);return}const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(s);return}catch(s){Zs&&r==="pong"?console.log("<<",r):st()&&console.error("Failed to parse message",s)}}async handleIncomingBinaryMessage(e){nV&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var r=new Uint8Array(t);const s=new r_(r),o=s.getBufferIdentifier(),a=this._listenersBinary[o],l=N6(s),c=z6(l);if(c&&typeof c=="string"&&(this._state[c]=l),!a)return;const h=l??s;for(const u of a)u(h)}handleIncomingStringMessage(e){var t,r;if(Zs&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const l=e.data;l&&(console.assert(l.id!==void 0&&l.id!==null&&l.id.length>0,"server did not send connection id",l.id),console.log("Your id is: "+l.id,this.context.alias??""),this._connectionId=l.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Zs&&console.log(e),e){this._isInRoom=!0;const l=e;this._currentRoomName=l.room,this._currentRoomViewId=l.viewId,this._currentRoomAllowEditing=l.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...l.inRoom),Zs&&console.log("joined room with",this._currentInRoom,this.context.alias??"");const c=new URL(window.location.href);c.searchParams.has("room")&&c.searchParams.delete("room"),c.searchParams.set("view",this._currentRoomViewId),console.log("Room view id: "+this._currentRoomViewId+`
5235
- `+c.href)}this.onSendQueued(dl.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const l=e.data;this._currentInRoom.push(l.userId),Zs&&console.log(l.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const l=e.data,c=this._currentInRoom.indexOf(l.userId);c>=0&&(Zs&&console.log(l.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(c,1)),l.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Zs&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const a=(t=e.data)==null?void 0:t.time;a&&(this._currentDelay=this.context.time.time-a),Zs&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((r=this._currentInRoom)==null?void 0:r.length));break}const s=e.data;s&&(this._state[s.guid]=s);let o=this._listeners[e.key];if(o){o=[...o];for(const a of o)try{a(e.data)}catch(l){console.error('Error invoking callback for "'+e.key+'"',l)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,r=dl.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[r]||[];o.push(()=>this.sendWithWebsocket(e,t,r)),this._waitingForSocket[r]=o;return}const s=JSON.stringify(this.toMessage(e,t));Zs&&console.log(">>",e),this._ws.send(s)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const r of t)r();t.length=0}}}const rA=te("debugwebxr");class GB{constructor(e,t){d(this,"controllerStates",[]),d(this,"userId"),d(this,"context"),d(this,"userStateEvtName"),d(this,"onReceivedControllerState",r=>{rA&&console.log(`XRSync: Received change for ${this.userId}: ${r.type} ${r.handedness}; tracked=${r.isTracking}`);let s=!1;for(let o=0;o<this.controllerStates.length;o++)if(this.controllerStates[o].index===r.index){this.controllerStates[o]=r,s=!0;break}s||this.controllerStates.push(r)}),this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const r=this.controllerStates[t];let s=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===r.index&&(s=!0);s||(rA&&console.log(`XRSync: ${r.type} ${r.handedness} removed`,r.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(r))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(r=>r.index===e.index);if(t){let r=!1;r||(r=t.isTracking!=e.isTracking),r&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const r={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(r),this.context.connection.send(this.userStateEvtName,r),rA&&console.log(`XRSync: ${r.type} ${r.handedness} added`,r.index)}}}class aV{constructor(e){d(this,"context"),d(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(rA&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new GB(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new GB(t,this.context))}}),d(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),d(this,"onOtherUserJoinedRoom",t=>{const r=t.userId;this._states.has(r)||(rA&&console.log("XRSync: Remote user joined room",r),this._states.set(r,new GB(r,this.context)))}),d(this,"onOtherUserLeftRoom",t=>{const r=t.userId;if(!this._states.has(r)){const s=this._states.get(r);s?.dispose(),this._states.delete(r)}}),d(this,"_states",new Map),this.context=e,this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.isTracking||!1}getDeviceType(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.type||"unknown"}destroy(){this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class lV{constructor(){d(this,"_fadeToColorQuad"),d(this,"_fadeToColorMaterial"),d(this,"_requestedFadeValue",0),d(this,"_transitionPromise",null),d(this,"_transitionResolve",null),this._fadeToColorMaterial=new $t({color:0,transparent:!0,depthTest:!1,fog:!1,side:yi}),this._fadeToColorQuad=new me(new tr(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const r=this._fadeToColorQuad,s=this._fadeToColorMaterial;r.parent!==e&&s.opacity>0?e.add(r):s.opacity===0&&r.removeFromParent(),r.layers.set(2),r.material=this._fadeToColorMaterial,r.position.z=-1,r.renderOrder=1/0;const o=this._requestedFadeValue;s.opacity=it.lerp(s.opacity,o,t/.03),Math.abs(s.opacity-o)<=.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 e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Yp=(n=>(n[n.Quad=0]="Quad",n[n.Cube=1]="Cube",n[n.Sphere=2]="Sphere",n))(Yp||{});class sA{static createPrimitive(e,t){let r;switch(e){case"Quad":case 0:{const s=new tr(1,1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Cube":case 1:{const s=new qi(1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Sphere":case 2:{const s=new ja(.5,16,16),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break}return this.applyDefaultObjectOptions(r,t),r}static createSprite(e){const t=new lx({color:16777215});e!=null&&e.texture&&"map"in t&&(t.map=e.texture);const r=new OT(t);return this.applyDefaultObjectOptions(r,e),r}static applyDefaultObjectOptions(e,t){t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&e.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&e.scale.set(t.scale.x,t.scale.y,t.scale.z)}}const cV=class{constructor(n,e,t){d(this,"_session"),d(this,"_mode"),d(this,"_init"),d(this,"_renderer"),d(this,"_camera"),d(this,"_scene"),d(this,"onEnd",()=>{var r;(r=this._session)==null||r.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),d(this,"_lastTime",0),d(this,"onFrame",(r,s)=>{const o=r-this._lastTime;this.update(r,o),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),d(this,"_objects",[]),this._mode=n,this._init=e,this._session=t,this._session.addEventListener("end",this.onEnd),this._renderer=new Wc({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(t),this._renderer.xr.enabled=!0,this._camera=new Lt,this._scene=new Ur,this._scene.fog=new ax(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(n,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 t=await navigator.xr.requestSession(n,e);return t.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new cV(n,e,t),this._active):(t.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 Ll(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 n={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,n}async onBeforeHandoff(){await Ll(1e3),this._scene.clear()}setupScene(){this._scene.background=new xe(0),this._scene.add(new Hx(5,10,1118481,1118481));const n=new lp(16777215,1);n.position.set(0,20,0),n.castShadow=!1,this._scene.add(n);const e=new lp(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const t=new ap(16777215,1,100,1);t.position.set(0,2,0),t.castShadow=!1,t.distance=200,this._scene.add(t);const r=50;for(let s=0;s<100;s++){const o=new vs({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new xe(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const a=it.random(0,1)>.5?Yp.Sphere:Yp.Cube,l=sA.createPrimitive(a,{material:o});l.position.x=it.random(-r,r),l.position.y=it.random(-2,r),l.position.z=it.random(-r,r),l.rotation.x=it.random(0,Math.PI*2),l.rotation.y=it.random(0,Math.PI*2),l.rotation.z=it.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(n,e){const t=n*4e-4;for(let r=0;r<this._objects.length;r++){const s=this._objects[r];s.position.y+=Math.sin(t+r*.5)*.005,s.rotateY(.002)}}};let Lg=cV;d(Lg,"_active",null),d(Lg,"_requestInFlight",!1);const Sr=te("debugwebxr"),gde=te("stats");function vde(n){let e=null;const t=n;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=n,e}yde();async function yde(){var n;if(te("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],di.addContextCreatedCallback(async t=>{if(!e)return;Nf(!0);const r=await e;if(r){const s=wt.getDefaultSessionInit("immersive-vr");wt.setSession("immersive-vr",r,s,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(n=navigator.xr)==null||n.addEventListener("sessiongranted",async()=>{Nf(!0),console.log("Received Session Granted..."),await Ll(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,r=t?JSON.parse(t):null;let s=null;if(hV()&&(await Lg.start(e||"immersive-vr",r||wt.getDefaultSessionInit("immersive-vr")),await _de(),s=await Lg.handoff()),s)wt.setSession(s.mode,s.session,s.init,kt.Current);else if(e&&t){console.log("Session Granted: Restore last session");const o=JSON.parse(t);wt.start(e,o).catch(a=>console.warn(a))}else wt.start("immersive-vr").catch(o=>console.warn("Session Granted failed:",o))},{once:!0})}}function Ade(n,e){sessionStorage.setItem("needle_xr_session_mode",n),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function bde(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const VB=new Set;di.registerCallback(Ci.ContextCreationStart,async n=>{VB.add(n.context)}),di.registerCallback(Ci.ContextCreated,async n=>{VB.delete(n.context)});function hV(){return VB.size>0}function _de(){return new Promise(n=>{const e=Date.now(),t=setInterval(()=>{(!hV()||Date.now()-e>6e4)&&(clearInterval(t),n())},100)})}fp()&&st()&&window.addEventListener("keydown",n=>{(n.key==="x"||n.key==="Escape")&&wt.active&&wt.stop()});const Vu=class{constructor(n,e,t,r){d(this,"context"),d(this,"session"),d(this,"mode"),d(this,"controllers",[]),d(this,"_rigScale",1),d(this,"_lastRigScaleUpdate",-1),d(this,"_rigs",[]),d(this,"_viewerHitTestSource",null),d(this,"_defaultRig"),d(this,"_xr_scripts"),d(this,"_xr_update_scripts",[]),d(this,"_inactive_scripts",[]),d(this,"_controllerAdded"),d(this,"_controllerRemoved"),d(this,"_originalCameraWorldPosition"),d(this,"_originalCameraWorldRotation"),d(this,"_originalCameraWorldScale"),d(this,"_originalCameraParent"),d(this,"_mainCamera",null),d(this,"onRendererSessionSet",()=>{var a;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(a=this.context.mainCameraComponent)==null||a.applyClearFlags())}),d(this,"onInputSourceAdded",a=>{if(a.targetRayMode==="screen")return;let l=0;for(let h=0;h<this.session.inputSources.length;h++)if(this.session.inputSources[h]===a){l=h;break}if(this.controllers.find(h=>h.inputSource===a)){console.warn("Controller already exists for input source",l);return}Sr&&console.log("Adding controller",l);const c=new vB(this,a,l);this._newControllers.push(c)}),d(this,"_ended",!1),d(this,"_newControllers",[]),d(this,"onEnd",a=>{var l,c,h;if(this._ended)return;this._ended=!0,Sr&&console.log("XR Session ended"),bde(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,zu(this.onBefore,Hi.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const p=this.context.post_render_callbacks.indexOf(this.onAfterRender);p>=0&&this.context.post_render_callbacks.splice(p,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var m;(m=this.context.mainCameraComponent)==null||m.applyClearFlags()}),R6({session:this});for(const m of Vu._xrEndListeners)m({xr:this});for(let m=0;m<this.controllers.length;m++)this.disconnectInputSource(this.controllers[m].inputSource);for(const m of this._xr_scripts)(l=m?.onLeaveXR)==null||l.call(m,{xr:this});(c=this.sync)==null||c.onExitXR(this),this.context.mainCamera&&((h=this._originalCameraParent)==null||h.add(this.context.mainCamera),this._originalCameraWorldPosition&&lr(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&ca(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Uf(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Nf(!1)}),d(this,"_didStart",!1),d(this,"onBefore",a=>{var l,c,h,u,p,m,f,g;const v=a.xrFrame;if(!v)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((l=this.rig)==null?void 0:l.isActive)==!1&&(Sr&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(c=this._mainCamera)!=null&&c.gameObject&&((u=(h=this._mainCamera)==null?void 0:h.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((p=this._mainCamera)==null?void 0:p.gameObject),this.internalUpdateState(),this.applyCustomForward();const y={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const A=[...this.context.new_scripts_xr];for(let _=0;_<A.length;_++){const b=this.context.new_scripts_xr[_];if(!b||b.destroyed||((m=b.supportsXR)==null?void 0:m.call(b,this.mode))==!1){this.context.new_scripts_xr.splice(_,1);continue}if(!b.activeAndEnabled){this.context.new_scripts_xr.splice(_,1),this.markInactive(b);continue}if(this.addScript(b)){this.invokeCallback_EnterXR(b);for(const x of this.controllers)this.invokeCallback_ControllerAdded(b,x)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const _=Ul(this.context.scene.children);if(_){const b=_.getSize(pi());if(b.length()>0){const x=this._defaultRig.gameObject;x.position.set(_.min.x+b.x*.5,_.min.y,_.max.z+b.z*.5+1.5);const E=_.getCenter(pi());E.y=x.position.y,x.lookAt(E)}}}I6({session:this});for(const _ of Vu._xrStartListeners)_(y);const A=[...this._xr_scripts];Sr&&console.log("NeedleXRSession start, handle scripts:",A);for(const _ of A){if(_.destroyed){this._script_to_remove.push(_);continue}if(!_.activeAndEnabled){this.markInactive(_);continue}this.invokeCallback_EnterXR(_);for(const b of this.controllers)this.invokeCallback_ControllerAdded(_,b)}}this.syncCameraCullingMask();for(const A of this.controllers)A.onUpdate(v);if(this._newControllers.length>0){const A=[...this._newControllers];this._newControllers.length=0;for(const _ of A)if(_.connected){this.controllers.push(_);for(const b of this._xr_scripts){if(b.destroyed){this._script_to_remove.push(b);continue}b.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(b,_)}}this.controllers.sort((_,b)=>_.index-b.index)}for(const A of this._xr_update_scripts){if(A.destroyed===!0){this._script_to_remove.push(A);continue}if(A.activeAndEnabled===!1){this.markInactive(A);continue}A.onUpdateXR&&A.onUpdateXR(y)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const A=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const _ of A)!_.destroyed&&this.running&&((f=_.onLeaveXR)==null||f.call(_,y)),this.removeScript(_)}(g=this.sync)==null||g.onUpdate(this),this.onRenderDebug()}),d(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),d(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),fp()){const a=this.context.renderer;if(a.xr.isPresenting&&this.context.mainCamera){const l=a.xr.enabled,c=a.getRenderTarget();a.xr.enabled=!1,a.setRenderTarget(null),a.render(this.context.scene,this.context.mainCamera),a.xr.enabled=l,a.setRenderTarget(c)}}}),d(this,"_script_to_remove",[]),d(this,"_camera"),d(this,"_cameraRenderParent",new ye().rotateY(Math.PI)),d(this,"_previousCameraParent"),d(this,"_customforward",!0),d(this,"originalCameraNearPlane"),d(this,"_viewerPose"),d(this,"_transformOrientation",new Ce),d(this,"_transformPosition",new C),d(this,"_transition");var s,o;Ade(n,r.init),this.session=e,this.mode=n,this.context=t,(Sr||te("console"))&&Nf(!0),this._xr_scripts=[...r.scripts],this._xr_update_scripts=this._xr_scripts.filter(a=>typeof a.onUpdateXR=="function"),this._controllerAdded=r.controller_added,this._controllerRemoved=r.controller_removed,Nu(this.onBefore,Hi.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((s=r.init.optionalFeatures)!=null&&s.includes("hit-test")||(o=r.init.requiredFeatures)!=null&&o.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(a=>{var l,c;return(c=(l=e.requestHitTestSource)==null?void 0:l.call(e,{space:a}))==null?void 0:c.then(h=>this._viewerHitTestSource=h)}).catch(a=>console.warn(a)),this.context.mainCamera&&(this._originalCameraWorldPosition=Bt(this.context.mainCamera,new C),this._originalCameraWorldRotation=Mi(this.context.mainCamera,new Ce),this._originalCameraWorldScale=Vi(this.context.mainCamera,new C),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new Sue,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let a=0;a<e.inputSources.length;a++){const l=e.inputSources[a];if(!l.handedness){console.warn("Input source in xr session has no handedness - ignoring",a);continue}this.onInputSourceAdded(l)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",a=>{for(const l of a.removed)this.disconnectInputSource(l);for(const l of a.added)this.onInputSourceAdded(l)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(n){return this._sync||(this._sync=new aV(n)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var n;return((n=this._activeSession)==null?void 0:n.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(n=>n.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(n){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(n).catch(t=>(Sr&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(n){this._sessionRequestStartListeners.push(n)}static offSessionRequestStart(n){const e=this._sessionRequestStartListeners.indexOf(n);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(n){this._sessionRequestEndListeners.push(n)}static offSessionRequestEnd(n){const e=this._sessionRequestEndListeners.indexOf(n);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(n){this._xrStartListeners.push(n)}static offXRSessionStart(n){const e=this._xrStartListeners.indexOf(n);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(n){this._xrEndListeners.push(n)}static offXRSessionEnd(n){const e=this._xrEndListeners.indexOf(n);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(n){this._controllerAddedListeners.push(n)}static offControllerAdded(n){const e=this._controllerAddedListeners.indexOf(n);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(n){this._controllerRemovedListeners.push(n)}static offControllerRemoved(n){const e=this._controllerRemovedListeners.indexOf(n);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(n,e,t){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+n),e=="default"&&(e=this.getDefaultSessionInit(n)),navigator.xr.offerSession(n,{...e}).then(r=>Vu.setSession(n,r,e,t)).catch(r=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(n){switch(n){case"immersive-ar":return{optionalFeatures:["anchors","local-floor","hand-tracking","layers","dom-overlay","hit-test"]};case"immersive-vr":return{optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};default:return console.warn("No default session init for mode",n),{}}}static async start(n,e,t){var r,s,o,a;if(st()&&te("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Lg.start(n,e||Vu.getDefaultSessionInit(n)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Sr||st())&&Di("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(t||(t=kt.Current),t||(t=di.All[0]),!t)throw new Error("No Needle Engine Context found");switch(e||(e={}),n){case"immersive-ar":{if(await((r=this.xrSystem)==null?void 0:r.isSessionSupported("immersive-ar"))!==!0)return console.error(n+" is not supported by this browser."),null;const h=this.getDefaultSessionInit(n),u=vde(t.domElement);u&&!ew()&&(h.domOverlay={root:u},h.optionalFeatures.push("dom-overlay")),e={...h,...e}}break;case"immersive-vr":{if(await((s=this.xrSystem)==null?void 0:s.isSessionSupported("immersive-vr"))!==!0)return console.error(n+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(n),...e}}break;default:console.warn("No default session init for mode",n);break}e.optionalFeatures??(e.optionalFeatures=[]),e.requiredFeatures??(e.requiredFeatures=[]),await Lg.stop();const l=n=="immersive-ar"?t.scripts_immersive_ar:t.scripts_immersive_vr;Sr?console.log(`%cRequesting ${n} session`,"font-weight:bold;",e,l):console.log(`%cRequesting ${n} session`,"font-weight:bold;");for(const h of l)h.onBeforeXR&&h.onBeforeXR(n,e);for(const h of this._sessionRequestStartListeners)h({mode:n,init:e});Sr&&rn("Requesting "+n+" session ("+Date.now()+")"),this._currentSessionRequest=(o=navigator.xr)==null?void 0:o.requestSession(n,e),this._currentSessionRequestMode=n;const c=await((a=this._currentSessionRequest)==null?void 0:a.catch(h=>{console.error(h,"Code: "+h.code),h.code===9&&Di("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:"&&Di("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const h of this._sessionRequestEndListeners)h({mode:n,init:e,newSession:c||null});return c?this.setSession(n,c,e,t):(console.warn("XR Session request was rejected"),null)}static setSession(n,e,t,r){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=n=="immersive-ar"?r.scripts_immersive_ar:r.scripts_immersive_vr;return this._activeSession=new Vu(n,e,r,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:t}),e.addEventListener("end",this.onEnd),Sr?console.log(`%cStarted ${n} session`,"font-weight:bold;",s):console.log(`%cStarted ${n} session`,"font-weight:bold;"),this._activeSession}static stop(){var n;(n=this._activeSession)==null||n.end()}get sync(){return Vu._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(n=>n.isLeft)}get rightController(){return this.controllers.find(n=>n.isRight)}getController(n){return typeof n=="number"?this.controllers[n]||null:this.controllers.find(e=>e.side===n)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(n=>n.inputSource.targetRayMode==="tracked-pointer")||st()&&fp()&&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 n=this.frame.getImageTrackingResults();for(const e of n)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const n=this._rigs[0]??null;return n!=null&&n.gameObject&&Jp(n.gameObject)||n?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):n}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(n){this._rigs.indexOf(n)>=0||(n.priority===void 0&&(n.priority=0),this._rigs.push(n),this.updateActiveXRRig())}removeRig(n){const e=this._rigs.indexOf(n);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(n){const e=this._rigs.indexOf(n);this._rigs.splice(e,1),this._rigs.unshift(n),this.updateActiveXRRig()}updateActiveXRRig(){const n=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 t=1;t<this._rigs.length;t++){const r=this._rigs[t];if(r.isActive){if(Jp(r.gameObject)){this._rigs.splice(t,1),t--;continue}(!e||e.isActive===!1||r.priority!==void 0&&r.priority>e.priority)&&(e=r)}}if(n!==e){const t=this._rigs.indexOf(e);t>=0&&this._rigs.splice(t,1),this._rigs.unshift(e)}Sr&&(n===e?console.log("Updated Active XR Rig:",e,"prev:",n):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(n){if(n)return this.getControllerHitTest(n);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,t=this.frame.getHitTestResults(e);if(t.length>0){const r=t[0];return this.convertHitTestResult(r)}return null}getControllerHitTest(n){const e=n.hitTestSource;if(!e)return null;const t=this.frame.getHitTestResultsForTransientInput(e);for(const r of t)if(r.inputSource===n.inputSource)for(const s of r.results)return this.convertHitTestResult(s);return null}convertHitTestResult(n){const e=this.context.renderer.xr.getReferenceSpace(),t=e&&n.getPose(e);if(t){const r=pi(t.transform.position),s=bp(t.transform.orientation),o=this.context.mainCamera;if(o?.parent!==this._cameraRenderParent&&r.applyMatrix4(Y1),o!=null&&o.parent){r.applyMatrix4(o.parent.matrixWorld),s.multiply(Sa);const a=Mi(o.parent);a.premultiply(Sa),s.premultiply(a)}return{hit:n,position:r,quaternion:s}}return null}convertSpace(n){const e=pi(n.position);e.applyMatrix4(Y1);const t=bp(n.orientation);return t.premultiply(Sa),{position:e,quaternion:t}}disconnectInputSource(n){const e=(t,r,s)=>{if(t.inputSource===n){Sr&&console.log("Disconnecting controller",t.index),this.controllers.splice(s,1),this.invokeControllerEvent(t,this._controllerRemoved,"removed");const o={xr:this,controller:t,change:"removed"};for(const a of this._xr_scripts)a.onXRControllerRemoved&&a.onXRControllerRemoved(o);t.onDisconnected()}};for(let t=this.controllers.length-1;t>=0;t--){const r=this.controllers[t];e(r,this.controllers,t)}for(let t=this._newControllers.length-1;t>=0;t--){const r=this._newControllers[t];e(r,this._newControllers,t)}}end(){this._ended||this.session.end().catch(n=>console.warn(n))}onRenderDebug(){if(Sr)for(const n of this.controllers)n.onRenderDebug();if((Sr||gde)&&this.rig){const n=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;n.add(e.multiplyScalar(1.5));const t=this.rig.gameObject.worldUp;n.add(t.multiplyScalar(2.5));let r="";if(r+=this.context.time.smoothedFps.toFixed(1),Sr)for(const s of this.controllers)r+=`
5236
- ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking}`;At.DrawLabel(n,r)}}addScript(n){return this._xr_scripts.includes(n)?!1:(Sr&&console.log("Register new XRScript",n),this._xr_scripts.push(n),typeof n.onUpdateXR=="function"&&this._xr_update_scripts.push(n),!0)}markInactive(n){if(!(this._inactive_scripts.indexOf(n)>=0)){this.removeScript(n,!1),this._inactive_scripts.push(n);for(const e of this.controllers)this.invokeCallback_ControllerRemoved(n,e);this.invokeCallback_LeaveXR(n)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let n=this._inactive_scripts.length-1;n>=0;n--){const e=this._inactive_scripts[n];if(e.activeAndEnabled){this._inactive_scripts.splice(n,1),this.addScript(e),this.invokeCallback_EnterXR(e);for(const t of this.controllers)this.invokeCallback_ControllerAdded(e,t)}}}removeScript(n,e=!0){Sr&&console.log("Remove XRScript",n);const t=this._xr_scripts.indexOf(n);t>=0&&this._xr_scripts.splice(t,1);const r=this._xr_update_scripts.indexOf(n);if(r>=0&&this._xr_update_scripts.splice(r,1),e){const s=this._inactive_scripts.indexOf(n);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(n){n.onEnterXR&&n.onEnterXR({xr:this})}invokeCallback_ControllerAdded(n,e){n.onXRControllerAdded&&n.onXRControllerAdded({xr:this,controller:e,change:"added"})}invokeCallback_ControllerRemoved(n,e){n.onXRControllerRemoved&&n.onXRControllerRemoved({xr:this,controller:e,change:"removed"})}invokeCallback_LeaveXR(n){n.onLeaveXR&&!n.destroyed&&n.onLeaveXR({xr:this})}syncCameraCullingMask(){var n;const e=this.context.xrCamera,t=(n=this.context.mainCameraComponent)==null?void 0:n.cullingMask;if(e&&t!==void 0){for(const r of e.cameras)r.layers.mask=t;e.layers.mask=t}else if(e){for(const r of e.cameras)r.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(n,e,t){for(let r=e.length-1;r>=0;r--){const s=e[r];if(s)try{s({xr:this,controller:n,change:t})}catch(o){console.error(o)}}}applyCustomForward(){var n;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(n=this._previousCameraParent)==null||n.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const t=Vi(this.rig.gameObject);e*=t.x}this._camera instanceof Lt&&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 Lt&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const n=this.context.renderer.xr.getReferenceSpace();if(!n){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(n),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 lV),this._transition}fadeTransition(){return this._transition||(this._transition=new lV),this._transition.fadeTransition()}updateFade(n){this._transition&&n instanceof Lt&&this._transition.update(n,this.context.time.deltaTime)}onUpdateFade_PostRender(){var n;(n=this._transition)==null||n.remove()}};let wt=Vu;d(wt,"_sync",null),d(wt,"_currentSessionRequestMode",null),d(wt,"_currentSessionRequest"),d(wt,"_activeSession"),d(wt,"_sessionRequestStartListeners",[]),d(wt,"_sessionRequestEndListeners",[]),d(wt,"_xrStartListeners",[]),d(wt,"_xrEndListeners",[]),d(wt,"_controllerAddedListeners",[]),d(wt,"_controllerRemovedListeners",[]),d(wt,"onEnd",()=>{Sr&&console.log("XR Session ended"),Vu._activeSession=null});const QB=te("debugwebxr");class uV{static tryFindAvatarObjects(e,t,r){if(r.head&&r.leftHand&&r.rightHand)return;const s=e.name.toLocaleLowerCase();!r.head&&s.includes("head")&&(QB&&console.log("FOUND AVATAR HEAD",e.name),r.head=new ti("",t,e)),s.includes("hand")&&(!r.leftHand&&s.includes("left")&&(QB&&console.log("FOUND AVATAR LEFT HAND",e.name),r.leftHand=new ti("",t,e)),!r.rightHand&&s.includes("right")&&(QB&&console.log("FOUND AVATAR RIGHT HAND",e.name),r.rightHand=new ti("",t,e)));for(let o=0;o<e.children.length;o++){if(r.head&&r.leftHand&&r.rightHand)return;const a=e.children[o];this.tryFindAvatarObjects(a,t,r)}}}var cS=(n=>(n.Visible="application-visible",n.Hidden="application-hidden",n.MuteChanged="application-mutechanged",n))(cS||{});let hS=!1;const Fg=[];function Ug(){if(hS)return;st()&&console.debug("User interaction registered: audio can now be played"),hS=!0;const n=[...Fg];Fg.length=0,n.forEach(e=>e())}document.addEventListener("pointerdown",Ug),document.addEventListener("click",Ug),document.addEventListener("dragstart",Ug),document.addEventListener("touchstart",Ug),document.addEventListener("keydown",Ug),wt.onXRSessionStart(()=>{Ug()});const dV=class extends EventTarget{constructor(n){super(),d(this,"_mute",!1),d(this,"context"),d(this,"_isVisible",!0),this.context=n,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return hS}static registerWaitForInteraction(n){if(n!==null){if(hS){n();return}Fg.indexOf(n)===-1&&Fg.push(n)}}static unregisterWaitForInteraction(n){const e=Fg.indexOf(n);e!==-1&&Fg.splice(e,1)}get muted(){return this._mute}set muted(n){n!==this._mute&&(this._mute=n,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(n){switch(n.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};let Qu=dV;d(Qu,"registerWaitForAllowAudio",dV.registerWaitForInteraction);function*pV(n,e=null){const t=e?e.time:kt.Current.time,r=t.time;for(;t.time-r<n;)yield}function*xde(n){for(let e=0;e<n;e++)yield}function*mV(n){let e=!0;for(n.then(()=>e=!1),n.catch(()=>e=!1);e;)yield}class oA extends hI{constructor(e){super(e),this.type=rr}parse(e){const t=Math.pow(2.7182818,2.2);function r(S,B){let j=0;for(let N=0;N<65536;++N)(N==0||S[N>>3]&1<<(N&7))&&(B[j++]=N);const ee=j-1;for(;j<65536;)B[j++]=0;return ee}function s(S){for(let B=0;B<16384;B++)S[B]={},S[B].len=0,S[B].lit=0,S[B].p=null}const o={l:0,c:0,lc:0};function a(S,B,j,ee,N){for(;j<S;)B=B<<8|X(ee,N),j+=8;j-=S,o.l=B>>j&(1<<S)-1,o.c=B,o.lc=j}const l=new Array(59);function c(S){for(let j=0;j<=58;++j)l[j]=0;for(let j=0;j<65537;++j)l[S[j]]+=1;let B=0;for(let j=58;j>0;--j){const ee=B+l[j]>>1;l[j]=B,B=ee}for(let j=0;j<65537;++j){const ee=S[j];ee>0&&(S[j]=ee|l[ee]++<<6)}}function h(S,B,j,ee,N,Y){const W=B;let ae=0,ce=0;for(;ee<=N;ee++){if(W.value-B.value>j)return!1;a(6,ae,ce,S,W);const _e=o.l;if(ae=o.c,ce=o.lc,Y[ee]=_e,_e==63){if(W.value-B.value>j)throw new Error("Something wrong with hufUnpackEncTable");a(8,ae,ce,S,W);let Re=o.l+6;if(ae=o.c,ce=o.lc,ee+Re>N+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Re--;)Y[ee++]=0;ee--}else if(_e>=59){let Re=_e-59+2;if(ee+Re>N+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Re--;)Y[ee++]=0;ee--}}c(Y)}function u(S){return S&63}function p(S){return S>>6}function m(S,B,j,ee){for(;B<=j;B++){const N=p(S[B]),Y=u(S[B]);if(N>>Y)throw new Error("Invalid table entry");if(Y>14){const W=ee[N>>Y-14];if(W.len)throw new Error("Invalid table entry");if(W.lit++,W.p){const ae=W.p;W.p=new Array(W.lit);for(let ce=0;ce<W.lit-1;++ce)W.p[ce]=ae[ce]}else W.p=new Array(1);W.p[W.lit-1]=B}else if(Y){let W=0;for(let ae=1<<14-Y;ae>0;ae--){const ce=ee[(N<<14-Y)+W];if(ce.len||ce.p)throw new Error("Invalid table entry");ce.len=Y,ce.lit=B,W++}}}return!0}const f={c:0,lc:0};function g(S,B,j,ee){S=S<<8|X(j,ee),B+=8,f.c=S,f.lc=B}const v={c:0,lc:0};function y(S,B,j,ee,N,Y,W,ae,ce){if(S==B){ee<8&&(g(j,ee,N,Y),j=f.c,ee=f.lc),ee-=8;let _e=j>>ee;if(_e=new Uint8Array([_e])[0],ae.value+_e>ce)return!1;const Re=W[ae.value-1];for(;_e-- >0;)W[ae.value++]=Re}else if(ae.value<ce)W[ae.value++]=S;else return!1;v.c=j,v.lc=ee}function A(S){return S&65535}function _(S){const B=A(S);return B>32767?B-65536:B}const b={a:0,b:0};function x(S,B){const j=_(S),ee=_(B),N=j+(ee&1)+(ee>>1),Y=N,W=N-ee;b.a=Y,b.b=W}function E(S,B){const j=A(S),ee=A(B),N=j-(ee>>1)&65535,Y=ee+N-32768&65535;b.a=Y,b.b=N}function I(S,B,j,ee,N,Y,W){const ae=W<16384,ce=j>N?N:j;let _e=1,Re,Xe;for(;_e<=ce;)_e<<=1;for(_e>>=1,Re=_e,_e>>=1;_e>=1;){Xe=0;const We=Xe+Y*(N-Re),Ke=Y*_e,gt=Y*Re,rt=ee*_e,xt=ee*Re;let Jt,Ui,en,pr;for(;Xe<=We;Xe+=gt){let ki=Xe;const ai=Xe+ee*(j-Re);for(;ki<=ai;ki+=xt){const Pn=ki+rt,ro=ki+Ke,Vn=ro+rt;ae?(x(S[ki+B],S[ro+B]),Jt=b.a,en=b.b,x(S[Pn+B],S[Vn+B]),Ui=b.a,pr=b.b,x(Jt,Ui),S[ki+B]=b.a,S[Pn+B]=b.b,x(en,pr),S[ro+B]=b.a,S[Vn+B]=b.b):(E(S[ki+B],S[ro+B]),Jt=b.a,en=b.b,E(S[Pn+B],S[Vn+B]),Ui=b.a,pr=b.b,E(Jt,Ui),S[ki+B]=b.a,S[Pn+B]=b.b,E(en,pr),S[ro+B]=b.a,S[Vn+B]=b.b)}if(j&_e){const Pn=ki+Ke;ae?x(S[ki+B],S[Pn+B]):E(S[ki+B],S[Pn+B]),Jt=b.a,S[Pn+B]=b.b,S[ki+B]=Jt}}if(N&_e){let ki=Xe;const ai=Xe+ee*(j-Re);for(;ki<=ai;ki+=xt){const Pn=ki+rt;ae?x(S[ki+B],S[Pn+B]):E(S[ki+B],S[Pn+B]),Jt=b.a,S[Pn+B]=b.b,S[ki+B]=Jt}}Re=_e,_e>>=1}return Xe}function T(S,B,j,ee,N,Y,W,ae,ce){let _e=0,Re=0;const Xe=W,We=Math.trunc(ee.value+(N+7)/8);for(;ee.value<We;)for(g(_e,Re,j,ee),_e=f.c,Re=f.lc;Re>=14;){const gt=_e>>Re-14&16383,rt=B[gt];if(rt.len)Re-=rt.len,y(rt.lit,Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;else{if(!rt.p)throw new Error("hufDecode issues");let xt;for(xt=0;xt<rt.lit;xt++){const Jt=u(S[rt.p[xt]]);for(;Re<Jt&&ee.value<We;)g(_e,Re,j,ee),_e=f.c,Re=f.lc;if(Re>=Jt&&p(S[rt.p[xt]])==(_e>>Re-Jt&(1<<Jt)-1)){Re-=Jt,y(rt.p[xt],Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;break}}if(xt==rt.lit)throw new Error("hufDecode issues")}}const Ke=8-N&7;for(_e>>=Ke,Re-=Ke;Re>0;){const gt=B[_e<<14-Re&16383];if(gt.len)Re-=gt.len,y(gt.lit,Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;else throw new Error("hufDecode issues")}return!0}function R(S,B,j,ee,N,Y){const W={value:0},ae=j.value,ce=fe(B,j),_e=fe(B,j);j.value+=4;const Re=fe(B,j);if(j.value+=4,ce<0||ce>=65537||_e<0||_e>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const Xe=new Array(65537),We=new Array(16384);s(We);const Ke=ee-(j.value-ae);if(h(S,j,Ke,ce,_e,Xe),Re>8*(ee-(j.value-ae)))throw new Error("Something wrong with hufUncompress");m(Xe,ce,_e,We),T(Xe,We,S,j,Re,_e,Y,N,W)}function D(S,B,j){for(let ee=0;ee<j;++ee)B[ee]=S[B[ee]]}function M(S){for(let B=1;B<S.length;B++){const j=S[B-1]+S[B]-128;S[B]=j}}function P(S,B){let j=0,ee=Math.floor((S.length+1)/2),N=0;const Y=S.length-1;for(;!(N>Y||(B[N++]=S[j++],N>Y));)B[N++]=S[ee++]}function z(S){let B=S.byteLength;const j=new Array;let ee=0;const N=new DataView(S);for(;B>0;){const Y=N.getInt8(ee++);if(Y<0){const W=-Y;B-=W+1;for(let ae=0;ae<W;ae++)j.push(N.getUint8(ee++))}else{const W=Y;B-=2;const ae=N.getUint8(ee++);for(let ce=0;ce<W+1;ce++)j.push(ae)}}return j}function V(S,B,j,ee,N,Y){let W=new DataView(Y.buffer);const ae=j[S.idx[0]].width,ce=j[S.idx[0]].height,_e=3,Re=Math.floor(ae/8),Xe=Math.ceil(ae/8),We=Math.ceil(ce/8),Ke=ae-(Xe-1)*8,gt=ce-(We-1)*8,rt={value:0},xt=new Array(_e),Jt=new Array(_e),Ui=new Array(_e),en=new Array(_e),pr=new Array(_e);for(let ai=0;ai<_e;++ai)pr[ai]=B[S.idx[ai]],xt[ai]=ai<1?0:xt[ai-1]+Xe*We,Jt[ai]=new Float32Array(64),Ui[ai]=new Uint16Array(64),en[ai]=new Uint16Array(Xe*64);for(let ai=0;ai<We;++ai){let Pn=8;ai==We-1&&(Pn=gt);let ro=8;for(let U=0;U<Xe;++U){U==Xe-1&&(ro=Ke);for(let ne=0;ne<_e;++ne)Ui[ne].fill(0),Ui[ne][0]=N[xt[ne]++],L(rt,ee,Ui[ne]),H(Ui[ne],Jt[ne]),O(Jt[ne]);F(Jt);for(let ne=0;ne<_e;++ne)G(Jt[ne],en[ne],U*64)}let Vn=0;for(let U=0;U<_e;++U){const ne=j[S.idx[U]].type;for(let pe=8*ai;pe<8*ai+Pn;++pe){Vn=pr[U][pe];for(let ge=0;ge<Re;++ge){const le=ge*64+(pe&7)*8;W.setUint16(Vn+0*2*ne,en[U][le+0],!0),W.setUint16(Vn+1*2*ne,en[U][le+1],!0),W.setUint16(Vn+2*2*ne,en[U][le+2],!0),W.setUint16(Vn+3*2*ne,en[U][le+3],!0),W.setUint16(Vn+4*2*ne,en[U][le+4],!0),W.setUint16(Vn+5*2*ne,en[U][le+5],!0),W.setUint16(Vn+6*2*ne,en[U][le+6],!0),W.setUint16(Vn+7*2*ne,en[U][le+7],!0),Vn+=8*2*ne}}if(Re!=Xe)for(let pe=8*ai;pe<8*ai+Pn;++pe){const ge=pr[U][pe]+8*Re*2*ne,le=Re*64+(pe&7)*8;for(let Ze=0;Ze<ro;++Ze)W.setUint16(ge+Ze*2*ne,en[U][le+Ze],!0)}}}const ki=new Uint16Array(ae);W=new DataView(Y.buffer);for(let ai=0;ai<_e;++ai){j[S.idx[ai]].decoded=!0;const Pn=j[S.idx[ai]].type;if(j[ai].type==2)for(let ro=0;ro<ce;++ro){const Vn=pr[ai][ro];for(let U=0;U<ae;++U)ki[U]=W.getUint16(Vn+U*2*Pn,!0);for(let U=0;U<ae;++U)W.setFloat32(Vn+U*2*Pn,Ae(ki[U]),!0)}}}function L(S,B,j){let ee,N=1;for(;N<64;)ee=B[S.value],ee==65280?N=64:ee>>8==255?N+=ee&255:(j[N]=ee,N++),S.value++}function H(S,B){B[0]=Ae(S[0]),B[1]=Ae(S[1]),B[2]=Ae(S[5]),B[3]=Ae(S[6]),B[4]=Ae(S[14]),B[5]=Ae(S[15]),B[6]=Ae(S[27]),B[7]=Ae(S[28]),B[8]=Ae(S[2]),B[9]=Ae(S[4]),B[10]=Ae(S[7]),B[11]=Ae(S[13]),B[12]=Ae(S[16]),B[13]=Ae(S[26]),B[14]=Ae(S[29]),B[15]=Ae(S[42]),B[16]=Ae(S[3]),B[17]=Ae(S[8]),B[18]=Ae(S[12]),B[19]=Ae(S[17]),B[20]=Ae(S[25]),B[21]=Ae(S[30]),B[22]=Ae(S[41]),B[23]=Ae(S[43]),B[24]=Ae(S[9]),B[25]=Ae(S[11]),B[26]=Ae(S[18]),B[27]=Ae(S[24]),B[28]=Ae(S[31]),B[29]=Ae(S[40]),B[30]=Ae(S[44]),B[31]=Ae(S[53]),B[32]=Ae(S[10]),B[33]=Ae(S[19]),B[34]=Ae(S[23]),B[35]=Ae(S[32]),B[36]=Ae(S[39]),B[37]=Ae(S[45]),B[38]=Ae(S[52]),B[39]=Ae(S[54]),B[40]=Ae(S[20]),B[41]=Ae(S[22]),B[42]=Ae(S[33]),B[43]=Ae(S[38]),B[44]=Ae(S[46]),B[45]=Ae(S[51]),B[46]=Ae(S[55]),B[47]=Ae(S[60]),B[48]=Ae(S[21]),B[49]=Ae(S[34]),B[50]=Ae(S[37]),B[51]=Ae(S[47]),B[52]=Ae(S[50]),B[53]=Ae(S[56]),B[54]=Ae(S[59]),B[55]=Ae(S[61]),B[56]=Ae(S[35]),B[57]=Ae(S[36]),B[58]=Ae(S[48]),B[59]=Ae(S[49]),B[60]=Ae(S[57]),B[61]=Ae(S[58]),B[62]=Ae(S[62]),B[63]=Ae(S[63])}function O(S){const B=.5*Math.cos(.7853975),j=.5*Math.cos(3.14159/16),ee=.5*Math.cos(3.14159/8),N=.5*Math.cos(3*3.14159/16),Y=.5*Math.cos(5*3.14159/16),W=.5*Math.cos(3*3.14159/8),ae=.5*Math.cos(7*3.14159/16),ce=new Array(4),_e=new Array(4),Re=new Array(4),Xe=new Array(4);for(let We=0;We<8;++We){const Ke=We*8;ce[0]=ee*S[Ke+2],ce[1]=W*S[Ke+2],ce[2]=ee*S[Ke+6],ce[3]=W*S[Ke+6],_e[0]=j*S[Ke+1]+N*S[Ke+3]+Y*S[Ke+5]+ae*S[Ke+7],_e[1]=N*S[Ke+1]-ae*S[Ke+3]-j*S[Ke+5]-Y*S[Ke+7],_e[2]=Y*S[Ke+1]-j*S[Ke+3]+ae*S[Ke+5]+N*S[Ke+7],_e[3]=ae*S[Ke+1]-Y*S[Ke+3]+N*S[Ke+5]-j*S[Ke+7],Re[0]=B*(S[Ke+0]+S[Ke+4]),Re[3]=B*(S[Ke+0]-S[Ke+4]),Re[1]=ce[0]+ce[3],Re[2]=ce[1]-ce[2],Xe[0]=Re[0]+Re[1],Xe[1]=Re[3]+Re[2],Xe[2]=Re[3]-Re[2],Xe[3]=Re[0]-Re[1],S[Ke+0]=Xe[0]+_e[0],S[Ke+1]=Xe[1]+_e[1],S[Ke+2]=Xe[2]+_e[2],S[Ke+3]=Xe[3]+_e[3],S[Ke+4]=Xe[3]-_e[3],S[Ke+5]=Xe[2]-_e[2],S[Ke+6]=Xe[1]-_e[1],S[Ke+7]=Xe[0]-_e[0]}for(let We=0;We<8;++We)ce[0]=ee*S[16+We],ce[1]=W*S[16+We],ce[2]=ee*S[48+We],ce[3]=W*S[48+We],_e[0]=j*S[8+We]+N*S[24+We]+Y*S[40+We]+ae*S[56+We],_e[1]=N*S[8+We]-ae*S[24+We]-j*S[40+We]-Y*S[56+We],_e[2]=Y*S[8+We]-j*S[24+We]+ae*S[40+We]+N*S[56+We],_e[3]=ae*S[8+We]-Y*S[24+We]+N*S[40+We]-j*S[56+We],Re[0]=B*(S[We]+S[32+We]),Re[3]=B*(S[We]-S[32+We]),Re[1]=ce[0]+ce[3],Re[2]=ce[1]-ce[2],Xe[0]=Re[0]+Re[1],Xe[1]=Re[3]+Re[2],Xe[2]=Re[3]-Re[2],Xe[3]=Re[0]-Re[1],S[0+We]=Xe[0]+_e[0],S[8+We]=Xe[1]+_e[1],S[16+We]=Xe[2]+_e[2],S[24+We]=Xe[3]+_e[3],S[32+We]=Xe[3]-_e[3],S[40+We]=Xe[2]-_e[2],S[48+We]=Xe[1]-_e[1],S[56+We]=Xe[0]-_e[0]}function F(S){for(let B=0;B<64;++B){const j=S[0][B],ee=S[1][B],N=S[2][B];S[0][B]=j+1.5747*N,S[1][B]=j-.1873*ee-.4682*N,S[2][B]=j+1.8556*ee}}function G(S,B,j){for(let ee=0;ee<64;++ee)B[j+ee]=Wd.toHalfFloat(J(S[ee]))}function J(S){return S<=1?Math.sign(S)*Math.pow(Math.abs(S),2.2):Math.sign(S)*Math.pow(t,Math.abs(S)-1)}function K(S){return new DataView(S.array.buffer,S.offset.value,S.size)}function oe(S){const B=S.viewer.buffer.slice(S.offset.value,S.offset.value+S.size),j=new Uint8Array(z(B)),ee=new Uint8Array(j.length);return M(j),P(j,ee),new DataView(ee.buffer)}function we(S){const B=S.array.slice(S.offset.value,S.offset.value+S.size),j=Iy(B),ee=new Uint8Array(j.length);return M(j),P(j,ee),new DataView(ee.buffer)}function De(S){const B=S.viewer,j={value:S.offset.value},ee=new Uint16Array(S.width*S.scanlineBlockSize*(S.channels*S.type)),N=new Uint8Array(8192);let Y=0;const W=new Array(S.channels);for(let gt=0;gt<S.channels;gt++)W[gt]={},W[gt].start=Y,W[gt].end=W[gt].start,W[gt].nx=S.width,W[gt].ny=S.lines,W[gt].size=S.type,Y+=W[gt].nx*W[gt].ny*W[gt].size;const ae=et(B,j),ce=et(B,j);if(ce>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(ae<=ce)for(let gt=0;gt<ce-ae+1;gt++)N[gt+ae]=ze(B,j);const _e=new Uint16Array(65536),Re=r(N,_e),Xe=fe(B,j);R(S.array,B,j,Xe,ee,Y);for(let gt=0;gt<S.channels;++gt){const rt=W[gt];for(let xt=0;xt<W[gt].size;++xt)I(ee,rt.start+xt,rt.nx,rt.size,rt.ny,rt.nx*rt.size,Re)}D(_e,ee,Y);let We=0;const Ke=new Uint8Array(ee.buffer.byteLength);for(let gt=0;gt<S.lines;gt++)for(let rt=0;rt<S.channels;rt++){const xt=W[rt],Jt=xt.nx*xt.size,Ui=new Uint8Array(ee.buffer,xt.end*2,Jt*2);Ke.set(Ui,We),We+=Jt*2,xt.end+=Jt}return new DataView(Ke.buffer)}function se(S){const B=S.array.slice(S.offset.value,S.offset.value+S.size),j=Iy(B),ee=S.lines*S.channels*S.width,N=S.type==1?new Uint16Array(ee):new Uint32Array(ee);let Y=0,W=0;const ae=new Array(4);for(let ce=0;ce<S.lines;ce++)for(let _e=0;_e<S.channels;_e++){let Re=0;switch(S.type){case 1:ae[0]=Y,ae[1]=ae[0]+S.width,Y=ae[1]+S.width;for(let Xe=0;Xe<S.width;++Xe){const We=j[ae[0]++]<<8|j[ae[1]++];Re+=We,N[W]=Re,W++}break;case 2:ae[0]=Y,ae[1]=ae[0]+S.width,ae[2]=ae[1]+S.width,Y=ae[2]+S.width;for(let Xe=0;Xe<S.width;++Xe){const We=j[ae[0]++]<<24|j[ae[1]++]<<16|j[ae[2]++]<<8;Re+=We,N[W]=Re,W++}break}}return new DataView(N.buffer)}function be(S){const B=S.viewer,j={value:S.offset.value},ee=new Uint8Array(S.width*S.lines*(S.channels*S.type*2)),N={version:Te(B,j),unknownUncompressedSize:Te(B,j),unknownCompressedSize:Te(B,j),acCompressedSize:Te(B,j),dcCompressedSize:Te(B,j),rleCompressedSize:Te(B,j),rleUncompressedSize:Te(B,j),rleRawSize:Te(B,j),totalAcUncompressedCount:Te(B,j),totalDcUncompressedCount:Te(B,j),acCompression:Te(B,j)};if(N.version<2)throw new Error("EXRLoader.parse: "+qt.compression+" version "+N.version+" is unsupported");const Y=new Array;let W=et(B,j)-2;for(;W>0;){const rt=Ie(B.buffer,j),xt=ze(B,j),Jt=xt>>2&3,Ui=(xt>>4)-1,en=new Int8Array([Ui])[0],pr=ze(B,j);Y.push({name:rt,index:en,type:pr,compression:Jt}),W-=rt.length+3}const ae=qt.channels,ce=new Array(S.channels);for(let rt=0;rt<S.channels;++rt){const xt=ce[rt]={},Jt=ae[rt];xt.name=Jt.name,xt.compression=0,xt.decoded=!1,xt.type=Jt.pixelType,xt.pLinear=Jt.pLinear,xt.width=S.width,xt.height=S.lines}const _e={idx:new Array(3)};for(let rt=0;rt<S.channels;++rt){const xt=ce[rt];for(let Jt=0;Jt<Y.length;++Jt){const Ui=Y[Jt];xt.name==Ui.name&&(xt.compression=Ui.compression,Ui.index>=0&&(_e.idx[Ui.index]=rt),xt.offset=rt)}}let Re,Xe,We;if(N.acCompressedSize>0)switch(N.acCompression){case 0:Re=new Uint16Array(N.totalAcUncompressedCount),R(S.array,B,j,N.acCompressedSize,Re,N.totalAcUncompressedCount);break;case 1:const rt=S.array.slice(j.value,j.value+N.totalAcUncompressedCount),xt=Iy(rt);Re=new Uint16Array(xt.buffer),j.value+=N.totalAcUncompressedCount;break}if(N.dcCompressedSize>0){const rt={array:S.array,offset:j,size:N.dcCompressedSize};Xe=new Uint16Array(we(rt).buffer),j.value+=N.dcCompressedSize}if(N.rleRawSize>0){const rt=S.array.slice(j.value,j.value+N.rleCompressedSize),xt=Iy(rt);We=z(xt.buffer),j.value+=N.rleCompressedSize}let Ke=0;const gt=new Array(ce.length);for(let rt=0;rt<gt.length;++rt)gt[rt]=new Array;for(let rt=0;rt<S.lines;++rt)for(let xt=0;xt<ce.length;++xt)gt[xt].push(Ke),Ke+=ce[xt].width*S.type*2;V(_e,gt,ce,Re,Xe,ee);for(let rt=0;rt<ce.length;++rt){const xt=ce[rt];if(!xt.decoded)switch(xt.compression){case 2:let Jt=0,Ui=0;for(let en=0;en<S.lines;++en){let pr=gt[rt][Jt];for(let ki=0;ki<xt.width;++ki){for(let ai=0;ai<2*xt.type;++ai)ee[pr++]=We[Ui+ai*xt.width*xt.height];Ui++}Jt++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(ee.buffer)}function Ie(S,B){const j=new Uint8Array(S);let ee=0;for(;j[B.value+ee]!=0;)ee+=1;const N=new TextDecoder().decode(j.slice(B.value,B.value+ee));return B.value=B.value+ee+1,N}function Je(S,B,j){const ee=new TextDecoder().decode(new Uint8Array(S).slice(B.value,B.value+j));return B.value=B.value+j,ee}function $e(S,B){const j=lt(S,B),ee=fe(S,B);return[j,ee]}function Oe(S,B){const j=fe(S,B),ee=fe(S,B);return[j,ee]}function lt(S,B){const j=S.getInt32(B.value,!0);return B.value=B.value+4,j}function fe(S,B){const j=S.getUint32(B.value,!0);return B.value=B.value+4,j}function X(S,B){const j=S[B.value];return B.value=B.value+1,j}function ze(S,B){const j=S.getUint8(B.value);return B.value=B.value+1,j}const Te=function(S,B){let j;return"getBigInt64"in DataView.prototype?j=Number(S.getBigInt64(B.value,!0)):j=S.getUint32(B.value+4,!0)+Number(S.getUint32(B.value,!0)<<32),B.value+=8,j};function Me(S,B){const j=S.getFloat32(B.value,!0);return B.value+=4,j}function Qe(S,B){return Wd.toHalfFloat(Me(S,B))}function Ae(S){const B=(S&31744)>>10,j=S&1023;return(S>>15?-1:1)*(B?B===31?j?NaN:1/0:Math.pow(2,B-15)*(1+j/1024):6103515625e-14*(j/1024))}function et(S,B){const j=S.getUint16(B.value,!0);return B.value+=2,j}function ct(S,B){return Ae(et(S,B))}function Tt(S,B,j,ee){const N=j.value,Y=[];for(;j.value<N+ee-1;){const W=Ie(B,j),ae=lt(S,j),ce=ze(S,j);j.value+=3;const _e=lt(S,j),Re=lt(S,j);Y.push({name:W,pixelType:ae,pLinear:ce,xSampling:_e,ySampling:Re})}return j.value+=1,Y}function Q(S,B){const j=Me(S,B),ee=Me(S,B),N=Me(S,B),Y=Me(S,B),W=Me(S,B),ae=Me(S,B),ce=Me(S,B),_e=Me(S,B);return{redX:j,redY:ee,greenX:N,greenY:Y,blueX:W,blueY:ae,whiteX:ce,whiteY:_e}}function k(S,B){const j=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],ee=ze(S,B);return j[ee]}function he(S,B){const j=fe(S,B),ee=fe(S,B),N=fe(S,B),Y=fe(S,B);return{xMin:j,yMin:ee,xMax:N,yMax:Y}}function Ee(S,B){const j=["INCREASING_Y"],ee=ze(S,B);return j[ee]}function Le(S,B){const j=Me(S,B),ee=Me(S,B);return[j,ee]}function Pe(S,B){const j=Me(S,B),ee=Me(S,B),N=Me(S,B);return[j,ee,N]}function vt(S,B,j,ee,N){if(ee==="string"||ee==="stringvector"||ee==="iccProfile")return Je(B,j,N);if(ee==="chlist")return Tt(S,B,j,N);if(ee==="chromaticities")return Q(S,j);if(ee==="compression")return k(S,j);if(ee==="box2i")return he(S,j);if(ee==="lineOrder")return Ee(S,j);if(ee==="float")return Me(S,j);if(ee==="v2f")return Le(S,j);if(ee==="v3f")return Pe(S,j);if(ee==="int")return lt(S,j);if(ee==="rational")return $e(S,j);if(ee==="timecode")return Oe(S,j);if(ee==="preview")return j.value+=N,"skipped";j.value+=N}function ht(S,B,j){const ee={};if(S.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");ee.version=S.getUint8(4);const N=S.getUint8(5);ee.spec={singleTile:!!(N&2),longName:!!(N&4),deepFormat:!!(N&8),multiPart:!!(N&16)},j.value=8;let Y=!0;for(;Y;){const W=Ie(B,j);if(W==0)Y=!1;else{const ae=Ie(B,j),ce=fe(S,j),_e=vt(S,B,j,ae,ce);_e===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${ae}'.`):ee[W]=_e}}if(N&-5)throw console.error("THREE.EXRHeader:",ee),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return ee}function je(S,B,j,ee,N){const Y={size:0,viewer:B,array:j,offset:ee,width:S.dataWindow.xMax-S.dataWindow.xMin+1,height:S.dataWindow.yMax-S.dataWindow.yMin+1,channels:S.channels.length,bytesPerLine:null,lines:null,inputSize:null,type:S.channels[0].pixelType,uncompress:null,getter:null,format:null,colorSpace:Ri};switch(S.compression){case"NO_COMPRESSION":Y.lines=1,Y.uncompress=K;break;case"RLE_COMPRESSION":Y.lines=1,Y.uncompress=oe;break;case"ZIPS_COMPRESSION":Y.lines=1,Y.uncompress=we;break;case"ZIP_COMPRESSION":Y.lines=16,Y.uncompress=we;break;case"PIZ_COMPRESSION":Y.lines=32,Y.uncompress=De;break;case"PXR24_COMPRESSION":Y.lines=16,Y.uncompress=se;break;case"DWAA_COMPRESSION":Y.lines=32,Y.uncompress=be;break;case"DWAB_COMPRESSION":Y.lines=256,Y.uncompress=be;break;default:throw new Error("EXRLoader.parse: "+S.compression+" is unsupported")}if(Y.scanlineBlockSize=Y.lines,Y.type==1)switch(N){case kn:Y.getter=ct,Y.inputSize=2;break;case rr:Y.getter=et,Y.inputSize=2;break}else if(Y.type==2)switch(N){case kn:Y.getter=Me,Y.inputSize=4;break;case rr:Y.getter=Qe,Y.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+Y.type+" for "+S.compression+".");Y.blockCount=(S.dataWindow.yMax+1)/Y.scanlineBlockSize;for(let ae=0;ae<Y.blockCount;ae++)Te(B,ee);Y.outputChannels=Y.channels==3?4:Y.channels;const W=Y.width*Y.height*Y.outputChannels;switch(N){case kn:Y.byteArray=new Float32Array(W),Y.channels<Y.outputChannels&&Y.byteArray.fill(1,0,W);break;case rr:Y.byteArray=new Uint16Array(W),Y.channels<Y.outputChannels&&Y.byteArray.fill(15360,0,W);break;default:console.error("THREE.EXRLoader: unsupported type: ",N);break}return Y.bytesPerLine=Y.width*Y.inputSize*Y.channels,Y.outputChannels==4?(Y.format=Yi,Y.colorSpace=Ri):(Y.format=Zm,Y.colorSpace=lo),Y}const Ve=new DataView(e),St=new Uint8Array(e),Ue={value:0},qt=ht(Ve,e,Ue),Fe=je(qt,Ve,St,Ue,this.type),_t={value:0},ut={R:0,G:1,B:2,A:3,Y:0};for(let S=0;S<Fe.height/Fe.scanlineBlockSize;S++){const B=fe(Ve,Ue);Fe.size=fe(Ve,Ue),Fe.lines=B+Fe.scanlineBlockSize>Fe.height?Fe.height-B:Fe.scanlineBlockSize;const j=Fe.size<Fe.lines*Fe.bytesPerLine?Fe.uncompress(Fe):K(Fe);Ue.value+=Fe.size;for(let ee=0;ee<Fe.scanlineBlockSize;ee++){const N=ee+S*Fe.scanlineBlockSize;if(N>=Fe.height)break;for(let Y=0;Y<Fe.channels;Y++){const W=ut[qt.channels[Y].name];for(let ae=0;ae<Fe.width;ae++){_t.value=(ee*(Fe.channels*Fe.width)+Y*Fe.width+ae)*Fe.inputSize;const ce=(Fe.height-1-N)*(Fe.width*Fe.outputChannels)+ae*Fe.outputChannels+W;Fe.byteArray[ce]=Fe.getter(j,_t)}}}}return{header:qt,width:Fe.width,height:Fe.height,data:Fe.byteArray,format:Fe.format,colorSpace:Fe.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,r,s){function o(a,l){a.colorSpace=l.colorSpace,a.minFilter=Pt,a.magFilter=Pt,a.generateMipmaps=!1,a.flipY=!1,t&&t(a,l)}return super.load(e,o,r,s)}}const wde=Object.freeze(Object.defineProperty({__proto__:null,EXRLoader:oA},Symbol.toStringTag,{value:"Module"}));class uS extends hI{constructor(e){super(e),this.type=rr}parse(e){const t=function(A,_){switch(A){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(_||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(_||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(_||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(_||""))}},r=`
5234
+ `+Gu),a(!0),this.onSendQueued(dl.OnConnection)}).onClose(p=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,a(!1)}).onError(p=>{console.error("\u22A0 Websocket error"),a(!1)}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();u.addEventListener(l.WebsocketEvent.message,(p,m)=>{this.onMessage(p,m)})})}onMessage(e,t){const r=t.data;try{if(typeof r!="string"){r.size&&this.handleIncomingBinaryMessage(r);return}const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(s);return}catch(s){Zs&&r==="pong"?console.log("<<",r):st()&&console.error("Failed to parse message",s)}}async handleIncomingBinaryMessage(e){n8&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var r=new Uint8Array(t);const s=new r_(r),o=s.getBufferIdentifier(),a=this._listenersBinary[o],l=N6(s),c=z6(l);if(c&&typeof c=="string"&&(this._state[c]=l),!a)return;const h=l??s;for(const u of a)u(h)}handleIncomingStringMessage(e){var t,r;if(Zs&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const l=e.data;l&&(console.assert(l.id!==void 0&&l.id!==null&&l.id.length>0,"server did not send connection id",l.id),console.log("Your id is: "+l.id,this.context.alias??""),this._connectionId=l.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Zs&&console.log(e),e){this._isInRoom=!0;const l=e;this._currentRoomName=l.room,this._currentRoomViewId=l.viewId,this._currentRoomAllowEditing=l.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...l.inRoom),Zs&&console.log("joined room with",this._currentInRoom,this.context.alias??"");const c=new URL(window.location.href);c.searchParams.has("room")&&c.searchParams.delete("room"),c.searchParams.set("view",this._currentRoomViewId),console.log("Room view id: "+this._currentRoomViewId+`
5235
+ `+c.href)}this.onSendQueued(dl.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const l=e.data;this._currentInRoom.push(l.userId),Zs&&console.log(l.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const l=e.data,c=this._currentInRoom.indexOf(l.userId);c>=0&&(Zs&&console.log(l.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(c,1)),l.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Zs&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const a=(t=e.data)==null?void 0:t.time;a&&(this._currentDelay=this.context.time.time-a),Zs&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((r=this._currentInRoom)==null?void 0:r.length));break}const s=e.data;s&&(this._state[s.guid]=s);let o=this._listeners[e.key];if(o){o=[...o];for(const a of o)try{a(e.data)}catch(l){console.error('Error invoking callback for "'+e.key+'"',l)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,r=dl.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[r]||[];o.push(()=>this.sendWithWebsocket(e,t,r)),this._waitingForSocket[r]=o;return}const s=JSON.stringify(this.toMessage(e,t));Zs&&console.log(">>",e),this._ws.send(s)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const r of t)r();t.length=0}}}const rA=te("debugwebxr");class GB{constructor(e,t){d(this,"controllerStates",[]),d(this,"userId"),d(this,"context"),d(this,"userStateEvtName"),d(this,"onReceivedControllerState",r=>{rA&&console.log(`XRSync: Received change for ${this.userId}: ${r.type} ${r.handedness}; tracked=${r.isTracking}`);let s=!1;for(let o=0;o<this.controllerStates.length;o++)if(this.controllerStates[o].index===r.index){this.controllerStates[o]=r,s=!0;break}s||this.controllerStates.push(r)}),this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const r=this.controllerStates[t];let s=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===r.index&&(s=!0);s||(rA&&console.log(`XRSync: ${r.type} ${r.handedness} removed`,r.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(r))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(r=>r.index===e.index);if(t){let r=!1;r||(r=t.isTracking!=e.isTracking),r&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const r={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(r),this.context.connection.send(this.userStateEvtName,r),rA&&console.log(`XRSync: ${r.type} ${r.handedness} added`,r.index)}}}class a8{constructor(e){d(this,"context"),d(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(rA&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new GB(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new GB(t,this.context))}}),d(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),d(this,"onOtherUserJoinedRoom",t=>{const r=t.userId;this._states.has(r)||(rA&&console.log("XRSync: Remote user joined room",r),this._states.set(r,new GB(r,this.context)))}),d(this,"onOtherUserLeftRoom",t=>{const r=t.userId;if(!this._states.has(r)){const s=this._states.get(r);s?.dispose(),this._states.delete(r)}}),d(this,"_states",new Map),this.context=e,this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.isTracking||!1}getDeviceType(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.type||"unknown"}destroy(){this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class l8{constructor(){d(this,"_fadeToColorQuad"),d(this,"_fadeToColorMaterial"),d(this,"_requestedFadeValue",0),d(this,"_transitionPromise",null),d(this,"_transitionResolve",null),this._fadeToColorMaterial=new $t({color:0,transparent:!0,depthTest:!1,fog:!1,side:yi}),this._fadeToColorQuad=new me(new tr(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const r=this._fadeToColorQuad,s=this._fadeToColorMaterial;r.parent!==e&&s.opacity>0?e.add(r):s.opacity===0&&r.removeFromParent(),r.layers.set(2),r.material=this._fadeToColorMaterial,r.position.z=-1,r.renderOrder=1/0;const o=this._requestedFadeValue;s.opacity=it.lerp(s.opacity,o,t/.03),Math.abs(s.opacity-o)<=.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 e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Yp=(n=>(n[n.Quad=0]="Quad",n[n.Cube=1]="Cube",n[n.Sphere=2]="Sphere",n))(Yp||{});class sA{static createPrimitive(e,t){let r;switch(e){case"Quad":case 0:{const s=new tr(1,1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Cube":case 1:{const s=new qi(1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Sphere":case 2:{const s=new ja(.5,16,16),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break}return this.applyDefaultObjectOptions(r,t),r}static createSprite(e){const t=new lx({color:16777215});e!=null&&e.texture&&"map"in t&&(t.map=e.texture);const r=new OT(t);return this.applyDefaultObjectOptions(r,e),r}static applyDefaultObjectOptions(e,t){t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&e.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&e.scale.set(t.scale.x,t.scale.y,t.scale.z)}}const c8=class{constructor(n,e,t){d(this,"_session"),d(this,"_mode"),d(this,"_init"),d(this,"_renderer"),d(this,"_camera"),d(this,"_scene"),d(this,"onEnd",()=>{var r;(r=this._session)==null||r.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),d(this,"_lastTime",0),d(this,"onFrame",(r,s)=>{const o=r-this._lastTime;this.update(r,o),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),d(this,"_objects",[]),this._mode=n,this._init=e,this._session=t,this._session.addEventListener("end",this.onEnd),this._renderer=new Wc({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(t),this._renderer.xr.enabled=!0,this._camera=new Lt,this._scene=new Ur,this._scene.fog=new ax(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(n,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 t=await navigator.xr.requestSession(n,e);return t.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new c8(n,e,t),this._active):(t.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 Ll(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 n={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,n}async onBeforeHandoff(){await Ll(1e3),this._scene.clear()}setupScene(){this._scene.background=new xe(0),this._scene.add(new Hx(5,10,1118481,1118481));const n=new lp(16777215,1);n.position.set(0,20,0),n.castShadow=!1,this._scene.add(n);const e=new lp(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const t=new ap(16777215,1,100,1);t.position.set(0,2,0),t.castShadow=!1,t.distance=200,this._scene.add(t);const r=50;for(let s=0;s<100;s++){const o=new vs({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new xe(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const a=it.random(0,1)>.5?Yp.Sphere:Yp.Cube,l=sA.createPrimitive(a,{material:o});l.position.x=it.random(-r,r),l.position.y=it.random(-2,r),l.position.z=it.random(-r,r),l.rotation.x=it.random(0,Math.PI*2),l.rotation.y=it.random(0,Math.PI*2),l.rotation.z=it.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(n,e){const t=n*4e-4;for(let r=0;r<this._objects.length;r++){const s=this._objects[r];s.position.y+=Math.sin(t+r*.5)*.005,s.rotateY(.002)}}};let Lg=c8;d(Lg,"_active",null),d(Lg,"_requestInFlight",!1);const Sr=te("debugwebxr"),gde=te("stats");function vde(n){let e=null;const t=n;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=n,e}yde();async function yde(){var n;if(te("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],di.addContextCreatedCallback(async t=>{if(!e)return;Nf(!0);const r=await e;if(r){const s=wt.getDefaultSessionInit("immersive-vr");wt.setSession("immersive-vr",r,s,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(n=navigator.xr)==null||n.addEventListener("sessiongranted",async()=>{Nf(!0),console.log("Received Session Granted..."),await Ll(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,r=t?JSON.parse(t):null;let s=null;if(h8()&&(await Lg.start(e||"immersive-vr",r||wt.getDefaultSessionInit("immersive-vr")),await _de(),s=await Lg.handoff()),s)wt.setSession(s.mode,s.session,s.init,kt.Current);else if(e&&t){console.log("Session Granted: Restore last session");const o=JSON.parse(t);wt.start(e,o).catch(a=>console.warn(a))}else wt.start("immersive-vr").catch(o=>console.warn("Session Granted failed:",o))},{once:!0})}}function Ade(n,e){sessionStorage.setItem("needle_xr_session_mode",n),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function bde(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const VB=new Set;di.registerCallback(Ci.ContextCreationStart,async n=>{VB.add(n.context)}),di.registerCallback(Ci.ContextCreated,async n=>{VB.delete(n.context)});function h8(){return VB.size>0}function _de(){return new Promise(n=>{const e=Date.now(),t=setInterval(()=>{(!h8()||Date.now()-e>6e4)&&(clearInterval(t),n())},100)})}fp()&&st()&&window.addEventListener("keydown",n=>{(n.key==="x"||n.key==="Escape")&&wt.active&&wt.stop()});const Vu=class{constructor(n,e,t,r){d(this,"context"),d(this,"session"),d(this,"mode"),d(this,"controllers",[]),d(this,"_rigScale",1),d(this,"_lastRigScaleUpdate",-1),d(this,"_rigs",[]),d(this,"_viewerHitTestSource",null),d(this,"_defaultRig"),d(this,"_xr_scripts"),d(this,"_xr_update_scripts",[]),d(this,"_inactive_scripts",[]),d(this,"_controllerAdded"),d(this,"_controllerRemoved"),d(this,"_originalCameraWorldPosition"),d(this,"_originalCameraWorldRotation"),d(this,"_originalCameraWorldScale"),d(this,"_originalCameraParent"),d(this,"_mainCamera",null),d(this,"onRendererSessionSet",()=>{var a;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(a=this.context.mainCameraComponent)==null||a.applyClearFlags())}),d(this,"onInputSourceAdded",a=>{if(a.targetRayMode==="screen")return;let l=0;for(let h=0;h<this.session.inputSources.length;h++)if(this.session.inputSources[h]===a){l=h;break}if(this.controllers.find(h=>h.inputSource===a)){console.warn("Controller already exists for input source",l);return}Sr&&console.log("Adding controller",l);const c=new vB(this,a,l);this._newControllers.push(c)}),d(this,"_ended",!1),d(this,"_newControllers",[]),d(this,"onEnd",a=>{var l,c,h;if(this._ended)return;this._ended=!0,Sr&&console.log("XR Session ended"),bde(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,zu(this.onBefore,Hi.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const p=this.context.post_render_callbacks.indexOf(this.onAfterRender);p>=0&&this.context.post_render_callbacks.splice(p,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var m;(m=this.context.mainCameraComponent)==null||m.applyClearFlags()}),R6({session:this});for(const m of Vu._xrEndListeners)m({xr:this});for(let m=0;m<this.controllers.length;m++)this.disconnectInputSource(this.controllers[m].inputSource);for(const m of this._xr_scripts)(l=m?.onLeaveXR)==null||l.call(m,{xr:this});(c=this.sync)==null||c.onExitXR(this),this.context.mainCamera&&((h=this._originalCameraParent)==null||h.add(this.context.mainCamera),this._originalCameraWorldPosition&&lr(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&ca(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Uf(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Nf(!1)}),d(this,"_didStart",!1),d(this,"onBefore",a=>{var l,c,h,u,p,m,f,g;const v=a.xrFrame;if(!v)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((l=this.rig)==null?void 0:l.isActive)==!1&&(Sr&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(c=this._mainCamera)!=null&&c.gameObject&&((u=(h=this._mainCamera)==null?void 0:h.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((p=this._mainCamera)==null?void 0:p.gameObject),this.internalUpdateState(),this.applyCustomForward();const y={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const A=[...this.context.new_scripts_xr];for(let _=0;_<A.length;_++){const b=this.context.new_scripts_xr[_];if(!b||b.destroyed||((m=b.supportsXR)==null?void 0:m.call(b,this.mode))==!1){this.context.new_scripts_xr.splice(_,1);continue}if(!b.activeAndEnabled){this.context.new_scripts_xr.splice(_,1),this.markInactive(b);continue}if(this.addScript(b)){this.invokeCallback_EnterXR(b);for(const x of this.controllers)this.invokeCallback_ControllerAdded(b,x)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const _=Ul(this.context.scene.children);if(_){const b=_.getSize(pi());if(b.length()>0){const x=this._defaultRig.gameObject;x.position.set(_.min.x+b.x*.5,_.min.y,_.max.z+b.z*.5+1.5);const E=_.getCenter(pi());E.y=x.position.y,x.lookAt(E)}}}I6({session:this});for(const _ of Vu._xrStartListeners)_(y);const A=[...this._xr_scripts];Sr&&console.log("NeedleXRSession start, handle scripts:",A);for(const _ of A){if(_.destroyed){this._script_to_remove.push(_);continue}if(!_.activeAndEnabled){this.markInactive(_);continue}this.invokeCallback_EnterXR(_);for(const b of this.controllers)this.invokeCallback_ControllerAdded(_,b)}}this.syncCameraCullingMask();for(const A of this.controllers)A.onUpdate(v);if(this._newControllers.length>0){const A=[...this._newControllers];this._newControllers.length=0;for(const _ of A)if(_.connected){this.controllers.push(_);for(const b of this._xr_scripts){if(b.destroyed){this._script_to_remove.push(b);continue}b.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(b,_)}}this.controllers.sort((_,b)=>_.index-b.index)}for(const A of this._xr_update_scripts){if(A.destroyed===!0){this._script_to_remove.push(A);continue}if(A.activeAndEnabled===!1){this.markInactive(A);continue}A.onUpdateXR&&A.onUpdateXR(y)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const A=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const _ of A)!_.destroyed&&this.running&&((f=_.onLeaveXR)==null||f.call(_,y)),this.removeScript(_)}(g=this.sync)==null||g.onUpdate(this),this.onRenderDebug()}),d(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),d(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),fp()){const a=this.context.renderer;if(a.xr.isPresenting&&this.context.mainCamera){const l=a.xr.enabled,c=a.getRenderTarget();a.xr.enabled=!1,a.setRenderTarget(null),a.render(this.context.scene,this.context.mainCamera),a.xr.enabled=l,a.setRenderTarget(c)}}}),d(this,"_script_to_remove",[]),d(this,"_camera"),d(this,"_cameraRenderParent",new ye().rotateY(Math.PI)),d(this,"_previousCameraParent"),d(this,"_customforward",!0),d(this,"originalCameraNearPlane"),d(this,"_viewerPose"),d(this,"_transformOrientation",new Ce),d(this,"_transformPosition",new C),d(this,"_transition");var s,o;Ade(n,r.init),this.session=e,this.mode=n,this.context=t,(Sr||te("console"))&&Nf(!0),this._xr_scripts=[...r.scripts],this._xr_update_scripts=this._xr_scripts.filter(a=>typeof a.onUpdateXR=="function"),this._controllerAdded=r.controller_added,this._controllerRemoved=r.controller_removed,Nu(this.onBefore,Hi.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((s=r.init.optionalFeatures)!=null&&s.includes("hit-test")||(o=r.init.requiredFeatures)!=null&&o.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(a=>{var l,c;return(c=(l=e.requestHitTestSource)==null?void 0:l.call(e,{space:a}))==null?void 0:c.then(h=>this._viewerHitTestSource=h)}).catch(a=>console.warn(a)),this.context.mainCamera&&(this._originalCameraWorldPosition=Bt(this.context.mainCamera,new C),this._originalCameraWorldRotation=Mi(this.context.mainCamera,new Ce),this._originalCameraWorldScale=Vi(this.context.mainCamera,new C),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new Sue,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let a=0;a<e.inputSources.length;a++){const l=e.inputSources[a];if(!l.handedness){console.warn("Input source in xr session has no handedness - ignoring",a);continue}this.onInputSourceAdded(l)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",a=>{for(const l of a.removed)this.disconnectInputSource(l);for(const l of a.added)this.onInputSourceAdded(l)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(n){return this._sync||(this._sync=new a8(n)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var n;return((n=this._activeSession)==null?void 0:n.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(n=>n.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(n){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(n).catch(t=>(Sr&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(n){this._sessionRequestStartListeners.push(n)}static offSessionRequestStart(n){const e=this._sessionRequestStartListeners.indexOf(n);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(n){this._sessionRequestEndListeners.push(n)}static offSessionRequestEnd(n){const e=this._sessionRequestEndListeners.indexOf(n);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(n){this._xrStartListeners.push(n)}static offXRSessionStart(n){const e=this._xrStartListeners.indexOf(n);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(n){this._xrEndListeners.push(n)}static offXRSessionEnd(n){const e=this._xrEndListeners.indexOf(n);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(n){this._controllerAddedListeners.push(n)}static offControllerAdded(n){const e=this._controllerAddedListeners.indexOf(n);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(n){this._controllerRemovedListeners.push(n)}static offControllerRemoved(n){const e=this._controllerRemovedListeners.indexOf(n);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(n,e,t){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+n),e=="default"&&(e=this.getDefaultSessionInit(n)),navigator.xr.offerSession(n,{...e}).then(r=>Vu.setSession(n,r,e,t)).catch(r=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(n){switch(n){case"immersive-ar":return{optionalFeatures:["anchors","local-floor","hand-tracking","layers","dom-overlay","hit-test","unbounded"]};case"immersive-vr":return{optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};default:return console.warn("No default session init for mode",n),{}}}static async start(n,e,t){var r,s,o,a;if(st()&&te("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Lg.start(n,e||Vu.getDefaultSessionInit(n)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Sr||st())&&Di("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(t||(t=kt.Current),t||(t=di.All[0]),!t)throw new Error("No Needle Engine Context found");switch(e||(e={}),n){case"immersive-ar":{if(await((r=this.xrSystem)==null?void 0:r.isSessionSupported("immersive-ar"))!==!0)return console.error(n+" is not supported by this browser."),null;const h=this.getDefaultSessionInit(n),u=vde(t.domElement);u&&!ew()&&(h.domOverlay={root:u},h.optionalFeatures.push("dom-overlay")),e={...h,...e}}break;case"immersive-vr":{if(await((s=this.xrSystem)==null?void 0:s.isSessionSupported("immersive-vr"))!==!0)return console.error(n+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(n),...e}}break;default:console.warn("No default session init for mode",n);break}e.optionalFeatures??(e.optionalFeatures=[]),e.requiredFeatures??(e.requiredFeatures=[]),await Lg.stop();const l=n=="immersive-ar"?t.scripts_immersive_ar:t.scripts_immersive_vr;Sr?console.log(`%cRequesting ${n} session`,"font-weight:bold;",e,l):console.log(`%cRequesting ${n} session`,"font-weight:bold;");for(const h of l)h.onBeforeXR&&h.onBeforeXR(n,e);for(const h of this._sessionRequestStartListeners)h({mode:n,init:e});Sr&&rn("Requesting "+n+" session ("+Date.now()+")"),this._currentSessionRequest=(o=navigator.xr)==null?void 0:o.requestSession(n,e),this._currentSessionRequestMode=n;const c=await((a=this._currentSessionRequest)==null?void 0:a.catch(h=>{console.error(h,"Code: "+h.code),h.code===9&&Di("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:"&&Di("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const h of this._sessionRequestEndListeners)h({mode:n,init:e,newSession:c||null});return c?this.setSession(n,c,e,t):(console.warn("XR Session request was rejected"),null)}static setSession(n,e,t,r){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=n=="immersive-ar"?r.scripts_immersive_ar:r.scripts_immersive_vr;return this._activeSession=new Vu(n,e,r,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:t}),e.addEventListener("end",this.onEnd),Sr?console.log(`%cStarted ${n} session`,"font-weight:bold;",s):console.log(`%cStarted ${n} session`,"font-weight:bold;"),this._activeSession}static stop(){var n;(n=this._activeSession)==null||n.end()}get sync(){return Vu._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(n=>n.isLeft)}get rightController(){return this.controllers.find(n=>n.isRight)}getController(n){return typeof n=="number"?this.controllers[n]||null:this.controllers.find(e=>e.side===n)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(n=>n.inputSource.targetRayMode==="tracked-pointer")||st()&&fp()&&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 n=this.frame.getImageTrackingResults();for(const e of n)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const n=this._rigs[0]??null;return n!=null&&n.gameObject&&Jp(n.gameObject)||n?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):n}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(n){this._rigs.indexOf(n)>=0||(n.priority===void 0&&(n.priority=0),this._rigs.push(n),this.updateActiveXRRig())}removeRig(n){const e=this._rigs.indexOf(n);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(n){const e=this._rigs.indexOf(n);this._rigs.splice(e,1),this._rigs.unshift(n),this.updateActiveXRRig()}updateActiveXRRig(){const n=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 t=1;t<this._rigs.length;t++){const r=this._rigs[t];if(r.isActive){if(Jp(r.gameObject)){this._rigs.splice(t,1),t--;continue}(!e||e.isActive===!1||r.priority!==void 0&&r.priority>e.priority)&&(e=r)}}if(n!==e){const t=this._rigs.indexOf(e);t>=0&&this._rigs.splice(t,1),this._rigs.unshift(e)}Sr&&(n===e?console.log("Updated Active XR Rig:",e,"prev:",n):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(n){if(n)return this.getControllerHitTest(n);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,t=this.frame.getHitTestResults(e);if(t.length>0){const r=t[0];return this.convertHitTestResult(r)}return null}getControllerHitTest(n){const e=n.hitTestSource;if(!e)return null;const t=this.frame.getHitTestResultsForTransientInput(e);for(const r of t)if(r.inputSource===n.inputSource)for(const s of r.results)return this.convertHitTestResult(s);return null}convertHitTestResult(n){const e=this.context.renderer.xr.getReferenceSpace(),t=e&&n.getPose(e);if(t){const r=pi(t.transform.position),s=bp(t.transform.orientation),o=this.context.mainCamera;if(o?.parent!==this._cameraRenderParent&&r.applyMatrix4(Y1),o!=null&&o.parent){r.applyMatrix4(o.parent.matrixWorld),s.multiply(Sa);const a=Mi(o.parent);a.premultiply(Sa),s.premultiply(a)}return{hit:n,position:r,quaternion:s}}return null}convertSpace(n){const e=pi(n.position);e.applyMatrix4(Y1);const t=bp(n.orientation);return t.premultiply(Sa),{position:e,quaternion:t}}disconnectInputSource(n){const e=(t,r,s)=>{if(t.inputSource===n){Sr&&console.log("Disconnecting controller",t.index),this.controllers.splice(s,1),this.invokeControllerEvent(t,this._controllerRemoved,"removed");const o={xr:this,controller:t,change:"removed"};for(const a of this._xr_scripts)a.onXRControllerRemoved&&a.onXRControllerRemoved(o);t.onDisconnected()}};for(let t=this.controllers.length-1;t>=0;t--){const r=this.controllers[t];e(r,this.controllers,t)}for(let t=this._newControllers.length-1;t>=0;t--){const r=this._newControllers[t];e(r,this._newControllers,t)}}end(){this._ended||this.session.end().catch(n=>console.warn(n))}onRenderDebug(){if(Sr)for(const n of this.controllers)n.onRenderDebug();if((Sr||gde)&&this.rig){const n=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;n.add(e.multiplyScalar(1.5));const t=this.rig.gameObject.worldUp;n.add(t.multiplyScalar(2.5));let r="";if(r+=this.context.time.smoothedFps.toFixed(1),Sr)for(const s of this.controllers)r+=`
5236
+ ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking}`;At.DrawLabel(n,r)}}addScript(n){return this._xr_scripts.includes(n)?!1:(Sr&&console.log("Register new XRScript",n),this._xr_scripts.push(n),typeof n.onUpdateXR=="function"&&this._xr_update_scripts.push(n),!0)}markInactive(n){if(!(this._inactive_scripts.indexOf(n)>=0)){this.removeScript(n,!1),this._inactive_scripts.push(n);for(const e of this.controllers)this.invokeCallback_ControllerRemoved(n,e);this.invokeCallback_LeaveXR(n)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let n=this._inactive_scripts.length-1;n>=0;n--){const e=this._inactive_scripts[n];if(e.activeAndEnabled){this._inactive_scripts.splice(n,1),this.addScript(e),this.invokeCallback_EnterXR(e);for(const t of this.controllers)this.invokeCallback_ControllerAdded(e,t)}}}removeScript(n,e=!0){Sr&&console.log("Remove XRScript",n);const t=this._xr_scripts.indexOf(n);t>=0&&this._xr_scripts.splice(t,1);const r=this._xr_update_scripts.indexOf(n);if(r>=0&&this._xr_update_scripts.splice(r,1),e){const s=this._inactive_scripts.indexOf(n);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(n){n.onEnterXR&&n.onEnterXR({xr:this})}invokeCallback_ControllerAdded(n,e){n.onXRControllerAdded&&n.onXRControllerAdded({xr:this,controller:e,change:"added"})}invokeCallback_ControllerRemoved(n,e){n.onXRControllerRemoved&&n.onXRControllerRemoved({xr:this,controller:e,change:"removed"})}invokeCallback_LeaveXR(n){n.onLeaveXR&&!n.destroyed&&n.onLeaveXR({xr:this})}syncCameraCullingMask(){var n;const e=this.context.xrCamera,t=(n=this.context.mainCameraComponent)==null?void 0:n.cullingMask;if(e&&t!==void 0){for(const r of e.cameras)r.layers.mask=t;e.layers.mask=t}else if(e){for(const r of e.cameras)r.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(n,e,t){for(let r=e.length-1;r>=0;r--){const s=e[r];if(s)try{s({xr:this,controller:n,change:t})}catch(o){console.error(o)}}}applyCustomForward(){var n;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(n=this._previousCameraParent)==null||n.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const t=Vi(this.rig.gameObject);e*=t.x}this._camera instanceof Lt&&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 Lt&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const n=this.context.renderer.xr.getReferenceSpace();if(!n){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(n),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 l8),this._transition}fadeTransition(){return this._transition||(this._transition=new l8),this._transition.fadeTransition()}updateFade(n){this._transition&&n instanceof Lt&&this._transition.update(n,this.context.time.deltaTime)}onUpdateFade_PostRender(){var n;(n=this._transition)==null||n.remove()}};let wt=Vu;d(wt,"_sync",null),d(wt,"_currentSessionRequestMode",null),d(wt,"_currentSessionRequest"),d(wt,"_activeSession"),d(wt,"_sessionRequestStartListeners",[]),d(wt,"_sessionRequestEndListeners",[]),d(wt,"_xrStartListeners",[]),d(wt,"_xrEndListeners",[]),d(wt,"_controllerAddedListeners",[]),d(wt,"_controllerRemovedListeners",[]),d(wt,"onEnd",()=>{Sr&&console.log("XR Session ended"),Vu._activeSession=null});const QB=te("debugwebxr");class u8{static tryFindAvatarObjects(e,t,r){if(r.head&&r.leftHand&&r.rightHand)return;const s=e.name.toLocaleLowerCase();!r.head&&s.includes("head")&&(QB&&console.log("FOUND AVATAR HEAD",e.name),r.head=new ti("",t,e)),s.includes("hand")&&(!r.leftHand&&s.includes("left")&&(QB&&console.log("FOUND AVATAR LEFT HAND",e.name),r.leftHand=new ti("",t,e)),!r.rightHand&&s.includes("right")&&(QB&&console.log("FOUND AVATAR RIGHT HAND",e.name),r.rightHand=new ti("",t,e)));for(let o=0;o<e.children.length;o++){if(r.head&&r.leftHand&&r.rightHand)return;const a=e.children[o];this.tryFindAvatarObjects(a,t,r)}}}var cS=(n=>(n.Visible="application-visible",n.Hidden="application-hidden",n.MuteChanged="application-mutechanged",n))(cS||{});let hS=!1;const Fg=[];function Ug(){if(hS)return;st()&&console.debug("User interaction registered: audio can now be played"),hS=!0;const n=[...Fg];Fg.length=0,n.forEach(e=>e())}document.addEventListener("pointerdown",Ug),document.addEventListener("click",Ug),document.addEventListener("dragstart",Ug),document.addEventListener("touchstart",Ug),document.addEventListener("keydown",Ug),wt.onXRSessionStart(()=>{Ug()});const d8=class extends EventTarget{constructor(n){super(),d(this,"_mute",!1),d(this,"context"),d(this,"_isVisible",!0),this.context=n,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return hS}static registerWaitForInteraction(n){if(n!==null){if(hS){n();return}Fg.indexOf(n)===-1&&Fg.push(n)}}static unregisterWaitForInteraction(n){const e=Fg.indexOf(n);e!==-1&&Fg.splice(e,1)}get muted(){return this._mute}set muted(n){n!==this._mute&&(this._mute=n,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(n){switch(n.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};let Qu=d8;d(Qu,"registerWaitForAllowAudio",d8.registerWaitForInteraction);function*p8(n,e=null){const t=e?e.time:kt.Current.time,r=t.time;for(;t.time-r<n;)yield}function*xde(n){for(let e=0;e<n;e++)yield}function*m8(n){let e=!0;for(n.then(()=>e=!1),n.catch(()=>e=!1);e;)yield}class oA extends hI{constructor(e){super(e),this.type=rr}parse(e){const t=Math.pow(2.7182818,2.2);function r(S,B){let j=0;for(let N=0;N<65536;++N)(N==0||S[N>>3]&1<<(N&7))&&(B[j++]=N);const ee=j-1;for(;j<65536;)B[j++]=0;return ee}function s(S){for(let B=0;B<16384;B++)S[B]={},S[B].len=0,S[B].lit=0,S[B].p=null}const o={l:0,c:0,lc:0};function a(S,B,j,ee,N){for(;j<S;)B=B<<8|X(ee,N),j+=8;j-=S,o.l=B>>j&(1<<S)-1,o.c=B,o.lc=j}const l=new Array(59);function c(S){for(let j=0;j<=58;++j)l[j]=0;for(let j=0;j<65537;++j)l[S[j]]+=1;let B=0;for(let j=58;j>0;--j){const ee=B+l[j]>>1;l[j]=B,B=ee}for(let j=0;j<65537;++j){const ee=S[j];ee>0&&(S[j]=ee|l[ee]++<<6)}}function h(S,B,j,ee,N,Y){const W=B;let ae=0,ce=0;for(;ee<=N;ee++){if(W.value-B.value>j)return!1;a(6,ae,ce,S,W);const _e=o.l;if(ae=o.c,ce=o.lc,Y[ee]=_e,_e==63){if(W.value-B.value>j)throw new Error("Something wrong with hufUnpackEncTable");a(8,ae,ce,S,W);let Re=o.l+6;if(ae=o.c,ce=o.lc,ee+Re>N+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Re--;)Y[ee++]=0;ee--}else if(_e>=59){let Re=_e-59+2;if(ee+Re>N+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Re--;)Y[ee++]=0;ee--}}c(Y)}function u(S){return S&63}function p(S){return S>>6}function m(S,B,j,ee){for(;B<=j;B++){const N=p(S[B]),Y=u(S[B]);if(N>>Y)throw new Error("Invalid table entry");if(Y>14){const W=ee[N>>Y-14];if(W.len)throw new Error("Invalid table entry");if(W.lit++,W.p){const ae=W.p;W.p=new Array(W.lit);for(let ce=0;ce<W.lit-1;++ce)W.p[ce]=ae[ce]}else W.p=new Array(1);W.p[W.lit-1]=B}else if(Y){let W=0;for(let ae=1<<14-Y;ae>0;ae--){const ce=ee[(N<<14-Y)+W];if(ce.len||ce.p)throw new Error("Invalid table entry");ce.len=Y,ce.lit=B,W++}}}return!0}const f={c:0,lc:0};function g(S,B,j,ee){S=S<<8|X(j,ee),B+=8,f.c=S,f.lc=B}const v={c:0,lc:0};function y(S,B,j,ee,N,Y,W,ae,ce){if(S==B){ee<8&&(g(j,ee,N,Y),j=f.c,ee=f.lc),ee-=8;let _e=j>>ee;if(_e=new Uint8Array([_e])[0],ae.value+_e>ce)return!1;const Re=W[ae.value-1];for(;_e-- >0;)W[ae.value++]=Re}else if(ae.value<ce)W[ae.value++]=S;else return!1;v.c=j,v.lc=ee}function A(S){return S&65535}function _(S){const B=A(S);return B>32767?B-65536:B}const b={a:0,b:0};function x(S,B){const j=_(S),ee=_(B),N=j+(ee&1)+(ee>>1),Y=N,W=N-ee;b.a=Y,b.b=W}function E(S,B){const j=A(S),ee=A(B),N=j-(ee>>1)&65535,Y=ee+N-32768&65535;b.a=Y,b.b=N}function I(S,B,j,ee,N,Y,W){const ae=W<16384,ce=j>N?N:j;let _e=1,Re,Xe;for(;_e<=ce;)_e<<=1;for(_e>>=1,Re=_e,_e>>=1;_e>=1;){Xe=0;const We=Xe+Y*(N-Re),Ke=Y*_e,gt=Y*Re,rt=ee*_e,xt=ee*Re;let Jt,Ui,en,pr;for(;Xe<=We;Xe+=gt){let ki=Xe;const ai=Xe+ee*(j-Re);for(;ki<=ai;ki+=xt){const Pn=ki+rt,ro=ki+Ke,Vn=ro+rt;ae?(x(S[ki+B],S[ro+B]),Jt=b.a,en=b.b,x(S[Pn+B],S[Vn+B]),Ui=b.a,pr=b.b,x(Jt,Ui),S[ki+B]=b.a,S[Pn+B]=b.b,x(en,pr),S[ro+B]=b.a,S[Vn+B]=b.b):(E(S[ki+B],S[ro+B]),Jt=b.a,en=b.b,E(S[Pn+B],S[Vn+B]),Ui=b.a,pr=b.b,E(Jt,Ui),S[ki+B]=b.a,S[Pn+B]=b.b,E(en,pr),S[ro+B]=b.a,S[Vn+B]=b.b)}if(j&_e){const Pn=ki+Ke;ae?x(S[ki+B],S[Pn+B]):E(S[ki+B],S[Pn+B]),Jt=b.a,S[Pn+B]=b.b,S[ki+B]=Jt}}if(N&_e){let ki=Xe;const ai=Xe+ee*(j-Re);for(;ki<=ai;ki+=xt){const Pn=ki+rt;ae?x(S[ki+B],S[Pn+B]):E(S[ki+B],S[Pn+B]),Jt=b.a,S[Pn+B]=b.b,S[ki+B]=Jt}}Re=_e,_e>>=1}return Xe}function T(S,B,j,ee,N,Y,W,ae,ce){let _e=0,Re=0;const Xe=W,We=Math.trunc(ee.value+(N+7)/8);for(;ee.value<We;)for(g(_e,Re,j,ee),_e=f.c,Re=f.lc;Re>=14;){const gt=_e>>Re-14&16383,rt=B[gt];if(rt.len)Re-=rt.len,y(rt.lit,Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;else{if(!rt.p)throw new Error("hufDecode issues");let xt;for(xt=0;xt<rt.lit;xt++){const Jt=u(S[rt.p[xt]]);for(;Re<Jt&&ee.value<We;)g(_e,Re,j,ee),_e=f.c,Re=f.lc;if(Re>=Jt&&p(S[rt.p[xt]])==(_e>>Re-Jt&(1<<Jt)-1)){Re-=Jt,y(rt.p[xt],Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;break}}if(xt==rt.lit)throw new Error("hufDecode issues")}}const Ke=8-N&7;for(_e>>=Ke,Re-=Ke;Re>0;){const gt=B[_e<<14-Re&16383];if(gt.len)Re-=gt.len,y(gt.lit,Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;else throw new Error("hufDecode issues")}return!0}function R(S,B,j,ee,N,Y){const W={value:0},ae=j.value,ce=fe(B,j),_e=fe(B,j);j.value+=4;const Re=fe(B,j);if(j.value+=4,ce<0||ce>=65537||_e<0||_e>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const Xe=new Array(65537),We=new Array(16384);s(We);const Ke=ee-(j.value-ae);if(h(S,j,Ke,ce,_e,Xe),Re>8*(ee-(j.value-ae)))throw new Error("Something wrong with hufUncompress");m(Xe,ce,_e,We),T(Xe,We,S,j,Re,_e,Y,N,W)}function D(S,B,j){for(let ee=0;ee<j;++ee)B[ee]=S[B[ee]]}function M(S){for(let B=1;B<S.length;B++){const j=S[B-1]+S[B]-128;S[B]=j}}function P(S,B){let j=0,ee=Math.floor((S.length+1)/2),N=0;const Y=S.length-1;for(;!(N>Y||(B[N++]=S[j++],N>Y));)B[N++]=S[ee++]}function z(S){let B=S.byteLength;const j=new Array;let ee=0;const N=new DataView(S);for(;B>0;){const Y=N.getInt8(ee++);if(Y<0){const W=-Y;B-=W+1;for(let ae=0;ae<W;ae++)j.push(N.getUint8(ee++))}else{const W=Y;B-=2;const ae=N.getUint8(ee++);for(let ce=0;ce<W+1;ce++)j.push(ae)}}return j}function V(S,B,j,ee,N,Y){let W=new DataView(Y.buffer);const ae=j[S.idx[0]].width,ce=j[S.idx[0]].height,_e=3,Re=Math.floor(ae/8),Xe=Math.ceil(ae/8),We=Math.ceil(ce/8),Ke=ae-(Xe-1)*8,gt=ce-(We-1)*8,rt={value:0},xt=new Array(_e),Jt=new Array(_e),Ui=new Array(_e),en=new Array(_e),pr=new Array(_e);for(let ai=0;ai<_e;++ai)pr[ai]=B[S.idx[ai]],xt[ai]=ai<1?0:xt[ai-1]+Xe*We,Jt[ai]=new Float32Array(64),Ui[ai]=new Uint16Array(64),en[ai]=new Uint16Array(Xe*64);for(let ai=0;ai<We;++ai){let Pn=8;ai==We-1&&(Pn=gt);let ro=8;for(let U=0;U<Xe;++U){U==Xe-1&&(ro=Ke);for(let ne=0;ne<_e;++ne)Ui[ne].fill(0),Ui[ne][0]=N[xt[ne]++],L(rt,ee,Ui[ne]),H(Ui[ne],Jt[ne]),O(Jt[ne]);F(Jt);for(let ne=0;ne<_e;++ne)G(Jt[ne],en[ne],U*64)}let Vn=0;for(let U=0;U<_e;++U){const ne=j[S.idx[U]].type;for(let pe=8*ai;pe<8*ai+Pn;++pe){Vn=pr[U][pe];for(let ge=0;ge<Re;++ge){const le=ge*64+(pe&7)*8;W.setUint16(Vn+0*2*ne,en[U][le+0],!0),W.setUint16(Vn+1*2*ne,en[U][le+1],!0),W.setUint16(Vn+2*2*ne,en[U][le+2],!0),W.setUint16(Vn+3*2*ne,en[U][le+3],!0),W.setUint16(Vn+4*2*ne,en[U][le+4],!0),W.setUint16(Vn+5*2*ne,en[U][le+5],!0),W.setUint16(Vn+6*2*ne,en[U][le+6],!0),W.setUint16(Vn+7*2*ne,en[U][le+7],!0),Vn+=8*2*ne}}if(Re!=Xe)for(let pe=8*ai;pe<8*ai+Pn;++pe){const ge=pr[U][pe]+8*Re*2*ne,le=Re*64+(pe&7)*8;for(let Ze=0;Ze<ro;++Ze)W.setUint16(ge+Ze*2*ne,en[U][le+Ze],!0)}}}const ki=new Uint16Array(ae);W=new DataView(Y.buffer);for(let ai=0;ai<_e;++ai){j[S.idx[ai]].decoded=!0;const Pn=j[S.idx[ai]].type;if(j[ai].type==2)for(let ro=0;ro<ce;++ro){const Vn=pr[ai][ro];for(let U=0;U<ae;++U)ki[U]=W.getUint16(Vn+U*2*Pn,!0);for(let U=0;U<ae;++U)W.setFloat32(Vn+U*2*Pn,Ae(ki[U]),!0)}}}function L(S,B,j){let ee,N=1;for(;N<64;)ee=B[S.value],ee==65280?N=64:ee>>8==255?N+=ee&255:(j[N]=ee,N++),S.value++}function H(S,B){B[0]=Ae(S[0]),B[1]=Ae(S[1]),B[2]=Ae(S[5]),B[3]=Ae(S[6]),B[4]=Ae(S[14]),B[5]=Ae(S[15]),B[6]=Ae(S[27]),B[7]=Ae(S[28]),B[8]=Ae(S[2]),B[9]=Ae(S[4]),B[10]=Ae(S[7]),B[11]=Ae(S[13]),B[12]=Ae(S[16]),B[13]=Ae(S[26]),B[14]=Ae(S[29]),B[15]=Ae(S[42]),B[16]=Ae(S[3]),B[17]=Ae(S[8]),B[18]=Ae(S[12]),B[19]=Ae(S[17]),B[20]=Ae(S[25]),B[21]=Ae(S[30]),B[22]=Ae(S[41]),B[23]=Ae(S[43]),B[24]=Ae(S[9]),B[25]=Ae(S[11]),B[26]=Ae(S[18]),B[27]=Ae(S[24]),B[28]=Ae(S[31]),B[29]=Ae(S[40]),B[30]=Ae(S[44]),B[31]=Ae(S[53]),B[32]=Ae(S[10]),B[33]=Ae(S[19]),B[34]=Ae(S[23]),B[35]=Ae(S[32]),B[36]=Ae(S[39]),B[37]=Ae(S[45]),B[38]=Ae(S[52]),B[39]=Ae(S[54]),B[40]=Ae(S[20]),B[41]=Ae(S[22]),B[42]=Ae(S[33]),B[43]=Ae(S[38]),B[44]=Ae(S[46]),B[45]=Ae(S[51]),B[46]=Ae(S[55]),B[47]=Ae(S[60]),B[48]=Ae(S[21]),B[49]=Ae(S[34]),B[50]=Ae(S[37]),B[51]=Ae(S[47]),B[52]=Ae(S[50]),B[53]=Ae(S[56]),B[54]=Ae(S[59]),B[55]=Ae(S[61]),B[56]=Ae(S[35]),B[57]=Ae(S[36]),B[58]=Ae(S[48]),B[59]=Ae(S[49]),B[60]=Ae(S[57]),B[61]=Ae(S[58]),B[62]=Ae(S[62]),B[63]=Ae(S[63])}function O(S){const B=.5*Math.cos(.7853975),j=.5*Math.cos(3.14159/16),ee=.5*Math.cos(3.14159/8),N=.5*Math.cos(3*3.14159/16),Y=.5*Math.cos(5*3.14159/16),W=.5*Math.cos(3*3.14159/8),ae=.5*Math.cos(7*3.14159/16),ce=new Array(4),_e=new Array(4),Re=new Array(4),Xe=new Array(4);for(let We=0;We<8;++We){const Ke=We*8;ce[0]=ee*S[Ke+2],ce[1]=W*S[Ke+2],ce[2]=ee*S[Ke+6],ce[3]=W*S[Ke+6],_e[0]=j*S[Ke+1]+N*S[Ke+3]+Y*S[Ke+5]+ae*S[Ke+7],_e[1]=N*S[Ke+1]-ae*S[Ke+3]-j*S[Ke+5]-Y*S[Ke+7],_e[2]=Y*S[Ke+1]-j*S[Ke+3]+ae*S[Ke+5]+N*S[Ke+7],_e[3]=ae*S[Ke+1]-Y*S[Ke+3]+N*S[Ke+5]-j*S[Ke+7],Re[0]=B*(S[Ke+0]+S[Ke+4]),Re[3]=B*(S[Ke+0]-S[Ke+4]),Re[1]=ce[0]+ce[3],Re[2]=ce[1]-ce[2],Xe[0]=Re[0]+Re[1],Xe[1]=Re[3]+Re[2],Xe[2]=Re[3]-Re[2],Xe[3]=Re[0]-Re[1],S[Ke+0]=Xe[0]+_e[0],S[Ke+1]=Xe[1]+_e[1],S[Ke+2]=Xe[2]+_e[2],S[Ke+3]=Xe[3]+_e[3],S[Ke+4]=Xe[3]-_e[3],S[Ke+5]=Xe[2]-_e[2],S[Ke+6]=Xe[1]-_e[1],S[Ke+7]=Xe[0]-_e[0]}for(let We=0;We<8;++We)ce[0]=ee*S[16+We],ce[1]=W*S[16+We],ce[2]=ee*S[48+We],ce[3]=W*S[48+We],_e[0]=j*S[8+We]+N*S[24+We]+Y*S[40+We]+ae*S[56+We],_e[1]=N*S[8+We]-ae*S[24+We]-j*S[40+We]-Y*S[56+We],_e[2]=Y*S[8+We]-j*S[24+We]+ae*S[40+We]+N*S[56+We],_e[3]=ae*S[8+We]-Y*S[24+We]+N*S[40+We]-j*S[56+We],Re[0]=B*(S[We]+S[32+We]),Re[3]=B*(S[We]-S[32+We]),Re[1]=ce[0]+ce[3],Re[2]=ce[1]-ce[2],Xe[0]=Re[0]+Re[1],Xe[1]=Re[3]+Re[2],Xe[2]=Re[3]-Re[2],Xe[3]=Re[0]-Re[1],S[0+We]=Xe[0]+_e[0],S[8+We]=Xe[1]+_e[1],S[16+We]=Xe[2]+_e[2],S[24+We]=Xe[3]+_e[3],S[32+We]=Xe[3]-_e[3],S[40+We]=Xe[2]-_e[2],S[48+We]=Xe[1]-_e[1],S[56+We]=Xe[0]-_e[0]}function F(S){for(let B=0;B<64;++B){const j=S[0][B],ee=S[1][B],N=S[2][B];S[0][B]=j+1.5747*N,S[1][B]=j-.1873*ee-.4682*N,S[2][B]=j+1.8556*ee}}function G(S,B,j){for(let ee=0;ee<64;++ee)B[j+ee]=Wd.toHalfFloat(J(S[ee]))}function J(S){return S<=1?Math.sign(S)*Math.pow(Math.abs(S),2.2):Math.sign(S)*Math.pow(t,Math.abs(S)-1)}function K(S){return new DataView(S.array.buffer,S.offset.value,S.size)}function oe(S){const B=S.viewer.buffer.slice(S.offset.value,S.offset.value+S.size),j=new Uint8Array(z(B)),ee=new Uint8Array(j.length);return M(j),P(j,ee),new DataView(ee.buffer)}function we(S){const B=S.array.slice(S.offset.value,S.offset.value+S.size),j=Iy(B),ee=new Uint8Array(j.length);return M(j),P(j,ee),new DataView(ee.buffer)}function De(S){const B=S.viewer,j={value:S.offset.value},ee=new Uint16Array(S.width*S.scanlineBlockSize*(S.channels*S.type)),N=new Uint8Array(8192);let Y=0;const W=new Array(S.channels);for(let gt=0;gt<S.channels;gt++)W[gt]={},W[gt].start=Y,W[gt].end=W[gt].start,W[gt].nx=S.width,W[gt].ny=S.lines,W[gt].size=S.type,Y+=W[gt].nx*W[gt].ny*W[gt].size;const ae=et(B,j),ce=et(B,j);if(ce>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(ae<=ce)for(let gt=0;gt<ce-ae+1;gt++)N[gt+ae]=ze(B,j);const _e=new Uint16Array(65536),Re=r(N,_e),Xe=fe(B,j);R(S.array,B,j,Xe,ee,Y);for(let gt=0;gt<S.channels;++gt){const rt=W[gt];for(let xt=0;xt<W[gt].size;++xt)I(ee,rt.start+xt,rt.nx,rt.size,rt.ny,rt.nx*rt.size,Re)}D(_e,ee,Y);let We=0;const Ke=new Uint8Array(ee.buffer.byteLength);for(let gt=0;gt<S.lines;gt++)for(let rt=0;rt<S.channels;rt++){const xt=W[rt],Jt=xt.nx*xt.size,Ui=new Uint8Array(ee.buffer,xt.end*2,Jt*2);Ke.set(Ui,We),We+=Jt*2,xt.end+=Jt}return new DataView(Ke.buffer)}function se(S){const B=S.array.slice(S.offset.value,S.offset.value+S.size),j=Iy(B),ee=S.lines*S.channels*S.width,N=S.type==1?new Uint16Array(ee):new Uint32Array(ee);let Y=0,W=0;const ae=new Array(4);for(let ce=0;ce<S.lines;ce++)for(let _e=0;_e<S.channels;_e++){let Re=0;switch(S.type){case 1:ae[0]=Y,ae[1]=ae[0]+S.width,Y=ae[1]+S.width;for(let Xe=0;Xe<S.width;++Xe){const We=j[ae[0]++]<<8|j[ae[1]++];Re+=We,N[W]=Re,W++}break;case 2:ae[0]=Y,ae[1]=ae[0]+S.width,ae[2]=ae[1]+S.width,Y=ae[2]+S.width;for(let Xe=0;Xe<S.width;++Xe){const We=j[ae[0]++]<<24|j[ae[1]++]<<16|j[ae[2]++]<<8;Re+=We,N[W]=Re,W++}break}}return new DataView(N.buffer)}function be(S){const B=S.viewer,j={value:S.offset.value},ee=new Uint8Array(S.width*S.lines*(S.channels*S.type*2)),N={version:Te(B,j),unknownUncompressedSize:Te(B,j),unknownCompressedSize:Te(B,j),acCompressedSize:Te(B,j),dcCompressedSize:Te(B,j),rleCompressedSize:Te(B,j),rleUncompressedSize:Te(B,j),rleRawSize:Te(B,j),totalAcUncompressedCount:Te(B,j),totalDcUncompressedCount:Te(B,j),acCompression:Te(B,j)};if(N.version<2)throw new Error("EXRLoader.parse: "+qt.compression+" version "+N.version+" is unsupported");const Y=new Array;let W=et(B,j)-2;for(;W>0;){const rt=Ie(B.buffer,j),xt=ze(B,j),Jt=xt>>2&3,Ui=(xt>>4)-1,en=new Int8Array([Ui])[0],pr=ze(B,j);Y.push({name:rt,index:en,type:pr,compression:Jt}),W-=rt.length+3}const ae=qt.channels,ce=new Array(S.channels);for(let rt=0;rt<S.channels;++rt){const xt=ce[rt]={},Jt=ae[rt];xt.name=Jt.name,xt.compression=0,xt.decoded=!1,xt.type=Jt.pixelType,xt.pLinear=Jt.pLinear,xt.width=S.width,xt.height=S.lines}const _e={idx:new Array(3)};for(let rt=0;rt<S.channels;++rt){const xt=ce[rt];for(let Jt=0;Jt<Y.length;++Jt){const Ui=Y[Jt];xt.name==Ui.name&&(xt.compression=Ui.compression,Ui.index>=0&&(_e.idx[Ui.index]=rt),xt.offset=rt)}}let Re,Xe,We;if(N.acCompressedSize>0)switch(N.acCompression){case 0:Re=new Uint16Array(N.totalAcUncompressedCount),R(S.array,B,j,N.acCompressedSize,Re,N.totalAcUncompressedCount);break;case 1:const rt=S.array.slice(j.value,j.value+N.totalAcUncompressedCount),xt=Iy(rt);Re=new Uint16Array(xt.buffer),j.value+=N.totalAcUncompressedCount;break}if(N.dcCompressedSize>0){const rt={array:S.array,offset:j,size:N.dcCompressedSize};Xe=new Uint16Array(we(rt).buffer),j.value+=N.dcCompressedSize}if(N.rleRawSize>0){const rt=S.array.slice(j.value,j.value+N.rleCompressedSize),xt=Iy(rt);We=z(xt.buffer),j.value+=N.rleCompressedSize}let Ke=0;const gt=new Array(ce.length);for(let rt=0;rt<gt.length;++rt)gt[rt]=new Array;for(let rt=0;rt<S.lines;++rt)for(let xt=0;xt<ce.length;++xt)gt[xt].push(Ke),Ke+=ce[xt].width*S.type*2;V(_e,gt,ce,Re,Xe,ee);for(let rt=0;rt<ce.length;++rt){const xt=ce[rt];if(!xt.decoded)switch(xt.compression){case 2:let Jt=0,Ui=0;for(let en=0;en<S.lines;++en){let pr=gt[rt][Jt];for(let ki=0;ki<xt.width;++ki){for(let ai=0;ai<2*xt.type;++ai)ee[pr++]=We[Ui+ai*xt.width*xt.height];Ui++}Jt++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(ee.buffer)}function Ie(S,B){const j=new Uint8Array(S);let ee=0;for(;j[B.value+ee]!=0;)ee+=1;const N=new TextDecoder().decode(j.slice(B.value,B.value+ee));return B.value=B.value+ee+1,N}function Je(S,B,j){const ee=new TextDecoder().decode(new Uint8Array(S).slice(B.value,B.value+j));return B.value=B.value+j,ee}function $e(S,B){const j=lt(S,B),ee=fe(S,B);return[j,ee]}function Oe(S,B){const j=fe(S,B),ee=fe(S,B);return[j,ee]}function lt(S,B){const j=S.getInt32(B.value,!0);return B.value=B.value+4,j}function fe(S,B){const j=S.getUint32(B.value,!0);return B.value=B.value+4,j}function X(S,B){const j=S[B.value];return B.value=B.value+1,j}function ze(S,B){const j=S.getUint8(B.value);return B.value=B.value+1,j}const Te=function(S,B){let j;return"getBigInt64"in DataView.prototype?j=Number(S.getBigInt64(B.value,!0)):j=S.getUint32(B.value+4,!0)+Number(S.getUint32(B.value,!0)<<32),B.value+=8,j};function Me(S,B){const j=S.getFloat32(B.value,!0);return B.value+=4,j}function Qe(S,B){return Wd.toHalfFloat(Me(S,B))}function Ae(S){const B=(S&31744)>>10,j=S&1023;return(S>>15?-1:1)*(B?B===31?j?NaN:1/0:Math.pow(2,B-15)*(1+j/1024):6103515625e-14*(j/1024))}function et(S,B){const j=S.getUint16(B.value,!0);return B.value+=2,j}function ct(S,B){return Ae(et(S,B))}function Tt(S,B,j,ee){const N=j.value,Y=[];for(;j.value<N+ee-1;){const W=Ie(B,j),ae=lt(S,j),ce=ze(S,j);j.value+=3;const _e=lt(S,j),Re=lt(S,j);Y.push({name:W,pixelType:ae,pLinear:ce,xSampling:_e,ySampling:Re})}return j.value+=1,Y}function Q(S,B){const j=Me(S,B),ee=Me(S,B),N=Me(S,B),Y=Me(S,B),W=Me(S,B),ae=Me(S,B),ce=Me(S,B),_e=Me(S,B);return{redX:j,redY:ee,greenX:N,greenY:Y,blueX:W,blueY:ae,whiteX:ce,whiteY:_e}}function k(S,B){const j=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],ee=ze(S,B);return j[ee]}function he(S,B){const j=fe(S,B),ee=fe(S,B),N=fe(S,B),Y=fe(S,B);return{xMin:j,yMin:ee,xMax:N,yMax:Y}}function Ee(S,B){const j=["INCREASING_Y"],ee=ze(S,B);return j[ee]}function Le(S,B){const j=Me(S,B),ee=Me(S,B);return[j,ee]}function Pe(S,B){const j=Me(S,B),ee=Me(S,B),N=Me(S,B);return[j,ee,N]}function vt(S,B,j,ee,N){if(ee==="string"||ee==="stringvector"||ee==="iccProfile")return Je(B,j,N);if(ee==="chlist")return Tt(S,B,j,N);if(ee==="chromaticities")return Q(S,j);if(ee==="compression")return k(S,j);if(ee==="box2i")return he(S,j);if(ee==="lineOrder")return Ee(S,j);if(ee==="float")return Me(S,j);if(ee==="v2f")return Le(S,j);if(ee==="v3f")return Pe(S,j);if(ee==="int")return lt(S,j);if(ee==="rational")return $e(S,j);if(ee==="timecode")return Oe(S,j);if(ee==="preview")return j.value+=N,"skipped";j.value+=N}function ht(S,B,j){const ee={};if(S.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");ee.version=S.getUint8(4);const N=S.getUint8(5);ee.spec={singleTile:!!(N&2),longName:!!(N&4),deepFormat:!!(N&8),multiPart:!!(N&16)},j.value=8;let Y=!0;for(;Y;){const W=Ie(B,j);if(W==0)Y=!1;else{const ae=Ie(B,j),ce=fe(S,j),_e=vt(S,B,j,ae,ce);_e===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${ae}'.`):ee[W]=_e}}if(N&-5)throw console.error("THREE.EXRHeader:",ee),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return ee}function je(S,B,j,ee,N){const Y={size:0,viewer:B,array:j,offset:ee,width:S.dataWindow.xMax-S.dataWindow.xMin+1,height:S.dataWindow.yMax-S.dataWindow.yMin+1,channels:S.channels.length,bytesPerLine:null,lines:null,inputSize:null,type:S.channels[0].pixelType,uncompress:null,getter:null,format:null,colorSpace:Ri};switch(S.compression){case"NO_COMPRESSION":Y.lines=1,Y.uncompress=K;break;case"RLE_COMPRESSION":Y.lines=1,Y.uncompress=oe;break;case"ZIPS_COMPRESSION":Y.lines=1,Y.uncompress=we;break;case"ZIP_COMPRESSION":Y.lines=16,Y.uncompress=we;break;case"PIZ_COMPRESSION":Y.lines=32,Y.uncompress=De;break;case"PXR24_COMPRESSION":Y.lines=16,Y.uncompress=se;break;case"DWAA_COMPRESSION":Y.lines=32,Y.uncompress=be;break;case"DWAB_COMPRESSION":Y.lines=256,Y.uncompress=be;break;default:throw new Error("EXRLoader.parse: "+S.compression+" is unsupported")}if(Y.scanlineBlockSize=Y.lines,Y.type==1)switch(N){case kn:Y.getter=ct,Y.inputSize=2;break;case rr:Y.getter=et,Y.inputSize=2;break}else if(Y.type==2)switch(N){case kn:Y.getter=Me,Y.inputSize=4;break;case rr:Y.getter=Qe,Y.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+Y.type+" for "+S.compression+".");Y.blockCount=(S.dataWindow.yMax+1)/Y.scanlineBlockSize;for(let ae=0;ae<Y.blockCount;ae++)Te(B,ee);Y.outputChannels=Y.channels==3?4:Y.channels;const W=Y.width*Y.height*Y.outputChannels;switch(N){case kn:Y.byteArray=new Float32Array(W),Y.channels<Y.outputChannels&&Y.byteArray.fill(1,0,W);break;case rr:Y.byteArray=new Uint16Array(W),Y.channels<Y.outputChannels&&Y.byteArray.fill(15360,0,W);break;default:console.error("THREE.EXRLoader: unsupported type: ",N);break}return Y.bytesPerLine=Y.width*Y.inputSize*Y.channels,Y.outputChannels==4?(Y.format=Yi,Y.colorSpace=Ri):(Y.format=Zm,Y.colorSpace=lo),Y}const Ve=new DataView(e),St=new Uint8Array(e),Ue={value:0},qt=ht(Ve,e,Ue),Fe=je(qt,Ve,St,Ue,this.type),_t={value:0},ut={R:0,G:1,B:2,A:3,Y:0};for(let S=0;S<Fe.height/Fe.scanlineBlockSize;S++){const B=fe(Ve,Ue);Fe.size=fe(Ve,Ue),Fe.lines=B+Fe.scanlineBlockSize>Fe.height?Fe.height-B:Fe.scanlineBlockSize;const j=Fe.size<Fe.lines*Fe.bytesPerLine?Fe.uncompress(Fe):K(Fe);Ue.value+=Fe.size;for(let ee=0;ee<Fe.scanlineBlockSize;ee++){const N=ee+S*Fe.scanlineBlockSize;if(N>=Fe.height)break;for(let Y=0;Y<Fe.channels;Y++){const W=ut[qt.channels[Y].name];for(let ae=0;ae<Fe.width;ae++){_t.value=(ee*(Fe.channels*Fe.width)+Y*Fe.width+ae)*Fe.inputSize;const ce=(Fe.height-1-N)*(Fe.width*Fe.outputChannels)+ae*Fe.outputChannels+W;Fe.byteArray[ce]=Fe.getter(j,_t)}}}}return{header:qt,width:Fe.width,height:Fe.height,data:Fe.byteArray,format:Fe.format,colorSpace:Fe.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,r,s){function o(a,l){a.colorSpace=l.colorSpace,a.minFilter=Pt,a.magFilter=Pt,a.generateMipmaps=!1,a.flipY=!1,t&&t(a,l)}return super.load(e,o,r,s)}}const wde=Object.freeze(Object.defineProperty({__proto__:null,EXRLoader:oA},Symbol.toStringTag,{value:"Module"}));class uS extends hI{constructor(e){super(e),this.type=rr}parse(e){const t=function(A,_){switch(A){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(_||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(_||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(_||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(_||""))}},r=`
5237
5237
  `,s=function(A,_,b){_=_||1024;let x=A.pos,E=-1,I=0,T="",R=String.fromCharCode.apply(null,new Uint16Array(A.subarray(x,x+128)));for(;0>(E=R.indexOf(r))&&I<_&&x<A.byteLength;)T+=R,I+=R.length,x+=128,R+=String.fromCharCode.apply(null,new Uint16Array(A.subarray(x,x+128)));return-1<E?(b!==!1&&(A.pos+=I+E+1),T+R.slice(0,E)):!1},o=function(A){const _=/^#\?(\S+)/,b=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,x=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,E=/^\s*FORMAT=(\S+)\s*$/,I=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,T={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let R,D;for((A.pos>=A.byteLength||!(R=s(A)))&&t(1,"no header found"),(D=R.match(_))||t(3,"bad initial token"),T.valid|=1,T.programtype=D[1],T.string+=R+`
5238
5238
  `;R=s(A),R!==!1;){if(T.string+=R+`
5239
5239
  `,R.charAt(0)==="#"){T.comments+=R+`
5240
- `;continue}if((D=R.match(b))&&(T.gamma=parseFloat(D[1])),(D=R.match(x))&&(T.exposure=parseFloat(D[1])),(D=R.match(E))&&(T.valid|=2,T.format=D[1]),(D=R.match(I))&&(T.valid|=4,T.height=parseInt(D[1],10),T.width=parseInt(D[2],10)),T.valid&2&&T.valid&4)break}return T.valid&2||t(3,"missing format specifier"),T.valid&4||t(3,"missing image size specifier"),T},a=function(A,_,b){const x=_;if(x<8||x>32767||A[0]!==2||A[1]!==2||A[2]&128)return new Uint8Array(A);x!==(A[2]<<8|A[3])&&t(3,"wrong scanline width");const E=new Uint8Array(4*_*b);E.length||t(4,"unable to allocate buffer space");let I=0,T=0;const R=4*x,D=new Uint8Array(4),M=new Uint8Array(R);let P=b;for(;P>0&&T<A.byteLength;){T+4>A.byteLength&&t(1),D[0]=A[T++],D[1]=A[T++],D[2]=A[T++],D[3]=A[T++],(D[0]!=2||D[1]!=2||(D[2]<<8|D[3])!=x)&&t(3,"bad rgbe scanline format");let z=0,V;for(;z<R&&T<A.byteLength;){V=A[T++];const H=V>128;if(H&&(V-=128),(V===0||z+V>R)&&t(3,"bad scanline data"),H){const O=A[T++];for(let F=0;F<V;F++)M[z++]=O}else M.set(A.subarray(T,T+V),z),z+=V,T+=V}const L=x;for(let H=0;H<L;H++){let O=0;E[I]=M[H+O],O+=x,E[I+1]=M[H+O],O+=x,E[I+2]=M[H+O],O+=x,E[I+3]=M[H+O],I+=4}P--}return E},l=function(A,_,b,x){const E=A[_+3],I=Math.pow(2,E-128)/255;b[x+0]=A[_+0]*I,b[x+1]=A[_+1]*I,b[x+2]=A[_+2]*I,b[x+3]=1},c=function(A,_,b,x){const E=A[_+3],I=Math.pow(2,E-128)/255;b[x+0]=Wd.toHalfFloat(Math.min(A[_+0]*I,65504)),b[x+1]=Wd.toHalfFloat(Math.min(A[_+1]*I,65504)),b[x+2]=Wd.toHalfFloat(Math.min(A[_+2]*I,65504)),b[x+3]=Wd.toHalfFloat(1)},h=new Uint8Array(e);h.pos=0;const u=o(h),p=u.width,m=u.height,f=a(h.subarray(h.pos),p,m);let g,v,y;switch(this.type){case kn:y=f.length/4;const A=new Float32Array(y*4);for(let b=0;b<y;b++)l(f,b*4,A,b*4);g=A,v=kn;break;case rr:y=f.length/4;const _=new Uint16Array(y*4);for(let b=0;b<y;b++)c(f,b*4,_,b*4);g=_,v=rr;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:p,height:m,data:g,header:u.string,gamma:u.gamma,exposure:u.exposure,type:v}}setDataType(e){return this.type=e,this}load(e,t,r,s){function o(a,l){switch(a.type){case kn:case rr:a.colorSpace=Ri,a.minFilter=Pt,a.magFilter=Pt,a.generateMipmaps=!1,a.flipY=!0;break}t&&t(a,l)}return super.load(e,o,r,s)}}const Sde=Object.freeze(Object.defineProperty({__proto__:null,RGBELoader:uS},Symbol.toStringTag,{value:"Module"})),fV="NEEDLE_lightmaps",aA=te("debuglightmapsextension")||te("debuglightmaps");var Hu=(n=>(n[n.Lightmap=0]="Lightmap",n[n.Skybox=1]="Skybox",n[n.Reflection=2]="Reflection",n))(Hu||{});class Cde{constructor(e,t,r){d(this,"parser"),d(this,"registry"),d(this,"source"),this.parser=e,this.registry=t,this.source=r}get name(){return fV}afterRoot(e){const t=this.parser.json.extensions;if(t){const r=t[fV];if(r){const s=r.textures;return s!=null&&s.length?(aA&&console.log(r),new Promise(async(o,a)=>{const l=[];for(const h of s)if(h.pointer){aA&&console.log(h);let u=null;if(h.pointer.startsWith("/textures/"))aA&&console.log("Load texture from gltf",h.pointer),u=nB(this.parser,h.pointer).then(p=>this.resolveTexture(h,p));else if(typeof h.pointer=="string"){aA&&console.log("Load texture from path",h.pointer);const p=cu(this.source,h.pointer);let m;p.endsWith(".exr")?m=new oA(this.parser.options.manager):p.endsWith(".hdr")?m=new uS(this.parser.options.manager):m=new Dl(this.parser.options.manager),u=m.loadAsync(p,void 0).then(f=>this.resolveTexture(h,f))}else h.pointer;u&&l.push(u)}const c=await tw(l);c!=null&&c.anyFailed&&st()&&console.error("Failed to load lightmap extension",c),o()})):null}}return null}resolveTexture(e,t){const r=t;aA&&console.log("Lightmap loaded:",r),r!=null&&r.isTexture&&(this.registry?(r.colorSpace=Ri,this.registry.registerTexture(this.source,e.type,r,e.index)):console.log(Hu[e.type],e.pointer,r))}}const gV=!!te("debuglightmaps");class Ede{constructor(e){d(this,"_context"),d(this,"_lightmaps",new Map),this._context=e}clear(){this._lightmaps.clear()}registerTexture(e,t,r,s){gV&&console.log("Registering ",Hu[t]+' "'+e+'"',r),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const o=this._lightmaps.get(e),a=o?.get(t)??[];a.length<s&&(a.length=s+1),a[s]=r,o?.set(t,a)}tryGetLightmap(e,t=0){return this.tryGet(e,Hu.Lightmap,t)}tryGetSkybox(e){return this.tryGet(e,Hu.Skybox,0)}tryGetReflection(e){return this.tryGet(e,Hu.Reflection,0)}tryGet(e,t,r){if(!e)return gV&&console.warn("Missing source id"),null;const s=this._lightmaps.get(e);if(!s)return null;const o=s.get(t);return o===void 0||!(o!=null&&o.length)||o.length<=r?null:o[r]}}Ct.lights_fragment_maps=Ct.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
5240
+ `;continue}if((D=R.match(b))&&(T.gamma=parseFloat(D[1])),(D=R.match(x))&&(T.exposure=parseFloat(D[1])),(D=R.match(E))&&(T.valid|=2,T.format=D[1]),(D=R.match(I))&&(T.valid|=4,T.height=parseInt(D[1],10),T.width=parseInt(D[2],10)),T.valid&2&&T.valid&4)break}return T.valid&2||t(3,"missing format specifier"),T.valid&4||t(3,"missing image size specifier"),T},a=function(A,_,b){const x=_;if(x<8||x>32767||A[0]!==2||A[1]!==2||A[2]&128)return new Uint8Array(A);x!==(A[2]<<8|A[3])&&t(3,"wrong scanline width");const E=new Uint8Array(4*_*b);E.length||t(4,"unable to allocate buffer space");let I=0,T=0;const R=4*x,D=new Uint8Array(4),M=new Uint8Array(R);let P=b;for(;P>0&&T<A.byteLength;){T+4>A.byteLength&&t(1),D[0]=A[T++],D[1]=A[T++],D[2]=A[T++],D[3]=A[T++],(D[0]!=2||D[1]!=2||(D[2]<<8|D[3])!=x)&&t(3,"bad rgbe scanline format");let z=0,V;for(;z<R&&T<A.byteLength;){V=A[T++];const H=V>128;if(H&&(V-=128),(V===0||z+V>R)&&t(3,"bad scanline data"),H){const O=A[T++];for(let F=0;F<V;F++)M[z++]=O}else M.set(A.subarray(T,T+V),z),z+=V,T+=V}const L=x;for(let H=0;H<L;H++){let O=0;E[I]=M[H+O],O+=x,E[I+1]=M[H+O],O+=x,E[I+2]=M[H+O],O+=x,E[I+3]=M[H+O],I+=4}P--}return E},l=function(A,_,b,x){const E=A[_+3],I=Math.pow(2,E-128)/255;b[x+0]=A[_+0]*I,b[x+1]=A[_+1]*I,b[x+2]=A[_+2]*I,b[x+3]=1},c=function(A,_,b,x){const E=A[_+3],I=Math.pow(2,E-128)/255;b[x+0]=Wd.toHalfFloat(Math.min(A[_+0]*I,65504)),b[x+1]=Wd.toHalfFloat(Math.min(A[_+1]*I,65504)),b[x+2]=Wd.toHalfFloat(Math.min(A[_+2]*I,65504)),b[x+3]=Wd.toHalfFloat(1)},h=new Uint8Array(e);h.pos=0;const u=o(h),p=u.width,m=u.height,f=a(h.subarray(h.pos),p,m);let g,v,y;switch(this.type){case kn:y=f.length/4;const A=new Float32Array(y*4);for(let b=0;b<y;b++)l(f,b*4,A,b*4);g=A,v=kn;break;case rr:y=f.length/4;const _=new Uint16Array(y*4);for(let b=0;b<y;b++)c(f,b*4,_,b*4);g=_,v=rr;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:p,height:m,data:g,header:u.string,gamma:u.gamma,exposure:u.exposure,type:v}}setDataType(e){return this.type=e,this}load(e,t,r,s){function o(a,l){switch(a.type){case kn:case rr:a.colorSpace=Ri,a.minFilter=Pt,a.magFilter=Pt,a.generateMipmaps=!1,a.flipY=!0;break}t&&t(a,l)}return super.load(e,o,r,s)}}const Sde=Object.freeze(Object.defineProperty({__proto__:null,RGBELoader:uS},Symbol.toStringTag,{value:"Module"})),f8="NEEDLE_lightmaps",aA=te("debuglightmapsextension")||te("debuglightmaps");var Hu=(n=>(n[n.Lightmap=0]="Lightmap",n[n.Skybox=1]="Skybox",n[n.Reflection=2]="Reflection",n))(Hu||{});class Cde{constructor(e,t,r){d(this,"parser"),d(this,"registry"),d(this,"source"),this.parser=e,this.registry=t,this.source=r}get name(){return f8}afterRoot(e){const t=this.parser.json.extensions;if(t){const r=t[f8];if(r){const s=r.textures;return s!=null&&s.length?(aA&&console.log(r),new Promise(async(o,a)=>{const l=[];for(const h of s)if(h.pointer){aA&&console.log(h);let u=null;if(h.pointer.startsWith("/textures/"))aA&&console.log("Load texture from gltf",h.pointer),u=nB(this.parser,h.pointer).then(p=>this.resolveTexture(h,p));else if(typeof h.pointer=="string"){aA&&console.log("Load texture from path",h.pointer);const p=cu(this.source,h.pointer);let m;p.endsWith(".exr")?m=new oA(this.parser.options.manager):p.endsWith(".hdr")?m=new uS(this.parser.options.manager):m=new Dl(this.parser.options.manager),u=m.loadAsync(p,void 0).then(f=>this.resolveTexture(h,f))}else h.pointer;u&&l.push(u)}const c=await tw(l);c!=null&&c.anyFailed&&st()&&console.error("Failed to load lightmap extension",c),o()})):null}}return null}resolveTexture(e,t){const r=t;aA&&console.log("Lightmap loaded:",r),r!=null&&r.isTexture&&(this.registry?(r.colorSpace=Ri,this.registry.registerTexture(this.source,e.type,r,e.index)):console.log(Hu[e.type],e.pointer,r))}}const g8=!!te("debuglightmaps");class Ede{constructor(e){d(this,"_context"),d(this,"_lightmaps",new Map),this._context=e}clear(){this._lightmaps.clear()}registerTexture(e,t,r,s){g8&&console.log("Registering ",Hu[t]+' "'+e+'"',r),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const o=this._lightmaps.get(e),a=o?.get(t)??[];a.length<s&&(a.length=s+1),a[s]=r,o?.set(t,a)}tryGetLightmap(e,t=0){return this.tryGet(e,Hu.Lightmap,t)}tryGetSkybox(e){return this.tryGet(e,Hu.Skybox,0)}tryGetReflection(e){return this.tryGet(e,Hu.Reflection,0)}tryGet(e,t,r){if(!e)return g8&&console.warn("Missing source id"),null;const s=this._lightmaps.get(e);if(!s)return null;const o=s.get(t);return o===void 0||!(o!=null&&o.length)||o.length<=r?null:o[r]}}Ct.lights_fragment_maps=Ct.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
5241
5241
  vec2 lUv = vLightMapUv.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
5242
5242
  vec4 lightMapTexel = texture2D( lightMap, lUv);
5243
5243
  // 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.
@@ -5266,7 +5266,7 @@ TEX `+r.texture_lod;if(HB=="density"&&(_+=`
5266
5266
  `+(A/l.lastScreenCoverage).toFixed(0)+` dens
5267
5267
  `+(l.lastScreenCoverage*100).toFixed(1)+`% cov
5268
5268
  `+(l.lastCentrality*100).toFixed(1)+`% centr
5269
- `+(dS.min.x.toFixed(2)+"-"+dS.max.x.toFixed(2)+"x"+dS.min.y.toFixed(2)+"-"+dS.max.y.toFixed(2))+" scr"),l.lastScreenCoverage>.1){const b=e,x=b.worldForward,E=b.worldPosition,I=pi(x).multiplyScalar(m*.7).add(p),T=I.distanceTo(E),R=f[Math.min(f.length-1,Math.max(0,c))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,M=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;At.DrawLabel(I,_,T*.012*D*M,void 0,16777215,R)}}}}}const mS=te("debugphysics"),vV=new ds;class ml{constructor(){d(this,"ray"),d(this,"cam"),d(this,"screenPoint"),d(this,"raycaster"),d(this,"results"),d(this,"targets"),d(this,"recursive",!0),d(this,"minDistance"),d(this,"maxDistance"),d(this,"lineThreshold"),d(this,"layerMask"),d(this,"ignore"),d(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new Z),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){vV.set(e),this.layerMask=vV}setMask(e){this.layerMask||(this.layerMask=new ds);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}d(ml,"AllLayers",4294967295);class yV{constructor(e,t,r){d(this,"distance"),d(this,"point"),d(this,"object"),this.object=e,this.distance=t,this.point=r}}class AV{constructor(e){d(this,"context"),d(this,"engine"),d(this,"raycaster",new pp),d(this,"defaultRaycastOptions",new ml),d(this,"targetBuffer",new Array(1)),d(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),d(this,"sphereResults",new Array),d(this,"sphereMask",new ds),d(this,"tempBoundingBox",new xi),this.context=e}raycastPhysicsFast(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(e,t,{maxDistance:r,solid:s}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(e,t,{maxDistance:r,solid:s}))??null}sphereOverlapPhysics(e,t){var r;return((r=this.context.physics.engine)==null?void 0:r.sphereOverlap(e,t))??null}sphereOverlap(e,t,r=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const s=new wn(e,t),o=this.sphereMask;o.enableAll(),o.disable(2);for(const a of this.context.scene.children)this.onSphereOverlap(a,s,o,this.sphereResults,r);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}onSphereOverlap(e,t,r,s,o){if(e.type==="Mesh"&&e.layers.test(r)&&!At.isGizmo(e)){const a=e,l=a.geometry;if(l&&(l.boundingBox||l.computeBoundingBox(),l.boundingBox)){a.matrixWorldNeedsUpdate&&a.updateMatrixWorld();const c=this.tempBoundingBox.copy(l.boundingBox).applyMatrix4(a.matrixWorld);if(t.intersectsBox(c)){const h=Bt(e),u=h.distanceTo(t.center),p=new yV(e,u,h);if(s.push(p),!o)return}}}if(e.children)for(const a of e.children){const l=s.length;if(this.onSphereOverlap(a,t,r,s,o),l!=s.length&&!o)return}}raycastFromRay(e,t=null){const r=t??this.defaultRaycastOptions;r.ray=e;const s=this.raycast(r);return r===this.defaultRaycastOptions&&(r.ray=void 0),s}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,r=e.raycaster??this.raycaster;if(r.near=e.minDistance??0,r.far=e.maxDistance??1/0,r.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),r.params.Line={threshold:e.lineThreshold},e.ray)r.ray.copy(e.ray);else{const l=e.cam??this.context.mainCamera;if(!l)return mS&&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 BT&&c.cameras.length>0?r.setFromCamera(t,c.cameras[0]):r.setFromCamera(t,l)}let s=e.targets;s||(s=this.targetBuffer,s.length=1,s[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ds?r.layers.mask=e.layerMask.mask:r.layers.mask=e.layerMask:(r.layers.enableAll(),r.layers.disable(2)),mS&&(At.DrawRay(r.ray.origin,r.ray.direction,16711680,2),console.time("raycast")),o.length=0,this.intersect(this.raycaster,s,o,e),o.sort((l,c)=>l.distance-c.distance);const a=e.ignore;return a!==void 0&&a.length>0&&(o=o.filter(l=>!a.includes(l.object))),mS&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing")),o}intersect(e,t,r,s){var o;for(const a of t){if(a.visible===!1||At.isGizmo(a)||s.lineThreshold!==void 0&&s.lineThreshold<0&&a instanceof Sn)continue;const l=(o=s.testObject)==null?void 0:o.call(s,a);if(l!==!1){if(l!=="continue in children"){const c=a,h=c.geometry;if(h){const u=wy(a);u&&(c.geometry=u);const p=r.length;e.intersectObject(a,!1,r),mS&&r.length!=p&&At.DrawWireMesh({mesh:a,depthTest:!1,duration:.2,color:u?8969557:7798784}),c.geometry=h}}s.recursive!==!1&&this.intersect(e,a.children,r,s)}}return r}}const Tde=te("debugplayerview");var Wu=(n=>(n.Browser="browser",n.Headset="headset",n.Handheld="handheld",n))(Wu||{});class bV{constructor(e,t){d(this,"userId"),d(this,"context"),d(this,"viewDevice","browser"),d(this,"removed",!1),d(this,"_object"),this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class _V{constructor(e){d(this,"context"),d(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,r){let s=this.playerViews.get(e);s||(s=new bV(e,this.context),this.playerViews.set(e,s)),s.viewDevice=r,s.currentObject=t,s.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const r=this.playerViews.get(e);r?.viewDevice===t&&(Tde&&console.log("REMOVE",e),r.removed=!0,this.playerViews.delete(e))}}new ys;const lA=new Uint8Array(4);lA[0]=255,lA[1]=255,lA[2]=255,lA[3]=255;const Ide=new Ro(lA,1,1,Yi);function WB(n,e=1){const t="alpha"in n,r=e*e,s=new Uint8Array(4*r),o=Math.floor(n.r*255),a=Math.floor(n.g*255),l=Math.floor(n.b*255);for(let h=0;h<r;h++){const u=h*4;s[u+0]=o,s[u+1]=a,s[u+2]=l,t?s[u+3]=Math.floor(n.alpha*255):s[u+3]=255}const c=new Ro(s,e,e);return c.needsUpdate=!0,c}function Rde(n,e,t,r=1,s=3){const o=r*s,a=[n,e,t],l=a.length,c=new Uint8Array(4*l*o),h=new xe;for(let p=0;p<s;p++){const m=Math.floor(p/s*l),f=it.clamp(m+1,0,l-1),g=a[m],v=a[f],y=p/s*l%1;h.lerpColors(g,v,y);const A=Math.floor(h.r*255),_=Math.floor(h.g*255),b=Math.floor(h.b*255);for(let x=0;x<r;x++){const E=(p*r+x)*4;c[E+0]=A,c[E+1]=_,c[E+2]=b,c[E+3]=255}}const u=new Ro(c,r,s);return u.needsUpdate=!0,u}function fS(n,e){const t=n.elements;e||(e=[]),e.length=0;for(let r=0;r<16;r+=4){const s=t[r],o=t[r+1],a=t[r+2],l=t[r+3],c=new Ye(s,o,a,l);e.push(c)}return e}const XB=[],xV=[];function Pde(n,e){if(XB.length===0)for(let t=0;t<27;t++)XB.push(0);e||(e=XB);for(let t=0;t<27;t++)xV[t]=e[t];e=xV,n.unity_SHAr={value:new Ye(e[9],e[3],e[6],e[0])},n.unity_SHBr={value:new Ye(e[12],e[15],e[18],e[21])},n.unity_SHAg={value:new Ye(e[10],e[4],e[7],e[1])},n.unity_SHBg={value:new Ye(e[13],e[16],e[19],e[22])},n.unity_SHAb={value:new Ye(e[11],e[5],e[8],e[2])},n.unity_SHBb={value:new Ye(e[14],e[17],e[20],e[23])},n.unity_SHC={value:new Ye(e[24],e[25],e[26],1)}}class Bde{constructor(e,t,r){d(this,"vertexShader"),d(this,"fragmentShader"),d(this,"technique"),this.vertexShader=e,this.fragmentShader=t,this.technique=r}}async function kde(n,e){if(!n)return console.error("Can not find technique: no shader data"),null;const t=n.programs[e],r=t.vertexShader,s=t.fragmentShader;if(r!==void 0&&s!==void 0){const o=n.shaders[r],a=n.shaders[s];if(o.uri&&a.uri||o.code&&a.code){if(!o.code&&o.uri&&await wV(o),!a.code&&a.uri&&await wV(a),!o.code||!a.code)return null;const l=n.techniques[e];return new Bde(o.code,a.code,l)}}return console.error("Shader technique not found",e),null}async function wV(n){const e=n.uri;if(e)if(e.endsWith(".glsl")){const t=await new ys().loadAsync(e);n.code=t.toString()}else n.code=Dde(n.uri)}function Dde(n){return decodeURIComponent(Array.prototype.map.call(atob(n),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const fl=te("debugenvlight");var Ng=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Ng||{}),gS=(n=>(n[n.Skybox=0]="Skybox",n[n.Custom=1]="Custom",n))(gS||{});class SV{constructor(e){d(this,"context"),d(this,"_currentLightSettingsId"),d(this,"_sceneLightSettings"),d(this,"_timevec4",new Ye),d(this,"__currentReflectionId",null),d(this,"_lighting",{}),this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var t;e instanceof ti&&(e=e.uri);const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Enable scene light settings",e,r),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,r.enabled=!0,!0):(fl&&console.warn("No light settings found for",e),!1)}disable(e){var t;if(e instanceof ti&&(e=e.uri),e==null)return!1;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Disable scene light settings",e,r),r.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}fl&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}fl&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){fl&&console.log("Register reflection",e,t);const r=new CV(this.context,t,1);this._lighting[e]=r}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var t;this.__currentReflectionId=e;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);switch(fl&&console.log("Enable reflection",e,r?Ng[r.ambientMode]:"Unknown ambient mode",r),r?.ambientMode){case 0:case 4:const s=this.internalGetReflection(e);if(s&&s.Source){fl&&console.log("Setting environment reflection",s);const o=this.context.scene,a=s.Source;a.mapping=so,o.environment=a;return}else fl&&console.warn("Could not find reflection for source",e);break}if(r?.environmentReflectionSource===1)switch(r?.ambientMode){case 1:if(r.ambientTrilight){const s=r.ambientTrilight,o=Rde(s[0],s[1],s[2],64,64);o.colorSpace=ft,o.mapping=so,this.context.scene.environment=o}else console.error("Missing ambient trilight",r.sourceId);return;case 3:if(r.ambientLight){const s=WB(r.ambientLight,64);s.colorSpace=ft,s.mapping=so,this.context.scene.environment=s}else console.error("Missing ambientlight",r.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){fl&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}fl&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class CV{constructor(e,t,r=1){d(this,"_source"),this._source=t,t.mapping=so}get Source(){return this._source}}const EV=te("timescale");let qB=1;typeof EV=="number"&&(qB=EV);class MV{constructor(){d(this,"_time",0),d(this,"_deltaTime",0),d(this,"_deltaTimeUnscaled",0),d(this,"timeScale",1),d(this,"_frame",0),d(this,"clock",new fI),d(this,"_smoothedFps",0),d(this,"_smoothedDeltaTime",0),d(this,"_fpsSamples",[]),d(this,"_fpsSampleIndex",0),typeof qB=="number"&&(this.timeScale=qB)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let TV=!1;function IV(n){TV||(TV=!0,Ode(),Lde())}IV();function Ode(){const n=`
5269
+ `+(dS.min.x.toFixed(2)+"-"+dS.max.x.toFixed(2)+"x"+dS.min.y.toFixed(2)+"-"+dS.max.y.toFixed(2))+" scr"),l.lastScreenCoverage>.1){const b=e,x=b.worldForward,E=b.worldPosition,I=pi(x).multiplyScalar(m*.7).add(p),T=I.distanceTo(E),R=f[Math.min(f.length-1,Math.max(0,c))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,M=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;At.DrawLabel(I,_,T*.012*D*M,void 0,16777215,R)}}}}}const mS=te("debugphysics"),v8=new ds;class ml{constructor(){d(this,"ray"),d(this,"cam"),d(this,"screenPoint"),d(this,"raycaster"),d(this,"results"),d(this,"targets"),d(this,"recursive",!0),d(this,"minDistance"),d(this,"maxDistance"),d(this,"lineThreshold"),d(this,"layerMask"),d(this,"ignore"),d(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new Z),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){v8.set(e),this.layerMask=v8}setMask(e){this.layerMask||(this.layerMask=new ds);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}d(ml,"AllLayers",4294967295);class y8{constructor(e,t,r){d(this,"distance"),d(this,"point"),d(this,"object"),this.object=e,this.distance=t,this.point=r}}class A8{constructor(e){d(this,"context"),d(this,"engine"),d(this,"raycaster",new pp),d(this,"defaultRaycastOptions",new ml),d(this,"targetBuffer",new Array(1)),d(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),d(this,"sphereResults",new Array),d(this,"sphereMask",new ds),d(this,"tempBoundingBox",new xi),this.context=e}raycastPhysicsFast(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(e,t,{maxDistance:r,solid:s}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(e,t,{maxDistance:r,solid:s}))??null}sphereOverlapPhysics(e,t){var r;return((r=this.context.physics.engine)==null?void 0:r.sphereOverlap(e,t))??null}sphereOverlap(e,t,r=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const s=new wn(e,t),o=this.sphereMask;o.enableAll(),o.disable(2);for(const a of this.context.scene.children)this.onSphereOverlap(a,s,o,this.sphereResults,r);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}onSphereOverlap(e,t,r,s,o){if(e.type==="Mesh"&&e.layers.test(r)&&!At.isGizmo(e)){const a=e,l=a.geometry;if(l&&(l.boundingBox||l.computeBoundingBox(),l.boundingBox)){a.matrixWorldNeedsUpdate&&a.updateMatrixWorld();const c=this.tempBoundingBox.copy(l.boundingBox).applyMatrix4(a.matrixWorld);if(t.intersectsBox(c)){const h=Bt(e),u=h.distanceTo(t.center),p=new y8(e,u,h);if(s.push(p),!o)return}}}if(e.children)for(const a of e.children){const l=s.length;if(this.onSphereOverlap(a,t,r,s,o),l!=s.length&&!o)return}}raycastFromRay(e,t=null){const r=t??this.defaultRaycastOptions;r.ray=e;const s=this.raycast(r);return r===this.defaultRaycastOptions&&(r.ray=void 0),s}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,r=e.raycaster??this.raycaster;if(r.near=e.minDistance??0,r.far=e.maxDistance??1/0,r.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),r.params.Line={threshold:e.lineThreshold},e.ray)r.ray.copy(e.ray);else{const l=e.cam??this.context.mainCamera;if(!l)return mS&&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 BT&&c.cameras.length>0?r.setFromCamera(t,c.cameras[0]):r.setFromCamera(t,l)}let s=e.targets;s||(s=this.targetBuffer,s.length=1,s[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ds?r.layers.mask=e.layerMask.mask:r.layers.mask=e.layerMask:(r.layers.enableAll(),r.layers.disable(2)),mS&&(At.DrawRay(r.ray.origin,r.ray.direction,16711680,2),console.time("raycast")),o.length=0,this.intersect(this.raycaster,s,o,e),o.sort((l,c)=>l.distance-c.distance);const a=e.ignore;return a!==void 0&&a.length>0&&(o=o.filter(l=>!a.includes(l.object))),mS&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing")),o}intersect(e,t,r,s){var o;for(const a of t){if(!a||a.visible===!1||At.isGizmo(a)||s.lineThreshold!==void 0&&s.lineThreshold<0&&a instanceof Sn)continue;const l=(o=s.testObject)==null?void 0:o.call(s,a);if(l!==!1){if(l!=="continue in children"){const c=a,h=c.geometry;if(h){const u=wy(a);u&&(c.geometry=u);const p=r.length;e.intersectObject(a,!1,r),mS&&r.length!=p&&At.DrawWireMesh({mesh:a,depthTest:!1,duration:.2,color:u?8969557:7798784}),c.geometry=h}}s.recursive!==!1&&this.intersect(e,a.children,r,s)}}return r}}const Tde=te("debugplayerview");var Wu=(n=>(n.Browser="browser",n.Headset="headset",n.Handheld="handheld",n))(Wu||{});class b8{constructor(e,t){d(this,"userId"),d(this,"context"),d(this,"viewDevice","browser"),d(this,"removed",!1),d(this,"_object"),this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class _8{constructor(e){d(this,"context"),d(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,r){let s=this.playerViews.get(e);s||(s=new b8(e,this.context),this.playerViews.set(e,s)),s.viewDevice=r,s.currentObject=t,s.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const r=this.playerViews.get(e);r?.viewDevice===t&&(Tde&&console.log("REMOVE",e),r.removed=!0,this.playerViews.delete(e))}}new ys;const lA=new Uint8Array(4);lA[0]=255,lA[1]=255,lA[2]=255,lA[3]=255;const Ide=new Ro(lA,1,1,Yi);function WB(n,e=1){const t="alpha"in n,r=e*e,s=new Uint8Array(4*r),o=Math.floor(n.r*255),a=Math.floor(n.g*255),l=Math.floor(n.b*255);for(let h=0;h<r;h++){const u=h*4;s[u+0]=o,s[u+1]=a,s[u+2]=l,t?s[u+3]=Math.floor(n.alpha*255):s[u+3]=255}const c=new Ro(s,e,e);return c.needsUpdate=!0,c}function Rde(n,e,t,r=1,s=3){const o=r*s,a=[n,e,t],l=a.length,c=new Uint8Array(4*l*o),h=new xe;for(let p=0;p<s;p++){const m=Math.floor(p/s*l),f=it.clamp(m+1,0,l-1),g=a[m],v=a[f],y=p/s*l%1;h.lerpColors(g,v,y);const A=Math.floor(h.r*255),_=Math.floor(h.g*255),b=Math.floor(h.b*255);for(let x=0;x<r;x++){const E=(p*r+x)*4;c[E+0]=A,c[E+1]=_,c[E+2]=b,c[E+3]=255}}const u=new Ro(c,r,s);return u.needsUpdate=!0,u}function fS(n,e){const t=n.elements;e||(e=[]),e.length=0;for(let r=0;r<16;r+=4){const s=t[r],o=t[r+1],a=t[r+2],l=t[r+3],c=new Ye(s,o,a,l);e.push(c)}return e}const XB=[],x8=[];function Pde(n,e){if(XB.length===0)for(let t=0;t<27;t++)XB.push(0);e||(e=XB);for(let t=0;t<27;t++)x8[t]=e[t];e=x8,n.unity_SHAr={value:new Ye(e[9],e[3],e[6],e[0])},n.unity_SHBr={value:new Ye(e[12],e[15],e[18],e[21])},n.unity_SHAg={value:new Ye(e[10],e[4],e[7],e[1])},n.unity_SHBg={value:new Ye(e[13],e[16],e[19],e[22])},n.unity_SHAb={value:new Ye(e[11],e[5],e[8],e[2])},n.unity_SHBb={value:new Ye(e[14],e[17],e[20],e[23])},n.unity_SHC={value:new Ye(e[24],e[25],e[26],1)}}class Bde{constructor(e,t,r){d(this,"vertexShader"),d(this,"fragmentShader"),d(this,"technique"),this.vertexShader=e,this.fragmentShader=t,this.technique=r}}async function kde(n,e){if(!n)return console.error("Can not find technique: no shader data"),null;const t=n.programs[e],r=t.vertexShader,s=t.fragmentShader;if(r!==void 0&&s!==void 0){const o=n.shaders[r],a=n.shaders[s];if(o.uri&&a.uri||o.code&&a.code){if(!o.code&&o.uri&&await w8(o),!a.code&&a.uri&&await w8(a),!o.code||!a.code)return null;const l=n.techniques[e];return new Bde(o.code,a.code,l)}}return console.error("Shader technique not found",e),null}async function w8(n){const e=n.uri;if(e)if(e.endsWith(".glsl")){const t=await new ys().loadAsync(e);n.code=t.toString()}else n.code=Dde(n.uri)}function Dde(n){return decodeURIComponent(Array.prototype.map.call(atob(n),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const fl=te("debugenvlight");var Ng=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Ng||{}),gS=(n=>(n[n.Skybox=0]="Skybox",n[n.Custom=1]="Custom",n))(gS||{});class S8{constructor(e){d(this,"context"),d(this,"_currentLightSettingsId"),d(this,"_sceneLightSettings"),d(this,"_timevec4",new Ye),d(this,"__currentReflectionId",null),d(this,"_lighting",{}),this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var t;e instanceof ti&&(e=e.uri);const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Enable scene light settings",e,r),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,r.enabled=!0,!0):(fl&&console.warn("No light settings found for",e),!1)}disable(e){var t;if(e instanceof ti&&(e=e.uri),e==null)return!1;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Disable scene light settings",e,r),r.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}fl&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}fl&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){fl&&console.log("Register reflection",e,t);const r=new C8(this.context,t,1);this._lighting[e]=r}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var t;this.__currentReflectionId=e;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);switch(fl&&console.log("Enable reflection",e,r?Ng[r.ambientMode]:"Unknown ambient mode",r),r?.ambientMode){case 0:case 4:const s=this.internalGetReflection(e);if(s&&s.Source){fl&&console.log("Setting environment reflection",s);const o=this.context.scene,a=s.Source;a.mapping=so,o.environment=a;return}else fl&&console.warn("Could not find reflection for source",e);break}if(r?.environmentReflectionSource===1)switch(r?.ambientMode){case 1:if(r.ambientTrilight){const s=r.ambientTrilight,o=Rde(s[0],s[1],s[2],64,64);o.colorSpace=ft,o.mapping=so,this.context.scene.environment=o}else console.error("Missing ambient trilight",r.sourceId);return;case 3:if(r.ambientLight){const s=WB(r.ambientLight,64);s.colorSpace=ft,s.mapping=so,this.context.scene.environment=s}else console.error("Missing ambientlight",r.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){fl&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}fl&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class C8{constructor(e,t,r=1){d(this,"_source"),this._source=t,t.mapping=so}get Source(){return this._source}}const E8=te("timescale");let qB=1;typeof E8=="number"&&(qB=E8);class M8{constructor(){d(this,"_time",0),d(this,"_deltaTime",0),d(this,"_deltaTimeUnscaled",0),d(this,"timeScale",1),d(this,"_frame",0),d(this,"clock",new fI),d(this,"_smoothedFps",0),d(this,"_smoothedDeltaTime",0),d(this,"_fpsSamples",[]),d(this,"_fpsSampleIndex",0),typeof qB=="number"&&(this.timeScale=qB)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let T8=!1;function I8(n){T8||(T8=!0,Ode(),Lde())}I8();function Ode(){const n=`
5270
5270
  float startCompression = 0.8;
5271
5271
  float desaturation = 0.5;
5272
5272
  // Patched tonemapping function
@@ -5398,7 +5398,7 @@ vec3 AgXToneMapping( vec3 color ) {
5398
5398
  color = _agxEotf(color);
5399
5399
  return color;
5400
5400
  }`,e="vec3 AgXToneMapping( vec3 color ) {",t=` return color;
5401
- }`,r=Ct.tonemapping_pars_fragment.indexOf(e),s=Ct.tonemapping_pars_fragment.indexOf(t,r);if(r>=0&&s>=0){const o=Ct.tonemapping_pars_fragment.substring(r,s+t.length);Ct.tonemapping_pars_fragment=Ct.tonemapping_pars_fragment.replace(o,n)}}function Ao(n){const e=document.createElement("span");return e.style.maxWidth="48px",e.style.maxHeight="48px",e.style.overflow="hidden",e.classList.add("material-symbols-outlined"),e.innerText=n,e}function RV(n){var e;return((e=n.classList)==null?void 0:e.contains("material-symbols-outlined"))||!1}const vS=new Map;async function YB(n){const e="Material Symbols Outlined";if(document.fonts.check(`1em '${e}'`)||(console.log("Font not loaded yet"),await document.fonts.ready),vS.has(n))return vS.get(n);const t=document.createElement("canvas"),r=48;t.width=r,t.height=r;const s=t.getContext("2d");if(s){s.font=`${r}px '${e}'`,s.fillStyle="black",s.fillText(n,0,r);const o=t.toDataURL(),a=new zt;return a.name=n+" icon",a.image=new Image,a.image.src=o,a.needsUpdate=!0,vS.set(n,a),a}return vS.set(n,null),null}const JB=class{constructor(){d(this,"_fullscreenButton"),d(this,"_muteButton"),d(this,"_qrButton")}static getOrCreate(){return this._instance||(this._instance=new JB),this._instance}static create(){return new JB}get fullscreenButton(){return this._fullscreenButton}createFullscreenButton(n){if(this._fullscreenButton)return this._fullscreenButton;if(!document.fullscreenEnabled)return st()&&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 t=Ao("fullscreen"),r=Ao("fullscreen_exit");return e.appendChild(t),e.onclick=()=>{document.fullscreenElement?document.exitFullscreen():"webkitRequestFullscreen"in n.domElement&&typeof n.domElement.webkitRequestFullscreen=="function"?n.domElement.webkitRequestFullscreen():"requestFullscreen"in n.domElement&&n.domElement.requestFullscreen()},document.addEventListener("fullscreenchange",()=>{document.fullscreenElement?(t.remove(),e.appendChild(r),e.title="Click to enter fullscreen mode"):(r.remove(),e.appendChild(t),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(n){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 t=Ao("volume_off"),r=Ao("volume_up");return n.application.muted?e.appendChild(t):e.appendChild(r),e.onclick=()=>{n.application.muted?(t.remove(),e.appendChild(r),n.application.muted=!1):(r.remove(),e.appendChild(t),n.application.muted=!0)},e}get qrButton(){return this._qrButton}createQRCode(){if(this._qrButton)return this._qrButton;const n=document.createElement("button");this._qrButton=n,n.innerText="QR Code",n.prepend(Ao("qr_code")),n.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(n),aa()&&(n.style.display="none");const e=document.createElement("div");e.style.position="fixed",e.style.display="inline-block",e.style.padding="1rem",e.style.backgroundColor="white",e.style.borderRadius="0.4rem",e.style.cursor="pointer",e.style.zIndex="1000",e.style.boxShadow="0 0 12px rgba(0, 0, 0, 0.2)";const t=document.createElement("div");t.classList.add("qr-code-container"),e.appendChild(t),n.addEventListener("click",()=>{if(e.parentNode)return s();window.location.href.includes("://localhost")&&Di("To access your website from another device in the same local network you have to use the IP address instead of localhost."),r()});async function r(){await o(),document.body.appendChild(e);const a=t.getBoundingClientRect(),l=n.getBoundingClientRect();e.style.left=l.left+l.width*.5-a.width*.5+"px",l.top<a.height?e.style.top=`calc(${l.bottom}px + ${e.style.padding} * .6)`:e.style.top=`calc(${l.top-a.height}px - ${e.style.padding} * 2.5)`,e.style.opacity="0",e.style.pointerEvents="all",e.style.transition="opacity 0.2s ease-in-out",setTimeout(()=>{e.style.opacity="1",window.addEventListener("click",s,{once:!0})}),window.addEventListener("resize",s),window.addEventListener("scroll",s),document.body.appendChild(e)}function s(){e.style.pointerEvents="none",e.style.transition="opacity 0.2s",e.style.opacity="0",setTimeout(()=>{var a;return(a=e.parentNode)==null?void 0:a.removeChild(e)},500),window.removeEventListener("click",s),window.removeEventListener("resize",s),window.removeEventListener("scroll",s)}async function o(){const a=await QU({text:window.location.href,width:200,height:200});t.innerHTML="",t.appendChild(a)}return n.addEventListener("pointerenter",()=>{o()},{once:!0}),n}hideElementDuringXRSession(n){X1(e=>{n["previous-display"]=n.style.display,n.style.display="none"}),mB(e=>{n["previous-display"]!=null&&(n.style.display=n["previous-display"])})}};let yh=JB;d(yh,"_instance");function yS(n,e){const t=e?.element||document.head,r=Array.from(t.querySelectorAll(`link[rel=stylesheet][href*='${n}']`));if(r.length<=0){const s=document.createElement("link");s.href=n,s.rel="stylesheet",t.appendChild(s),r.push(s)}if(e!=null&&e.loadedCallback)for(let s=0;s<r.length;s++)e!=null&&e.loadedCallback&&r[s].addEventListener("load",e.loadedCallback)}function PV(){yS("https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap")}const KB="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0",AS="needle-logo-element";class BV extends HTMLElement{constructor(){super(),d(this,"_root"),d(this,"wrapper"),d(this,"logoElement",document.createElement("img")),d(this,"textElement",document.createElement("span")),this._root=this.attachShadow({mode:"closed"});const e=document.createElement("template");e.innerHTML=`<style>
5401
+ }`,r=Ct.tonemapping_pars_fragment.indexOf(e),s=Ct.tonemapping_pars_fragment.indexOf(t,r);if(r>=0&&s>=0){const o=Ct.tonemapping_pars_fragment.substring(r,s+t.length);Ct.tonemapping_pars_fragment=Ct.tonemapping_pars_fragment.replace(o,n)}}function Ao(n){const e=document.createElement("span");return e.style.maxWidth="48px",e.style.maxHeight="48px",e.style.overflow="hidden",e.classList.add("material-symbols-outlined"),e.innerText=n,e}function R8(n){var e;return((e=n.classList)==null?void 0:e.contains("material-symbols-outlined"))||!1}const vS=new Map;async function YB(n){const e="Material Symbols Outlined";if(document.fonts.check(`1em '${e}'`)||(console.log("Font not loaded yet"),await document.fonts.ready),vS.has(n))return vS.get(n);const t=document.createElement("canvas"),r=48;t.width=r,t.height=r;const s=t.getContext("2d");if(s){s.font=`${r}px '${e}'`,s.fillStyle="black",s.fillText(n,0,r);const o=t.toDataURL(),a=new zt;return a.name=n+" icon",a.image=new Image,a.image.src=o,a.needsUpdate=!0,vS.set(n,a),a}return vS.set(n,null),null}const JB=class{constructor(){d(this,"_fullscreenButton"),d(this,"_muteButton"),d(this,"_qrButton")}static getOrCreate(){return this._instance||(this._instance=new JB),this._instance}static create(){return new JB}get fullscreenButton(){return this._fullscreenButton}createFullscreenButton(n){if(this._fullscreenButton)return this._fullscreenButton;if(!document.fullscreenEnabled)return st()&&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 t=Ao("fullscreen"),r=Ao("fullscreen_exit");return e.appendChild(t),e.onclick=()=>{document.fullscreenElement?document.exitFullscreen():"webkitRequestFullscreen"in n.domElement&&typeof n.domElement.webkitRequestFullscreen=="function"?n.domElement.webkitRequestFullscreen():"requestFullscreen"in n.domElement&&n.domElement.requestFullscreen()},document.addEventListener("fullscreenchange",()=>{document.fullscreenElement?(t.remove(),e.appendChild(r),e.title="Click to enter fullscreen mode"):(r.remove(),e.appendChild(t),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(n){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 t=Ao("volume_off"),r=Ao("volume_up");return n.application.muted?e.appendChild(t):e.appendChild(r),e.onclick=()=>{n.application.muted?(t.remove(),e.appendChild(r),n.application.muted=!1):(r.remove(),e.appendChild(t),n.application.muted=!0)},e}get qrButton(){return this._qrButton}createQRCode(){if(this._qrButton)return this._qrButton;const n=document.createElement("button");this._qrButton=n,n.innerText="QR Code",n.prepend(Ao("qr_code")),n.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(n),aa()&&(n.style.display="none");const e=document.createElement("div");e.style.position="fixed",e.style.display="inline-block",e.style.padding="1rem",e.style.backgroundColor="white",e.style.borderRadius="0.4rem",e.style.cursor="pointer",e.style.zIndex="1000",e.style.boxShadow="0 0 12px rgba(0, 0, 0, 0.2)";const t=document.createElement("div");t.classList.add("qr-code-container"),e.appendChild(t),n.addEventListener("click",()=>{if(e.parentNode)return s();window.location.href.includes("://localhost")&&Di("To access your website from another device in the same local network you have to use the IP address instead of localhost."),r()});async function r(){await o(),document.body.appendChild(e);const a=t.getBoundingClientRect(),l=n.getBoundingClientRect();e.style.left=l.left+l.width*.5-a.width*.5+"px",l.top<a.height?e.style.top=`calc(${l.bottom}px + ${e.style.padding} * .6)`:e.style.top=`calc(${l.top-a.height}px - ${e.style.padding} * 2.5)`,e.style.opacity="0",e.style.pointerEvents="all",e.style.transition="opacity 0.2s ease-in-out",setTimeout(()=>{e.style.opacity="1",window.addEventListener("click",s,{once:!0})}),window.addEventListener("resize",s),window.addEventListener("scroll",s),document.body.appendChild(e)}function s(){e.style.pointerEvents="none",e.style.transition="opacity 0.2s",e.style.opacity="0",setTimeout(()=>{var a;return(a=e.parentNode)==null?void 0:a.removeChild(e)},500),window.removeEventListener("click",s),window.removeEventListener("resize",s),window.removeEventListener("scroll",s)}async function o(){const a=await QU({text:window.location.href,width:200,height:200});t.innerHTML="",t.appendChild(a)}return n.addEventListener("pointerenter",()=>{o()},{once:!0}),n}hideElementDuringXRSession(n){X1(e=>{n["previous-display"]=n.style.display,n.style.display="none"}),mB(e=>{n["previous-display"]!=null&&(n.style.display=n["previous-display"])})}};let yh=JB;d(yh,"_instance");function yS(n,e){const t=e?.element||document.head,r=Array.from(t.querySelectorAll(`link[rel=stylesheet][href*='${n}']`));if(r.length<=0){const s=document.createElement("link");s.href=n,s.rel="stylesheet",t.appendChild(s),r.push(s)}if(e!=null&&e.loadedCallback)for(let s=0;s<r.length;s++)e!=null&&e.loadedCallback&&r[s].addEventListener("load",e.loadedCallback)}function P8(){yS("https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap")}const KB="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0",AS="needle-logo-element";class B8 extends HTMLElement{constructor(){super(),d(this,"_root"),d(this,"wrapper"),d(this,"logoElement",document.createElement("img")),d(this,"textElement",document.createElement("span")),this._root=this.attachShadow({mode:"closed"});const e=document.createElement("template");e.innerHTML=`<style>
5402
5402
  :host {
5403
5403
  position: relative;
5404
5404
  min-width: fit-content;
@@ -5429,7 +5429,7 @@ vec3 AgXToneMapping( vec3 color ) {
5429
5429
  <div class="wrapper">
5430
5430
  <img class="logo" src=${vne} />
5431
5431
  </div>
5432
- `,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 AS}static create(){return document.createElement(AS)}setLogoVisible(e){this.logoElement.style.display=e?"block":"none"}}customElements.get(AS)||customElements.define(AS,BV);const ZB=te("debugspatialmenu");class Fde{constructor(e,t){d(this,"_context"),d(this,"needleMenu"),d(this,"htmlButtonsMap",new Map),d(this,"enabled",!0),d(this,"uiisDirty",!1),d(this,"_showNeedleLogo"),d(this,"_wasInXR",!1),d(this,"preRender",()=>{var o;if(!this.enabled){(o=this.menu)==null||o.removeFromParent();return}ZB&&fp()&&this.updateMenu();const a=this._context.xr;if(!(a!=null&&a.running)){this._wasInXR&&(this._wasInXR=!1,this.onExitXR());return}this._wasInXR||(this._wasInXR=!0,this.onEnterXR()),this.updateMenu()}),d(this,"_menuTarget",new ye),d(this,"positionFilter",new gR(90,.5)),d(this,"familyName","Needle Spatial Menu"),d(this,"menu"),d(this,"_poweredByNeedleElement");var r;this._context=e,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=t;const s=(r=this.needleMenu.shadowRoot)==null?void 0:r.querySelector(".options");s?new MutationObserver(o=>{if(this.enabled&&!(this._context.isInXR==!1&&!ZB))for(const a of o)a.type==="childList"&&(a.addedNodes.forEach(l=>{this.createButtonFromHTMLNode(l)}),a.removedNodes.forEach(l=>{const c=l,h=this.htmlButtonsMap.get(c);h&&(this.htmlButtonsMap.delete(c),h.remove(),Ni.update())}))}).observe(s,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(e){var t;this.enabled=e,e||(t=this.menu)==null||t.removeFromParent()}onDestroy(){const e=this._context.pre_render_callbacks.indexOf(this.preRender);e>-1&&this._context.pre_render_callbacks.splice(e,1)}markDirty(){this.uiisDirty=!0}showNeedleLogo(e){this._showNeedleLogo=e}onEnterXR(){var e;const t=(e=this.needleMenu.shadowRoot)==null?void 0:e.querySelector(".options");t&&t.childNodes.forEach(r=>{this.createButtonFromHTMLNode(r)})}onExitXR(){var e;(e=this.menu)==null||e.removeFromParent()}createButtonFromHTMLNode(e){const t=this.getMenu(),r=this.htmlButtonsMap.get(e);if(r){r.add();return}if(e instanceof HTMLButtonElement){const s=this.createButton(t,e);this.htmlButtonsMap.set(e,s),s.add()}else e instanceof HTMLSlotElement&&e.assignedNodes().forEach(s=>{this.createButtonFromHTMLNode(s)})}updateMenu(){var e,t;const r=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(r);const s=this._context.mainCamera,o=this._context.xr,a=o?.rigScale||1;if(s){const l=s.worldPosition,c=s.worldForward.multiplyScalar(-1),h=c.y>.6,u=c.y>.4,p=r.visible?u:h,m=!r.visible&&p;r.visible=p||fp()&&ZB,c.multiplyScalar(3*a),l.add(c),m&&(r.position.copy(this._menuTarget.position),r.position.y+=1,this._menuTarget.position.copy(r.position),this.positionFilter.reset(r.position),r.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const f=this._menuTarget.position.distanceTo(l);(m||f>1.5*a)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(l),this._context.scene.add(this._menuTarget),Hv(this._menuTarget,this._context.mainCamera,!1,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,r.position,this._context.time.time);const g=5;(e=this.menu)==null||e.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*g),(t=this.menu)==null||t.scale.setScalar(a)}this.uiisDirty&&(this.uiisDirty=!1,Ni.update())}ensureRenderOnTop(e,t=0){e instanceof me&&(e.material.depthTest=!1,e.material.depthWrite=!1),e.renderOrder=1e3+t*2;for(const r of e.children)this.ensureRenderOnTop(r,t+1)}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new Ni.Block({boxSizing:"border-box",fontFamily:this.familyName,height:"auto",fontSize:.1,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:.55,borderRadius:.04,whiteSpace:"pre-wrap",flexDirection:"row",alignItems:"center",padding:new Ye(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const e=q.get("ObjectRaycaster");return e&&Zp(this.menu,new e),this.menu}handleNeedleWatermark(){var e;if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new Ni.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 t=new kV(this._context,()=>globalThis.open("https://needle.tools","_self"));Zp(this._poweredByNeedleElement,t);const r=new Ni.Text({textContent:"Powered by",width:"auto",height:"auto"}),s=new Ni.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new Ye(0,0,0,.02)});this._poweredByNeedleElement.add(r),this._poweredByNeedleElement.add(s),(e=this.menu)==null||e.add(this._poweredByNeedleElement),this.markDirty(),new Dl().load("./include/needle/poweredbyneedle.webp",o=>{var a;t.allowModifyUI=!1,r.removeFromParent(),s.removeFromParent();const l=o.image.width/o.image.height;(a=this._poweredByNeedleElement)==null||a.set({backgroundImage:o,backgroundOpacity:1,width:.1*l,height:.1}),this.markDirty()})}if(this.menu){const t=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&uu())t>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const r=this.menu.children.indexOf(this._poweredByNeedleElement);t!==r&&this.markDirty()}}}ensureFont(){let e=Ni.FontLibrary.getFontFamily(this.familyName);if(!e){e=Ni.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t?.addEventListener("ready",()=>{this.markDirty()})}}createButton(e,t){const r=new Ni.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}),s=new Ni.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});r.add(s),r["needle:use_eventsystem"]=!0;const o=new kV(this._context,()=>t.click());return Zp(r,o),new Ude(this,e,t,r,s)}}class Ude{constructor(e,t,r,s,o){d(this,"menu"),d(this,"root"),d(this,"htmlbutton"),d(this,"spatialContainer"),d(this,"spatialText"),d(this,"spatialIcon"),d(this,"_lastText",""),d(this,"_lastTexture"),this.menu=e,this.root=t,this.htmlbutton=r,this.spatialContainer=s,this.spatialText=o,new MutationObserver(a=>{for(const l of a)l.type==="attributes"?l.attributeName==="style"&&this.updateVisible():l.type==="childList"&&this.updateText()}).observe(r,{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 e=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",e!==this.spatialContainer.visible&&this.menu.markDirty()}updateText(){let e="",t="";this.htmlbutton.childNodes.forEach(r=>{r.nodeType===Node.TEXT_NODE?e+=r.textContent:r instanceof HTMLElement&&RV(r)&&r.textContent&&(t=r.textContent)}),this._lastText!==e&&(this._lastText=e,this.spatialText.name=e,this.spatialText.set({textContent:e}),this.menu.markDirty()),e.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),t&&this.createIcon(t)}async createIcon(e){var t;if(!this.spatialIcon){const s=await YB(e);if(s&&!this.spatialIcon){const o=new Ni.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:s,backgroundOpacity:1,margin:new Ye(0,.005,0,0)});this.spatialIcon=o,this.spatialContainer.add(o),this.menu.markDirty()}}if(e!=this._lastTexture){this._lastTexture=e;const s=await YB(e);s&&((t=this.spatialIcon)==null||t.set({backgroundImage:s}),this.menu.markDirty())}const r=this.spatialContainer.children.indexOf(this.spatialIcon);r>0&&(this.spatialContainer.children.splice(r,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class kV{constructor(e,t){d(this,"isComponent",!0),d(this,"enabled",!0),d(this,"gameObject"),d(this,"allowModifyUI",!0),d(this,"context"),d(this,"onclick"),this.context=e,this.onclick=t}get activeAndEnabled(){return!0}__internalAwake(){}__internalEnable(){}__internalDisable(){}__internalStart(){}onEnable(){}onDisable(){}get element(){return this.gameObject}onPointerEnter(){this.context.input.setCursorPointer(),this.allowModifyUI&&(this.element.set({backgroundOpacity:1}),Ni.update())}onPointerExit(){this.context.input.setCursorNormal(),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),Ni.update())}onPointerDown(e){e.use()}onPointerUp(e){e.use()}onPointerClick(e){e.use(),this.onclick()}}const zg="needle-menu",cA=te("debugmenu"),DV=te("debugnoncommercial");let Nde=class{constructor(n){d(this,"_context"),d(this,"_menu"),d(this,"_spatialMenu"),d(this,"onPostMessage",e=>{if(e.origin===globalThis.location.origin&&typeof e.data=="object"){const t=e.data,r=t.type;if(r==="needle:menu"){const s=t.button;if(s){if(!s.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!s.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const o=document.createElement("button");if(o.textContent=s.label,s.icon){const a=Ao(s.icon);o.prepend(a)}s.priority&&o.setAttribute("priority",s.priority.toString()),o.onclick=()=>{if(s.onclick){const a=s.onclick.startsWith("http")||s.onclick.startsWith("www."),l=s.target||"_blank";a?globalThis.open(s.onclick,l):console.error("NeedleMenu: onclick is not a valid link",s.onclick)}},this._menu.appendChild(o)}else cA&&console.error("NeedleMenu: unknown postMessage event",t)}else cA&&console.warn("NeedleMenu: unknown postMessage type",r,t)}}),d(this,"onStartXR",e=>{e.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),e.session.session.addEventListener("end",this.onExitXR))}),d(this,"onExitXR",()=>{this._menu.previousParent&&(this._menu.previousParent.appendChild(this._menu),delete this._menu.previousParent)}),d(this,"_muteButton"),d(this,"_fullscreenButton"),this._menu=qE.getOrCreate(n.domElement,n),this._context=n,this._spatialMenu=new Fde(n,this._menu),window.addEventListener("message",this.onPostMessage),X1(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}setPosition(n){this._menu.setPosition(n)}setVisible(n){this._menu.setVisible(n)}showNeedleLogo(n){var e;this._menu.showNeedleLogo(n),(e=this._spatialMenu)==null||e.showNeedleLogo(n)}showSpatialMenu(n){this._spatialMenu.setEnabled(n)}showQRCodeButton(n){if(n==="desktop-only"&&(n=!aa()),n){const e=yh.getOrCreate().createQRCode();return e.style.display="",this._menu.appendChild(e),e}else{const e=yh.getOrCreate().qrButton;return e&&(e.style.display="none"),e??null}}showAudioPlaybackOption(n){var e;if(!n){(e=this._muteButton)==null||e.remove();return}this._muteButton=yh.getOrCreate().createMuteButton(this._context),this._muteButton.setAttribute("priority","100"),this._menu.appendChild(this._muteButton)}showFullscreenOption(n){var e;if(!n){(e=this._fullscreenButton)==null||e.remove();return}this._fullscreenButton=yh.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&(this._fullscreenButton.setAttribute("priority","150"),this._menu.appendChild(this._fullscreenButton))}appendChild(n){return this._menu.appendChild(n)}};class qE extends HTMLElement{constructor(){var e,t,r,s;super(),d(this,"_domElement",null),d(this,"_context",null),d(this,"_sizeChangeInterval"),d(this,"_userRequestedLogoVisible"),d(this,"_userRequestedMenuVisible"),d(this,"root"),d(this,"wrapper"),d(this,"options"),d(this,"logoContainer"),d(this,"_isHandlingChange",!1),d(this,"_didSort",new Map),d(this,"_lastAvailableWidthChange",0),d(this,"_timeoutHandle",0),d(this,"handleSizeChange",(m,f)=>{if(!this._domElement)return;const g=this._domElement.clientWidth;if(g<500){this.root.classList.add("compact");return}const v=20*2,y=g-v;if(!f&&Math.abs(y-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=y,clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{const b=_();b<0?this.root.classList.add("compact"):b>0&&(this.root.classList.remove("compact"),_()<0&&this.root.classList.add("compact"))},5);const A=()=>this.options.clientWidth+this.logoContainer.clientWidth,_=()=>y-A()});const o=document.createElement("template");o.innerHTML=`<style>
5432
+ `,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 AS}static create(){return document.createElement(AS)}setLogoVisible(e){this.logoElement.style.display=e?"block":"none"}}customElements.get(AS)||customElements.define(AS,B8);const ZB=te("debugspatialmenu");class Fde{constructor(e,t){d(this,"_context"),d(this,"needleMenu"),d(this,"htmlButtonsMap",new Map),d(this,"enabled",!0),d(this,"uiisDirty",!1),d(this,"_showNeedleLogo"),d(this,"_wasInXR",!1),d(this,"preRender",()=>{var o;if(!this.enabled){(o=this.menu)==null||o.removeFromParent();return}ZB&&fp()&&this.updateMenu();const a=this._context.xr;if(!(a!=null&&a.running)){this._wasInXR&&(this._wasInXR=!1,this.onExitXR());return}this._wasInXR||(this._wasInXR=!0,this.onEnterXR()),this.updateMenu()}),d(this,"_menuTarget",new ye),d(this,"positionFilter",new gR(90,.5)),d(this,"familyName","Needle Spatial Menu"),d(this,"menu"),d(this,"_poweredByNeedleElement");var r;this._context=e,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=t;const s=(r=this.needleMenu.shadowRoot)==null?void 0:r.querySelector(".options");s?new MutationObserver(o=>{if(this.enabled&&!(this._context.isInXR==!1&&!ZB))for(const a of o)a.type==="childList"&&(a.addedNodes.forEach(l=>{this.createButtonFromHTMLNode(l)}),a.removedNodes.forEach(l=>{const c=l,h=this.htmlButtonsMap.get(c);h&&(this.htmlButtonsMap.delete(c),h.remove(),Ni.update())}))}).observe(s,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(e){var t;this.enabled=e,e||(t=this.menu)==null||t.removeFromParent()}onDestroy(){const e=this._context.pre_render_callbacks.indexOf(this.preRender);e>-1&&this._context.pre_render_callbacks.splice(e,1)}markDirty(){this.uiisDirty=!0}showNeedleLogo(e){this._showNeedleLogo=e}onEnterXR(){var e;const t=(e=this.needleMenu.shadowRoot)==null?void 0:e.querySelector(".options");t&&t.childNodes.forEach(r=>{this.createButtonFromHTMLNode(r)})}onExitXR(){var e;(e=this.menu)==null||e.removeFromParent()}createButtonFromHTMLNode(e){const t=this.getMenu(),r=this.htmlButtonsMap.get(e);if(r){r.add();return}if(e instanceof HTMLButtonElement){const s=this.createButton(t,e);this.htmlButtonsMap.set(e,s),s.add()}else e instanceof HTMLSlotElement&&e.assignedNodes().forEach(s=>{this.createButtonFromHTMLNode(s)})}updateMenu(){var e,t;const r=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(r);const s=this._context.mainCamera,o=this._context.xr,a=o?.rigScale||1;if(s){const l=s.worldPosition,c=s.worldForward.multiplyScalar(-1),h=c.y>.6,u=c.y>.4,p=r.visible?u:h,m=!r.visible&&p;r.visible=p||fp()&&ZB,c.multiplyScalar(3*a),l.add(c),m&&(r.position.copy(this._menuTarget.position),r.position.y+=1,this._menuTarget.position.copy(r.position),this.positionFilter.reset(r.position),r.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const f=this._menuTarget.position.distanceTo(l);(m||f>1.5*a)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(l),this._context.scene.add(this._menuTarget),Hv(this._menuTarget,this._context.mainCamera,!1,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,r.position,this._context.time.time);const g=5;(e=this.menu)==null||e.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*g),(t=this.menu)==null||t.scale.setScalar(a)}this.uiisDirty&&(this.uiisDirty=!1,Ni.update())}ensureRenderOnTop(e,t=0){e instanceof me&&(e.material.depthTest=!1,e.material.depthWrite=!1),e.renderOrder=1e3+t*2;for(const r of e.children)this.ensureRenderOnTop(r,t+1)}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new Ni.Block({boxSizing:"border-box",fontFamily:this.familyName,height:"auto",fontSize:.1,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:.55,borderRadius:.04,whiteSpace:"pre-wrap",flexDirection:"row",alignItems:"center",padding:new Ye(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const e=q.get("ObjectRaycaster");return e&&Zp(this.menu,new e),this.menu}handleNeedleWatermark(){var e;if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new Ni.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 t=new k8(this._context,()=>globalThis.open("https://needle.tools","_self"));Zp(this._poweredByNeedleElement,t);const r=new Ni.Text({textContent:"Powered by",width:"auto",height:"auto"}),s=new Ni.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new Ye(0,0,0,.02)});this._poweredByNeedleElement.add(r),this._poweredByNeedleElement.add(s),(e=this.menu)==null||e.add(this._poweredByNeedleElement),this.markDirty(),new Dl().load("./include/needle/poweredbyneedle.webp",o=>{var a;t.allowModifyUI=!1,r.removeFromParent(),s.removeFromParent();const l=o.image.width/o.image.height;(a=this._poweredByNeedleElement)==null||a.set({backgroundImage:o,backgroundOpacity:1,width:.1*l,height:.1}),this.markDirty()})}if(this.menu){const t=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&uu())t>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const r=this.menu.children.indexOf(this._poweredByNeedleElement);t!==r&&this.markDirty()}}}ensureFont(){let e=Ni.FontLibrary.getFontFamily(this.familyName);if(!e){e=Ni.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t?.addEventListener("ready",()=>{this.markDirty()})}}createButton(e,t){const r=new Ni.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}),s=new Ni.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});r.add(s),r["needle:use_eventsystem"]=!0;const o=new k8(this._context,()=>t.click());return Zp(r,o),new Ude(this,e,t,r,s)}}class Ude{constructor(e,t,r,s,o){d(this,"menu"),d(this,"root"),d(this,"htmlbutton"),d(this,"spatialContainer"),d(this,"spatialText"),d(this,"spatialIcon"),d(this,"_lastText",""),d(this,"_lastTexture"),this.menu=e,this.root=t,this.htmlbutton=r,this.spatialContainer=s,this.spatialText=o,new MutationObserver(a=>{for(const l of a)l.type==="attributes"?l.attributeName==="style"&&this.updateVisible():l.type==="childList"&&this.updateText()}).observe(r,{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 e=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",e!==this.spatialContainer.visible&&this.menu.markDirty()}updateText(){let e="",t="";this.htmlbutton.childNodes.forEach(r=>{r.nodeType===Node.TEXT_NODE?e+=r.textContent:r instanceof HTMLElement&&R8(r)&&r.textContent&&(t=r.textContent)}),this._lastText!==e&&(this._lastText=e,this.spatialText.name=e,this.spatialText.set({textContent:e}),this.menu.markDirty()),e.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),t&&this.createIcon(t)}async createIcon(e){var t;if(!this.spatialIcon){const s=await YB(e);if(s&&!this.spatialIcon){const o=new Ni.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:s,backgroundOpacity:1,margin:new Ye(0,.005,0,0)});this.spatialIcon=o,this.spatialContainer.add(o),this.menu.markDirty()}}if(e!=this._lastTexture){this._lastTexture=e;const s=await YB(e);s&&((t=this.spatialIcon)==null||t.set({backgroundImage:s}),this.menu.markDirty())}const r=this.spatialContainer.children.indexOf(this.spatialIcon);r>0&&(this.spatialContainer.children.splice(r,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class k8{constructor(e,t){d(this,"isComponent",!0),d(this,"enabled",!0),d(this,"gameObject"),d(this,"allowModifyUI",!0),d(this,"context"),d(this,"onclick"),this.context=e,this.onclick=t}get activeAndEnabled(){return!0}__internalAwake(){}__internalEnable(){}__internalDisable(){}__internalStart(){}onEnable(){}onDisable(){}get element(){return this.gameObject}onPointerEnter(){this.context.input.setCursorPointer(),this.allowModifyUI&&(this.element.set({backgroundOpacity:1}),Ni.update())}onPointerExit(){this.context.input.setCursorNormal(),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),Ni.update())}onPointerDown(e){e.use()}onPointerUp(e){e.use()}onPointerClick(e){e.use(),this.onclick()}}const zg="needle-menu",cA=te("debugmenu"),D8=te("debugnoncommercial");let Nde=class{constructor(n){d(this,"_context"),d(this,"_menu"),d(this,"_spatialMenu"),d(this,"onPostMessage",e=>{if(e.origin===globalThis.location.origin&&typeof e.data=="object"){const t=e.data,r=t.type;if(r==="needle:menu"){const s=t.button;if(s){if(!s.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!s.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const o=document.createElement("button");if(o.textContent=s.label,s.icon){const a=Ao(s.icon);o.prepend(a)}s.priority&&o.setAttribute("priority",s.priority.toString()),o.onclick=()=>{if(s.onclick){const a=s.onclick.startsWith("http")||s.onclick.startsWith("www."),l=s.target||"_blank";a?globalThis.open(s.onclick,l):console.error("NeedleMenu: onclick is not a valid link",s.onclick)}},this._menu.appendChild(o)}else cA&&console.error("NeedleMenu: unknown postMessage event",t)}else cA&&console.warn("NeedleMenu: unknown postMessage type",r,t)}}),d(this,"onStartXR",e=>{e.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),e.session.session.addEventListener("end",this.onExitXR))}),d(this,"onExitXR",()=>{this._menu.previousParent&&(this._menu.previousParent.appendChild(this._menu),delete this._menu.previousParent)}),d(this,"_muteButton"),d(this,"_fullscreenButton"),this._menu=qE.getOrCreate(n.domElement,n),this._context=n,this._spatialMenu=new Fde(n,this._menu),window.addEventListener("message",this.onPostMessage),X1(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}setPosition(n){this._menu.setPosition(n)}setVisible(n){this._menu.setVisible(n)}showNeedleLogo(n){var e;this._menu.showNeedleLogo(n),(e=this._spatialMenu)==null||e.showNeedleLogo(n)}showSpatialMenu(n){this._spatialMenu.setEnabled(n)}showQRCodeButton(n){if(n==="desktop-only"&&(n=!aa()),n){const e=yh.getOrCreate().createQRCode();return e.style.display="",this._menu.appendChild(e),e}else{const e=yh.getOrCreate().qrButton;return e&&(e.style.display="none"),e??null}}showAudioPlaybackOption(n){var e;if(!n){(e=this._muteButton)==null||e.remove();return}this._muteButton=yh.getOrCreate().createMuteButton(this._context),this._muteButton.setAttribute("priority","100"),this._menu.appendChild(this._muteButton)}showFullscreenOption(n){var e;if(!n){(e=this._fullscreenButton)==null||e.remove();return}this._fullscreenButton=yh.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&(this._fullscreenButton.setAttribute("priority","150"),this._menu.appendChild(this._fullscreenButton))}appendChild(n){return this._menu.appendChild(n)}};class qE extends HTMLElement{constructor(){var e,t,r,s;super(),d(this,"_domElement",null),d(this,"_context",null),d(this,"_sizeChangeInterval"),d(this,"_userRequestedLogoVisible"),d(this,"_userRequestedMenuVisible"),d(this,"root"),d(this,"wrapper"),d(this,"options"),d(this,"logoContainer"),d(this,"_isHandlingChange",!1),d(this,"_didSort",new Map),d(this,"_lastAvailableWidthChange",0),d(this,"_timeoutHandle",0),d(this,"handleSizeChange",(m,f)=>{if(!this._domElement)return;const g=this._domElement.clientWidth;if(g<500){this.root.classList.add("compact");return}const v=20*2,y=g-v;if(!f&&Math.abs(y-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=y,clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{const b=_();b<0?this.root.classList.add("compact"):b>0&&(this.root.classList.remove("compact"),_()<0&&this.root.classList.add("compact"))},5);const A=()=>this.options.clientWidth+this.logoContainer.clientWidth,_=()=>y-A()});const o=document.createElement("template");o.innerHTML=`<style>
5433
5433
 
5434
5434
  #root {
5435
5435
  position: absolute;
@@ -5643,20 +5643,20 @@ vec3 AgXToneMapping( vec3 color ) {
5643
5643
  </div>
5644
5644
  </div>
5645
5645
  </div>
5646
- `;const a=this.attachShadow({mode:"open"});PV(),yS(KB,{loadedCallback:()=>{this.handleSizeChange()}}),yS(KB,{element:a});const l=o.content.cloneNode(!0);a?.appendChild(l),this.root=a.querySelector("#root"),this.wrapper=(e=this.root)==null?void 0:e.querySelector(".wrapper"),this.options=(t=this.root)==null?void 0:t.querySelector(".options"),this.logoContainer=(r=this.root)==null?void 0:r.querySelector(".logo"),(s=this.root)==null||s.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const c=BV.create();c.style.minHeight="1rem",this.logoContainer.append(c),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")}),yne(m=>{m==!0&&eh()&&!DV&&(this.logoContainer.style.display=this._userRequestedLogoVisible?"":"none")});let h=this._context;setTimeout(()=>h=this._context);let u=0;const p=(m,f)=>{var g,v,y;cA&&console.log("Set menu visible",f),h!=null&&h.isInAR&&h.arOverlayElement?m!=h.arOverlayElement&&h.arOverlayElement.appendChild(this):this.parentNode!=((g=this._domElement)==null?void 0:g.shadowRoot)&&((y=(v=this._domElement)==null?void 0:v.shadowRoot)==null||y.appendChild(this)),this.style.display=f?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};new MutationObserver(m=>{var f;this.onChangeDetected(m);const g=this==null?void 0:this.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||g!=((f=this._domElement)==null?void 0:f.shadowRoot))&&!eh()){const v=u++;js()&&this._userRequestedMenuVisible===!1?(v===0&&p(g,this._userRequestedMenuVisible),v===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu \u2192 The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):v===0?p(g,!0):setTimeout(()=>p(g,!0),5)}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),cA&&this.___insertDebugOptions()}static create(){return document.createElement(zg,{is:zg})}static getOrCreate(e,t){let r=e.querySelector(zg);return!r&&e.shadowRoot&&(r=e.shadowRoot.querySelector(zg)),r||(r=qE.create(),e.shadowRoot?e.shadowRoot.appendChild(r):e.appendChild(r)),r._domElement=e,r._context=t,r}connectedCallback(){var e;window.addEventListener("resize",this.handleSizeChange),(e=this._domElement)==null||e.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!0),5e3)}disconnectedCallback(){var e;window.removeEventListener("resize",this.handleSizeChange),(e=this._domElement)==null||e.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval)}showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!eh()||DV)&&(console.warn("Needle Menu: You need a PRO license to hide the Needle Engine logo."),!js()))&&(this.logoContainer.style.display=e?"":"none")}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"}append(...e){for(const t of e)if(typeof t=="string"){const r=document.createTextNode(t);this.options.appendChild(r)}else this.options.appendChild(t)}appendChild(e){if(!(e instanceof Node)){const t=document.createElement("button");t.textContent=e.label,t.onclick=e.onClick,e=t}return this.options.appendChild(e)}prepend(...e){for(const t of e)if(typeof t=="string"){const r=document.createTextNode(t);this.options.prepend(r)}else this.options.prepend(t)}onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of e)t.target==this.options&&this.onOptionsChildrenChanged(t)}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.logoContainer.classList.toggle("any-options",this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type==="childList"){let t=!1;const r=Date.now();for(let s=0;s<e.addedNodes.length;s++){const o=e.addedNodes[s],a=this._didSort.get(o);typeof a=="number"&&r-a<100||(this._didSort.set(o,r),t=!0)}if(t){const s=Array.from(this.options.children);s.sort((o,a)=>{const l=parseInt(o.getAttribute("priority")||"0"),c=parseInt(a.getAttribute("priority")||"0");return l-c});for(const o of s)this.options.appendChild(o)}}}handleMenuVisible(){cA&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.logoContainer.classList.toggle("any-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 t=this.options.children[e];if(t.tagName==="SLOT"){const r=t.assignedNodes();for(const s of r)if(s instanceof HTMLElement&&s.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}___insertDebugOptions(){window.addEventListener("keydown",r=>{r.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const r=new Array(this.options.children.length);for(let s=0;s<this.options.children.length;s++)r[s]=this.options.children[s];for(const s of r)this.options.removeChild(s);setTimeout(()=>{for(const s of r)this.options.appendChild(s)},1e3)},this.appendChild(e);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}}customElements.get(zg)||customElements.define(zg,qE);const hr=te("debugcontext"),zde=te("stats"),jde=te("debugactive"),Gde=te("debugframerate"),Vde=te("debugcoroutine"),Qde={};class Hde{constructor(){d(this,"name"),d(this,"alias"),d(this,"hash"),d(this,"runInBackground"),d(this,"domElement"),d(this,"renderer"),d(this,"camera"),d(this,"scene")}}var Hi=(n=>(n[n.Start=-1]="Start",n[n.EarlyUpdate=0]="EarlyUpdate",n[n.Update=1]="Update",n[n.LateUpdate=2]="LateUpdate",n[n.OnBeforeRender=3]="OnBeforeRender",n[n.OnAfterRender=4]="OnAfterRender",n[n.PrePhysicsStep=9]="PrePhysicsStep",n[n.PostPhysicsStep=10]="PostPhysicsStep",n[n.Undefined=-1]="Undefined",n))(Hi||{});function bS(n,e){if(!n)return;if(!n.isComponent){(st()||hr)&&console.error(`Registered script is not a Needle Engine component.
5646
+ `;const a=this.attachShadow({mode:"open"});P8(),yS(KB,{loadedCallback:()=>{this.handleSizeChange()}}),yS(KB,{element:a});const l=o.content.cloneNode(!0);a?.appendChild(l),this.root=a.querySelector("#root"),this.wrapper=(e=this.root)==null?void 0:e.querySelector(".wrapper"),this.options=(t=this.root)==null?void 0:t.querySelector(".options"),this.logoContainer=(r=this.root)==null?void 0:r.querySelector(".logo"),(s=this.root)==null||s.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const c=B8.create();c.style.minHeight="1rem",this.logoContainer.append(c),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")}),yne(m=>{m==!0&&eh()&&!D8&&(this.logoContainer.style.display=this._userRequestedLogoVisible?"":"none")});let h=this._context;setTimeout(()=>h=this._context);let u=0;const p=(m,f)=>{var g,v,y;cA&&console.log("Set menu visible",f),h!=null&&h.isInAR&&h.arOverlayElement?m!=h.arOverlayElement&&h.arOverlayElement.appendChild(this):this.parentNode!=((g=this._domElement)==null?void 0:g.shadowRoot)&&((y=(v=this._domElement)==null?void 0:v.shadowRoot)==null||y.appendChild(this)),this.style.display=f?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};new MutationObserver(m=>{var f;this.onChangeDetected(m);const g=this==null?void 0:this.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||g!=((f=this._domElement)==null?void 0:f.shadowRoot))&&!eh()){const v=u++;js()&&this._userRequestedMenuVisible===!1?(v===0&&p(g,this._userRequestedMenuVisible),v===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu \u2192 The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):v===0?p(g,!0):setTimeout(()=>p(g,!0),5)}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),cA&&this.___insertDebugOptions()}static create(){return document.createElement(zg,{is:zg})}static getOrCreate(e,t){let r=e.querySelector(zg);return!r&&e.shadowRoot&&(r=e.shadowRoot.querySelector(zg)),r||(r=qE.create(),e.shadowRoot?e.shadowRoot.appendChild(r):e.appendChild(r)),r._domElement=e,r._context=t,r}connectedCallback(){var e;window.addEventListener("resize",this.handleSizeChange),(e=this._domElement)==null||e.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!0),5e3)}disconnectedCallback(){var e;window.removeEventListener("resize",this.handleSizeChange),(e=this._domElement)==null||e.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval)}showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!eh()||D8)&&(console.warn("Needle Menu: You need a PRO license to hide the Needle Engine logo."),!js()))&&(this.logoContainer.style.display=e?"":"none")}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"}append(...e){for(const t of e)if(typeof t=="string"){const r=document.createTextNode(t);this.options.appendChild(r)}else this.options.appendChild(t)}appendChild(e){if(!(e instanceof Node)){const t=document.createElement("button");t.textContent=e.label,t.onclick=e.onClick,e=t}return this.options.appendChild(e)}prepend(...e){for(const t of e)if(typeof t=="string"){const r=document.createTextNode(t);this.options.prepend(r)}else this.options.prepend(t)}onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of e)t.target==this.options&&this.onOptionsChildrenChanged(t)}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.logoContainer.classList.toggle("any-options",this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type==="childList"){let t=!1;const r=Date.now();for(let s=0;s<e.addedNodes.length;s++){const o=e.addedNodes[s],a=this._didSort.get(o);typeof a=="number"&&r-a<100||(this._didSort.set(o,r),t=!0)}if(t){const s=Array.from(this.options.children);s.sort((o,a)=>{const l=parseInt(o.getAttribute("priority")||"0"),c=parseInt(a.getAttribute("priority")||"0");return l-c});for(const o of s)this.options.appendChild(o)}}}handleMenuVisible(){cA&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.logoContainer.classList.toggle("any-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 t=this.options.children[e];if(t.tagName==="SLOT"){const r=t.assignedNodes();for(const s of r)if(s instanceof HTMLElement&&s.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}___insertDebugOptions(){window.addEventListener("keydown",r=>{r.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const r=new Array(this.options.children.length);for(let s=0;s<this.options.children.length;s++)r[s]=this.options.children[s];for(const s of r)this.options.removeChild(s);setTimeout(()=>{for(const s of r)this.options.appendChild(s)},1e3)},this.appendChild(e);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}}customElements.get(zg)||customElements.define(zg,qE);const hr=te("debugcontext"),zde=te("stats"),jde=te("debugactive"),Gde=te("debugframerate"),Vde=te("debugcoroutine"),Qde={};class Hde{constructor(){d(this,"name"),d(this,"alias"),d(this,"hash"),d(this,"runInBackground"),d(this,"domElement"),d(this,"renderer"),d(this,"camera"),d(this,"scene")}}var Hi=(n=>(n[n.Start=-1]="Start",n[n.EarlyUpdate=0]="EarlyUpdate",n[n.Update=1]="Update",n[n.LateUpdate=2]="LateUpdate",n[n.OnBeforeRender=3]="OnBeforeRender",n[n.OnAfterRender=4]="OnAfterRender",n[n.PrePhysicsStep=9]="PrePhysicsStep",n[n.PostPhysicsStep=10]="PostPhysicsStep",n[n.Undefined=-1]="Undefined",n))(Hi||{});function bS(n,e){if(!n)return;if(!n.isComponent){(st()||hr)&&console.error(`Registered script is not a Needle Engine component.
5647
5647
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
5648
- `,n);return}e||(e=kt.Current,hr&&console.warn("> Registering component without context"));const t=e?.new_scripts;t.includes(n)||t.push(n)}const Zi=class{constructor(n){d(this,"name"),d(this,"alias"),d(this,"isManagedExternally",!1),d(this,"isPaused",!1),d(this,"runInBackground",!1),d(this,"targetFrameRate"),d(this,"physicsSteps",1),d(this,"hash"),d(this,"domElement"),d(this,"_resolutionScaleFactor",1),d(this,"_boundingClientRectFrame",-1),d(this,"_boundingClientRect",null),d(this,"_domX"),d(this,"_domY"),d(this,"xr",null),d(this,"_xrFrame",null),d(this,"_currentFrameEvent",-1),d(this,"scene"),d(this,"renderer"),d(this,"composer",null),d(this,"scripts",[]),d(this,"scripts_pausedChanged",[]),d(this,"scripts_earlyUpdate",[]),d(this,"scripts_update",[]),d(this,"scripts_lateUpdate",[]),d(this,"scripts_onBeforeRender",[]),d(this,"scripts_onAfterRender",[]),d(this,"scripts_WithCorroutines",[]),d(this,"scripts_immersive_vr",[]),d(this,"scripts_immersive_ar",[]),d(this,"coroutines",{}),d(this,"post_setup_callbacks",[]),d(this,"pre_update_callbacks",[]),d(this,"pre_render_callbacks",[]),d(this,"post_render_callbacks",[]),d(this,"pre_update_oneshot_callbacks",[]),d(this,"new_scripts",[]),d(this,"new_script_start",[]),d(this,"new_scripts_pre_setup_callbacks",[]),d(this,"new_scripts_post_setup_callbacks",[]),d(this,"new_scripts_xr",[]),d(this,"mainCameraComponent"),d(this,"_camera",null),d(this,"application"),d(this,"animations"),d(this,"time"),d(this,"input"),d(this,"physics"),d(this,"connection"),d(this,"assets"),d(this,"mainLight",null),d(this,"sceneLighting"),d(this,"addressables"),d(this,"lightmaps"),d(this,"players"),d(this,"lodsManager"),d(this,"menu"),d(this,"_sizeChanged",!1),d(this,"_isCreated",!1),d(this,"_isCreating",!1),d(this,"_isVisible",!1),d(this,"_stats",zde?new Vhe:null),d(this,"_intersectionObserver",null),d(this,"_disposeCallbacks",[]),d(this,"maxRenderResolution"),d(this,"_originalCreationArgs"),d(this,"onUnhandledRejection",r=>{this.domElement.dispatchEvent(new CustomEvent("error",{detail:r.reason}))}),d(this,"_cameraStack",[]),d(this,"_onBeforeRenderListeners",new Map),d(this,"_onAfterRenderListeners",new Map),d(this,"_requireDepthTexture",!1),d(this,"_requireColorTexture",!1),d(this,"_renderTarget"),d(this,"_isRendering",!1),d(this,"_createId",0),d(this,"_renderlooperrors",0),d(this,"_lastTimestamp",0),d(this,"_accumulatedTime",0),d(this,"_dispatchReadyAfterFrame",!1),d(this,"_wasPaused",!1),this.name=n?.name||"",this.alias=n?.alias,this.domElement=n?.domElement||document.body,this.hash=n?.hash,n!=null&&n.renderer&&(this.renderer=n.renderer,this.isManagedExternally=!0),n?.runInBackground!==void 0&&(this.runInBackground=n.runInBackground),n!=null&&n.scene?this.scene=n.scene:this.scene=new Ur,n!=null&&n.camera&&(this._camera=n.camera),this.application=new Qu(this),this.time=new MV,this.input=new D6(this),this.physics=new AV(this),this.connection=new oV(this),this.assets=new R5,this.sceneLighting=new SV(this),this.addressables=new E6(this),this.lightmaps=new Ede(this),this.players=new _V(this),this.menu=new Nde(this),this.lodsManager=new Mde(this),this.animations=new hue(this);const e=()=>this._sizeChanged=!0;window.addEventListener("resize",e),this._disposeCallbacks.push(()=>window.removeEventListener("resize",e));const t=new ResizeObserver(r=>this._sizeChanged=!0);t.observe(this.domElement),this._disposeCallbacks.push(()=>t.disconnect()),this._intersectionObserver=new IntersectionObserver(r=>{this._isVisible=r[0].isIntersecting}),this._disposeCallbacks.push(()=>{var r;return(r=this._intersectionObserver)==null?void 0:r.disconnect()}),di.register(this)}static get DefaultTargetFrameRate(){return Zi._defaultTargetFramerate.value}static set DefaultTargetFrameRate(n){Zi._defaultTargetFramerate.value=n}static get DefaultWebGLRendererParameters(){return Zi._defaultWebglRendererParameters}get version(){return el}static get Current(){return di.Current}static set Current(n){di.Current=n}appendHTMLElement(n){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(n):this.domElement.appendChild(n)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(n){if(n!==this._resolutionScaleFactor&&typeof n=="number"){if(n<=0){console.error("Invalid resolution scale factor",n);return}this._resolutionScaleFactor=n,this.updateSize()}}calculateBoundingClientRect(){if(this.isInAR){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 n,e;return((e=(n=this.renderer)==null?void 0:n.xr)==null?void 0:e.isPresenting)||!1}get xrSessionMode(){var n;return(n=this.xr)==null?void 0:n.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 n,e;return(e=(n=this.renderer)==null?void 0:n.xr)==null?void 0:e.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var n,e;return this.renderer.xr.isPresenting?(e=(n=this.renderer)==null?void 0:n.xr)==null?void 0:e.getCamera():void 0}get arOverlayElement(){const n=this.domElement;return typeof n.getAROverlayContainer=="function"?n.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._camera)return this._camera;if(this.mainCameraComponent){const n=this.mainCameraComponent;return n.cam||n.buildCamera(),n.cam}return null}set mainCamera(n){this._camera=n}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(n){var e,t,r;if((e=this.renderer)==null||e.dispose(),n={...Zi.DefaultWebGLRendererParameters,...n},!n.canvas){const s=(r=(t=this.domElement)==null?void 0:t.shadowRoot)==null?void 0:r.querySelector("canvas");s&&(n.canvas=s,hr&&console.log("Using canvas from shadow root",s))}hr&&console.log("Using Renderer Parameters:",n,this.domElement),this.renderer=new Wc(n),this.renderer.debug.checkShaderErrors=st()||te("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Ls,this.renderer.setClearColor(new xe("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=sM,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=ft,this.lodsManager.setRenderer(this.renderer),this.input.bindEvents()}internalOnUpdateVisible(){var n,e;(n=this._intersectionObserver)==null||n.disconnect(),(e=this._intersectionObserver)==null||e.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(n=!1){var e,t,r;if(n||!this.isManagedExternally&&((e=this.renderer.xr)==null?void 0:e.isPresenting)===!1){this._sizeChanged=!1;const s=this.resolutionScaleFactor;let o=this.domWidth*s,a=this.domHeight*s;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),o=Math.min(this.maxRenderResolution.x,o),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),a=Math.min(this.maxRenderResolution.y,a));const l=this.mainCamera;this.updateAspect(l),this.renderer.setSize(o,a,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((t=this.composer.setSize)==null||t.call(this.composer,o,a),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((r=this.composer.setPixelRatio)==null||r.call(this.composer,window.devicePixelRatio)))}}updateAspect(n,e,t){if(!n)return;e===void 0&&(e=this.domWidth),t===void 0&&(t=this.domHeight);const r=n.aspect;n.aspect=e/t,r!==n.aspect&&n.updateProjectionMatrix()}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(n){return this.create(n)}async create(n){try{this._isCreating=!0,n!==this._originalCreationArgs&&(this._originalCreationArgs=Nv(n)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const e=await this.internalOnCreate(n);return this._isCreated=!0,e}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}clear(){var n,e,t,r;di.dispatchCallback(Ci.ContextClearing,this),Yl(this,Ci.ContextClearing),Ca(this.scene,!0,!0),this.scene=new Ur,(n=this.addressables)==null||n.dispose(),(e=this.lightmaps)==null||e.clear(),(r=(t=this.physics)==null?void 0:t.engine)==null||r.clearCaches(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),di.dispatchCallback(Ci.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var n,e;Zi.Current=this,di.dispatchCallback(Ci.ContextDestroying,this),Yl(this,Ci.ContextDestroying),this.clear(),(n=this.renderer)==null||n.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(hr&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const t of this._disposeCallbacks)try{t()}catch(r){console.error("Error in on dispose callback:",r,t)}(e=this.domElement)!=null&&e.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,di.dispatchCallback(Ci.ContextDestroyed,this),Yl(this,Ci.ContextDestroyed),di.unregister(this),Zi.Current===this&&(Zi.Current=null)}registerCoroutineUpdate(n,e,t){return typeof e?.next!="function"?(console.error("Registered invalid coroutine function from "+n.name+`
5648
+ `,n);return}e||(e=kt.Current,hr&&console.warn("> Registering component without context"));const t=e?.new_scripts;t.includes(n)||t.push(n)}const Zi=class{constructor(n){d(this,"name"),d(this,"alias"),d(this,"isManagedExternally",!1),d(this,"isPaused",!1),d(this,"runInBackground",!1),d(this,"targetFrameRate"),d(this,"physicsSteps",1),d(this,"hash"),d(this,"domElement"),d(this,"_resolutionScaleFactor",1),d(this,"_boundingClientRectFrame",-1),d(this,"_boundingClientRect",null),d(this,"_domX"),d(this,"_domY"),d(this,"xr",null),d(this,"_xrFrame",null),d(this,"_currentFrameEvent",-1),d(this,"scene"),d(this,"renderer"),d(this,"composer",null),d(this,"scripts",[]),d(this,"scripts_pausedChanged",[]),d(this,"scripts_earlyUpdate",[]),d(this,"scripts_update",[]),d(this,"scripts_lateUpdate",[]),d(this,"scripts_onBeforeRender",[]),d(this,"scripts_onAfterRender",[]),d(this,"scripts_WithCorroutines",[]),d(this,"scripts_immersive_vr",[]),d(this,"scripts_immersive_ar",[]),d(this,"coroutines",{}),d(this,"post_setup_callbacks",[]),d(this,"pre_update_callbacks",[]),d(this,"pre_render_callbacks",[]),d(this,"post_render_callbacks",[]),d(this,"pre_update_oneshot_callbacks",[]),d(this,"new_scripts",[]),d(this,"new_script_start",[]),d(this,"new_scripts_pre_setup_callbacks",[]),d(this,"new_scripts_post_setup_callbacks",[]),d(this,"new_scripts_xr",[]),d(this,"mainCameraComponent"),d(this,"_camera",null),d(this,"application"),d(this,"animations"),d(this,"time"),d(this,"input"),d(this,"physics"),d(this,"connection"),d(this,"assets"),d(this,"mainLight",null),d(this,"sceneLighting"),d(this,"addressables"),d(this,"lightmaps"),d(this,"players"),d(this,"lodsManager"),d(this,"menu"),d(this,"_sizeChanged",!1),d(this,"_isCreated",!1),d(this,"_isCreating",!1),d(this,"_isVisible",!1),d(this,"_stats",zde?new Vhe:null),d(this,"_intersectionObserver",null),d(this,"_disposeCallbacks",[]),d(this,"maxRenderResolution"),d(this,"_originalCreationArgs"),d(this,"onUnhandledRejection",r=>{this.domElement.dispatchEvent(new CustomEvent("error",{detail:r.reason}))}),d(this,"_cameraStack",[]),d(this,"_onBeforeRenderListeners",new Map),d(this,"_onAfterRenderListeners",new Map),d(this,"_requireDepthTexture",!1),d(this,"_requireColorTexture",!1),d(this,"_renderTarget"),d(this,"_isRendering",!1),d(this,"_createId",0),d(this,"_renderlooperrors",0),d(this,"_lastTimestamp",0),d(this,"_accumulatedTime",0),d(this,"_dispatchReadyAfterFrame",!1),d(this,"_wasPaused",!1),this.name=n?.name||"",this.alias=n?.alias,this.domElement=n?.domElement||document.body,this.hash=n?.hash,n!=null&&n.renderer&&(this.renderer=n.renderer,this.isManagedExternally=!0),n?.runInBackground!==void 0&&(this.runInBackground=n.runInBackground),n!=null&&n.scene?this.scene=n.scene:this.scene=new Ur,n!=null&&n.camera&&(this._camera=n.camera),this.application=new Qu(this),this.time=new M8,this.input=new D6(this),this.physics=new A8(this),this.connection=new o8(this),this.assets=new R5,this.sceneLighting=new S8(this),this.addressables=new E6(this),this.lightmaps=new Ede(this),this.players=new _8(this),this.menu=new Nde(this),this.lodsManager=new Mde(this),this.animations=new hue(this);const e=()=>this._sizeChanged=!0;window.addEventListener("resize",e),this._disposeCallbacks.push(()=>window.removeEventListener("resize",e));const t=new ResizeObserver(r=>this._sizeChanged=!0);t.observe(this.domElement),this._disposeCallbacks.push(()=>t.disconnect()),this._intersectionObserver=new IntersectionObserver(r=>{this._isVisible=r[0].isIntersecting}),this._disposeCallbacks.push(()=>{var r;return(r=this._intersectionObserver)==null?void 0:r.disconnect()}),di.register(this)}static get DefaultTargetFrameRate(){return Zi._defaultTargetFramerate.value}static set DefaultTargetFrameRate(n){Zi._defaultTargetFramerate.value=n}static get DefaultWebGLRendererParameters(){return Zi._defaultWebglRendererParameters}get version(){return el}static get Current(){return di.Current}static set Current(n){di.Current=n}appendHTMLElement(n){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(n):this.domElement.appendChild(n)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(n){if(n!==this._resolutionScaleFactor&&typeof n=="number"){if(n<=0){console.error("Invalid resolution scale factor",n);return}this._resolutionScaleFactor=n,this.updateSize()}}calculateBoundingClientRect(){if(this.isInAR){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 n,e;return((e=(n=this.renderer)==null?void 0:n.xr)==null?void 0:e.isPresenting)||!1}get xrSessionMode(){var n;return(n=this.xr)==null?void 0:n.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 n,e;return(e=(n=this.renderer)==null?void 0:n.xr)==null?void 0:e.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var n,e;return this.renderer.xr.isPresenting?(e=(n=this.renderer)==null?void 0:n.xr)==null?void 0:e.getCamera():void 0}get arOverlayElement(){const n=this.domElement;return typeof n.getAROverlayContainer=="function"?n.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._camera)return this._camera;if(this.mainCameraComponent){const n=this.mainCameraComponent;return n.cam||n.buildCamera(),n.cam}return null}set mainCamera(n){this._camera=n}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(n){var e,t,r;if((e=this.renderer)==null||e.dispose(),n={...Zi.DefaultWebGLRendererParameters,...n},!n.canvas){const s=(r=(t=this.domElement)==null?void 0:t.shadowRoot)==null?void 0:r.querySelector("canvas");s&&(n.canvas=s,hr&&console.log("Using canvas from shadow root",s))}hr&&console.log("Using Renderer Parameters:",n,this.domElement),this.renderer=new Wc(n),this.renderer.debug.checkShaderErrors=st()||te("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Ls,this.renderer.setClearColor(new xe("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=sM,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=ft,this.lodsManager.setRenderer(this.renderer),this.input.bindEvents()}internalOnUpdateVisible(){var n,e;(n=this._intersectionObserver)==null||n.disconnect(),(e=this._intersectionObserver)==null||e.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(n=!1){var e,t,r;if(n||!this.isManagedExternally&&((e=this.renderer.xr)==null?void 0:e.isPresenting)===!1){this._sizeChanged=!1;const s=this.resolutionScaleFactor;let o=this.domWidth*s,a=this.domHeight*s;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),o=Math.min(this.maxRenderResolution.x,o),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),a=Math.min(this.maxRenderResolution.y,a));const l=this.mainCamera;this.updateAspect(l),this.renderer.setSize(o,a,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((t=this.composer.setSize)==null||t.call(this.composer,o,a),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((r=this.composer.setPixelRatio)==null||r.call(this.composer,window.devicePixelRatio)))}}updateAspect(n,e,t){if(!n)return;e===void 0&&(e=this.domWidth),t===void 0&&(t=this.domHeight);const r=n.aspect;n.aspect=e/t,r!==n.aspect&&n.updateProjectionMatrix()}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(n){return this.create(n)}async create(n){try{this._isCreating=!0,n!==this._originalCreationArgs&&(this._originalCreationArgs=Nv(n)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const e=await this.internalOnCreate(n);return this._isCreated=!0,e}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}clear(){var n,e,t,r;di.dispatchCallback(Ci.ContextClearing,this),Yl(this,Ci.ContextClearing),Ca(this.scene,!0,!0),this.scene=new Ur,(n=this.addressables)==null||n.dispose(),(e=this.lightmaps)==null||e.clear(),(r=(t=this.physics)==null?void 0:t.engine)==null||r.clearCaches(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),di.dispatchCallback(Ci.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var n,e;Zi.Current=this,di.dispatchCallback(Ci.ContextDestroying,this),Yl(this,Ci.ContextDestroying),this.clear(),(n=this.renderer)==null||n.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(hr&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const t of this._disposeCallbacks)try{t()}catch(r){console.error("Error in on dispose callback:",r,t)}(e=this.domElement)!=null&&e.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,di.dispatchCallback(Ci.ContextDestroyed,this),Yl(this,Ci.ContextDestroyed),di.unregister(this),Zi.Current===this&&(Zi.Current=null)}registerCoroutineUpdate(n,e,t){return typeof e?.next!="function"?(console.error("Registered invalid coroutine function from "+n.name+`
5649
5649
  Coroutine functions must be generators: "*myCoroutine() {...}"
5650
5650
  Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),e):(this.coroutines[t]||(this.coroutines[t]=[]),this.coroutines[t].push({comp:n,main:e}),e)}unregisterCoroutineUpdate(n,e){if(!this.coroutines[e])return;const t=this.coroutines[e].findIndex(r=>r.main===n);t>=0&&this.coroutines[e].splice(t,1)}stopAllCoroutinesFrom(n){for(const e in this.coroutines){const t=this.coroutines[e];for(let r=t.length-1;r>=0;r--)t[r].comp===n&&t.splice(r,1)}}setCurrentCamera(n){var e;if(!n)return;if(n.cam||n.buildCamera(),!n.cam){console.warn("Camera component is missing camera",n);return}const t=this._cameraStack.indexOf(n);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(n),this.mainCameraComponent=n;const r=n.cam;r.isPerspectiveCamera&&this.updateAspect(r),(e=this.mainCameraComponent)==null||e.applyClearFlagsIfIsActiveCamera()}removeCamera(n){if(!n)return;const e=this._cameraStack.indexOf(n);if(e>=0&&this._cameraStack.splice(e,1),this.mainCameraComponent===n&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const t=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(t)}}addBeforeRenderListener(n,e){this._onBeforeRenderListeners.has(n.uuid)||(this._onBeforeRenderListeners.set(n.uuid,[]),n.onBeforeRender=this._createRenderCallbackWrapper(n,this._onBeforeRenderListeners)),this._onBeforeRenderListeners.get(n.uuid).push(e)}removeBeforeRenderListener(n,e){if(this._onBeforeRenderListeners.has(n.uuid)){const t=this._onBeforeRenderListeners.get(n.uuid),r=t.indexOf(e);r>=0&&t.splice(r,1)}}addAfterRenderListener(n,e){var t;this._onAfterRenderListeners.has(n.uuid)||(this._onAfterRenderListeners.set(n.uuid,[]),n.onAfterRender=this._createRenderCallbackWrapper(n,this._onAfterRenderListeners)),(t=this._onAfterRenderListeners.get(n.uuid))==null||t.push(e)}removeAfterRenderListener(n,e){if(this._onAfterRenderListeners.has(n.uuid)){const t=this._onAfterRenderListeners.get(n.uuid),r=t.indexOf(e);r>=0&&t.splice(r,1)}}_createRenderCallbackWrapper(n,e){return(t,r,s,o,a,l)=>{const c=e.get(n.uuid);if(c)for(let h=0;h<c.length;h++){const u=c[h];u(t,r,s,o,a,l)}}}get isRendering(){return this._isRendering}setRequireDepth(n){this._requireDepthTexture=n}setRequireColor(n){this._requireColorTexture=n}get depthTexture(){var n;return((n=this._renderTarget)==null?void 0:n.depthTexture)||null}get opaqueColorTexture(){var n;return((n=this._renderTarget)==null?void 0:n.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const n=getComputedStyle(this.domElement);return n.visibility!=="hidden"&&n.display!=="none"&&n.opacity!=="0"}async internalOnCreate(n){var e,t,r,s,o,a,l,c;const h=++this._createId;hr&&console.log("Creating context",this.name,n);const u=globalThis["needle:dependencies:ready"];u instanceof Promise&&(hr&&console.log("Waiting for dependencies to be ready"),await u.catch(g=>{(hr||st())&&console.error("Needle Engine dependencies failed to load",g)}).then(()=>{hr&&console.log("Needle Engine dependencies are ready")})),this.clear(),this.isManagedExternally===!1&&(this.createNewRenderer(),(e=this.renderer)==null||e.setAnimationLoop(null)),await Ll(1),Zi.Current=this,await di.dispatchCallback(Ci.ContextCreationStart,this);let p=!0,m;try{Zi.Current=this,n?m=await this.internalLoadInitialContent(h,n):m=[]}catch(g){console.error(g),p=!1}if(!p||h!==this._createId||(t=n?.abortSignal)!=null&&t.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return hr&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),Zi.Current=this,Zi.Current=this;for(let g=0;g<this.new_scripts.length;g++){const v=this.new_scripts[g];if(v.gameObject!==void 0&&v.gameObject!==null){v.gameObject.userData===void 0&&(v.gameObject.userData={}),v.gameObject.userData.components===void 0&&(v.gameObject.userData.components=[]);const y=v.gameObject.userData.components;y.includes(v)||y.push(v)}}if(this.post_setup_callbacks)for(let g=0;g<this.post_setup_callbacks.length;g++)Zi.Current=this,await this.post_setup_callbacks[g](this);if(!this.mainCamera){Zi.Current=this;let g=null;Kp(this.scene,v=>{const y=v;if(y!=null&&y.isCamera){if(Gy(y.gameObject),!y.activeAndEnabled)return;if(y.tag==="MainCamera")return g=y,!0;g=y}}),g?this.setCurrentCamera(g):!di.dispatchCallback(Ci.MissingCamera,this,{files:m})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}if(this.input.bindEvents(),Zi.Current=this,B1(this),this.physics.engine&&((r=this.physics.engine)==null||r.step(0),(s=this.physics.engine)==null||s.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera){const g=new F1(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(g),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",(o=this.domElement.shadowRoot)==null||o.appendChild(this._stats.dom)),hr&&yw(this.scene,!0),this.targetFrameRate===void 0?(hr&&console.warn("No target framerate set, using default",Zi.DefaultTargetFrameRate),this.targetFrameRate=Zi._defaultTargetFramerate):hr&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const f=di.dispatchCallback(Ci.ContextCreated,this,{files:m});return f&&("internalSetLoadingMessage"in this.domElement&&typeof this.domElement.internalSetLoadingMessage=="function"&&((a=this.domElement)==null||a.internalSetLoadingMessage("finish loading")),await f),(l=n?.abortSignal)!=null&&l.aborted?!1:(Yl(this,Ci.ContextCreated),hr&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!((c=n?.abortSignal)!=null&&c.aborted)&&this.restartRenderLoop(),f)}async internalLoadInitialContent(n,e){var t,r,s,o;const a=new Array;if(e.files.length===0)return a;const l=[...e.files],c={name:"",progress:null,index:0,count:l.length},h=Ka(),u=0;for(let p=0;p<l.length;p++){if((t=e.abortSignal)!=null&&t.aborted){hr&&console.log("Aborting loading because of abort signal");break}if(n!==this._createId){hr&&console.log("Aborting loading because create id changed",n,this._createId);break}const m=l[p];(r=e?.onLoadingStart)==null||r.call(this,p,m),hr&&console.log("Context Load "+m);const f=await h.loadSync(this,m,m,u,g=>{var v,y;(v=e.abortSignal)!=null&&v.aborted||(c.name=m,c.progress=g,c.index=p,c.count=l.length,(y=e.onLoadingProgress)==null||y.call(this,c))});(s=e?.onLoadingFinished)==null||s.call(this,p,m,f??null),f?a.push({src:m,file:f}):console.warn("Could not load file: "+m)}if(n!==this._createId||(o=e.abortSignal)!=null&&o.aborted){for(const p of a)if(p&&p.file)for(const m of p.file.scenes)Ca(m,!0,!0)}else for(const p of a)p&&p.file&&this.scene.add(p.file.scene);return a}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((n,e)=>{this.isManagedExternally||this.update(n,e)}),!0):(console.error("Can not start render loop without renderer"),!1)}update(n,e){if(e===void 0&&(e=null),st()||hr||Ple())try{this.internalStep(n,e),this._renderlooperrors=0}catch(t){this._renderlooperrors+=1,(st()||hr)&&(t instanceof Error||t instanceof TypeError)&&rn("Caught unhandled exception during render-loop - see console for details.",Bo.Error),console.error("Frame #"+this.time.frame+`
5651
5651
  `,t),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:t}))}else this.internalStep(n,e)}updatePhysics(n){this.internalUpdatePhysics(n)}internalStep(n,e){this.internalOnBeforeRender(n,e)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(n,e){var t;this.renderer.info.autoReset=!1;const r=e!==null&&this._xrFrame===null;if(this._xrFrame=e,r&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:e}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=n),this._accumulatedTime+=(n-this._lastTimestamp)/1e3,this._lastTimestamp=n;let s=this.targetFrameRate;if(typeof s=="object"&&(s=s.value),this._accumulatedTime<1/(s+1))return!1;this._accumulatedTime=0}if((t=this._stats)==null||t.begin(),Zi.Current=this,this.onHandlePaused())return!1;for(Zi.Current=this,this.time.update(),Gde&&console.log("FPS",this.time.smoothedFps.toFixed(0)),B1(this),k1(this.scene),N5(this),Yl(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const s=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(s)}if(this.pre_update_oneshot_callbacks){for(const s in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[s]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const s in this.pre_update_callbacks)this.pre_update_callbacks[s]();this._currentFrameEvent=0;for(let s=0;s<this.scripts_earlyUpdate.length;s++){const o=this.scripts_earlyUpdate[s];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(Zi.Current=this,o.earlyUpdate())}if(this.executeCoroutines(0),Yl(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let s=0;s<this.scripts_update.length;s++){const o=this.scripts_update[s];o.activeAndEnabled&&o.update!==void 0&&(Zi.Current=this,o.update())}if(this.executeCoroutines(1),Yl(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let s=0;s<this.scripts_lateUpdate.length;s++){const o=this.scripts_lateUpdate[s];o.activeAndEnabled&&o.lateUpdate!==void 0&&(Zi.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),Yl(this,2),this.onHandlePaused()||(this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.onHandlePaused()))return!1;if(this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let s=0;s<this.scripts_onBeforeRender.length;s++){const o=this.scripts_onBeforeRender[s];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(Zi.Current=this,o.onBeforeRender(e))}if(this.executeCoroutines(3),Yl(this,3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const s in this.pre_render_callbacks)this.pre_render_callbacks[s](e)}return!0}internalUpdatePhysics(n){if(!this.physics.engine)return!1;const e=n,t=this.time.deltaTime/e;for(let r=0;r<e;r++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(t),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(Ole(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let n=0;n<this.scripts_onAfterRender.length;n++){const e=this.scripts_onAfterRender[n];e.activeAndEnabled&&e.onAfterRender!==void 0&&(Zi.Current=this,e.onAfterRender())}if(this.executeCoroutines(4),Yl(this,4),this.post_render_callbacks)for(const n in this.post_render_callbacks)this.post_render_callbacks[n]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
5652
5652
  Render:`,{...this.renderer.info.render},`
5653
5653
  Memory:`,{...this.renderer.info.memory},`
5654
- Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),di.dispatchCallback(Ci.ContextFirstFrameRendered,this)),this.renderer.info.reset()}renderNow(n){return!n&&(n=this.mainCamera,!n)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==Ls&&IV(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):n&&this.renderer.render(this.scene,n),this._isRendering=!1,!0)}onHandlePaused(){const n=this.evaluatePaused();if(this._wasPaused!==n){jde&&console.log("Paused?",n,"context:"+this.alias);for(let e=0;e<this.scripts_pausedChanged.length;e++){const t=this.scripts_pausedChanged[e];t.activeAndEnabled&&t.onPausedChanged!==void 0&&(Zi.Current=this,t.onPausedChanged(n,this._wasPaused))}}return this._wasPaused=n,n}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Wt(this.domWidth,this.domHeight),this._requireDepthTexture){const t=new _f(this.domWidth,this.domHeight);this._renderTarget.depthTexture=t}this._requireColorTexture&&(this._renderTarget.texture=new zt,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Nt,this._renderTarget.texture.magFilter=Nt,this._renderTarget.texture.format=Yi)}const n=this._renderTarget;n.texture&&(n.texture.colorSpace=this.renderer.outputColorSpace);const e=this.renderer.getRenderTarget();this.renderer.setRenderTarget(n),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(e)}executeCoroutines(n){var e;if(this.coroutines[n]){const r=this.coroutines[n];for(let s=0;s<r.length;s++)try{const o=r[s];if(!o.comp||o.comp.destroyed||!o.main||o.comp.enabled===!1){Vde&&console.log("Removing coroutine",o.comp,o.comp.enabled),r.splice(s,1),--s;continue}const a=o.chained;if(a&&a.length>0){const h=a[a.length-1].next();if(h.done&&a.pop(),t(h)&&(o.chained||(o.chained=[]),o.chained.push(h.value)),!h.done)continue}const l=o.main.next();if(l.done===!0){r.splice(s,1),--s;continue}const c=l.value;if(t(c)){if(c.next().done)continue;o.chained||(o.chained=[]),o.chained.push(c)}else if(c instanceof Promise){const h=c;o.chained||(o.chained=[]);const u=mV(h);(e=o.chained)==null||e.push(u);continue}}catch(o){console.error(o)}}function t(r){return!!(r&&r.next&&r.return)}}};let kt=Zi;d(kt,"_defaultTargetFramerate",{value:90,toString(){return this.value}}),d(kt,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:"high-performance"}),di.registerCallback(Ci.ContextCreated,n=>{const e=n.context;NV(e),FV(e)});const _S=te("debugcomponents"),OV="eff8ba80-635d-11ec-90d6-0242ac120003";class Dr{constructor(e){d(this,"_originalSeed"),d(this,"_seed"),typeof e=="string"&&(e=Dr.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return G5(e,OV);const t=this._seed;return this._seed-=1,G5(t.toString(),OV)}initialize(e){typeof e=="string"?this._seed=Dr.hash(e):this._seed=e}static createFromString(e){return new Dr(this.hash(e))}static hash(e){let t=0;for(let r=0;r<e.length;r++)t=e.charCodeAt(r)+((t<<5)-t);return t}}var LV=(n=>(n.NewInstanceCreated="new-instance-created",n.InstanceDestroyed="instance-destroyed",n))(LV||{});class Wde{constructor(e){d(this,"guid"),d(this,"dontSave"),this.guid=e}}function hA(n,e,t=!0,r){if(!n)return;const s=n;if(Ca(n,t),!e){console.warn("Can not send destroy: No networking connection provided",n.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",n.guid);return}let o=n.guid;if(!o&&s.uuid&&(o=s.uuid),!o){console.warn("Can not send destroy: failed to find guid",n);return}$B(o,e,r)}function $B(n,e,t){const r=new Wde(n);t?.saveInRoom===!1&&(r.dontSave=!0),e.send("instance-destroyed",r,dl.Queued)}function FV(n){n.connection.beginListen("instance-destroyed",e=>{_S&&console.log("[Remote] Destroyed",n.scene,e);const t=dA(e.guid,n.scene);t&&Ca(t)})}class Xde{constructor(e,t,r){d(this,"filename"),d(this,"hash"),d(this,"size"),this.filename=e,this.hash=t,this.size=r}}class UV{constructor(e,t){d(this,"guid"),d(this,"originalGuid"),d(this,"seed"),d(this,"visible"),d(this,"hostData"),d(this,"dontSave"),d(this,"parent"),d(this,"position"),d(this,"rotation"),d(this,"scale"),d(this,"preventCreation"),d(this,"deleteStateOnDisconnect"),this.originalGuid=e,this.guid=t}}function ek(n,e,t,r){var s;const o=n;if(!o.guid)return console.warn("Can not instantiate: No guid",o),null;if(e.context||(e.context=kt.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const a=e?{...e}:null,{instance:l,seed:c}=qde(o,e);if(l){const h=l;if(h.guid){_S&&console.log("[Local] new instance","gameobject:",l?.guid);const u=new UV(o.guid,h.guid);u.seed=c,e.deleteOnDisconnect===!0&&(u.deleteStateOnDisconnect=!0),a&&(a.position&&(u.position={x:a.position.x,y:a.position.y,z:a.position.z}),a.rotation&&(u.rotation={x:a.rotation.x,y:a.rotation.y,z:a.rotation.z,w:a.rotation.w}),a.scale&&(u.scale={x:a.scale.x,y:a.scale.y,z:a.scale.z})),u.position||(u.position={x:h.position.x,y:h.position.y,z:h.position.z}),u.rotation||(u.rotation={x:h.quaternion.x,y:h.quaternion.y,z:h.quaternion.z,w:h.quaternion.w}),u.scale||(u.scale={x:h.scale.x,y:h.scale.y,z:h.scale.z}),u.visible=o.visible,a!=null&&a.parent&&(typeof a.parent=="string"?u.parent=a.parent:u.parent=a.parent.guid),u.hostData=t,r===!1&&(u.dontSave=!0),(s=e?.context)==null||s.connection.send("new-instance-created",u)}else console.warn("Missing guid, can not send new instance event",h)}return l}function xS(){return Math.random()*9999999}function NV(n){n.connection.beginListen("new-instance-created",async e=>{const t=await Yde(e.originalGuid,n.scene);if(e.preventCreation===!0)return;if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const r=new Ml;e.position&&(r.position=new C(e.position.x,e.position.y,e.position.z)),e.rotation&&(r.rotation=new Ce(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(r.scale=new C(e.scale.x,e.scale.y,e.scale.z)),r.parent=e.parent,e.seed&&(r.idProvider=new Dr(e.seed)),r.visible=e.visible,r.context=n,_S&&n.alias&&console.log("[Remote] instantiate in: "+n.alias);const s=Gg(t,r);s&&(e.parent==="scene"&&n.scene.add(s),_S&&console.log("[Remote] new instance","gameobject:",s?.guid,t))})}function qde(n,e){const t=xS(),r=e??new Ml;r.idProvider=new Dr(t);const s=Gg(n,r);return{seed:t,instance:s}}const zV={};function jV(n,e){zV[n]=e}async function Yde(n,e){const t=zV[n];if(t!=null){const r=await t(n);if(r)return r}return GV(n,e)}function GV(n,e){if(e===null||!n)return null;if(e.guid===n)return e;if(e.children)for(const t of e.children){const r=GV(n,t);if(r)return r}return null}const wS=te("debuggetcomponent"),SS=te("debuginstantiate");var VV=(n=>(n[n.None=0]="None",n[n.HideInHierarchy=1]="HideInHierarchy",n[n.HideInInspector=2]="HideInInspector",n[n.DontSaveInEditor=4]="DontSaveInEditor",n[n.NotEditable=8]="NotEditable",n[n.DontSaveInBuild=16]="DontSaveInBuild",n[n.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",n[n.DontSave=52]="DontSave",n[n.HideAndDontSave=61]="HideAndDontSave",n))(VV||{});class Ml{constructor(){d(this,"idProvider"),d(this,"parent"),d(this,"keepWorldPosition"),d(this,"position"),d(this,"rotation"),d(this,"scale"),d(this,"visible"),d(this,"context"),d(this,"components")}clone(){var e,t,r;const s=new Ml;return s.idProvider=this.idProvider,s.parent=this.parent,s.keepWorldPosition=this.keepWorldPosition,s.position=(e=this.position)==null?void 0:e.clone(),s.rotation=(t=this.rotation)==null?void 0:t.clone(),s.scale=(r=this.scale)==null?void 0:r.clone(),s.visible=this.visible,s.context=this.context,s.components=this.components,s}cloneAssign(e){var t,r,s;this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=(t=e.position)==null?void 0:t.clone(),this.rotation=(r=e.rotation)==null?void 0:r.clone(),this.scale=(s=e.scale)==null?void 0:s.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function jg(n){return n.visible}function uA(n,e){return typeof e=="number"&&(e=e>.5),n.visible=e,n.visible}function QV(n){return n[$c]||CS(n)}function HV(n,e){n[F5]=e}function CS(n){return Qa.isUsingInstancing(n)}function dA(n,e){return Df(n,e,!0,!0)}const WV=Symbol("isDestroyed");function Jp(n){return n[WV]}function XV(n,e){n[WV]=e}const tk=Symbol("isDontDestroy");function ik(n,e=!0){n[tk]=e}const ES=[],MS=[];function Ca(n,e=!0,t=!1){ES.length=0,MS.length=0,nk(n,e,!0);for(const r of ES)r.gameObject=null,r.context=null;for(const r of MS)XV(r,!0),t&&Qi(r),O5(r);MS.length=0,ES.length=0}function nk(n,e=!0,t=!0){var r;if(n==null)return;const s=n;if(s.isComponent){if(s[tk])return;ES.push(s);const l=s.gameObject;s.__internalDisable(),s.__internalDestroy(),s.gameObject=l;return}if(n[tk])return;const o=n;wS&&console.log(o),MS.push(o);const a=(r=o.userData)==null?void 0:r.components;if(a!=null&&Array.isArray(a)){let l=a.length;for(let c=0;c<a.length;c++){const h=a[c];nk(h,e,!1),a.length<l&&(l=a.length,c--)}}if(e&&o.children)for(const l of o.children)nk(l,e,!1);t&&o.removeFromParent()}function Kp(n,e,t=!0){return qV(n,e,t)}function*TS(n,e,t=!1,r=999,s=0){if(n!=null&&n.userData.components&&!(s>r)){for(const o of n.userData.components)e&&o?.isComponent===!0&&o instanceof e?yield o:yield o;if(t===!0)for(const o of n.children)yield*TS(o,e,!0,r,s+1)}}function qV(n,e,t,r=0){var s;if(n){if(n.isObject3D,r>1e3){console.warn("Failed to iterate components: too many levels");return}if((s=n.userData)!=null&&s.components)for(let o=0;o<n.userData.components.length;o++){const a=n.userData.components[o];if(a?.isComponent===!0){const l=e(a);if(l!==void 0)return l}}if(t&&n.children){const o=r+1;for(let a=0;a<n.children.length;a++){const l=n.children[a];if(!l)continue;const c=qV(l,e,t,o);if(c!==void 0)return c}}}}function Gg(n,e=null){let t=null;e!==null&&(e.x!==void 0?(t=new Ml,t.position=e):t=e);let r=kt.Current;t!=null&&t.context&&(r=t.context),wS&&r.alias&&console.log("context",r.alias),t&&!t.idProvider&&(t.idProvider=new Dr(Date.now()));const s=[],o={},a={},l=YV(r,n,t,s,o,a);l&&(Kde(o),Jde(a,o)),wS&&(yw(n,!0),yw(l,!0));const c={};if(t?.components!==!1){for(const h in s){const u=s[h],p=u.guid;t&&t.idProvider&&(u.guid=t.idProvider.generateUUID(),c[p]=u.guid,wS&&console.log(u.name,u.guid)),bS(u,r),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const h in s){const u=s[h];u.resolveGuids&&u.resolveGuids(c),u.enabled!==!1&&(u.enabled=!0)}B1(r)}return l}function YV(n,e,t,r,s,o){var a;if(!e)return null;const l=e.userData;e.userData={};const c=e.children;e.children=[];const h=e.clone(!1);if(IS(h),e.userData=l,e.children=c,s[e.uuid]={original:e,clone:h},SS&&console.log("ADD",e,h),e.type==="SkinnedMesh"&&(o[e.uuid]={original:e,clone:h}),t?.visible!==void 0&&(h.visible=t.visible),t!=null&&t.idProvider){h.uuid=t.idProvider.generateUUID();const p=h;p&&(p.guid=h.uuid)}e.animations&&e.animations.length>0&&(h.animations=[...e.animations]);const u=e.parent;if(u&&u.add(h),t!=null&&t.position?lr(h,t.position):h.position.copy(e.position),t!=null&&t.rotation?ca(h,t.rotation):h.quaternion.copy(e.quaternion),t!=null&&t.scale?h.scale.copy(t.scale):h.scale.copy(e.scale),t!=null&&t.parent&&t.parent!=="scene"){let p=null;if(typeof t.parent=="string"?p=Df(t.parent,n.scene,!0):p=t.parent,p){const m=t.keepWorldPosition===!0?p.attach:p.add;m?m.call(p,h):console.error("Invalid parent object",p,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[p,m]of Object.entries(e.userData))p!=="components"&&(h.userData[p]=m);if((a=e.userData)!=null&&a.components){const p=e.userData.components,m=[];h.userData.components=m;for(let f=0;f<p.length;f++){const g=p[f],v=new g.constructor;Rg(v,g),g[Kv]!==void 0&&(v[Kv]=g[Kv]),m.push(v),v.gameObject=h,r.push(v),Ny.dispatchComponentLifecycleEvent(Uy.Added,v)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(const p in e.children){const m=e.children[p],f=YV(n,m,t,r,s,o);f&&h.add(f)}return h}function Jde(n,e){for(const t in n){const r=n[t],s=r.original,o=s.skeleton,a=r.clone;if(!o){console.warn("Skinned mesh has no skeleton?",r);continue}const l=o.bones,c=a.skeleton.clone();a.skeleton=c,a.bindMatrix.clone().copy(s.bindMatrix),a.bindMatrixInverse.copy(s.bindMatrixInverse);const h=[];c.bones=h;for(let u=0;u<l.length;u++){const p=l[u],m=e[p.uuid].clone;h.push(m)}}for(const t in n){const r=n[t].clone;r.skeleton.update(),r.bind(r.skeleton,r.bindMatrix),r.updateMatrixWorld(!0)}}function Kde(n){var e;for(const t in n){const r=n[t].clone;if((e=r.userData)!=null&&e.components)for(let s=0;s<r.userData.components.length;s++){const o=r.userData.components[s],a=Object.entries(o);for(const[l,c]of a)if(Array.isArray(c)){const h=[];o[l]=h;for(let u=0;u<c.length;u++){const p=c[u];if(typeof p!="object"){h.push(p);continue}const m=JV(o,l,p,n);m!==void 0?h.push(m):h.push(p)}}else if(typeof c=="object"){const h=JV(o,l,c,n);h!==void 0&&(o[l]=h)}}}}function JV(n,e,t,r){var s,o;if(t!=null)if(t.isComponent===!0){const a=t.gameObject;if(a){const l=a.uuid,c=(s=r[l])==null?void 0:s.clone;if(!c){SS&&console.log("reference did not change",e,n,t);return}const h=a.userData.components.indexOf(t);if(h>=0)return SS&&console.log(e,l),c.userData.components[h];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const a=t;if(a){const l=a.uuid,c=(o=r[l])==null?void 0:o.clone;if(c)return SS&&console.log(e,"old",t,"new",c),c}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler||t.isColor===!0)return t.clone();if(t.isEventList===!0)return new t.constructor}}const KV=new Map;function Zde(n,e){if(!n)return;if(!e){console.warn("No prototype found",n,n.prototype,n.constructor);return}const t=KV.get(e);t&&t.apply(n)}function $de(n){const e=epe(n.prototype);KV.set(n,e)}function epe(n){return new tpe(n)}class tpe{constructor(e){d(this,"$symbol"),d(this,"extensions"),d(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const r=this.extensions[t],s=Object.getOwnPropertyDescriptor(e,r);s&&this.descriptors.push(s)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const r=this.extensions[t],s=this.descriptors[t];s&&Object.defineProperty(e,r,s)}}}}function IS(n){n&&n.isObject3D===!0&&Zde(n,ye)}ye.prototype.SetActive=function(n){this.visible=n},ye.prototype.setActive=function(n){this.visible=n},ye.prototype.destroy=function(){Ca(this)},ye.prototype.addComponent=function(n,e){return gl(this,n,e)},ye.prototype.addNewComponent=function(n,e){return gl(this,n,e)},ye.prototype.removeComponent=function(n){return rk(this,n)},ye.prototype.getOrAddComponent=function(n,e){return pA(this,n,e)},ye.prototype.getComponent=function(n){return $p(this,n)},ye.prototype.getComponents=function(n,e){return mA(this,n,e)},ye.prototype.getComponentInChildren=function(n){return fA(this,n)},ye.prototype.getComponentsInChildren=function(n,e){return Vg(this,n,e)},ye.prototype.getComponentInParent=function(n){return gA(this,n)},ye.prototype.getComponentsInParent=function(n,e){return RS(this,n,e)},Object.getOwnPropertyDescriptor(ye.prototype,"activeSelf")||Object.defineProperty(ye.prototype,"activeSelf",{get:function(){return jg(this)},set:function(n){uA(this,n)}}),Object.getOwnPropertyDescriptor(ye.prototype,"transform")||Object.defineProperty(ye.prototype,"transform",{get:function(){return this}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldPosition")||Object.defineProperty(ye.prototype,"worldPosition",{get:function(){return this instanceof DP?Bt(this.object):Bt(this)},set:function(n){lr(this,n)}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldQuaternion")||Object.defineProperty(ye.prototype,"worldQuaternion",{get:function(){return this instanceof DP?Mi(this.object):Mi(this)},set:function(n){ca(this,n)}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldRotation")||Object.defineProperty(ye.prototype,"worldRotation",{get:function(){return Wv(this)},set:function(n){MR(this,n)}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldScale")||Object.defineProperty(ye.prototype,"worldScale",{get:function(){return Vi(this)},set:function(n){Uf(this,n)}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldForward")||Object.defineProperty(ye.prototype,"worldForward",{get:function(){return pi().set(0,0,1).applyQuaternion(Mi(this))}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldRight")||Object.defineProperty(ye.prototype,"worldRight",{get:function(){return pi().set(1,0,0).applyQuaternion(Mi(this))}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldUp")||Object.defineProperty(ye.prototype,"worldUp",{get:function(){return pi().set(0,1,0).applyQuaternion(Mi(this))}}),$de(ye);const ipe=te("debuggetcomponent"),ZV=()=>ipe||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function npe(n){return n==null||n.isObject3D?n:n.object&&n.object.isObject3D?n.object:n}function rk(n,e){if(!n||!n.userData.components)return e;const t=n.userData.components.indexOf(e);return t<0||(Ny.dispatchComponentLifecycleEvent(Uy.Removing,e),e.gameObject=null,n.userData.components.splice(t,1)),e}function pA(n,e,t){return $p(n,e)||gl(n,e,t)}const $V=new Dr("addComponentIdProvider");function Zp(n,e,t=!0){n.userData||(n.userData={}),n.userData.components||(n.userData.components=[]),n.userData.components.push(e),e.gameObject=n,(e.guid===void 0||e.guid==="invalid")&&(e.guid=$V.generateUUID()),IS(n),bS(e,e.context);try{t&&e.__internalAwake&&(Gy(n),e.activeAndEnabled&&e.__internalAwake()),Ny.dispatchComponentLifecycleEvent(Uy.Added,e)}catch(r){console.error(r)}return e}function gl(n,e,t,r){if(typeof e=="function"){const s=new e;t&&s.__internalNewInstanceCreated(t);let o=!0;return r?.callAwake!=null&&(o=r.callAwake),Zp(n,s,o)}if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===n)return e;if(e.gameObject&&e.gameObject.userData.components){const s=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(s,1)}if(!n.userData.components)n.userData.components=[];else if(n.userData.components.includes(e))return e;return n.userData.components.push(e),e.gameObject=n,(e.guid===void 0||e.guid==="invalid")&&(e.guid=$V.generateUUID()),t&&e._internalInit(t),bS(e,e.context),e}function e8(n){if(n.gameObject&&n.gameObject.userData.components){const e=n.gameObject.userData.components.indexOf(n);n.gameObject.userData.components.splice(e,1)}n.__internalDisable&&n.__internalDisable(),dh(n,n.context??kt.Current),n.destroy(),n.gameObject=null}let t8=!1;function i8(n,e,t){var r;if(n==null)return null;if(!n.isObject3D)return console.error("Object is not object3D"),null;if(!((r=n?.userData)!=null&&r.components)||(typeof e=="string"&&(t8||(t8=!0,console.warn(`Accessing components by name is not supported.
5654
+ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),di.dispatchCallback(Ci.ContextFirstFrameRendered,this)),this.renderer.info.reset()}renderNow(n){return!n&&(n=this.mainCamera,!n)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==Ls&&I8(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):n&&this.renderer.render(this.scene,n),this._isRendering=!1,!0)}onHandlePaused(){const n=this.evaluatePaused();if(this._wasPaused!==n){jde&&console.log("Paused?",n,"context:"+this.alias);for(let e=0;e<this.scripts_pausedChanged.length;e++){const t=this.scripts_pausedChanged[e];t.activeAndEnabled&&t.onPausedChanged!==void 0&&(Zi.Current=this,t.onPausedChanged(n,this._wasPaused))}}return this._wasPaused=n,n}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Wt(this.domWidth,this.domHeight),this._requireDepthTexture){const t=new _f(this.domWidth,this.domHeight);this._renderTarget.depthTexture=t}this._requireColorTexture&&(this._renderTarget.texture=new zt,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Nt,this._renderTarget.texture.magFilter=Nt,this._renderTarget.texture.format=Yi)}const n=this._renderTarget;n.texture&&(n.texture.colorSpace=this.renderer.outputColorSpace);const e=this.renderer.getRenderTarget();this.renderer.setRenderTarget(n),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(e)}executeCoroutines(n){var e;if(this.coroutines[n]){const r=this.coroutines[n];for(let s=0;s<r.length;s++)try{const o=r[s];if(!o.comp||o.comp.destroyed||!o.main||o.comp.enabled===!1){Vde&&console.log("Removing coroutine",o.comp,o.comp.enabled),r.splice(s,1),--s;continue}const a=o.chained;if(a&&a.length>0){const h=a[a.length-1].next();if(h.done&&a.pop(),t(h)&&(o.chained||(o.chained=[]),o.chained.push(h.value)),!h.done)continue}const l=o.main.next();if(l.done===!0){r.splice(s,1),--s;continue}const c=l.value;if(t(c)){if(c.next().done)continue;o.chained||(o.chained=[]),o.chained.push(c)}else if(c instanceof Promise){const h=c;o.chained||(o.chained=[]);const u=m8(h);(e=o.chained)==null||e.push(u);continue}}catch(o){console.error(o)}}function t(r){return!!(r&&r.next&&r.return)}}};let kt=Zi;d(kt,"_defaultTargetFramerate",{value:90,toString(){return this.value}}),d(kt,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:"high-performance"}),di.registerCallback(Ci.ContextCreated,n=>{const e=n.context;N8(e),F8(e)});const _S=te("debugcomponents"),O8="eff8ba80-635d-11ec-90d6-0242ac120003";class Dr{constructor(e){d(this,"_originalSeed"),d(this,"_seed"),typeof e=="string"&&(e=Dr.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return G5(e,O8);const t=this._seed;return this._seed-=1,G5(t.toString(),O8)}initialize(e){typeof e=="string"?this._seed=Dr.hash(e):this._seed=e}static createFromString(e){return new Dr(this.hash(e))}static hash(e){let t=0;for(let r=0;r<e.length;r++)t=e.charCodeAt(r)+((t<<5)-t);return t}}var L8=(n=>(n.NewInstanceCreated="new-instance-created",n.InstanceDestroyed="instance-destroyed",n))(L8||{});class Wde{constructor(e){d(this,"guid"),d(this,"dontSave"),this.guid=e}}function hA(n,e,t=!0,r){if(!n)return;const s=n;if(Ca(n,t),!e){console.warn("Can not send destroy: No networking connection provided",n.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",n.guid);return}let o=n.guid;if(!o&&s.uuid&&(o=s.uuid),!o){console.warn("Can not send destroy: failed to find guid",n);return}$B(o,e,r)}function $B(n,e,t){const r=new Wde(n);t?.saveInRoom===!1&&(r.dontSave=!0),e.send("instance-destroyed",r,dl.Queued)}function F8(n){n.connection.beginListen("instance-destroyed",e=>{_S&&console.log("[Remote] Destroyed",n.scene,e);const t=dA(e.guid,n.scene);t&&Ca(t)})}class Xde{constructor(e,t,r){d(this,"filename"),d(this,"hash"),d(this,"size"),this.filename=e,this.hash=t,this.size=r}}class U8{constructor(e,t){d(this,"guid"),d(this,"originalGuid"),d(this,"seed"),d(this,"visible"),d(this,"hostData"),d(this,"dontSave"),d(this,"parent"),d(this,"position"),d(this,"rotation"),d(this,"scale"),d(this,"preventCreation"),d(this,"deleteStateOnDisconnect"),this.originalGuid=e,this.guid=t}}function ek(n,e,t,r){var s;const o=n;if(!o.guid)return console.warn("Can not instantiate: No guid",o),null;if(e.context||(e.context=kt.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const a=e?{...e}:null,{instance:l,seed:c}=qde(o,e);if(l){const h=l;if(h.guid){_S&&console.log("[Local] new instance","gameobject:",l?.guid);const u=new U8(o.guid,h.guid);u.seed=c,e.deleteOnDisconnect===!0&&(u.deleteStateOnDisconnect=!0),a&&(a.position&&(u.position={x:a.position.x,y:a.position.y,z:a.position.z}),a.rotation&&(u.rotation={x:a.rotation.x,y:a.rotation.y,z:a.rotation.z,w:a.rotation.w}),a.scale&&(u.scale={x:a.scale.x,y:a.scale.y,z:a.scale.z})),u.position||(u.position={x:h.position.x,y:h.position.y,z:h.position.z}),u.rotation||(u.rotation={x:h.quaternion.x,y:h.quaternion.y,z:h.quaternion.z,w:h.quaternion.w}),u.scale||(u.scale={x:h.scale.x,y:h.scale.y,z:h.scale.z}),u.visible=o.visible,a!=null&&a.parent&&(typeof a.parent=="string"?u.parent=a.parent:u.parent=a.parent.guid),u.hostData=t,r===!1&&(u.dontSave=!0),(s=e?.context)==null||s.connection.send("new-instance-created",u)}else console.warn("Missing guid, can not send new instance event",h)}return l}function xS(){return Math.random()*9999999}function N8(n){n.connection.beginListen("new-instance-created",async e=>{const t=await Yde(e.originalGuid,n.scene);if(e.preventCreation===!0)return;if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const r=new Ml;e.position&&(r.position=new C(e.position.x,e.position.y,e.position.z)),e.rotation&&(r.rotation=new Ce(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(r.scale=new C(e.scale.x,e.scale.y,e.scale.z)),r.parent=e.parent,e.seed&&(r.idProvider=new Dr(e.seed)),r.visible=e.visible,r.context=n,_S&&n.alias&&console.log("[Remote] instantiate in: "+n.alias);const s=Gg(t,r);s&&(e.parent==="scene"&&n.scene.add(s),_S&&console.log("[Remote] new instance","gameobject:",s?.guid,t))})}function qde(n,e){const t=xS(),r=e??new Ml;r.idProvider=new Dr(t);const s=Gg(n,r);return{seed:t,instance:s}}const z8={};function j8(n,e){z8[n]=e}async function Yde(n,e){const t=z8[n];if(t!=null){const r=await t(n);if(r)return r}return G8(n,e)}function G8(n,e){if(e===null||!n)return null;if(e.guid===n)return e;if(e.children)for(const t of e.children){const r=G8(n,t);if(r)return r}return null}const wS=te("debuggetcomponent"),SS=te("debuginstantiate");var V8=(n=>(n[n.None=0]="None",n[n.HideInHierarchy=1]="HideInHierarchy",n[n.HideInInspector=2]="HideInInspector",n[n.DontSaveInEditor=4]="DontSaveInEditor",n[n.NotEditable=8]="NotEditable",n[n.DontSaveInBuild=16]="DontSaveInBuild",n[n.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",n[n.DontSave=52]="DontSave",n[n.HideAndDontSave=61]="HideAndDontSave",n))(V8||{});class Ml{constructor(){d(this,"idProvider"),d(this,"parent"),d(this,"keepWorldPosition"),d(this,"position"),d(this,"rotation"),d(this,"scale"),d(this,"visible"),d(this,"context"),d(this,"components")}clone(){var e,t,r;const s=new Ml;return s.idProvider=this.idProvider,s.parent=this.parent,s.keepWorldPosition=this.keepWorldPosition,s.position=(e=this.position)==null?void 0:e.clone(),s.rotation=(t=this.rotation)==null?void 0:t.clone(),s.scale=(r=this.scale)==null?void 0:r.clone(),s.visible=this.visible,s.context=this.context,s.components=this.components,s}cloneAssign(e){var t,r,s;this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=(t=e.position)==null?void 0:t.clone(),this.rotation=(r=e.rotation)==null?void 0:r.clone(),this.scale=(s=e.scale)==null?void 0:s.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function jg(n){return n.visible}function uA(n,e){return typeof e=="number"&&(e=e>.5),n.visible=e,n.visible}function Q8(n){return n[$c]||CS(n)}function H8(n,e){n[F5]=e}function CS(n){return Qa.isUsingInstancing(n)}function dA(n,e){return Df(n,e,!0,!0)}const W8=Symbol("isDestroyed");function Jp(n){return n[W8]}function X8(n,e){n[W8]=e}const tk=Symbol("isDontDestroy");function ik(n,e=!0){n[tk]=e}const ES=[],MS=[];function Ca(n,e=!0,t=!1){ES.length=0,MS.length=0,nk(n,e,!0);for(const r of ES)r.gameObject=null,r.context=null;for(const r of MS)X8(r,!0),t&&Qi(r),O5(r);MS.length=0,ES.length=0}function nk(n,e=!0,t=!0){var r;if(n==null)return;const s=n;if(s.isComponent){if(s[tk])return;ES.push(s);const l=s.gameObject;s.__internalDisable(),s.__internalDestroy(),s.gameObject=l;return}if(n[tk])return;const o=n;wS&&console.log(o),MS.push(o);const a=(r=o.userData)==null?void 0:r.components;if(a!=null&&Array.isArray(a)){let l=a.length;for(let c=0;c<a.length;c++){const h=a[c];nk(h,e,!1),a.length<l&&(l=a.length,c--)}}if(e&&o.children)for(const l of o.children)nk(l,e,!1);t&&o.removeFromParent()}function Kp(n,e,t=!0){return q8(n,e,t)}function*TS(n,e,t=!1,r=999,s=0){if(n!=null&&n.userData.components&&!(s>r)){for(const o of n.userData.components)e&&o?.isComponent===!0&&o instanceof e?yield o:yield o;if(t===!0)for(const o of n.children)yield*TS(o,e,!0,r,s+1)}}function q8(n,e,t,r=0){var s;if(n){if(n.isObject3D,r>1e3){console.warn("Failed to iterate components: too many levels");return}if((s=n.userData)!=null&&s.components)for(let o=0;o<n.userData.components.length;o++){const a=n.userData.components[o];if(a?.isComponent===!0){const l=e(a);if(l!==void 0)return l}}if(t&&n.children){const o=r+1;for(let a=0;a<n.children.length;a++){const l=n.children[a];if(!l)continue;const c=q8(l,e,t,o);if(c!==void 0)return c}}}}function Gg(n,e=null){let t=null;e!==null&&(e.x!==void 0?(t=new Ml,t.position=e):t=e);let r=kt.Current;t!=null&&t.context&&(r=t.context),wS&&r.alias&&console.log("context",r.alias),t&&!t.idProvider&&(t.idProvider=new Dr(Date.now()));const s=[],o={},a={},l=Y8(r,n,t,s,o,a);l&&(Kde(o),Jde(a,o)),wS&&(yw(n,!0),yw(l,!0));const c={};if(t?.components!==!1){for(const h in s){const u=s[h],p=u.guid;t&&t.idProvider&&(u.guid=t.idProvider.generateUUID(),c[p]=u.guid,wS&&console.log(u.name,u.guid)),bS(u,r),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const h in s){const u=s[h];u.resolveGuids&&u.resolveGuids(c),u.enabled!==!1&&(u.enabled=!0)}B1(r)}return l}function Y8(n,e,t,r,s,o){var a;if(!e)return null;const l=e.userData;e.userData={};const c=e.children;e.children=[];const h=e.clone(!1);if(IS(h),e.userData=l,e.children=c,s[e.uuid]={original:e,clone:h},SS&&console.log("ADD",e,h),e.type==="SkinnedMesh"&&(o[e.uuid]={original:e,clone:h}),t?.visible!==void 0&&(h.visible=t.visible),t!=null&&t.idProvider){h.uuid=t.idProvider.generateUUID();const p=h;p&&(p.guid=h.uuid)}e.animations&&e.animations.length>0&&(h.animations=[...e.animations]);const u=e.parent;if(u&&u.add(h),t!=null&&t.position?lr(h,t.position):h.position.copy(e.position),t!=null&&t.rotation?ca(h,t.rotation):h.quaternion.copy(e.quaternion),t!=null&&t.scale?h.scale.copy(t.scale):h.scale.copy(e.scale),t!=null&&t.parent&&t.parent!=="scene"){let p=null;if(typeof t.parent=="string"?p=Df(t.parent,n.scene,!0):p=t.parent,p){const m=t.keepWorldPosition===!0?p.attach:p.add;m?m.call(p,h):console.error("Invalid parent object",p,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[p,m]of Object.entries(e.userData))p!=="components"&&(h.userData[p]=m);if((a=e.userData)!=null&&a.components){const p=e.userData.components,m=[];h.userData.components=m;for(let f=0;f<p.length;f++){const g=p[f],v=new g.constructor;Rg(v,g),g[Kv]!==void 0&&(v[Kv]=g[Kv]),m.push(v),v.gameObject=h,r.push(v),Ny.dispatchComponentLifecycleEvent(Uy.Added,v)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(const p in e.children){const m=e.children[p],f=Y8(n,m,t,r,s,o);f&&h.add(f)}return h}function Jde(n,e){for(const t in n){const r=n[t],s=r.original,o=s.skeleton,a=r.clone;if(!o){console.warn("Skinned mesh has no skeleton?",r);continue}const l=o.bones,c=a.skeleton.clone();a.skeleton=c,a.bindMatrix.clone().copy(s.bindMatrix),a.bindMatrixInverse.copy(s.bindMatrixInverse);const h=[];c.bones=h;for(let u=0;u<l.length;u++){const p=l[u],m=e[p.uuid].clone;h.push(m)}}for(const t in n){const r=n[t].clone;r.skeleton.update(),r.bind(r.skeleton,r.bindMatrix),r.updateMatrixWorld(!0)}}function Kde(n){var e;for(const t in n){const r=n[t].clone;if((e=r.userData)!=null&&e.components)for(let s=0;s<r.userData.components.length;s++){const o=r.userData.components[s],a=Object.entries(o);for(const[l,c]of a)if(Array.isArray(c)){const h=[];o[l]=h;for(let u=0;u<c.length;u++){const p=c[u];if(typeof p!="object"){h.push(p);continue}const m=J8(o,l,p,n);m!==void 0?h.push(m):h.push(p)}}else if(typeof c=="object"){const h=J8(o,l,c,n);h!==void 0&&(o[l]=h)}}}}function J8(n,e,t,r){var s,o;if(t!=null)if(t.isComponent===!0){const a=t.gameObject;if(a){const l=a.uuid,c=(s=r[l])==null?void 0:s.clone;if(!c){SS&&console.log("reference did not change",e,n,t);return}const h=a.userData.components.indexOf(t);if(h>=0)return SS&&console.log(e,l),c.userData.components[h];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const a=t;if(a){const l=a.uuid,c=(o=r[l])==null?void 0:o.clone;if(c)return SS&&console.log(e,"old",t,"new",c),c}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler||t.isColor===!0)return t.clone();if(t.isEventList===!0)return new t.constructor}}const K8=new Map;function Zde(n,e){if(!n)return;if(!e){console.warn("No prototype found",n,n.prototype,n.constructor);return}const t=K8.get(e);t&&t.apply(n)}function $de(n){const e=epe(n.prototype);K8.set(n,e)}function epe(n){return new tpe(n)}class tpe{constructor(e){d(this,"$symbol"),d(this,"extensions"),d(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const r=this.extensions[t],s=Object.getOwnPropertyDescriptor(e,r);s&&this.descriptors.push(s)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const r=this.extensions[t],s=this.descriptors[t];s&&Object.defineProperty(e,r,s)}}}}function IS(n){n&&n.isObject3D===!0&&Zde(n,ye)}ye.prototype.SetActive=function(n){this.visible=n},ye.prototype.setActive=function(n){this.visible=n},ye.prototype.destroy=function(){Ca(this)},ye.prototype.addComponent=function(n,e){return gl(this,n,e)},ye.prototype.addNewComponent=function(n,e){return gl(this,n,e)},ye.prototype.removeComponent=function(n){return rk(this,n)},ye.prototype.getOrAddComponent=function(n,e){return pA(this,n,e)},ye.prototype.getComponent=function(n){return $p(this,n)},ye.prototype.getComponents=function(n,e){return mA(this,n,e)},ye.prototype.getComponentInChildren=function(n){return fA(this,n)},ye.prototype.getComponentsInChildren=function(n,e){return Vg(this,n,e)},ye.prototype.getComponentInParent=function(n){return gA(this,n)},ye.prototype.getComponentsInParent=function(n,e){return RS(this,n,e)},Object.getOwnPropertyDescriptor(ye.prototype,"activeSelf")||Object.defineProperty(ye.prototype,"activeSelf",{get:function(){return jg(this)},set:function(n){uA(this,n)}}),Object.getOwnPropertyDescriptor(ye.prototype,"transform")||Object.defineProperty(ye.prototype,"transform",{get:function(){return this}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldPosition")||Object.defineProperty(ye.prototype,"worldPosition",{get:function(){return this instanceof DP?Bt(this.object):Bt(this)},set:function(n){lr(this,n)}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldQuaternion")||Object.defineProperty(ye.prototype,"worldQuaternion",{get:function(){return this instanceof DP?Mi(this.object):Mi(this)},set:function(n){ca(this,n)}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldRotation")||Object.defineProperty(ye.prototype,"worldRotation",{get:function(){return Wv(this)},set:function(n){MR(this,n)}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldScale")||Object.defineProperty(ye.prototype,"worldScale",{get:function(){return Vi(this)},set:function(n){Uf(this,n)}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldForward")||Object.defineProperty(ye.prototype,"worldForward",{get:function(){return pi().set(0,0,1).applyQuaternion(Mi(this))}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldRight")||Object.defineProperty(ye.prototype,"worldRight",{get:function(){return pi().set(1,0,0).applyQuaternion(Mi(this))}}),Object.getOwnPropertyDescriptor(ye.prototype,"worldUp")||Object.defineProperty(ye.prototype,"worldUp",{get:function(){return pi().set(0,1,0).applyQuaternion(Mi(this))}}),$de(ye);const ipe=te("debuggetcomponent"),Z8=()=>ipe||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function npe(n){return n==null||n.isObject3D?n:n.object&&n.object.isObject3D?n.object:n}function rk(n,e){if(!n||!n.userData.components)return e;const t=n.userData.components.indexOf(e);return t<0||(Ny.dispatchComponentLifecycleEvent(Uy.Removing,e),e.gameObject=null,n.userData.components.splice(t,1)),e}function pA(n,e,t){return $p(n,e)||gl(n,e,t)}const $8=new Dr("addComponentIdProvider");function Zp(n,e,t=!0){n.userData||(n.userData={}),n.userData.components||(n.userData.components=[]),n.userData.components.push(e),e.gameObject=n,(e.guid===void 0||e.guid==="invalid")&&(e.guid=$8.generateUUID()),IS(n),bS(e,e.context);try{t&&e.__internalAwake&&(Gy(n),e.activeAndEnabled&&e.__internalAwake()),Ny.dispatchComponentLifecycleEvent(Uy.Added,e)}catch(r){console.error(r)}return e}function gl(n,e,t,r){if(typeof e=="function"){const s=new e;t&&s.__internalNewInstanceCreated(t);let o=!0;return r?.callAwake!=null&&(o=r.callAwake),Zp(n,s,o)}if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===n)return e;if(e.gameObject&&e.gameObject.userData.components){const s=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(s,1)}if(!n.userData.components)n.userData.components=[];else if(n.userData.components.includes(e))return e;return n.userData.components.push(e),e.gameObject=n,(e.guid===void 0||e.guid==="invalid")&&(e.guid=$8.generateUUID()),t&&e._internalInit(t),bS(e,e.context),e}function eV(n){if(n.gameObject&&n.gameObject.userData.components){const e=n.gameObject.userData.components.indexOf(n);n.gameObject.userData.components.splice(e,1)}n.__internalDisable&&n.__internalDisable(),dh(n,n.context??kt.Current),n.destroy(),n.gameObject=null}let tV=!1;function iV(n,e,t){var r;if(n==null)return null;if(!n.isObject3D)return console.error("Object is not object3D"),null;if(!((r=n?.userData)!=null&&r.components)||(typeof e=="string"&&(tV||(tV=!0,console.warn(`Accessing components by name is not supported.
5655
5655
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
5656
5656
 
5657
5657
  You can import other modules your main module to get access to types
5658
5658
  or if you use npmdefs you can make types available globally using globalThis:
5659
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,e))),ZV()&&console.log("[onGetComponent] FIND",e),e==null))return null;for(let s=0;s<n.userData.components.length;s++){const o=n.userData.components[s];let a=Object.getPrototypeOf(o);for(;a;){if(a===e.prototype)if(ZV()&&console.log("[onGetComponent] MATCH BY PROTOYPE",a),t)t.push(o);else return o;a=Object.getPrototypeOf(a)}}return t||null}function $p(n,e){const t=i8(n,e);return t?Array.isArray(t)?t[0]:t:null}function mA(n,e,t,r=!0){return t||(t=[]),r&&(t.length=0),i8(n,e,t),t}function fA(n,e,t){var r;const s=$p(n,e);if(t===!1&&s?.enabled===!1)return null;if(s)return s;for(let o=0;o<((r=n?.children)==null?void 0:r.length);o++){const a=fA(n.children[o],e);if(a)return a}return null}function Vg(n,e,t,r=!0){var s;t||(t=[]),r&&(t.length=0),mA(n,e,t,!1);for(let o=0;o<((s=n?.children)==null?void 0:s.length);o++)Vg(n.children[o],e,t,!1);return t}function gA(n,e){if(!n)return null;if(Array.isArray(n)){for(let r=0;r<n.length;r++){const s=npe(n[r]),o=gA(s,e);if(o)return o}return null}return $p(n,e)||(n.parent?gA(n.parent,e):null)}function RS(n,e,t,r=!0){return t||(t=[]),r&&(t.length=0),n?(mA(n,e,t,!1),n.parent?RS(n.parent,e,t,!1):t):t}function PS(n,e=void 0,t=!0){if(!n)return null;if(!e&&(e=kt.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let r=e;if(r.isScene||(r=e?.scene),!r)return null;for(const s in r.children){const o=r.children[s];if(t===!1&&o[$c]===!1)continue;const a=fA(o,n);if(a)return a}return null}function n8(n,e,t=void 0){if(!n)return e;if(e||(e=[]),e.length=0,!t&&(t=kt.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;"scene"in t&&(t=t.scene);const r=t;if(!r)return e;for(const s in r.children){const o=r.children[s];Vg(o,n,e,!1)}return e}class ie extends ye{constructor(){super(...arguments),d(this,"guid")}static isDestroyed(e){return Jp(e)}static setActive(e,t,r=!0){e&&(uA(e,t),k1(e),t&&r&&N5(kt.Current,e))}static isActiveSelf(e){return jg(e)}static isActiveInHierarchy(e){return QV(e)}static markAsInstancedRendered(e,t){HV(e,t)}static isUsingInstancing(e){return CS(e)}static foreachComponent(e,t,r=!0){return Kp(e,t,r)}static instantiateSynced(e,t){return e?ek(e,t):null}static instantiate(e,t=null){return Gg(e,t)}static destroySynced(e,t,r=!0){if(!e)return;const s=e;t=t??kt.Current,hA(s,t.connection,r)}static destroy(e,t=!0){return Ca(e,t)}static add(e,t,r){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}r||(r=kt.Current),t.add(e),uA(e,!0),k1(e),r?ie.foreachComponent(e,s=>{GP(s,r),!s.__internalDidAwakeAndStart&&r.new_script_start.includes(s)===!1&&r.new_script_start.push(s)},!0):console.warn("Missing context")}}static remove(e){var t;e&&((t=e.parent)==null||t.remove(e),uA(e,!1),k1(e),ie.foreachComponent(e,r=>{Ble(r)},!0))}static invokeOnChildren(e,t,...r){this.invoke(e,t,!0,r)}static invoke(e,t,r=!1,...s){e&&this.foreachComponent(e,o=>{const a=o[t];a&&typeof a=="function"&&a?.call(o,...s)},r)}static addNewComponent(e,t,r,s=!0){return gl(e,t,r,{callAwake:s})}static addComponent(e,t,r,s){return gl(e,t,r,s)}static moveComponent(e,t){return gl(e,t)}static removeComponent(e){return rk(e.gameObject,e),e}static getOrAddComponent(e,t){return pA(e,t)}static getComponent(e,t){return e===null?null:$p(e,t)}static getComponents(e,t,r=null){return e===null?r??[]:mA(e,t,r)}static findByGuid(e,t){return dA(e,t)}static findObjectOfType(e,t,r=!0){return PS(e,t??kt.Current,r)}static findObjectsOfType(e,t){const r=[];return n8(e,r,t),r}static getComponentInChildren(e,t){return fA(e,t)}static getComponentsInChildren(e,t,r=null){return Vg(e,t,r??void 0)}static getComponentInParent(e,t){return gA(e,t)}static getComponentsInParent(e,t,r=null){return RS(e,t,r)}static getAllComponents(e){var t;return[...(t=e.userData)==null?void 0:t.components]}static*iterateComponents(e){var t;const r=(t=e?.userData)==null?void 0:t.components;if(r&&Array.isArray(r))for(let s=0;s<r.length;s++)yield r[s]}}var Xu;let Be=(Xu=class{constructor(n){d(this,"__context"),d(this,"__name"),d(this,"gameObject"),d(this,"guid","invalid"),d(this,"sourceId"),d(this,"__didAwake",!1),d(this,"__didStart",!1),d(this,"__didEnable",!1),d(this,"__isEnabled"),d(this,"__destroyed",!1),d(this,"_eventListeners",new Map),this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(n)}get isComponent(){return!0}get context(){return this.__context??kt.Current}set context(n){this.__context=n}get scene(){return this.context.scene}get layer(){var n,e;return(e=(n=this.gameObject)==null?void 0:n.userData)==null?void 0:e.layer}get name(){var n,e;return(n=this.gameObject)!=null&&n.name?this.gameObject.name:(e=this.gameObject)==null?void 0:e.userData.name}set name(n){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=n,this.__name=n):this.__name=n}get tag(){var n;return(n=this.gameObject)==null?void 0:n.userData.tag}set tag(n){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=n)}get static(){var n;return(n=this.gameObject)==null?void 0:n.userData.static}set static(n){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=n)}get hideFlags(){var n;return(n=this.gameObject)==null?void 0:n.userData.hideFlags}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const n=this.gameObject[$c];return n===void 0?!0:n}set __isActiveInHierarchy(n){this.gameObject&&(this.gameObject[$c]=n)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(n,e=Hi.Update){return this.context.registerCoroutineUpdate(this,n,e)}stopCoroutine(n,e=Hi.Update){this.context.unregisterCoroutineUpdate(n,e)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(n){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(n),this}_internalInit(n){if(typeof n=="object")for(const e of Object.keys(n)){const t=n[e];typeof t!="function"&&(this[e]=t)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(n){return this.__destroyed?(st()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(n!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(n){if(this.__didAwake){if(!this.__didEnable){n!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var n;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((n=this.onDestroy)==null||n.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),e8(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(n){if(this.__destroyed){st()&&console.warn(`[Needle Engine Dev] Trying to ${n?"enable":"disable"} destroyed component`);return}if(typeof n=="number"&&(n>=.5?n=!0:n=!1),!this.__didAwake){this.__isEnabled=n;return}n?this.__internalEnable():this.__internalDisable()}get worldPosition(){return Bt(this.gameObject)}set worldPosition(n){lr(this.gameObject,n)}setWorldPosition(n,e,t){_p(this.gameObject,n,e,t)}get worldQuaternion(){return Mi(this.gameObject)}set worldQuaternion(n){ca(this.gameObject,n)}setWorldQuaternion(n,e,t,r){wR(this.gameObject,n,e,t,r)}get worldEuler(){return CR(this.gameObject)}set worldEuler(n){ER(this.gameObject,n)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(n){this.setWorldRotation(n.x,n.y,n.z,!0)}setWorldRotation(n,e,t,r=!0){Xv(this.gameObject,n,e,t,r)}get forward(){return Xu._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return Xu._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return Xu._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(n,e){this._eventListeners[n]=this._eventListeners[n]||[],this._eventListeners[n].push(e)}removeEventListener(n,e){if(!this._eventListeners[n])return;const t=this._eventListeners[n].indexOf(e);t>=0&&this._eventListeners[n].splice(t,1)}dispatchEvent(n){if(!n||!this._eventListeners[n.type])return!1;const e=this._eventListeners[n.type];for(let t=0;t<e.length;t++)e[t](n);return!1}},d(Xu,"_forward",new C),d(Xu,"_right",new C),d(Xu,"_up",new C),Xu);const rpe=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:Be,Component:Be,GameObject:ie},Symbol.toStringTag,{value:"Module"}));var spe=Object.defineProperty,ope=Object.getOwnPropertyDescriptor,r8=(n,e,t,r)=>{for(var s=r>1?void 0:r?ope(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&spe(e,t,s),s};class vA extends Be{constructor(){super(...arguments),d(this,"from"),d(this,"to"),d(this,"width",0),d(this,"centered",!0),d(this,"_centerPos")}awake(){this._centerPos=new C}update(){if(!this.from||!this.to)return;const e=Bt(this.from).clone(),t=Bt(this.to).clone(),r=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),lr(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(Bt(this.to).clone()),this.gameObject.scale.set(this.width,this.width,r)}}r8([w(ie)],vA.prototype,"from",2),r8([w(ie)],vA.prototype,"to",2);var ape=Object.defineProperty,lpe=Object.getOwnPropertyDescriptor,em=(n,e,t,r)=>{for(var s=r>1?void 0:r?lpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ape(e,t,s),s};const tm=te("debuganimation");let s8=class{constructor(){d(this,"x"),d(this,"y")}};class Es extends Be{constructor(){super(...arguments),d(this,"playAutomatically",!0),d(this,"randomStartTime",!0),d(this,"minMaxSpeed"),d(this,"minMaxOffsetNormalized"),d(this,"loop",!0),d(this,"clampWhenFinished",!1),d(this,"_tempAnimationClipBeforeGameObjectExisted",null),d(this,"_tempAnimationsArray"),d(this,"mixer"),d(this,"_actions",[]),d(this,"_handles",[]),d(this,"_didInit",!1)}get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.push(e)}get clip(){var e;return(e=this.animations)!=null&&e.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){tm&&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(){tm&&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.playAutomatically&&this.init()}onEnable(){var e;if(this.playAutomatically&&((e=this.animations)==null?void 0:e.length)>0){const t=Math.floor(Math.random()*this.animations.length),r=this.animations[t];this.play(t,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*r.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&this.mixer.update(this.context.time.deltaTime)}onDisable(){this.mixer&&(this.mixer.stopAllAction(),this.mixer=void 0)}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){var t;return((t=this.actions)==null?void 0:t.find(r=>r.getClip().name===e))||null}get isPlaying(){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0;return!1}stopAll(e){for(const t of this.actions)e!=null&&e.fadeDuration?t.fadeOut(e.fadeDuration):t.stop()}stop(e,t){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){tm&&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 r=this.actions.find(s=>s.getClip()===e);if(!r){console.error("Could not find action",e);return}t!=null&&t.fadeDuration?r.fadeOut(t.fadeDuration):r.stop()}play(e=0,t){if(tm&&console.log("PLAY",e),this.init(),!this.mixer){tm&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let r=e;if(typeof e=="number"){if(e>=this.animations.length){tm&&console.log("No animation at index",e);return}r=this.animations[e]}else typeof e=="string"&&(r=this.animations.find(o=>o.name===e));if(!r){console.error("Could not find clip",e);return}t||(t={});for(const o of this.actions)if(o.getClip()===r)return this.internalOnPlay(o,t);if(!r.tracks){console.warn("Clip is no AnimationClip",r);return}const s=this.mixer.clipAction(r);return this.actions.push(s),this.internalOnPlay(s,t)}internalOnPlay(e,t){var r=this.actions.find(o=>o===e);if(r===e&&r.isRunning()&&r.time<r.getClip().duration){const o=this.tryFindHandle(e);if(o)return o.waitForFinish()}if(t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed),t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),(t?.exclusive??!0)&&this.stopAll(t),t!=null&&t.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t!=null&&t.minMaxOffsetNormalized){const o=e.getClip();e.time=it.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*o.duration}else t?.startTime!=null&&(e.time=t.startTime);t!=null&&t.minMaxSpeed?e.timeScale=it.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?HM:nv:e.loop=nv,t!=null&&t.clampWhenFinished&&(e.clampWhenFinished=!0),e.play(),tm&&console.log("PLAY",e.getClip().name,e);const s=new cpe(e,this.mixer,t,o=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new zx(this.gameObject),this.context.animations.registerAnimationMixer(this.mixer)))}}em([w()],Es.prototype,"playAutomatically",2),em([w()],Es.prototype,"randomStartTime",2),em([w(s8)],Es.prototype,"minMaxSpeed",2),em([w(s8)],Es.prototype,"minMaxOffsetNormalized",2),em([w()],Es.prototype,"loop",2),em([w()],Es.prototype,"clampWhenFinished",2),em([w(zs)],Es.prototype,"clips",1);class cpe{constructor(e,t,r,s){d(this,"mixer"),d(this,"action"),d(this,"promise",null),d(this,"resolve",null),d(this,"reject",null),d(this,"_options"),d(this,"_resolveCallback",null),d(this,"_rejectCallback",null),d(this,"_loopCallback"),d(this,"_finishedCallback"),d(this,"_resolvedOrRejectedCallback"),this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=s,this._options=r}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),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 e,t;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(t=this._resolveCallback)==null||t.call(this,this.action)}onReject(e){var t,r;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(r=this._rejectCallback)==null||r.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}}var hpe=Object.defineProperty,upe=Object.getOwnPropertyDescriptor,qu=(n,e,t,r)=>{for(var s=r>1?void 0:r?upe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&hpe(e,t,s),s};class Ea{constructor(){d(this,"time"),d(this,"value"),d(this,"inTangent"),d(this,"inWeight"),d(this,"outTangent"),d(this,"outWeight"),d(this,"weightedMode")}}qu([w()],Ea.prototype,"time",2),qu([w()],Ea.prototype,"value",2),qu([w()],Ea.prototype,"inTangent",2),qu([w()],Ea.prototype,"inWeight",2),qu([w()],Ea.prototype,"outTangent",2),qu([w()],Ea.prototype,"outWeight",2),qu([w()],Ea.prototype,"weightedMode",2);const sk=class{constructor(){d(this,"keys")}clone(){var n;const e=new sk;return e.keys=((n=this.keys)==null?void 0:n.map(t=>{const r=new Ea;return r.time=t.time,r.value=t.value,r.inTangent=t.inTangent,r.inWeight=t.inWeight,r.outTangent=t.outTangent,r.outWeight=t.outWeight,r.weightedMode=t.weightedMode,r}))||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(n){if(!this.keys||this.keys.length==0)return 0;if(this.keys[0].time>=n)return this.keys[0].value;for(let e=0;e<this.keys.length;e++){const t=this.keys[e];if(t.time<=n)if(e+1<this.keys.length){const r=this.keys[e+1];if(r.time<n)continue;return!isFinite(t.outTangent)||!isFinite(r.inTangent)?t.value:sk.interpolateValue(n,t,r)}else return t.value}return this.keys[this.keys.length-1].value}static interpolateValue(n,e,t){const r=e.time,s=e.value,o=e.outTangent,a=t.time,l=t.value,c=t.inTangent,h=a-r,u=h*h,p=u*h,m=((o+c)*h-2*(l-s))/p,f=(3*(l-s)-(c+2*o)*h)/u,g=o,v=s,y=n-r,A=y*y,_=A*y;return m*_+f*A+g*y+v}};let im=sk;qu([w(Ea)],im.prototype,"keys",2);class Qg{constructor(e,t){d(this,"method"),d(this,"enabled"),this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}}const dpe=n=>/^[A-Z]*$/.test(n);class BS extends Event{constructor(){super(...arguments),d(this,"args")}}class Un{constructor(e){d(this,"isEventList",!0),d(this,"target"),d(this,"key"),d(this,"_isInvoking",!1),d(this,"methods",[]),d(this,"_methodsCopy",[]),this.methods=e??[]}setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let r="",s=!1;for(const o of this.key)s&&dpe(o)&&(r+="-"),s=!0,r+=o.toLowerCase();this.key=r}}get listenerCount(){var e;return((e=this.methods)==null?void 0:e.length)??0}get isInvoking(){return this._isInvoking}invoke(...e){var t;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((t=this.methods)==null?void 0:t.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const r of this._methodsCopy)r.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const r=this.target.dispatchEvent;if(typeof r=="function"){const s=new BS(this.key);s.args=e,r.call(this.target,s)}}}finally{this._isInvoking=!1}return!0}addEventListener(e){return this.methods.push(new Qg(e,!0)),e}removeEventListener(e){if(e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}}class Si extends xe{constructor(e,t,r,s){super(e,t,r),d(this,"alpha",1),this.alpha=s}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,t){const r=e;return r.alpha!=null&&(this.alpha=it.lerp(this.alpha,r.alpha,t)),super.lerp(e,t)}lerpColors(e,t,r){const s=e,o=t;return s.alpha!=null&&o.alpha!=null&&(this.alpha=it.lerp(s.alpha,o.alpha,r)),super.lerpColors(e,t,r)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}}const o8=Symbol("previous-visibility"),yA=class extends Wt{render(n,e,t){if(t instanceof JP)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else{this.onBeforeRender();const r=t.getRenderTarget(),s=t.xr.enabled;t.xr.enabled=!1,t.setRenderTarget(this),t.clear(!0,!0,!0),t.render(n,e),t.setRenderTarget(r),t.xr.enabled=s,this.onAfterRender()}}onBeforeRender(){yA._userSet.clear();const n=NP(this.texture,!0,null,yA._userSet);for(const e of n)e instanceof me&&(e[o8]=e.visible,e.visible=!1)}onAfterRender(){for(const n of yA._userSet)n instanceof me&&(n.visible=n[o8]);yA._userSet.clear()}};let Hg=yA;d(Hg,"_userSet",new Set);class ppe extends wa{constructor(){super([xe,Si],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new Si(e.r,e.g,e.b,e.a):e.alpha!==void 0?new Si(e.r,e.g,e.b,e.alpha):new xe(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}}const mpe=new ppe;class fpe extends wa{constructor(){super([ii],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new ii(e.x,e.y,e.z,e.order);if(e.x!=null)return new ii(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const gpe=new fpe;class vpe extends wa{constructor(){super(ye,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const r=t.objectToNode[e.uuid];return xr&&console.log(r,e.name,e.uuid),{node:r}}}onDeserialize(e,t){var r,s,o;if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(ti))return;st()&&Di("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const a=(s=(r=t.target)==null?void 0:r.constructor)==null?void 0:s.name;console.warn(`Wrong usage of @serializable detected in your script "${a}"
5659
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,e))),Z8()&&console.log("[onGetComponent] FIND",e),e==null))return null;for(let s=0;s<n.userData.components.length;s++){const o=n.userData.components[s];let a=Object.getPrototypeOf(o);for(;a;){if(a===e.prototype)if(Z8()&&console.log("[onGetComponent] MATCH BY PROTOYPE",a),t)t.push(o);else return o;a=Object.getPrototypeOf(a)}}return t||null}function $p(n,e){const t=iV(n,e);return t?Array.isArray(t)?t[0]:t:null}function mA(n,e,t,r=!0){return t||(t=[]),r&&(t.length=0),iV(n,e,t),t}function fA(n,e,t){var r;const s=$p(n,e);if(t===!1&&s?.enabled===!1)return null;if(s)return s;for(let o=0;o<((r=n?.children)==null?void 0:r.length);o++){const a=fA(n.children[o],e);if(a)return a}return null}function Vg(n,e,t,r=!0){var s;t||(t=[]),r&&(t.length=0),mA(n,e,t,!1);for(let o=0;o<((s=n?.children)==null?void 0:s.length);o++)Vg(n.children[o],e,t,!1);return t}function gA(n,e){if(!n)return null;if(Array.isArray(n)){for(let r=0;r<n.length;r++){const s=npe(n[r]),o=gA(s,e);if(o)return o}return null}return $p(n,e)||(n.parent?gA(n.parent,e):null)}function RS(n,e,t,r=!0){return t||(t=[]),r&&(t.length=0),n?(mA(n,e,t,!1),n.parent?RS(n.parent,e,t,!1):t):t}function PS(n,e=void 0,t=!0){if(!n)return null;if(!e&&(e=kt.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let r=e;if(r.isScene||(r=e?.scene),!r)return null;for(const s in r.children){const o=r.children[s];if(t===!1&&o[$c]===!1)continue;const a=fA(o,n);if(a)return a}return null}function nV(n,e,t=void 0){if(!n)return e;if(e||(e=[]),e.length=0,!t&&(t=kt.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;"scene"in t&&(t=t.scene);const r=t;if(!r)return e;for(const s in r.children){const o=r.children[s];Vg(o,n,e,!1)}return e}class ie extends ye{constructor(){super(...arguments),d(this,"guid")}static isDestroyed(e){return Jp(e)}static setActive(e,t,r=!0){e&&(uA(e,t),k1(e),t&&r&&N5(kt.Current,e))}static isActiveSelf(e){return jg(e)}static isActiveInHierarchy(e){return Q8(e)}static markAsInstancedRendered(e,t){H8(e,t)}static isUsingInstancing(e){return CS(e)}static foreachComponent(e,t,r=!0){return Kp(e,t,r)}static instantiateSynced(e,t){return e?ek(e,t):null}static instantiate(e,t=null){return Gg(e,t)}static destroySynced(e,t,r=!0){if(!e)return;const s=e;t=t??kt.Current,hA(s,t.connection,r)}static destroy(e,t=!0){return Ca(e,t)}static add(e,t,r){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}r||(r=kt.Current),t.add(e),uA(e,!0),k1(e),r?ie.foreachComponent(e,s=>{GP(s,r),!s.__internalDidAwakeAndStart&&r.new_script_start.includes(s)===!1&&r.new_script_start.push(s)},!0):console.warn("Missing context")}}static remove(e){var t;e&&((t=e.parent)==null||t.remove(e),uA(e,!1),k1(e),ie.foreachComponent(e,r=>{Ble(r)},!0))}static invokeOnChildren(e,t,...r){this.invoke(e,t,!0,r)}static invoke(e,t,r=!1,...s){e&&this.foreachComponent(e,o=>{const a=o[t];a&&typeof a=="function"&&a?.call(o,...s)},r)}static addNewComponent(e,t,r,s=!0){return gl(e,t,r,{callAwake:s})}static addComponent(e,t,r,s){return gl(e,t,r,s)}static moveComponent(e,t){return gl(e,t)}static removeComponent(e){return rk(e.gameObject,e),e}static getOrAddComponent(e,t){return pA(e,t)}static getComponent(e,t){return e===null?null:$p(e,t)}static getComponents(e,t,r=null){return e===null?r??[]:mA(e,t,r)}static findByGuid(e,t){return dA(e,t)}static findObjectOfType(e,t,r=!0){return PS(e,t??kt.Current,r)}static findObjectsOfType(e,t){const r=[];return nV(e,r,t),r}static getComponentInChildren(e,t){return fA(e,t)}static getComponentsInChildren(e,t,r=null){return Vg(e,t,r??void 0)}static getComponentInParent(e,t){return gA(e,t)}static getComponentsInParent(e,t,r=null){return RS(e,t,r)}static getAllComponents(e){var t;return[...(t=e.userData)==null?void 0:t.components]}static*iterateComponents(e){var t;const r=(t=e?.userData)==null?void 0:t.components;if(r&&Array.isArray(r))for(let s=0;s<r.length;s++)yield r[s]}}var Xu;let Be=(Xu=class{constructor(n){d(this,"__context"),d(this,"__name"),d(this,"gameObject"),d(this,"guid","invalid"),d(this,"sourceId"),d(this,"__didAwake",!1),d(this,"__didStart",!1),d(this,"__didEnable",!1),d(this,"__isEnabled"),d(this,"__destroyed",!1),d(this,"_eventListeners",new Map),this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(n)}get isComponent(){return!0}get context(){return this.__context??kt.Current}set context(n){this.__context=n}get scene(){return this.context.scene}get layer(){var n,e;return(e=(n=this.gameObject)==null?void 0:n.userData)==null?void 0:e.layer}get name(){var n,e;return(n=this.gameObject)!=null&&n.name?this.gameObject.name:(e=this.gameObject)==null?void 0:e.userData.name}set name(n){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=n,this.__name=n):this.__name=n}get tag(){var n;return(n=this.gameObject)==null?void 0:n.userData.tag}set tag(n){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=n)}get static(){var n;return(n=this.gameObject)==null?void 0:n.userData.static}set static(n){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=n)}get hideFlags(){var n;return(n=this.gameObject)==null?void 0:n.userData.hideFlags}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const n=this.gameObject[$c];return n===void 0?!0:n}set __isActiveInHierarchy(n){this.gameObject&&(this.gameObject[$c]=n)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(n,e=Hi.Update){return this.context.registerCoroutineUpdate(this,n,e)}stopCoroutine(n,e=Hi.Update){this.context.unregisterCoroutineUpdate(n,e)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(n){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(n),this}_internalInit(n){if(typeof n=="object")for(const e of Object.keys(n)){const t=n[e];typeof t!="function"&&(this[e]=t)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(n){return this.__destroyed?(st()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(n!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(n){if(this.__didAwake){if(!this.__didEnable){n!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var n;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((n=this.onDestroy)==null||n.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),eV(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(n){if(this.__destroyed){st()&&console.warn(`[Needle Engine Dev] Trying to ${n?"enable":"disable"} destroyed component`);return}if(typeof n=="number"&&(n>=.5?n=!0:n=!1),!this.__didAwake){this.__isEnabled=n;return}n?this.__internalEnable():this.__internalDisable()}get worldPosition(){return Bt(this.gameObject)}set worldPosition(n){lr(this.gameObject,n)}setWorldPosition(n,e,t){_p(this.gameObject,n,e,t)}get worldQuaternion(){return Mi(this.gameObject)}set worldQuaternion(n){ca(this.gameObject,n)}setWorldQuaternion(n,e,t,r){wR(this.gameObject,n,e,t,r)}get worldEuler(){return CR(this.gameObject)}set worldEuler(n){ER(this.gameObject,n)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(n){this.setWorldRotation(n.x,n.y,n.z,!0)}setWorldRotation(n,e,t,r=!0){Xv(this.gameObject,n,e,t,r)}get forward(){return Xu._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return Xu._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return Xu._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(n,e){this._eventListeners[n]=this._eventListeners[n]||[],this._eventListeners[n].push(e)}removeEventListener(n,e){if(!this._eventListeners[n])return;const t=this._eventListeners[n].indexOf(e);t>=0&&this._eventListeners[n].splice(t,1)}dispatchEvent(n){if(!n||!this._eventListeners[n.type])return!1;const e=this._eventListeners[n.type];for(let t=0;t<e.length;t++)e[t](n);return!1}},d(Xu,"_forward",new C),d(Xu,"_right",new C),d(Xu,"_up",new C),Xu);const rpe=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:Be,Component:Be,GameObject:ie},Symbol.toStringTag,{value:"Module"}));var spe=Object.defineProperty,ope=Object.getOwnPropertyDescriptor,rV=(n,e,t,r)=>{for(var s=r>1?void 0:r?ope(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&spe(e,t,s),s};class vA extends Be{constructor(){super(...arguments),d(this,"from"),d(this,"to"),d(this,"width",0),d(this,"centered",!0),d(this,"_centerPos")}awake(){this._centerPos=new C}update(){if(!this.from||!this.to)return;const e=Bt(this.from).clone(),t=Bt(this.to).clone(),r=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),lr(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(Bt(this.to).clone()),this.gameObject.scale.set(this.width,this.width,r)}}rV([w(ie)],vA.prototype,"from",2),rV([w(ie)],vA.prototype,"to",2);var ape=Object.defineProperty,lpe=Object.getOwnPropertyDescriptor,em=(n,e,t,r)=>{for(var s=r>1?void 0:r?lpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ape(e,t,s),s};const tm=te("debuganimation");let sV=class{constructor(){d(this,"x"),d(this,"y")}};class Es extends Be{constructor(){super(...arguments),d(this,"playAutomatically",!0),d(this,"randomStartTime",!0),d(this,"minMaxSpeed"),d(this,"minMaxOffsetNormalized"),d(this,"loop",!0),d(this,"clampWhenFinished",!1),d(this,"_tempAnimationClipBeforeGameObjectExisted",null),d(this,"_tempAnimationsArray"),d(this,"mixer"),d(this,"_actions",[]),d(this,"_handles",[]),d(this,"_didInit",!1)}get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.push(e)}get clip(){var e;return(e=this.animations)!=null&&e.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){tm&&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(){tm&&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.playAutomatically&&this.init()}onEnable(){var e;if(this.playAutomatically&&((e=this.animations)==null?void 0:e.length)>0){const t=Math.floor(Math.random()*this.animations.length),r=this.animations[t];this.play(t,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*r.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&this.mixer.update(this.context.time.deltaTime)}onDisable(){this.mixer&&(this.mixer.stopAllAction(),this.mixer=void 0)}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){var t;return((t=this.actions)==null?void 0:t.find(r=>r.getClip().name===e))||null}get isPlaying(){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0;return!1}stopAll(e){for(const t of this.actions)e!=null&&e.fadeDuration?t.fadeOut(e.fadeDuration):t.stop()}stop(e,t){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){tm&&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 r=this.actions.find(s=>s.getClip()===e);if(!r){console.error("Could not find action",e);return}t!=null&&t.fadeDuration?r.fadeOut(t.fadeDuration):r.stop()}play(e=0,t){if(tm&&console.log("PLAY",e),this.init(),!this.mixer){tm&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let r=e;if(typeof e=="number"){if(e>=this.animations.length){tm&&console.log("No animation at index",e);return}r=this.animations[e]}else typeof e=="string"&&(r=this.animations.find(o=>o.name===e));if(!r){console.error("Could not find clip",e);return}t||(t={});for(const o of this.actions)if(o.getClip()===r)return this.internalOnPlay(o,t);if(!r.tracks){console.warn("Clip is no AnimationClip",r);return}const s=this.mixer.clipAction(r);return this.actions.push(s),this.internalOnPlay(s,t)}internalOnPlay(e,t){var r=this.actions.find(o=>o===e);if(r===e&&r.isRunning()&&r.time<r.getClip().duration){const o=this.tryFindHandle(e);if(o)return o.waitForFinish()}if(t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed),t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),(t?.exclusive??!0)&&this.stopAll(t),t!=null&&t.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t!=null&&t.minMaxOffsetNormalized){const o=e.getClip();e.time=it.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*o.duration}else t?.startTime!=null&&(e.time=t.startTime);t!=null&&t.minMaxSpeed?e.timeScale=it.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?HM:nv:e.loop=nv,t!=null&&t.clampWhenFinished&&(e.clampWhenFinished=!0),e.play(),tm&&console.log("PLAY",e.getClip().name,e);const s=new cpe(e,this.mixer,t,o=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new zx(this.gameObject),this.context.animations.registerAnimationMixer(this.mixer)))}}em([w()],Es.prototype,"playAutomatically",2),em([w()],Es.prototype,"randomStartTime",2),em([w(sV)],Es.prototype,"minMaxSpeed",2),em([w(sV)],Es.prototype,"minMaxOffsetNormalized",2),em([w()],Es.prototype,"loop",2),em([w()],Es.prototype,"clampWhenFinished",2),em([w(zs)],Es.prototype,"clips",1);class cpe{constructor(e,t,r,s){d(this,"mixer"),d(this,"action"),d(this,"promise",null),d(this,"resolve",null),d(this,"reject",null),d(this,"_options"),d(this,"_resolveCallback",null),d(this,"_rejectCallback",null),d(this,"_loopCallback"),d(this,"_finishedCallback"),d(this,"_resolvedOrRejectedCallback"),this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=s,this._options=r}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),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 e,t;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(t=this._resolveCallback)==null||t.call(this,this.action)}onReject(e){var t,r;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(r=this._rejectCallback)==null||r.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}}var hpe=Object.defineProperty,upe=Object.getOwnPropertyDescriptor,qu=(n,e,t,r)=>{for(var s=r>1?void 0:r?upe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&hpe(e,t,s),s};class Ea{constructor(){d(this,"time"),d(this,"value"),d(this,"inTangent"),d(this,"inWeight"),d(this,"outTangent"),d(this,"outWeight"),d(this,"weightedMode")}}qu([w()],Ea.prototype,"time",2),qu([w()],Ea.prototype,"value",2),qu([w()],Ea.prototype,"inTangent",2),qu([w()],Ea.prototype,"inWeight",2),qu([w()],Ea.prototype,"outTangent",2),qu([w()],Ea.prototype,"outWeight",2),qu([w()],Ea.prototype,"weightedMode",2);const sk=class{constructor(){d(this,"keys")}clone(){var n;const e=new sk;return e.keys=((n=this.keys)==null?void 0:n.map(t=>{const r=new Ea;return r.time=t.time,r.value=t.value,r.inTangent=t.inTangent,r.inWeight=t.inWeight,r.outTangent=t.outTangent,r.outWeight=t.outWeight,r.weightedMode=t.weightedMode,r}))||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(n){if(!this.keys||this.keys.length==0)return 0;if(this.keys[0].time>=n)return this.keys[0].value;for(let e=0;e<this.keys.length;e++){const t=this.keys[e];if(t.time<=n)if(e+1<this.keys.length){const r=this.keys[e+1];if(r.time<n)continue;return!isFinite(t.outTangent)||!isFinite(r.inTangent)?t.value:sk.interpolateValue(n,t,r)}else return t.value}return this.keys[this.keys.length-1].value}static interpolateValue(n,e,t){const r=e.time,s=e.value,o=e.outTangent,a=t.time,l=t.value,c=t.inTangent,h=a-r,u=h*h,p=u*h,m=((o+c)*h-2*(l-s))/p,f=(3*(l-s)-(c+2*o)*h)/u,g=o,v=s,y=n-r,A=y*y,_=A*y;return m*_+f*A+g*y+v}};let im=sk;qu([w(Ea)],im.prototype,"keys",2);class Qg{constructor(e,t){d(this,"method"),d(this,"enabled"),this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}}const dpe=n=>/^[A-Z]*$/.test(n);class BS extends Event{constructor(){super(...arguments),d(this,"args")}}class Un{constructor(e){d(this,"isEventList",!0),d(this,"target"),d(this,"key"),d(this,"_isInvoking",!1),d(this,"methods",[]),d(this,"_methodsCopy",[]),this.methods=e??[]}setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let r="",s=!1;for(const o of this.key)s&&dpe(o)&&(r+="-"),s=!0,r+=o.toLowerCase();this.key=r}}get listenerCount(){var e;return((e=this.methods)==null?void 0:e.length)??0}get isInvoking(){return this._isInvoking}invoke(...e){var t;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((t=this.methods)==null?void 0:t.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const r of this._methodsCopy)r.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const r=this.target.dispatchEvent;if(typeof r=="function"){const s=new BS(this.key);s.args=e,r.call(this.target,s)}}}finally{this._isInvoking=!1}return!0}addEventListener(e){return this.methods.push(new Qg(e,!0)),e}removeEventListener(e){if(e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}}class Si extends xe{constructor(e,t,r,s){super(e,t,r),d(this,"alpha",1),this.alpha=s}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,t){const r=e;return r.alpha!=null&&(this.alpha=it.lerp(this.alpha,r.alpha,t)),super.lerp(e,t)}lerpColors(e,t,r){const s=e,o=t;return s.alpha!=null&&o.alpha!=null&&(this.alpha=it.lerp(s.alpha,o.alpha,r)),super.lerpColors(e,t,r)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}}const oV=Symbol("previous-visibility"),yA=class extends Wt{render(n,e,t){if(t instanceof JP)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else{this.onBeforeRender();const r=t.getRenderTarget(),s=t.xr.enabled;t.xr.enabled=!1,t.setRenderTarget(this),t.clear(!0,!0,!0),t.render(n,e),t.setRenderTarget(r),t.xr.enabled=s,this.onAfterRender()}}onBeforeRender(){yA._userSet.clear();const n=NP(this.texture,!0,null,yA._userSet);for(const e of n)e instanceof me&&(e[oV]=e.visible,e.visible=!1)}onAfterRender(){for(const n of yA._userSet)n instanceof me&&(n.visible=n[oV]);yA._userSet.clear()}};let Hg=yA;d(Hg,"_userSet",new Set);class ppe extends wa{constructor(){super([xe,Si],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new Si(e.r,e.g,e.b,e.a):e.alpha!==void 0?new Si(e.r,e.g,e.b,e.alpha):new xe(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}}const mpe=new ppe;class fpe extends wa{constructor(){super([ii],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new ii(e.x,e.y,e.z,e.order);if(e.x!=null)return new ii(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const gpe=new fpe;class vpe extends wa{constructor(){super(ye,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const r=t.objectToNode[e.uuid];return xr&&console.log(r,e.name,e.uuid),{node:r}}}onDeserialize(e,t){var r,s,o;if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(ti))return;st()&&Di("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const a=(s=(r=t.target)==null?void 0:r.constructor)==null?void 0:s.name;console.warn(`Wrong usage of @serializable detected in your script "${a}"
5660
5660
 
5661
5661
  It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
5662
5662
 
@@ -5664,11 +5664,11 @@ To fix this please change your code to:
5664
5664
 
5665
5665
  @serializable(AssetReference)
5666
5666
  ${t.path}! : AssetReference;
5667
- \0`)}return}if(e){if(e.node!==void 0&&t.nodeToObject){const a=t.nodeToObject[e.node];return xr&&console.log("Deserialized object reference?",e,a,t?.nodeToObject),a||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),a}else if(e.guid){if(!t.context){console.error("Missing context");return}let a;const l=(o=t.gltf)==null?void 0:o.scene;return l&&(a=ie.findByGuid(e.guid,l)),a||(a=ie.findByGuid(e.guid,t.context.scene)),a?(a&&a.isComponent===!0&&(xr&&console.warn("Deserialized object reference is a component"),a=a.gameObject),xr&&console.log("Deserialized object reference?",e,a,t?.nodeToObject)):((st()||xr)&&console.warn("Could not resolve object reference",t.path,e,t.target,t.context.scene),e.could_not_resolve=!0),a}}}}const a8=new vpe;class ype extends wa{constructor(){super([Be,Be],"ComponentSerializer")}onSerialize(e,t){if(e!=null&&e.guid)return{guid:e.guid}}onDeserialize(e,t){var r;if(e!=null&&e.guid){if(e.___persistentAsset){xr&&console.log("Skipping component deserialization because it's a persistent asset",e);return}const s=t.path;xr&&console.log(e.guid,t.root,t.object,t.target);let o=this.findObjectForGuid(e.guid,t.root);if(o||t.context&&(o=this.findObjectForGuid(e.guid,(r=t.context)==null?void 0:r.scene),o))return o;(st()||xr)&&console.warn('Could not resolve component reference: "'+s+'" using guid '+e.guid,t.target),e.could_not_resolve=!0;return}}findObjectForGuid(e,t){if(t.guid===e)return t;const r=ie.foreachComponent(t,s=>{if(s.guid===e)return s},!1);if(r!==void 0)return r;for(let s=0;s<t.children.length;s++){const o=t.children[s],a=this.findObjectForGuid(e,o);if(a)return a}}}const kS=new ype,Ape=Symbol("eventListDebugInfo");class bpe extends wa{constructor(){super([Un])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){var r,s,o,a;if(typeof e=="function")return new Un([new Qg(e,!0)]);if(e&&e.type==="EventList"){xr&&console.log("DESERIALIZE EVENT",e);const l=new Array;if(e.calls&&Array.isArray(e.calls))for(const u of e.calls){let p=function(A){if(typeof A=="object"){let _=a8.onDeserialize(A,t);if(_||(_=kS.onDeserialize(A,t)),_)return _}return A};xr&&console.log(u);let m=kS.findObjectForGuid(u.target,t.root);!m&&(r=t.context)!=null&&r.scene&&(m=kS.findObjectForGuid(u.target,(s=t.context)==null?void 0:s.scene));const f=((o=u.method)==null?void 0:o.length)>0;if(m&&f){const A=()=>{const _=u.method[0].toUpperCase()+u.method.slice(1);if(typeof m[_]=="function"){console.warn(`EventList method:
5667
+ \0`)}return}if(e){if(e.node!==void 0&&t.nodeToObject){const a=t.nodeToObject[e.node];return xr&&console.log("Deserialized object reference?",e,a,t?.nodeToObject),a||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),a}else if(e.guid){if(!t.context){console.error("Missing context");return}let a;const l=(o=t.gltf)==null?void 0:o.scene;return l&&(a=ie.findByGuid(e.guid,l)),a||(a=ie.findByGuid(e.guid,t.context.scene)),a?(a&&a.isComponent===!0&&(xr&&console.warn("Deserialized object reference is a component"),a=a.gameObject),xr&&console.log("Deserialized object reference?",e,a,t?.nodeToObject)):((st()||xr)&&console.warn("Could not resolve object reference",t.path,e,t.target,t.context.scene),e.could_not_resolve=!0),a}}}}const aV=new vpe;class ype extends wa{constructor(){super([Be,Be],"ComponentSerializer")}onSerialize(e,t){if(e!=null&&e.guid)return{guid:e.guid}}onDeserialize(e,t){var r;if(e!=null&&e.guid){if(e.___persistentAsset){xr&&console.log("Skipping component deserialization because it's a persistent asset",e);return}const s=t.path;xr&&console.log(e.guid,t.root,t.object,t.target);let o=this.findObjectForGuid(e.guid,t.root);if(o||t.context&&(o=this.findObjectForGuid(e.guid,(r=t.context)==null?void 0:r.scene),o))return o;(st()||xr)&&console.warn('Could not resolve component reference: "'+s+'" using guid '+e.guid,t.target),e.could_not_resolve=!0;return}}findObjectForGuid(e,t){if(t.guid===e)return t;const r=ie.foreachComponent(t,s=>{if(s.guid===e)return s},!1);if(r!==void 0)return r;for(let s=0;s<t.children.length;s++){const o=t.children[s],a=this.findObjectForGuid(e,o);if(a)return a}}}const kS=new ype,Ape=Symbol("eventListDebugInfo");class bpe extends wa{constructor(){super([Un])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){var r,s,o,a;if(typeof e=="function")return new Un([new Qg(e,!0)]);if(e&&e.type==="EventList"){xr&&console.log("DESERIALIZE EVENT",e);const l=new Array;if(e.calls&&Array.isArray(e.calls))for(const u of e.calls){let p=function(A){if(typeof A=="object"){let _=aV.onDeserialize(A,t);if(_||(_=kS.onDeserialize(A,t)),_)return _}return A};xr&&console.log(u);let m=kS.findObjectForGuid(u.target,t.root);!m&&(r=t.context)!=null&&r.scene&&(m=kS.findObjectForGuid(u.target,(s=t.context)==null?void 0:s.scene));const f=((o=u.method)==null?void 0:o.length)>0;if(m&&f){const A=()=>{const _=u.method[0].toUpperCase()+u.method.slice(1);if(typeof m[_]=="function"){console.warn(`EventList method:
5668
5668
  Could not find method ${u.method} on object ${m.name}. Please rename ${u.method} to ${_}?
5669
5669
  `,m[_],`
5670
5670
  in script: `,m),Di("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
5671
- Could not find method ${u.method} on object ${m.name}`,m,typeof m[u.method])};if(typeof m[u.method]!="function"){let _=!1,b=m;for(;b;){const x=Object.getOwnPropertyDescriptor(b,u.method);if(x&&(x.writable===!0||x.set)){_=!0;break}b=Object.getPrototypeOf(b)}!_&&(st()||xr)&&A()}}let g=u.argument;g!==void 0?g=p(g):u.arguments!==void 0&&(g=u.arguments.map(p));const v=f?this.createEventMethod(m,u.method,g):void 0,y=new Qg(v,u.enabled);if(y.method||(y[Ape]=(a=t.object)==null?void 0:a.name),!m||!y.method){const A=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;m?console.warn('EventList method not found: "'+u.method+'" on',m):console.warn("EventList is missing target - will be ignored",u.target,A,e)}else l.push(y)}const c=new Un(l);xr&&console.log(c);const h=t.target;return h!==void 0&&t.path!==void 0&&c.setEventTarget(t.path,h),c}}createEventMethod(e,t,r){return(...s)=>{const o=e[t];typeof o=="function"?r!==void 0?Array.isArray(r)?o?.call(e,...r):o?.call(e,r):o?.call(e,...s):e[t]=r}}}const _pe=new bpe;class l8 extends wa{constructor(){super([Hg,Wt])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof zt&&t.type===Hg){const r=e,s=new Hg(r.image.width,r.image.height,{colorSpace:Ri});return s.texture=r,r.isRenderTargetTexture=!0,r.flipY=!0,r.offset.y=1,r.repeat.y=-1,r.needsUpdate=!0,r.mipmaps=[],r instanceof ou&&(r.isCompressedTexture=!1,r.format=RGBAFormat),s}}}new l8;class c8 extends wa{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return cu(t.gltfId,e)}}new c8;const h8={type:"change"},ok={type:"start"},u8={type:"end"},DS=new co,d8=new ms,xpe=Math.cos(70*ui.DEG2RAD);let p8=class extends mr{constructor(n,e){super(),this.object=n,this.domElement=e,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new C,this.cursor=new C,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Dd.ROTATE,MIDDLE:Dd.DOLLY,RIGHT:Dd.PAN},this.touches={ONE:Od.ROTATE,TWO:Od.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return a.phi},this.getAzimuthalAngle=function(){return a.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(S){S.addEventListener("keydown",ht),this._domElementKeyEvents=S},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",ht),this._domElementKeyEvents=null},this.saveState=function(){t.target0.copy(t.target),t.position0.copy(t.object.position),t.zoom0=t.object.zoom},this.reset=function(){t.target.copy(t.target0),t.object.position.copy(t.position0),t.object.zoom=t.zoom0,t.object.updateProjectionMatrix(),t.dispatchEvent(h8),t.update(),s=r.NONE},this.update=function(){const S=new C,B=new Ce().setFromUnitVectors(n.up,new C(0,1,0)),j=B.clone().invert(),ee=new C,N=new Ce,Y=new C,W=2*Math.PI;return function(ae=null){const ce=t.object.getWorldPosition(n.position);S.copy(ce).sub(t.target),S.applyQuaternion(B),a.setFromVector3(S),t.autoRotate&&s===r.NONE&&z(M(ae)),t.enableDamping?(a.theta+=l.theta*t.dampingFactor,a.phi+=l.phi*t.dampingFactor):(a.theta+=l.theta,a.phi+=l.phi);let _e=t.minAzimuthAngle,Re=t.maxAzimuthAngle;isFinite(_e)&&isFinite(Re)&&(_e<-Math.PI?_e+=W:_e>Math.PI&&(_e-=W),Re<-Math.PI?Re+=W:Re>Math.PI&&(Re-=W),_e<=Re?a.theta=Math.max(_e,Math.min(Re,a.theta)):a.theta=a.theta>(_e+Re)/2?Math.max(_e,a.theta):Math.min(Re,a.theta)),a.phi=Math.max(t.minPolarAngle,Math.min(t.maxPolarAngle,a.phi)),a.makeSafe(),t.enableDamping===!0?t.target.addScaledVector(u,t.dampingFactor):t.target.add(u),t.target.sub(t.cursor),t.target.clampLength(t.minTargetRadius,t.maxTargetRadius),t.target.add(t.cursor);let Xe=!1;if(t.zoomToCursor&&I||t.object.isOrthographicCamera)a.radius=K(a.radius);else{t.enableDamping?h=ui.lerp(h,c,t.dampingFactor):h=c,a.radius=K(a.radius*h);const We=a.radius;a.radius=K(a.radius*c),Xe=We!=a.radius}if(S.setFromSpherical(a),S.applyQuaternion(j),ce.copy(t.target).add(S),t.object.parent?t.object.parent.worldToLocal(ce):t.object.position.copy(ce),t.object.lookAt(t.target),t.enableDamping===!0?(l.theta*=1-t.dampingFactor,l.phi*=1-t.dampingFactor,u.multiplyScalar(1-t.dampingFactor)):(l.set(0,0,0),u.set(0,0,0)),t.zoomToCursor&&I){let We=null;if(t.object.isPerspectiveCamera){const Ke=S.length();We=K(Ke*c);const gt=Ke-We;t.object.position.addScaledVector(x,gt),t.object.updateMatrixWorld(),Xe=!!gt}else if(t.object.isOrthographicCamera){const Ke=new C(E.x,E.y,0);Ke.unproject(t.object);const gt=t.object.zoom;t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom/c)),t.object.updateProjectionMatrix(),Xe=gt!==t.object.zoom;const rt=new C(E.x,E.y,0);rt.unproject(t.object),t.object.position.sub(rt).add(Ke),t.object.updateMatrixWorld(),We=S.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),t.zoomToCursor=!1;We!==null&&(this.screenSpacePanning?t.target.set(0,0,-1).transformDirection(t.object.matrix).multiplyScalar(We).add(t.object.position):(DS.origin.copy(t.object.position),DS.direction.set(0,0,-1).transformDirection(t.object.matrix),Math.abs(t.object.up.dot(DS.direction))<xpe?n.lookAt(t.target):(d8.setFromNormalAndCoplanarPoint(t.object.up,t.target),DS.intersectPlane(d8,t.target))))}else if(t.object.isOrthographicCamera){const We=t.object.zoom;t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom/c)),We!==t.object.zoom&&(t.object.updateProjectionMatrix(),Xe=!0)}return c=1,I=!1,Xe||ee.distanceToSquared(t.object.position)>o||8*(1-N.dot(t.object.quaternion))>o||Y.distanceToSquared(t.target)>o?(t.dispatchEvent(h8),ee.copy(t.object.position),N.copy(t.object.quaternion),Y.copy(t.target),!0):!1}}(),this.dispose=function(){t.domElement.removeEventListener("contextmenu",St),t.domElement.removeEventListener("pointerdown",ct),t.domElement.removeEventListener("pointercancel",Q),t.domElement.removeEventListener("wheel",Ee),t.domElement.removeEventListener("pointermove",Tt),window.removeEventListener("pointerup",Q),t.domElement.getRootNode().removeEventListener("keydown",Pe,{capture:!0}),t._domElementKeyEvents!==null&&(t._domElementKeyEvents.removeEventListener("keydown",ht),t._domElementKeyEvents=null)};const t=this,r={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let s=r.NONE;const o=1e-6,a=new bI,l=new bI;let c=1,h=1;const u=new C,p=new Z,m=new Z,f=new Z,g=new Z,v=new Z,y=new Z,A=new Z,_=new Z,b=new Z,x=new C,E=new Z;let I=!1;const T=[],R={};let D=!1;function M(S){return S!==null?2*Math.PI/60*t.autoRotateSpeed*S:2*Math.PI/60/60*t.autoRotateSpeed}function P(S){const B=Math.abs(S*.01);return Math.pow(.95,t.zoomSpeed*B)}function z(S){l.theta-=S}function V(S){l.phi-=S}const L=function(){const S=new C;return function(B,j){S.setFromMatrixColumn(j,0),S.multiplyScalar(-B),u.add(S)}}(),H=function(){const S=new C;return function(B,j){t.screenSpacePanning===!0?S.setFromMatrixColumn(j,1):(S.setFromMatrixColumn(j,0),S.crossVectors(t.object.up,S)),S.multiplyScalar(B),u.add(S)}}(),O=function(){const S=new C,B=new C;return function(j,ee){const N=t.domElement;if(t.object.isPerspectiveCamera){t.object.getWorldPosition(B),S.copy(B).sub(t.target);let Y=S.length();Y*=Math.tan(t.object.fov/2*Math.PI/180),L(2*j*Y/N.clientHeight,t.object.matrixWorld),H(2*ee*Y/N.clientHeight,t.object.matrixWorld)}else t.object.isOrthographicCamera?(L(j*(t.object.right-t.object.left)/t.object.zoom/N.clientWidth,t.object.matrixWorld),H(ee*(t.object.top-t.object.bottom)/t.object.zoom/N.clientHeight,t.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),t.enablePan=!1)}}();function F(S){t.object.isPerspectiveCamera||t.object.isOrthographicCamera?c/=S:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function G(S){t.object.isPerspectiveCamera||t.object.isOrthographicCamera?c*=S:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function J(S,B){if(!t.zoomToCursor)return;I=!0;const j=t.domElement.getBoundingClientRect(),ee=S-j.left,N=B-j.top,Y=j.width,W=j.height;E.x=ee/Y*2-1,E.y=-(N/W)*2+1,x.set(E.x,E.y,1).unproject(t.object).sub(t.object.position).normalize()}function K(S){return Math.max(t.minDistance,Math.min(t.maxDistance,S))}function oe(S){p.set(S.clientX,S.clientY)}function we(S){J(S.clientX,S.clientX),A.set(S.clientX,S.clientY)}function De(S){g.set(S.clientX,S.clientY)}function se(S){m.set(S.clientX,S.clientY),f.subVectors(m,p).multiplyScalar(t.rotateSpeed);const B=t.domElement;z(2*Math.PI*f.x/B.clientHeight),V(2*Math.PI*f.y/B.clientHeight),p.copy(m),t.update()}function be(S){_.set(S.clientX,S.clientY),b.subVectors(_,A),b.y>0?F(P(b.y)):b.y<0&&G(P(b.y)),A.copy(_),t.update()}function Ie(S){v.set(S.clientX,S.clientY),y.subVectors(v,g).multiplyScalar(t.panSpeed),O(y.x,y.y),g.copy(v),t.update()}function Je(S){J(S.clientX,S.clientY),S.deltaY<0?G(P(S.deltaY)):S.deltaY>0&&F(P(S.deltaY)),t.update()}function $e(S){let B=!1;switch(S.code){case t.keys.UP:S.ctrlKey||S.metaKey||S.shiftKey?V(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):O(0,t.keyPanSpeed),B=!0;break;case t.keys.BOTTOM:S.ctrlKey||S.metaKey||S.shiftKey?V(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):O(0,-t.keyPanSpeed),B=!0;break;case t.keys.LEFT:S.ctrlKey||S.metaKey||S.shiftKey?z(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):O(t.keyPanSpeed,0),B=!0;break;case t.keys.RIGHT:S.ctrlKey||S.metaKey||S.shiftKey?z(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):O(-t.keyPanSpeed,0),B=!0;break}B&&(S.preventDefault(),t.update())}function Oe(S){if(T.length===1)p.set(S.pageX,S.pageY);else{const B=ut(S),j=.5*(S.pageX+B.x),ee=.5*(S.pageY+B.y);p.set(j,ee)}}function lt(S){if(T.length===1)g.set(S.pageX,S.pageY);else{const B=ut(S),j=.5*(S.pageX+B.x),ee=.5*(S.pageY+B.y);g.set(j,ee)}}function fe(S){const B=ut(S),j=S.pageX-B.x,ee=S.pageY-B.y,N=Math.sqrt(j*j+ee*ee);A.set(0,N)}function X(S){t.enableZoom&&fe(S),t.enablePan&&lt(S)}function ze(S){t.enableZoom&&fe(S),t.enableRotate&&Oe(S)}function Te(S){if(T.length==1)m.set(S.pageX,S.pageY);else{const j=ut(S),ee=.5*(S.pageX+j.x),N=.5*(S.pageY+j.y);m.set(ee,N)}f.subVectors(m,p).multiplyScalar(t.rotateSpeed);const B=t.domElement;z(2*Math.PI*f.x/B.clientHeight),V(2*Math.PI*f.y/B.clientHeight),p.copy(m)}function Me(S){if(T.length===1)v.set(S.pageX,S.pageY);else{const B=ut(S),j=.5*(S.pageX+B.x),ee=.5*(S.pageY+B.y);v.set(j,ee)}y.subVectors(v,g).multiplyScalar(t.panSpeed),O(y.x,y.y),g.copy(v)}function Qe(S){const B=ut(S),j=S.pageX-B.x,ee=S.pageY-B.y,N=Math.sqrt(j*j+ee*ee);_.set(0,N),b.set(0,Math.pow(_.y/A.y,t.zoomSpeed)),F(b.y),A.copy(_);const Y=(S.pageX+B.x)*.5,W=(S.pageY+B.y)*.5;J(Y,W)}function Ae(S){t.enableZoom&&Qe(S),t.enablePan&&Me(S)}function et(S){t.enableZoom&&Qe(S),t.enableRotate&&Te(S)}function ct(S){t.enabled!==!1&&(T.length===0&&(t.domElement.setPointerCapture(S.pointerId),t.domElement.addEventListener("pointermove",Tt),window.addEventListener("pointerup",Q)),!Fe(S)&&(Ue(S),S.pointerType==="touch"?je(S):k(S)))}function Tt(S){t.enabled!==!1&&(S.pointerType==="touch"?Ve(S):he(S))}function Q(S){switch(qt(S),T.length){case 0:t.domElement.releasePointerCapture(S.pointerId),t.domElement.removeEventListener("pointermove",Tt),t.domElement.removeEventListener("pointerup",Q),t.dispatchEvent(u8),s=r.NONE;break;case 1:const B=T[0],j=R[B];je({pointerId:B,pageX:j.x,pageY:j.y});break}}function k(S){let B;switch(S.button){case 0:B=t.mouseButtons.LEFT;break;case 1:B=t.mouseButtons.MIDDLE;break;case 2:B=t.mouseButtons.RIGHT;break;default:B=-1}switch(B){case Dd.DOLLY:if(t.enableZoom===!1)return;we(S),s=r.DOLLY;break;case Dd.ROTATE:if(S.ctrlKey||S.metaKey||S.shiftKey){if(t.enablePan===!1)return;De(S),s=r.PAN}else{if(t.enableRotate===!1)return;oe(S),s=r.ROTATE}break;case Dd.PAN:if(S.ctrlKey||S.metaKey||S.shiftKey){if(t.enableRotate===!1)return;oe(S),s=r.ROTATE}else{if(t.enablePan===!1)return;De(S),s=r.PAN}break;default:s=r.NONE}s!==r.NONE&&t.dispatchEvent(ok)}function he(S){switch(s){case r.ROTATE:if(t.enableRotate===!1)return;se(S);break;case r.DOLLY:if(t.enableZoom===!1)return;be(S);break;case r.PAN:if(t.enablePan===!1)return;Ie(S);break}}function Ee(S){t.enabled===!1||t.enableZoom===!1||s!==r.NONE||(S.preventDefault(),t.dispatchEvent(ok),Je(Le(S)),t.dispatchEvent(u8))}function Le(S){const B=S.deltaMode,j={clientX:S.clientX,clientY:S.clientY,deltaY:S.deltaY};switch(B){case 1:j.deltaY*=16;break;case 2:j.deltaY*=100;break}return S.ctrlKey&&!D&&(j.deltaY*=10),j}function Pe(S){S.key==="Control"&&(D=!0,t.domElement.getRootNode().addEventListener("keyup",vt,{passive:!0,capture:!0}))}function vt(S){S.key==="Control"&&(D=!1,t.domElement.getRootNode().removeEventListener("keyup",vt,{passive:!0,capture:!0}))}function ht(S){t.enabled===!1||t.enablePan===!1||$e(S)}function je(S){switch(_t(S),T.length){case 1:switch(t.touches.ONE){case Od.ROTATE:if(t.enableRotate===!1)return;Oe(S),s=r.TOUCH_ROTATE;break;case Od.PAN:if(t.enablePan===!1)return;lt(S),s=r.TOUCH_PAN;break;default:s=r.NONE}break;case 2:switch(t.touches.TWO){case Od.DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;X(S),s=r.TOUCH_DOLLY_PAN;break;case Od.DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;ze(S),s=r.TOUCH_DOLLY_ROTATE;break;default:s=r.NONE}break;default:s=r.NONE}s!==r.NONE&&t.dispatchEvent(ok)}function Ve(S){switch(_t(S),s){case r.TOUCH_ROTATE:if(t.enableRotate===!1)return;Te(S),t.update();break;case r.TOUCH_PAN:if(t.enablePan===!1)return;Me(S),t.update();break;case r.TOUCH_DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;Ae(S),t.update();break;case r.TOUCH_DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;et(S),t.update();break;default:s=r.NONE}}function St(S){t.enabled!==!1&&S.preventDefault()}function Ue(S){T.push(S.pointerId)}function qt(S){delete R[S.pointerId];for(let B=0;B<T.length;B++)if(T[B]==S.pointerId){T.splice(B,1);return}}function Fe(S){for(let B=0;B<T.length;B++)if(T[B]==S.pointerId)return!0;return!1}function _t(S){let B=R[S.pointerId];B===void 0&&(B=new Z,R[S.pointerId]=B),B.set(S.pageX,S.pageY)}function ut(S){const B=S.pointerId===T[0]?T[1]:T[0];return R[B]}t.domElement.addEventListener("contextmenu",St),t.domElement.addEventListener("pointerdown",ct),t.domElement.addEventListener("pointercancel",Q),t.domElement.addEventListener("wheel",Ee,{passive:!1}),t.domElement.getRootNode().addEventListener("keydown",Pe,{passive:!0,capture:!0}),this.update()}};var wpe=Object.defineProperty,Spe=Object.getOwnPropertyDescriptor,OS=(n,e,t,r)=>{for(var s=r>1?void 0:r?Spe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&wpe(e,t,s),s};const m8=te("debuggroundprojection");class Yu extends Be{constructor(){super(...arguments),d(this,"applyOnAwake",!1),d(this,"autoFit",!0),d(this,"_radius",100),d(this,"_height",3),d(this,"_lastEnvironment"),d(this,"_lastRadius"),d(this,"_lastHeight"),d(this,"_projection"),d(this,"_watcher"),d(this,"_blurrynessShader",null),d(this,"_lastBlurriness",-1)}set radius(e){this._radius=e,this.updateProjection()}get radius(){return this._radius}set height(e){this._height=e,this.updateProjection()}get height(){return this._height}awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new Nh(this.context.scene,"environment"),this._watcher.subscribeWrite(e=>{this.updateProjection()}))}onDisable(){var e,t;(e=this._watcher)==null||e.revoke(),(t=this._projection)==null||t.removeFromParent()}onEnterXR(){this.updateProjection()}onLeaveXR(){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.updateBlurriness()}updateAndCreate(){var e;this.updateProjection(),(e=this._watcher)==null||e.apply()}updateProjection(){var e,t,r;if(!this.context.scene.environment||(e=this.context.xr)!=null&&e.isPassThrough){(t=this._projection)==null||t.removeFromParent();return}const s=.01;if((!this._projection||this.context.scene.environment!==this._lastEnvironment||this._height!==this._lastHeight||this._radius!==this._lastRadius)&&(m8&&console.log("Create/Update Ground Projection",this.context.scene.environment.name),(r=this._projection)==null||r.removeFromParent(),this._projection=new ZN(this.context.scene.environment,this._height,this.radius),this._projection.position.y=this._height-s,this.context.scene.backgroundBlurriness>.001&&this.updateBlurriness()),this._lastEnvironment=this.context.scene.environment,this._lastHeight=this._height,this._lastRadius=this._radius,this._projection.parent||this.gameObject.add(this._projection),this.autoFit){this._projection.updateWorldMatrix(!0,!0);const o=Ul(this.context.scene.children,[this._projection]),a=o.min.y;if(a<1/0){const l=Bt(this._projection);l.x=o.min.x+(o.max.x-o.min.x)*.5,l.y=a+this._height-s,l.z=o.min.z+(o.max.z-o.min.z)*.5,lr(this._projection,l)}}this._projection.isObject3D===!0&&this._projection.layers.set(2)}updateBlurriness(){if(this._projection){if(!this.context.scene.environment)return}else return;m8&&console.log("Update Blurriness",this.context.scene.backgroundBlurriness),this._blurrynessShader??(this._blurrynessShader=new Rt({uniforms:{map:{value:this.context.scene.environment},blurriness:{value:this.context.scene.backgroundBlurriness}},vertexShader:Cpe,fragmentShader:Epe})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.blurriness.value=this.context.scene.backgroundBlurriness,this._lastBlurriness=this.context.scene.backgroundBlurriness,this._projection.material.map=ha.copyTexture(this.context.scene.environment,this._blurrynessShader)}}OS([w()],Yu.prototype,"applyOnAwake",2),OS([w()],Yu.prototype,"autoFit",2),OS([w()],Yu.prototype,"radius",1),OS([w()],Yu.prototype,"height",1);const Cpe=`
5671
+ Could not find method ${u.method} on object ${m.name}`,m,typeof m[u.method])};if(typeof m[u.method]!="function"){let _=!1,b=m;for(;b;){const x=Object.getOwnPropertyDescriptor(b,u.method);if(x&&(x.writable===!0||x.set)){_=!0;break}b=Object.getPrototypeOf(b)}!_&&(st()||xr)&&A()}}let g=u.argument;g!==void 0?g=p(g):u.arguments!==void 0&&(g=u.arguments.map(p));const v=f?this.createEventMethod(m,u.method,g):void 0,y=new Qg(v,u.enabled);if(y.method||(y[Ape]=(a=t.object)==null?void 0:a.name),!m||!y.method){const A=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;m?console.warn('EventList method not found: "'+u.method+'" on',m):console.warn("EventList is missing target - will be ignored",u.target,A,e)}else l.push(y)}const c=new Un(l);xr&&console.log(c);const h=t.target;return h!==void 0&&t.path!==void 0&&c.setEventTarget(t.path,h),c}}createEventMethod(e,t,r){return(...s)=>{const o=e[t];typeof o=="function"?r!==void 0?Array.isArray(r)?o?.call(e,...r):o?.call(e,r):o?.call(e,...s):e[t]=r}}}const _pe=new bpe;class lV extends wa{constructor(){super([Hg,Wt])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof zt&&t.type===Hg){const r=e,s=new Hg(r.image.width,r.image.height,{colorSpace:Ri});return s.texture=r,r.isRenderTargetTexture=!0,r.flipY=!0,r.offset.y=1,r.repeat.y=-1,r.needsUpdate=!0,r.mipmaps=[],r instanceof ou&&(r.isCompressedTexture=!1,r.format=RGBAFormat),s}}}new lV;class cV extends wa{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return cu(t.gltfId,e)}}new cV;const hV={type:"change"},ok={type:"start"},uV={type:"end"},DS=new co,dV=new ms,xpe=Math.cos(70*ui.DEG2RAD);let pV=class extends mr{constructor(n,e){super(),this.object=n,this.domElement=e,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new C,this.cursor=new C,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Dd.ROTATE,MIDDLE:Dd.DOLLY,RIGHT:Dd.PAN},this.touches={ONE:Od.ROTATE,TWO:Od.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return a.phi},this.getAzimuthalAngle=function(){return a.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(S){S.addEventListener("keydown",ht),this._domElementKeyEvents=S},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",ht),this._domElementKeyEvents=null},this.saveState=function(){t.target0.copy(t.target),t.position0.copy(t.object.position),t.zoom0=t.object.zoom},this.reset=function(){t.target.copy(t.target0),t.object.position.copy(t.position0),t.object.zoom=t.zoom0,t.object.updateProjectionMatrix(),t.dispatchEvent(hV),t.update(),s=r.NONE},this.update=function(){const S=new C,B=new Ce().setFromUnitVectors(n.up,new C(0,1,0)),j=B.clone().invert(),ee=new C,N=new Ce,Y=new C,W=2*Math.PI;return function(ae=null){const ce=t.object.getWorldPosition(n.position);S.copy(ce).sub(t.target),S.applyQuaternion(B),a.setFromVector3(S),t.autoRotate&&s===r.NONE&&z(M(ae)),t.enableDamping?(a.theta+=l.theta*t.dampingFactor,a.phi+=l.phi*t.dampingFactor):(a.theta+=l.theta,a.phi+=l.phi);let _e=t.minAzimuthAngle,Re=t.maxAzimuthAngle;isFinite(_e)&&isFinite(Re)&&(_e<-Math.PI?_e+=W:_e>Math.PI&&(_e-=W),Re<-Math.PI?Re+=W:Re>Math.PI&&(Re-=W),_e<=Re?a.theta=Math.max(_e,Math.min(Re,a.theta)):a.theta=a.theta>(_e+Re)/2?Math.max(_e,a.theta):Math.min(Re,a.theta)),a.phi=Math.max(t.minPolarAngle,Math.min(t.maxPolarAngle,a.phi)),a.makeSafe(),t.enableDamping===!0?t.target.addScaledVector(u,t.dampingFactor):t.target.add(u),t.target.sub(t.cursor),t.target.clampLength(t.minTargetRadius,t.maxTargetRadius),t.target.add(t.cursor);let Xe=!1;if(t.zoomToCursor&&I||t.object.isOrthographicCamera)a.radius=K(a.radius);else{t.enableDamping?h=ui.lerp(h,c,t.dampingFactor):h=c,a.radius=K(a.radius*h);const We=a.radius;a.radius=K(a.radius*c),Xe=We!=a.radius}if(S.setFromSpherical(a),S.applyQuaternion(j),ce.copy(t.target).add(S),t.object.parent?t.object.parent.worldToLocal(ce):t.object.position.copy(ce),t.object.lookAt(t.target),t.enableDamping===!0?(l.theta*=1-t.dampingFactor,l.phi*=1-t.dampingFactor,u.multiplyScalar(1-t.dampingFactor)):(l.set(0,0,0),u.set(0,0,0)),t.zoomToCursor&&I){let We=null;if(t.object.isPerspectiveCamera){const Ke=S.length();We=K(Ke*c);const gt=Ke-We;t.object.position.addScaledVector(x,gt),t.object.updateMatrixWorld(),Xe=!!gt}else if(t.object.isOrthographicCamera){const Ke=new C(E.x,E.y,0);Ke.unproject(t.object);const gt=t.object.zoom;t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom/c)),t.object.updateProjectionMatrix(),Xe=gt!==t.object.zoom;const rt=new C(E.x,E.y,0);rt.unproject(t.object),t.object.position.sub(rt).add(Ke),t.object.updateMatrixWorld(),We=S.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),t.zoomToCursor=!1;We!==null&&(this.screenSpacePanning?t.target.set(0,0,-1).transformDirection(t.object.matrix).multiplyScalar(We).add(t.object.position):(DS.origin.copy(t.object.position),DS.direction.set(0,0,-1).transformDirection(t.object.matrix),Math.abs(t.object.up.dot(DS.direction))<xpe?n.lookAt(t.target):(dV.setFromNormalAndCoplanarPoint(t.object.up,t.target),DS.intersectPlane(dV,t.target))))}else if(t.object.isOrthographicCamera){const We=t.object.zoom;t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom/c)),We!==t.object.zoom&&(t.object.updateProjectionMatrix(),Xe=!0)}return c=1,I=!1,Xe||ee.distanceToSquared(t.object.position)>o||8*(1-N.dot(t.object.quaternion))>o||Y.distanceToSquared(t.target)>o?(t.dispatchEvent(hV),ee.copy(t.object.position),N.copy(t.object.quaternion),Y.copy(t.target),!0):!1}}(),this.dispose=function(){t.domElement.removeEventListener("contextmenu",St),t.domElement.removeEventListener("pointerdown",ct),t.domElement.removeEventListener("pointercancel",Q),t.domElement.removeEventListener("wheel",Ee),t.domElement.removeEventListener("pointermove",Tt),window.removeEventListener("pointerup",Q),t.domElement.getRootNode().removeEventListener("keydown",Pe,{capture:!0}),t._domElementKeyEvents!==null&&(t._domElementKeyEvents.removeEventListener("keydown",ht),t._domElementKeyEvents=null)};const t=this,r={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let s=r.NONE;const o=1e-6,a=new bI,l=new bI;let c=1,h=1;const u=new C,p=new Z,m=new Z,f=new Z,g=new Z,v=new Z,y=new Z,A=new Z,_=new Z,b=new Z,x=new C,E=new Z;let I=!1;const T=[],R={};let D=!1;function M(S){return S!==null?2*Math.PI/60*t.autoRotateSpeed*S:2*Math.PI/60/60*t.autoRotateSpeed}function P(S){const B=Math.abs(S*.01);return Math.pow(.95,t.zoomSpeed*B)}function z(S){l.theta-=S}function V(S){l.phi-=S}const L=function(){const S=new C;return function(B,j){S.setFromMatrixColumn(j,0),S.multiplyScalar(-B),u.add(S)}}(),H=function(){const S=new C;return function(B,j){t.screenSpacePanning===!0?S.setFromMatrixColumn(j,1):(S.setFromMatrixColumn(j,0),S.crossVectors(t.object.up,S)),S.multiplyScalar(B),u.add(S)}}(),O=function(){const S=new C,B=new C;return function(j,ee){const N=t.domElement;if(t.object.isPerspectiveCamera){t.object.getWorldPosition(B),S.copy(B).sub(t.target);let Y=S.length();Y*=Math.tan(t.object.fov/2*Math.PI/180),L(2*j*Y/N.clientHeight,t.object.matrixWorld),H(2*ee*Y/N.clientHeight,t.object.matrixWorld)}else t.object.isOrthographicCamera?(L(j*(t.object.right-t.object.left)/t.object.zoom/N.clientWidth,t.object.matrixWorld),H(ee*(t.object.top-t.object.bottom)/t.object.zoom/N.clientHeight,t.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),t.enablePan=!1)}}();function F(S){t.object.isPerspectiveCamera||t.object.isOrthographicCamera?c/=S:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function G(S){t.object.isPerspectiveCamera||t.object.isOrthographicCamera?c*=S:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function J(S,B){if(!t.zoomToCursor)return;I=!0;const j=t.domElement.getBoundingClientRect(),ee=S-j.left,N=B-j.top,Y=j.width,W=j.height;E.x=ee/Y*2-1,E.y=-(N/W)*2+1,x.set(E.x,E.y,1).unproject(t.object).sub(t.object.position).normalize()}function K(S){return Math.max(t.minDistance,Math.min(t.maxDistance,S))}function oe(S){p.set(S.clientX,S.clientY)}function we(S){J(S.clientX,S.clientX),A.set(S.clientX,S.clientY)}function De(S){g.set(S.clientX,S.clientY)}function se(S){m.set(S.clientX,S.clientY),f.subVectors(m,p).multiplyScalar(t.rotateSpeed);const B=t.domElement;z(2*Math.PI*f.x/B.clientHeight),V(2*Math.PI*f.y/B.clientHeight),p.copy(m),t.update()}function be(S){_.set(S.clientX,S.clientY),b.subVectors(_,A),b.y>0?F(P(b.y)):b.y<0&&G(P(b.y)),A.copy(_),t.update()}function Ie(S){v.set(S.clientX,S.clientY),y.subVectors(v,g).multiplyScalar(t.panSpeed),O(y.x,y.y),g.copy(v),t.update()}function Je(S){J(S.clientX,S.clientY),S.deltaY<0?G(P(S.deltaY)):S.deltaY>0&&F(P(S.deltaY)),t.update()}function $e(S){let B=!1;switch(S.code){case t.keys.UP:S.ctrlKey||S.metaKey||S.shiftKey?V(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):O(0,t.keyPanSpeed),B=!0;break;case t.keys.BOTTOM:S.ctrlKey||S.metaKey||S.shiftKey?V(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):O(0,-t.keyPanSpeed),B=!0;break;case t.keys.LEFT:S.ctrlKey||S.metaKey||S.shiftKey?z(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):O(t.keyPanSpeed,0),B=!0;break;case t.keys.RIGHT:S.ctrlKey||S.metaKey||S.shiftKey?z(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):O(-t.keyPanSpeed,0),B=!0;break}B&&(S.preventDefault(),t.update())}function Oe(S){if(T.length===1)p.set(S.pageX,S.pageY);else{const B=ut(S),j=.5*(S.pageX+B.x),ee=.5*(S.pageY+B.y);p.set(j,ee)}}function lt(S){if(T.length===1)g.set(S.pageX,S.pageY);else{const B=ut(S),j=.5*(S.pageX+B.x),ee=.5*(S.pageY+B.y);g.set(j,ee)}}function fe(S){const B=ut(S),j=S.pageX-B.x,ee=S.pageY-B.y,N=Math.sqrt(j*j+ee*ee);A.set(0,N)}function X(S){t.enableZoom&&fe(S),t.enablePan&&lt(S)}function ze(S){t.enableZoom&&fe(S),t.enableRotate&&Oe(S)}function Te(S){if(T.length==1)m.set(S.pageX,S.pageY);else{const j=ut(S),ee=.5*(S.pageX+j.x),N=.5*(S.pageY+j.y);m.set(ee,N)}f.subVectors(m,p).multiplyScalar(t.rotateSpeed);const B=t.domElement;z(2*Math.PI*f.x/B.clientHeight),V(2*Math.PI*f.y/B.clientHeight),p.copy(m)}function Me(S){if(T.length===1)v.set(S.pageX,S.pageY);else{const B=ut(S),j=.5*(S.pageX+B.x),ee=.5*(S.pageY+B.y);v.set(j,ee)}y.subVectors(v,g).multiplyScalar(t.panSpeed),O(y.x,y.y),g.copy(v)}function Qe(S){const B=ut(S),j=S.pageX-B.x,ee=S.pageY-B.y,N=Math.sqrt(j*j+ee*ee);_.set(0,N),b.set(0,Math.pow(_.y/A.y,t.zoomSpeed)),F(b.y),A.copy(_);const Y=(S.pageX+B.x)*.5,W=(S.pageY+B.y)*.5;J(Y,W)}function Ae(S){t.enableZoom&&Qe(S),t.enablePan&&Me(S)}function et(S){t.enableZoom&&Qe(S),t.enableRotate&&Te(S)}function ct(S){t.enabled!==!1&&(T.length===0&&(t.domElement.setPointerCapture(S.pointerId),t.domElement.addEventListener("pointermove",Tt),window.addEventListener("pointerup",Q)),!Fe(S)&&(Ue(S),S.pointerType==="touch"?je(S):k(S)))}function Tt(S){t.enabled!==!1&&(S.pointerType==="touch"?Ve(S):he(S))}function Q(S){switch(qt(S),T.length){case 0:t.domElement.releasePointerCapture(S.pointerId),t.domElement.removeEventListener("pointermove",Tt),t.domElement.removeEventListener("pointerup",Q),t.dispatchEvent(uV),s=r.NONE;break;case 1:const B=T[0],j=R[B];je({pointerId:B,pageX:j.x,pageY:j.y});break}}function k(S){let B;switch(S.button){case 0:B=t.mouseButtons.LEFT;break;case 1:B=t.mouseButtons.MIDDLE;break;case 2:B=t.mouseButtons.RIGHT;break;default:B=-1}switch(B){case Dd.DOLLY:if(t.enableZoom===!1)return;we(S),s=r.DOLLY;break;case Dd.ROTATE:if(S.ctrlKey||S.metaKey||S.shiftKey){if(t.enablePan===!1)return;De(S),s=r.PAN}else{if(t.enableRotate===!1)return;oe(S),s=r.ROTATE}break;case Dd.PAN:if(S.ctrlKey||S.metaKey||S.shiftKey){if(t.enableRotate===!1)return;oe(S),s=r.ROTATE}else{if(t.enablePan===!1)return;De(S),s=r.PAN}break;default:s=r.NONE}s!==r.NONE&&t.dispatchEvent(ok)}function he(S){switch(s){case r.ROTATE:if(t.enableRotate===!1)return;se(S);break;case r.DOLLY:if(t.enableZoom===!1)return;be(S);break;case r.PAN:if(t.enablePan===!1)return;Ie(S);break}}function Ee(S){t.enabled===!1||t.enableZoom===!1||s!==r.NONE||(S.preventDefault(),t.dispatchEvent(ok),Je(Le(S)),t.dispatchEvent(uV))}function Le(S){const B=S.deltaMode,j={clientX:S.clientX,clientY:S.clientY,deltaY:S.deltaY};switch(B){case 1:j.deltaY*=16;break;case 2:j.deltaY*=100;break}return S.ctrlKey&&!D&&(j.deltaY*=10),j}function Pe(S){S.key==="Control"&&(D=!0,t.domElement.getRootNode().addEventListener("keyup",vt,{passive:!0,capture:!0}))}function vt(S){S.key==="Control"&&(D=!1,t.domElement.getRootNode().removeEventListener("keyup",vt,{passive:!0,capture:!0}))}function ht(S){t.enabled===!1||t.enablePan===!1||$e(S)}function je(S){switch(_t(S),T.length){case 1:switch(t.touches.ONE){case Od.ROTATE:if(t.enableRotate===!1)return;Oe(S),s=r.TOUCH_ROTATE;break;case Od.PAN:if(t.enablePan===!1)return;lt(S),s=r.TOUCH_PAN;break;default:s=r.NONE}break;case 2:switch(t.touches.TWO){case Od.DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;X(S),s=r.TOUCH_DOLLY_PAN;break;case Od.DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;ze(S),s=r.TOUCH_DOLLY_ROTATE;break;default:s=r.NONE}break;default:s=r.NONE}s!==r.NONE&&t.dispatchEvent(ok)}function Ve(S){switch(_t(S),s){case r.TOUCH_ROTATE:if(t.enableRotate===!1)return;Te(S),t.update();break;case r.TOUCH_PAN:if(t.enablePan===!1)return;Me(S),t.update();break;case r.TOUCH_DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;Ae(S),t.update();break;case r.TOUCH_DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;et(S),t.update();break;default:s=r.NONE}}function St(S){t.enabled!==!1&&S.preventDefault()}function Ue(S){T.push(S.pointerId)}function qt(S){delete R[S.pointerId];for(let B=0;B<T.length;B++)if(T[B]==S.pointerId){T.splice(B,1);return}}function Fe(S){for(let B=0;B<T.length;B++)if(T[B]==S.pointerId)return!0;return!1}function _t(S){let B=R[S.pointerId];B===void 0&&(B=new Z,R[S.pointerId]=B),B.set(S.pageX,S.pageY)}function ut(S){const B=S.pointerId===T[0]?T[1]:T[0];return R[B]}t.domElement.addEventListener("contextmenu",St),t.domElement.addEventListener("pointerdown",ct),t.domElement.addEventListener("pointercancel",Q),t.domElement.addEventListener("wheel",Ee,{passive:!1}),t.domElement.getRootNode().addEventListener("keydown",Pe,{passive:!0,capture:!0}),this.update()}};var wpe=Object.defineProperty,Spe=Object.getOwnPropertyDescriptor,OS=(n,e,t,r)=>{for(var s=r>1?void 0:r?Spe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&wpe(e,t,s),s};const mV=te("debuggroundprojection");class Yu extends Be{constructor(){super(...arguments),d(this,"applyOnAwake",!1),d(this,"autoFit",!0),d(this,"_radius",100),d(this,"_height",3),d(this,"_lastEnvironment"),d(this,"_lastRadius"),d(this,"_lastHeight"),d(this,"_projection"),d(this,"_watcher"),d(this,"_blurrynessShader",null),d(this,"_lastBlurriness",-1)}set radius(e){this._radius=e,this.updateProjection()}get radius(){return this._radius}set height(e){this._height=e,this.updateProjection()}get height(){return this._height}awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new Nh(this.context.scene,"environment"),this._watcher.subscribeWrite(e=>{this.updateProjection()}))}onDisable(){var e,t;(e=this._watcher)==null||e.revoke(),(t=this._projection)==null||t.removeFromParent()}onEnterXR(){this.updateProjection()}onLeaveXR(){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.updateBlurriness()}updateAndCreate(){var e;this.updateProjection(),(e=this._watcher)==null||e.apply()}updateProjection(){var e,t,r;if(!this.context.scene.environment||(e=this.context.xr)!=null&&e.isPassThrough){(t=this._projection)==null||t.removeFromParent();return}const s=.01;if((!this._projection||this.context.scene.environment!==this._lastEnvironment||this._height!==this._lastHeight||this._radius!==this._lastRadius)&&(mV&&console.log("Create/Update Ground Projection",this.context.scene.environment.name),(r=this._projection)==null||r.removeFromParent(),this._projection=new ZN(this.context.scene.environment,this._height,this.radius),this._projection.position.y=this._height-s,this.context.scene.backgroundBlurriness>.001&&this.updateBlurriness()),this._lastEnvironment=this.context.scene.environment,this._lastHeight=this._height,this._lastRadius=this._radius,this._projection.parent||this.gameObject.add(this._projection),this.autoFit){this._projection.updateWorldMatrix(!0,!0);const o=Ul(this.context.scene.children,[this._projection]),a=o.min.y;if(a<1/0){const l=Bt(this._projection);l.x=o.min.x+(o.max.x-o.min.x)*.5,l.y=a+this._height-s,l.z=o.min.z+(o.max.z-o.min.z)*.5,lr(this._projection,l)}}this._projection.isObject3D===!0&&this._projection.layers.set(2)}updateBlurriness(){if(this._projection){if(!this.context.scene.environment)return}else return;mV&&console.log("Update Blurriness",this.context.scene.backgroundBlurriness),this._blurrynessShader??(this._blurrynessShader=new Rt({uniforms:{map:{value:this.context.scene.environment},blurriness:{value:this.context.scene.backgroundBlurriness}},vertexShader:Cpe,fragmentShader:Epe})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.blurriness.value=this.context.scene.backgroundBlurriness,this._lastBlurriness=this.context.scene.backgroundBlurriness,this._projection.material.map=ha.copyTexture(this.context.scene.environment,this._blurrynessShader)}}OS([w()],Yu.prototype,"applyOnAwake",2),OS([w()],Yu.prototype,"autoFit",2),OS([w()],Yu.prototype,"radius",1),OS([w()],Yu.prototype,"height",1);const Cpe=`
5672
5672
  varying vec2 vUv;
5673
5673
 
5674
5674
  void main() {
@@ -5729,16 +5729,16 @@ Could not find method ${u.method} on object ${m.name}`,m,typeof m[u.method])};if
5729
5729
  // Uncomment to visualize blur amount
5730
5730
  // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
5731
5731
  }
5732
- `;var Mpe=Object.defineProperty,Tpe=Object.getOwnPropertyDescriptor,ak=(n,e,t,r)=>{for(var s=r>1?void 0:r?Tpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Mpe(e,t,s),s};class nm extends Be{constructor(){super(...arguments),d(this,"constraintActive",!0),d(this,"locked",!1),d(this,"sources",[])}}ak([w()],nm.prototype,"constraintActive",2),ak([w()],nm.prototype,"locked",2),ak([w(ye)],nm.prototype,"sources",2);function Ipe(n,e){return Nu(n,Ci.ContextCreated,e),()=>zu(n,Ci.ContextCreated)}function Rpe(n,e){return Nu(n,Ci.ContextClearing,e),()=>zu(n,Ci.ContextClearing)}function Ppe(n,e){return Nu(n,Ci.ContextDestroying,e),()=>zu(n,Ci.ContextDestroying)}function f8(n,e){return Nu(n,Hi.Start,e),()=>zu(n,Hi.Start)}function g8(n,e){return Nu(n,Hi.Update,e),()=>zu(n,Hi.Update)}function Bpe(n,e){return Nu(n,Hi.OnBeforeRender,e),()=>zu(n,Hi.OnBeforeRender)}function kpe(n,e){return Nu(n,Hi.OnAfterRender,e),()=>zu(n,Hi.OnAfterRender)}class rm{constructor(){d(this,"bb",null),d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,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(e,t,r,s){return e.prep(4,12),e.writeFloat32(s),e.writeFloat32(r),e.writeFloat32(t),e.offset()}}class v8{constructor(){d(this,"bb",null),d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new rm).__init(this.bb_pos,this.bb)}rotation(e){return(e||new rm).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new rm).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,r,s,o,a,l,c,h,u){return e.prep(4,36),e.prep(4,12),e.writeFloat32(u),e.writeFloat32(h),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(a),e.writeFloat32(o),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(r),e.writeFloat32(t),e.offset()}}class Vh{constructor(){d(this,"bb",null),d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Vh).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+bB),(t||new Vh).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new v8).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var Cr=(n=>(n[n.Average=0]="Average",n[n.Multiply=1]="Multiply",n[n.Minimum=2]="Minimum",n[n.Maximum=3]="Maximum",n))(Cr||{}),LS=(n=>(n[n.Discrete=0]="Discrete",n[n.Continuous=1]="Continuous",n))(LS||{}),Nn=(n=>(n[n.None=0]="None",n[n.FreezePositionX=2]="FreezePositionX",n[n.FreezePositionY=4]="FreezePositionY",n[n.FreezePositionZ=8]="FreezePositionZ",n[n.FreezePosition=14]="FreezePosition",n[n.FreezeRotationX=16]="FreezeRotationX",n[n.FreezeRotationY=32]="FreezeRotationY",n[n.FreezeRotationZ=64]="FreezeRotationZ",n[n.FreezeRotation=112]="FreezeRotation",n[n.FreezeAll=126]="FreezeAll",n))(Nn||{}),Wg=(n=>(n[n.None=0]="None",n[n.X=2]="X",n[n.Y=4]="Y",n[n.Z=8]="Z",n[n.All=-1]="All",n))(Wg||{});const Hr=function(n,e){return function(t,r,s){Dpe(t,r,s,n,e)}};function Dpe(n,e,t,r,s){if(!s&&!r&&!n.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",n,e,t),rn("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Bo.Error);return}let o="";if(typeof e=="string"?o=e:o=e.name,n.__internalAwake){const a=Symbol(o),l=n.__internalAwake;n.__internalAwake=function(){var c;if(!this.onValidate){st()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((c=n.constructor)==null?void 0:c.name)+'"');return}if(this[a]===void 0){this[a]=this[o];const h=this[o];if(h instanceof Z||h instanceof C||h instanceof Ye||h instanceof Ce){const u=this[o];Zx(u,()=>{this.onValidate(o)})}Object.defineProperty(this,o,{set:function(u){var p;if(this[lB]===!0)this[a]=u;else{r?.call(this,u);const m=this[a];this[a]=u,(p=this.onValidate)==null||p.call(this,o,m)}},get:function(){return s?.call(this),this[a]}})}l.call(this)}}}const Ope=function(n){return function(e,t,r){let s="";typeof t=="string"?s=t:s=t.name;const o=n.prototype,a=Object.getOwnPropertyDescriptor(o,s);if(!(a!=null&&a.value)){console.warn("Can not apply prefix: type does not have method named",t,n);return}const l=a.value,c=e[s];Object.defineProperty(o,s,{value:function(...h){const u=c?.call(this,...h);if(u instanceof Promise){u.then(p=>{if(p!==!1)return l.call(this,...h)});return}if(u!==!1)return l.call(this,...h)}})}};var Lpe=Object.defineProperty,Fpe=Object.getOwnPropertyDescriptor,Uo=(n,e,t,r)=>{for(var s=r>1?void 0:r?Fpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Lpe(e,t,s),s};class Upe{constructor(e,t){d(this,"positionChanged",!1),d(this,"rotationChanged",!1),d(this,"position"),d(this,"quaternion"),d(this,"_positionKeys",["x","y","z"]),d(this,"_quaternionKeys",["_x","_y","_z","_w"]),d(this,"mute",!1),d(this,"context"),d(this,"obj"),d(this,"_positionWatch"),d(this,"_rotationWatch"),this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new Nh(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((o,a)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const c=this.position[a];Math.abs(c-o)<1e-5||(this.position[a]=o,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new Nh(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((o,a)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const c=this.quaternion[a];Math.abs(c-o)<1e-5||(this.quaternion[a]=o,this.rotationChanged=!0)}));const r=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),s=new ve;this.obj.matrixWorld.multiplyMatrices=(o,a)=>{var l;return(l=this.context.physics.engine)!=null&&l.isUpdating||this.mute||s.equals(o)||(this.positionChanged=!0,this.rotationChanged=!0,s.copy(o)),r(o,a)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var lk;const ck=(lk=class extends Be{constructor(){super(...arguments),d(this,"autoMass",!0),d(this,"_mass",0),d(this,"useGravity",!0),d(this,"centerOfMass",new C(0,0,0)),d(this,"constraints",Nn.None),d(this,"isKinematic",!1),d(this,"drag",0),d(this,"angularDrag",1),d(this,"detectCollisions",!0),d(this,"sleepThreshold",.01),d(this,"collisionDetectionMode",LS.Discrete),d(this,"_gravityScale",1),d(this,"dominanceGroup",0),d(this,"_propertiesChanged",!1),d(this,"_currentVelocity",new C),d(this,"_smoothedVelocity",new C),d(this,"_smoothedVelocityGetter",new C),d(this,"_lastPosition",new C),d(this,"_watch")}set mass(n){n!==this._mass&&(this._mass=n,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var n,e;return this.autoMass?((e=(n=this.context.physics.engine)==null?void 0:n.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Nn.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Nn.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Nn.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Nn.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Nn.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Nn.FreezeRotationZ)!==0}set lockPositionX(n){n?this.constraints|=Nn.FreezePositionX:this.constraints&=~Nn.FreezePositionX}set lockPositionY(n){n?this.constraints|=Nn.FreezePositionY:this.constraints&=~Nn.FreezePositionY}set lockPositionZ(n){n?this.constraints|=Nn.FreezePositionZ:this.constraints&=~Nn.FreezePositionZ}set lockRotationX(n){n?this.constraints|=Nn.FreezeRotationX:this.constraints&=~Nn.FreezeRotationX}set lockRotationY(n){n?this.constraints|=Nn.FreezeRotationY:this.constraints&=~Nn.FreezeRotationY}set lockRotationZ(n){n?this.constraints|=Nn.FreezeRotationZ:this.constraints&=~Nn.FreezeRotationZ}set gravityScale(n){this._gravityScale=n}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new Upe(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Hi.LateUpdate)}onDisable(){var n,e;(n=this._watch)==null||n.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var n;(n=this.context.physics.engine)==null||n.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var n,e,t,r;;)this._propertiesChanged&&(this._propertiesChanged=!1,(n=this.context.physics.engine)==null||n.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(r=this._watch)==null||r.syncValues(),this.captureVelocity(),yield}teleport(n,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(n.x,n.y,n.z):this.setWorldPosition(n.x,n.y,n.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(n=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,n)}resetTorques(n=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,n)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var n;(n=this.context.physics.engine)==null||n.wakeup(this)}get isSleeping(){var n;return(n=this.context.physics.engine)==null?void 0:n.isSleeping(this)}updateProperties(){var n;return this._propertiesChanged=!1,(n=this.context.physics.engine)==null?void 0:n.updateProperties(this)}applyForce(n,e,t=!0){var r;this._propertiesChanged&&this.updateProperties(),(r=this.context.physics.engine)==null||r.addForce(this,n,t)}applyImpulse(n,e=!0){var t;this._propertiesChanged&&this.updateProperties(),(t=this.context.physics.engine)==null||t.applyImpulse(this,n,e)}setForce(n,e,t,r=!0){var s,o,a;(s=this.context.physics.engine)==null||s.resetForces(this,r),typeof n=="number"?(e??(e=0),t??(t=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:n,y:e,z:t},r)):(a=this.context.physics.engine)==null||a.addForce(this,n,r)}getVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,r=!0){var s,o;if(n instanceof C){const a=n;(s=this.context.physics.engine)==null||s.setLinearVelocity(this,a,r);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:n,y:e,z:t},r)}getAngularVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,r=!0){var s,o;if(n instanceof C){const a=n;(s=this.context.physics.engine)==null||s.setAngularVelocity(this,a,r);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:n,y:e,z:t},r)}setTorque(n,e,t){this.setAngularVelocity(n,e,t)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(n=null){}captureVelocity(){const n=Bt(this.gameObject);ck.tempPosition.copy(n);const e=n.sub(this._lastPosition);this._lastPosition.copy(ck.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},d(lk,"tempPosition",new C),lk);let Oi=ck;Uo([Hr()],Oi.prototype,"autoMass",2),Uo([w()],Oi.prototype,"mass",1),Uo([Hr(),w()],Oi.prototype,"useGravity",2),Uo([w(C)],Oi.prototype,"centerOfMass",2),Uo([Hr(),w()],Oi.prototype,"constraints",2),Uo([Hr(),w()],Oi.prototype,"isKinematic",2),Uo([Hr(),w()],Oi.prototype,"drag",2),Uo([Hr(),w()],Oi.prototype,"angularDrag",2),Uo([Hr(),w()],Oi.prototype,"detectCollisions",2),Uo([Hr(),w()],Oi.prototype,"sleepThreshold",2),Uo([Hr(),w()],Oi.prototype,"collisionDetectionMode",2),Uo([Hr()],Oi.prototype,"_gravityScale",2),Uo([Hr()],Oi.prototype,"dominanceGroup",2);const Ju=te("debugsync"),AA="STRS";wB(AA,Vh.getRootAsSyncedTransformModel);const Zl=new s_;function y8(n,e,t=!0){Zl.clear();const r=Zl.createString(n);Vh.startSyncedTransformModel(Zl),Vh.addGuid(Zl,r),Vh.addFast(Zl,t);const s=e.worldPosition,o=e.worldEuler,a=e.gameObject.scale;Vh.addTransform(Zl,v8.createTransform(Zl,s.x,s.y,s.z,o.x,o.y,o.z,a.x,a.y,a.z));const l=Vh.endSyncedTransformModel(Zl);return Zl.finish(l,AA),Zl.asUint8Array()}let hk=0,bA=0;g8(n=>{var e;const t=(e=n.connection.currentServerUrl)!=null&&e.includes("glitch")?10:40;bA=Math.floor(hk/t),hk=0,Ju&&bA>0&&console.log("Sync Transform Fast Interval",bA)});class Ku extends Be{constructor(){super(...arguments),d(this,"overridePhysics",!0),d(this,"interpolatePosition",!0),d(this,"interpolateRotation",!0),d(this,"fastMode",!1),d(this,"syncDestroy",!1),d(this,"_model",null),d(this,"_needsUpdate",!0),d(this,"rb",null),d(this,"_wasKinematic",!1),d(this,"_receivedDataBefore",!1),d(this,"_targetPosition"),d(this,"_targetRotation"),d(this,"_receivedFastUpdate",!1),d(this,"_shouldRequestOwnership",!1),d(this,"joinedRoomCallback",null),d(this,"receivedDataCallback",null),d(this,"tempEuler",new ii),d(this,"receivedUpdate",!1),d(this,"lastWorldPos"),d(this,"lastWorldRotation")}requestOwnership(){Ju&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}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(){Ju&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new C,this._targetRotation=new Ce,this.lastWorldPos=new C,this.lastWorldRotation=new Ce,this.rb=ie.getComponentInChildren(this.gameObject,Oi),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new jB(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Vt.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(AA,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&$B(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Vt.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(AA,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Ju&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const r=e.transform();if(r){Qa.markDirty(this.gameObject,!0);const s=r.position();s&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(s.x(),s.y(),s.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(s.x(),s.y(),s.z()));const o=r.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&ER(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),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){Ju&&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,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=e.distanceTo(this.lastWorldPos),a=t.angleTo(this.lastWorldRotation),l=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>l||a>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(Ju&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),Qa.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const o=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,o),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,o),this.worldQuaternion=l,a=!0}a&&Qa.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Ju&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const r=10,s=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%r===0||s)){if(hk++,s&&bA>0&&this.context.time.frameCount%bA!==0)return;Ju&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const o=y8(this.guid,this,!!s);this.context.connection.sendBinary(o)}}}const Npe=te("debugshadowcomponents");pR.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};const Ma=Symbol("shadowDomOwner");class Va extends Be{constructor(){super(...arguments),d(this,"_shadowComponent",null),d(this,"_controlsChildLayout",!0),d(this,"_root"),d(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(){Ta.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=ie.getComponentInParent(this.gameObject,_A)),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,t){var r;if(!e)return;this.removeShadowComponent();const s=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=ie.getComponentInParent(s,Va),!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[Ma]=this,this.setShadowComponentOwner(e);let o=!1;if(((r=this.Root)==null?void 0:r.gameObject)===this.gameObject)this.gameObject.add(e);else{const a=this._parentComponent.shadowComponent;a&&(a?.add(e),o=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Wy&&e.add(new Po(.5)),this.onAfterAddedToScene(),o&&YN(),Npe&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Ma]===void 0||e[Ma]===this)&&(e[Ma]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,r){if(e&&e[Ma]===t){r(e);for(const s of e.children)this.traverseOwnedShadowComponents(s,t,r)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class _A extends Va{awake(){super.awake()}}class q0{constructor(e,t){d(this,"event"),d(this,"button"),d(this,"buttonName"),d(this,"_used",!1),d(this,"_propagationStopped",!1),d(this,"z__pointer_ctured",!1),d(this,"z__pointer_cture_rleased",!1),d(this,"inputSource"),d(this,"object"),d(this,"point"),d(this,"normal"),d(this,"face"),d(this,"distance"),d(this,"instanceId"),d(this,"intersection"),d(this,"isDown"),d(this,"isUp"),d(this,"isPressed"),d(this,"isClick"),d(this,"isDoubleClick"),d(this,"input"),this.event=t,this.input=e,this.button=t.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(),this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId))}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 e=new q0(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function uk(n,e){return ie.foreachComponent(n,t=>{if(!t.enabled)return;const r=t;if(e)switch(e){case"pointerdown":if(r.onPointerDown)return!0;break;case"pointerup":if(r.onPointerUp||r.onPointerClick)return!0;break;case"pointermove":if(r.onPointerEnter||r.onPointerExit||r.onPointerMove)return!0;break}else if(r.onPointerDown||r.onPointerUp||r.onPointerEnter||r.onPointerExit||r.onPointerClick)return!0},!1)===!0}var zpe=Object.defineProperty,jpe=Object.getOwnPropertyDescriptor,Gpe=(n,e,t,r)=>{for(var s=r>1?void 0:r?jpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&zpe(e,t,s),s};class xA extends Be{awake(){Ta.createIfNoneExists(this.context)}onEnable(){var e;(e=Ta.get(this.context))==null||e.register(this)}onDisable(){var e;(e=Ta.get(this.context))==null||e.unregister(this)}}class No extends xA{constructor(){super(...arguments),d(this,"targets",null),d(this,"raycastHits",[]),d(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new ml),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=s=>s instanceof uo?"continue in children":t?t(s):!0);const r=this.context.physics.raycast(e);return e.testObject=t,r}}Gpe([w()],No.prototype,"ignoreSkinnedMeshes",2);class FS extends No{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class wA extends xA{performRaycast(e){if(!wt.active||!(e!=null&&e.ray))return null;const t=e.ray.origin,r=.01;return this.context.physics.sphereOverlap(t,r)}}class US{static getObject(e){const t=e[Ma];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const r=this.tryFindCanvasGroup(e);if(r?.isCanvasGroup===!0&&(t&&(t.canvasGroup=r),r.blocksRaycasts===!1||r.interactable===!1))return!1;const s=Kp(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&s?.isGraphic===!0&&(t.graphic=s),!(s?.raycastTarget===!1||s?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Kp(e,r=>{const s=r;if(s.blocksRaycasts!==void 0&&s.interactable!==void 0)return s},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function dk(n){return n[Ma]||(n.parent?dk(n.parent):null)}function Vpe(n){return n.isUI===!0||typeof n[Ma]=="object"}function NS(n,e){if(!n)return;const t=n.material;if(t?.isMaterial===!0){const r=n.parent;r&&r.isText,t.side=e.doubleSided??!0?yi:nr,t.shadowSide=e.doubleSided?yi:nr,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const r of n.children)NS(r,e)}function Xg(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const r=Proxy.revocable(n[e],{set(a,l,c,h){const u=a[l],p=Reflect.set(a,l,c,h);return t(c,u),p}}),s=r.revoke,o=n[e];return r.revoke=()=>{n[e]=o,s()},n[e]=r.proxy,r}const A8=Symbol("Scheduled action");function Qpe(n,e,t=Hi.OnBeforeRender){let r=n[A8];r||(r=n[A8]={});const s=e.name;r[t]||(r[t]={});const o=r[t];if(o[s])return;function*a(){e?.call(n),o[s]=null}const l=n.startCoroutine(a(),t);o[s]=l}const Ah=te("debugeventsystem");var pk=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))(pk||{});const bh=class extends Be{constructor(){super(),d(this,"raycaster",[]),d(this,"_handleInputFn"),d(this,"pressedByID",new Map),d(this,"hoveredByID",new Map),d(this,"_sortedHits",[]),d(this,"_testObjectsCache",new Map),d(this,"_currentlyActiveRaycaster",null),d(this,"_currentPointerEventName",null),d(this,"shouldRaycastObject",n=>{var e;let t=null;if(Vpe(n)&&(t=(e=n[Ma])==null?void 0:e.gameObject),this._testObjectsCache.has(n)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(n)===!1?"continue in children":!0;{let r=uk(n,this._currentPointerEventName);if(!r&&t&&(r=uk(t,this._currentPointerEventName)),r){this._testObjectsCache.set(n,!0);for(const s of n.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(n,!1),"continue in children"}}),d(this,"_sortingBuffer",[]),d(this,"_noDepthTestingResults",[]),d(this,"out",{}),d(this,"_capturedPointer",{}),d(this,"pointerEnterSymbol",Symbol("pointerEnter")),d(this,"pointerExitSymbol",Symbol("pointerExit")),d(this,"currentActiveMeshUIComponents",[]),bh.systems.push(this)}static createIfNoneExists(n){this.didSearchEventSystem||(this.didSearchEventSystem=!0,bh.systems.length<=0&&bh.systems.push(...ie.findObjectsOfType(bh,n)));for(const t of bh.systems)if(t.context===n)return;const e=new ye;ie.addNewComponent(e,bh),n.scene.add(e)}static get systems(){const n=kt.Current;return this._eventSystemMap.has(n)||this._eventSystemMap.set(n,[]),this._eventSystemMap.get(n)}static get(n){const e=this._eventSystemMap.get(n);return e&&e.length>0?e[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(n,e,t=!1){Zu.update(n,e,t)}static markUIDirty(n){Zu.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){bh.systems.splice(bh.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!ie.findObjectOfType(xA,this.context)){const n=ie.addNewComponent(this.context.scene,No);this.raycaster.push(n),(st()||Ah)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(n){var e;n&&this.raycaster&&!this.raycaster.includes(n)&&((e=this.raycaster)==null||e.push(n))}unregister(n){var e,t;const r=(e=this.raycaster)==null?void 0:e.indexOf(n);r!==void 0&&r!==-1&&((t=this.raycaster)==null||t.splice(r,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(an.PointerDown,this._handleInputFn),this.context.input.addEventListener(an.PointerUp,this._handleInputFn),this.context.input.addEventListener(an.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(an.PointerDown,this._handleInputFn),this.context.input.removeEventListener(an.PointerUp,this._handleInputFn),this.context.input.removeEventListener(an.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(n){if(n===void 0||n.propagationStopped)return;const e=new q0(this.context.input,n);this._currentPointerEventName=n.type,e.inputSource=this.context.input,e.isClick=n.isClick,e.isDoubleClick=n.isDoubleClick,e.isDown=n.type==an.PointerDown,e.isUp=n.type==an.PointerUp,e.isPressed=this.context.input.getPointerPressed(n.pointerId),Ah&&(e.isDown?console.log("DOWN",e.pointerId):e.isUp&&console.log("UP",e.pointerId),e.isClick&&console.log("CLICK",e.pointerId));const t=new ml;n.hasRay?t.ray=n.ray:t.screenPoint=this.context.input.getPointerPositionRC(n.pointerId);const r=this.performRaycast(t);if(r){for(const o of r)o.event=n,n.intersections.push(o);n.origin.onPointerHits&&n.origin.onPointerHits({sender:this,event:n,hits:r})}Ah&&e.isClick&&rn("EventSystem: "+e.pointerId+" - "+this.context.time.frame+" - Up:"+e.isUp+", Down:"+e.isDown);const s={sender:this,args:e,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),this.handleIntersections(r,e),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))}shouldRaycastObject_AddToYesCache(n){this._testObjectsCache.set(n,!0);for(const e of n.children)this.shouldRaycastObject_AddToYesCache(e)}performRaycast(n){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,n||(n=new ml),n.testObject=this.shouldRaycastObject;for(const e of this.raycaster){if(!e.activeAndEnabled)continue;this._currentlyActiveRaycaster=e;const t=e.performRaycast(n);this._currentlyActiveRaycaster=null,t&&t.length>0&&this._sortedHits.push(...t)}return this._sortedHits.sort((e,t)=>e.distance-t.distance),this._sortedHits}assignHitInformation(n,e){e?(n.intersection=e,n.point=e.point,n.normal=e.normal,n.face=e.face,n.distance=e.distance,n.instanceId=e.instanceId):(n.intersection=void 0,n.point=void 0,n.normal=void 0,n.face=void 0,n.distance=void 0,n.instanceId=void 0)}handleIntersections(n,e){var t;if(n!=null&&n.length){n=this.sortCandidates(n);for(const s of n){if(e.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(e,s),this.handleEventOnObject(s.object,e))return!0}}this.assignHitInformation(e,n?.[0]),this.invokePointerCapture(e);const r=this.hoveredByID.get(e.pointerId);return r&&this.propagatePointerExit(r.obj,r.data,null),this.hoveredByID.delete(e.pointerId),e.isUp&&((t=this.pressedByID.get(e.pointerId))==null||t.handlers.forEach(s=>this.invokeOnPointerUp(e,s)),this.pressedByID.delete(e.pointerId)),!1}sortCandidates(n){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let e=0;e<n.length;e++){const t=n[e],r=t.object;if(r.material&&r.material.depthTest===!1){this._noDepthTestingResults.push(t);continue}this._sortingBuffer.push(t)}for(const e of this._sortingBuffer)this._noDepthTestingResults.push(e);return this._noDepthTestingResults}handleEventOnObject(n,e){if(!this.testIsVisible(n))return e.isClick&&Ah&&console.log("not allowed",n),!1;if(e.pointerId===void 0)return Ah&&console.error("Event without pointer can't be handled",e),!1;e.object=n;const t=n.parent,r=e.isClick??!1;let s=null;if(t&&t.isUI){const c=(e.isPressed||e.isClick)??!1;if(t[Ma]){const h=t[Ma].gameObject;if(h){if(!US.isInteractable(h,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(n,c),n=h}}}r&&Ah&&console.log(this.context.time.frame,n);const o=this.hoveredByID.get(e.pointerId),a=o?.obj;a!==n&&a&&this.propagatePointerExit(a,o.data,n);const l=this.hoveredByID.get(e.pointerId);if(l?(l.obj=n,l.data=e):this.hoveredByID.set(e.pointerId,{obj:n,data:e}),e.isDown){const c=this.pressedByID.get(e.pointerId);c?(c.obj=n,c.data=e):this.pressedByID.set(e.pointerId,{obj:n,data:e,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(n,e,a??null),!0}propagate(n,e){for(;n;)ie.foreachComponent(n,t=>{e(t)},!1),n=n.parent}handleMainInteraction(n,e,t){const r=this.pressedByID.get(e.pointerId),s=t!==n;let o=!0;switch(e.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(e.pointerId),l=this.context.input.getPointerPosition(e.pointerId);o=a&&!it.approximately(a,l);break}this.propagate(n,a=>{var l;const c=a;c.interactable!==!1&&(!c.activeAndEnabled||!c.enabled||(c.onPointerEnter&&s&&this.handlePointerEnter(c,e),e.isDown&&c.onPointerDown&&(c.onPointerDown(e),r?.handlers.add(c),this.handlePointerCapture(e,c)),c.onPointerMove&&(o&&c.onPointerMove(e),this.handlePointerCapture(e,c)),e.isUp&&(c.onPointerUp&&(this.invokeOnPointerUp(e,c),r?.handlers.delete(c)),c.onPointerExit&&((l=e.event)==null?void 0:l.pointerType)===q1.Touch&&(this.handlePointerExit(c,e),this.hoveredByID.delete(e.pointerId))),e.isClick&&c.onPointerClick&&c.onPointerClick(e)))}),e.isUp&&(r?.handlers.forEach(a=>{this.invokeOnPointerUp(e,a)}),this.pressedByID.delete(e.pointerId))}propagatePointerExit(n,e,t){this.propagate(n,r=>{if(!r.gameObject||r.destroyed)return;const s=r;if(s.onPointerExit){if(t&&this.isChild(t,r.gameObject))return;this.handlePointerExit(s,e)}})}invokeOnPointerUp(n,e){var t;(t=e.onPointerUp)==null||t.call(e,n),this.releasePointerCapture(n,e)}handlePointerEnter(n,e){n.onPointerEnter&&this.updatePointerState(n,e.pointerId,this.pointerEnterSymbol,!0)&&n.onPointerEnter(e),this.updatePointerState(n,e.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(n,e){n.onPointerExit&&this.updatePointerState(n,e.pointerId,this.pointerExitSymbol,!0)&&n.onPointerExit(e),this.updatePointerState(n,e.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(n,e,t,r){let s=n[t];if(r)return s&&s.includes(e)?!1:(s=s||[],s.push(e),n[t]=s,!0);{if(!s||!s.includes(e))return!1;const o=s.indexOf(e);return o!==-1&&s.splice(o,1),!0}}handlePointerCapture(n,e){if(n.z__pointer_ctured){n.z__pointer_ctured=!1;const t=n.pointerId;if(e.onPointerMove){const r=this._capturedPointer[t]||[];r.push(e),this._capturedPointer[t]=r}else st()&&!e.z__warned_no_pointermove&&(e.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 n.z__pointer_cture_rleased&&(n.z__pointer_cture_rleased=!1,this.releasePointerCapture(n,e))}releasePointerCapture(n,e){const t=n.pointerId;if(this._capturedPointer[t]){const r=this._capturedPointer[t].indexOf(e);r!==-1&&(this._capturedPointer[t].splice(r,1),Ah&&console.log("released pointer capture",t,e,this._capturedPointer))}}invokePointerCapture(n){var e;if(n.event.type===an.PointerMove){const t=n.pointerId,r=this._capturedPointer[t];if(r){Ah&&console.log("Captured",t,r);for(let s=0;s<r.length;s++){const o=r[s];if(o.destroyed){r.splice(s,1),s--;continue}(e=o.onPointerMove)==null||e.call(o,n)}}}}isChild(n,e){return!n||!e?!1:n===e?!0:n.parent?this.isChild(n.parent,e):!1}handleMeshUiObjectWithoutShadowDom(n,e){return!n||!n.isUI?!0:this.handleMeshUIIntersection(n,e)}handleMeshUIIntersection(n,e){const t=Zu.updateState(n,e);return t&&this.currentActiveMeshUIComponents.push(t),t!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Zu.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let n=0;n<this.currentActiveMeshUIComponents.length;n++){const e=this.currentActiveMeshUIComponents[n];Zu.resetState(e)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(n){return n?ie.isActiveSelf(n)?this.testIsVisible(n.parent):!1:!0}};let Ta=bh;d(Ta,"_eventSystemMap",new Map),d(Ta,"didSearchEventSystem",!1);class Zu{static markDirty(){this.needsUpdate=!0}static update(e,t,r=!1){if(r){e.update();return}const s=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(s===o.frame)return;o.frame=s;let a=this.needsUpdate||s<1;o.nextUpdate===t.time.frameCount&&(a=!0),a&&(Ah&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:s,nextUpdate:s}],e.update()}static updateState(e,t){let r=null;if(e&&(r=this.findBlockInParent(e),r&&r!==this.lastSelected)){if(r.interactable===!1)return null;this.needsUpdate=!0}return r}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockInParent(e){return e?e.isBlock?e:this.findBlockInParent(e.parent):null}}d(Zu,"lastSelected",null),d(Zu,"lastUpdateFrame",[]),d(Zu,"needsUpdate",!1);var Hpe=Object.defineProperty,Wpe=Object.getOwnPropertyDescriptor,ln=(n,e,t,r)=>{for(var s=r>1?void 0:r?Wpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Hpe(e,t,s),s};const mk=te("debugorbit"),zS=te("freecam"),jS=te("debugcamerafit"),GS=te("smoothcam"),Xpe={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let fk;class SA extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class bi extends Be{constructor(){super(...arguments),d(this,"autoTarget",!0),d(this,"autoFit",!1),d(this,"enableRotate",!0),d(this,"autoRotate",!1),d(this,"autoRotateSpeed",1),d(this,"minAzimuthAngle",1/0),d(this,"maxAzimuthAngle",1/0),d(this,"minPolarAngle",0),d(this,"maxPolarAngle",Math.PI),d(this,"enableKeys",!0),d(this,"enableDamping",!0),d(this,"dampingFactor",.1),d(this,"enableZoom",!0),d(this,"minZoom",0),d(this,"maxZoom",1/0),d(this,"zoomSpeed",1),d(this,"zoomToCursor",!1),d(this,"enablePan",!0),d(this,"lookAtConstraint",null),d(this,"lookAtConstraint01",1),d(this,"allowInterrupt",!0),d(this,"middleClickToFocus",!0),d(this,"doubleClickToFocus",!0),d(this,"clickBackgroundToFitScene",2),d(this,"debugLog",!1),d(this,"targetLerpDuration",1),d(this,"_controls",null),d(this,"_cameraObject",null),d(this,"_lookTargetLerpActive",!1),d(this,"_lookTargetStartPosition",new C),d(this,"_lookTargetEndPosition",new C),d(this,"_lookTargetLerp01",0),d(this,"_lookTargetLerpDuration",0),d(this,"_cameraLerpActive",!1),d(this,"_cameraStartPosition",new C),d(this,"_cameraEndPosition",new C),d(this,"_cameraLerp01",0),d(this,"_cameraLerpDuration",0),d(this,"_inputs",0),d(this,"_enableTime",0),d(this,"_startedListeningToKeyEvents",!1),d(this,"_eventSystem"),d(this,"_afterHandleInputFn"),d(this,"_camera",null),d(this,"_syncedTransform"),d(this,"_didSetTarget",0),d(this,"targetElement",null),d(this,"_lastTimeClickOnBackground",-1),d(this,"_clickOnBackgroundCount",0),d(this,"_onPointerDown",e=>{if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}mk&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),d(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),d(this,"_shouldDisable",!1),d(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(this.scene.children,{centerCamera:"y",immediate:!0}))}),d(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Ta.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(pk.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(pk.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=ie.getComponent(this.gameObject,Li);this._camera=e;let t=e?.cam;if(!t&&this.gameObject instanceof Lt&&(t=this.gameObject),t&&vR(t,this,!0),!this._controls&&t instanceof Lt){this._cameraObject=t;const r=this.targetElement??this.context.renderer.domElement,s=t?.quaternion.clone();this._controls=new p8(t,r),t?.quaternion.copy(s),fk===void 0&&(fk={...this._controls.keys})}this._controls&&(zS&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,aa()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),t?.type==="PerspectiveCamera"?zS||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):zS||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=ie.getComponent(this.gameObject,Ku)??void 0,this.context.input.addEventListener("pointerup",this._onPointerDown),this.context.pre_render_callbacks.push(this.__onPreRender)}onDisable(){var e;(e=this._camera)!=null&&e.cam&&vR(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted)),this.context.input.removeEventListener("pointerup",this._onPointerDown)}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 e,t;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)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.length()||0>.1)&&(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 s=ie.getComponent(this.gameObject,Li);if(s&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const o=Bt(s.cam),a=Math.max(.01,o.length()),l=new C(0,0,-a).applyMatrix4(s.cam.matrixWorld);this.setLookTargetPosition(l,!0)}if(!this.setLookTargetFromConstraint()){const o=new ml;o.screenPoint=new Z(0,0),o.lineThreshold=.1;const a=this.context.physics.raycast(o);a.length>0&&this.setLookTargetPosition(a[0].point,!0),jS&&console.log("OrbitControls hits",...a)}}let r=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(r||(r=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),r&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive){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 SA(this,"camera"));else{const s=it.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,s)}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 SA(this,"lookat"));else{const s=it.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,s)}}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._controls.keys=this.enableKeys?fk:Xpe,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,typeof GS=="number"||GS===!0){this._controls.enableDamping=!0;const s=typeof GS=="number"?GS:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,s))}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||(!zS&&(t=this.lookAtConstraint)!=null&&t.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),mk&&At.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(e){if(!e||!(e instanceof ye))return;const t=Bt(e),r=SR(e);this.setTargetFromRaycast(new co(t,r)),this.setCameraTargetPosition(t)}setCameraTargetPosition(e,t=!1){var r,s;e&&(e instanceof ye&&(e=Bt(e)),this._cameraEndPosition||(this._cameraEndPosition=new C),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,(r=this.controllerObject)==null||r.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof ye&&(e=Bt(e)),this._lookTargetEndPosition.copy(e),mk&&(console.warn("OrbitControls: setLookTargetPosition",e,t),At.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var r;if(!this._controls)return!1;const s=(r=this.lookAtConstraint)==null?void 0:r.sources;if(s&&s.length>0){const o=s[e];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e){if(!this.controls)return;const t=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const r of t)if(r.distance>0&&ie.isActiveInHierarchy(r.object)){const s=dk(r.object);if(s){const o=s.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(r.point);break}}fitCamera(e,t={fitOffset:void 0,immediate:!1}){if(this.context.isInXR)return;const{immediate:r=!1,centerCamera:s}=t;let{fitOffset:o}=t;o==null&&(o=1.1);const a=this._cameraObject,l=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),e.length<=0){console.warn("No objects to fit camera to...");return}if(!a||!l){console.warn("No camera or controls found to fit camera to objects...");return}const c=new C,h=new C,u=Ul(e,void 0);a.updateMatrixWorld(),a.updateProjectionMatrix(),u.getCenter(h);const p=new C;if(u.getSize(p),u.applyMatrix4(a.matrixWorldInverse),u.getSize(c),u.setFromCenterAndSize(h,c),Number.isNaN(c.x)||Number.isNaN(c.y)||Number.isNaN(c.z)){console.warn("Camera fit size resultet in NaN",a,u,[...e]);return}if(c.length()<=1e-10){jS&&console.warn("Camera fit size is zero",u,[...e]);return}const m=a.fov,f=2*Math.atan(Math.tan(m*Math.PI/360/2)*a.aspect)/Math.PI*360,g=c.y/(2*Math.atan(Math.PI*m/360)),v=c.x/(2*Math.atan(Math.PI*f/360)),y=o*Math.max(g,v)+c.z/2;jS&&console.log("Fit camera to objects",g,v,"distance",y),l.maxDistance=y*10,l.minDistance=y*.01;const A=.05,_=h.clone();_.y-=c.y*A,this.setLookTargetPosition(_,r),this.autoTarget=!1;const b=ie.findObjectOfType(Yu),x=b?b.radius:0,E=Math.max(p.x,p.y,p.z,x);a.near=y/100,a.far=E+y*10,a.updateMatrixWorld(),a.updateProjectionMatrix();const I=Bt(a),T=h.clone();if(T.sub(I),s==="y"&&(T.y=0),T.normalize(),T.multiplyScalar(y),s==="y"&&(T.y+=-A*4*c.y),a.parent){const R=a.parent.worldToLocal(h.clone().sub(T));this.setCameraTargetPosition(R,r)}else console.error(`Can not fit camera ${a.name} because it has no parent`);if(jS){const R=new wI(u);this.context.scene.add(R),MR(R,Wv(a)),setTimeout(()=>{this.context.scene.remove(R)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",D=>{D.code==="KeyF"&&this.fitCamera(e,{fitOffset:o,immediate:r})}))}l.update()}}ln([w()],bi.prototype,"autoTarget",2),ln([w()],bi.prototype,"autoFit",2),ln([w()],bi.prototype,"enableRotate",2),ln([w()],bi.prototype,"autoRotate",2),ln([w()],bi.prototype,"autoRotateSpeed",2),ln([w()],bi.prototype,"minAzimuthAngle",2),ln([w()],bi.prototype,"maxAzimuthAngle",2),ln([w()],bi.prototype,"minPolarAngle",2),ln([w()],bi.prototype,"maxPolarAngle",2),ln([w()],bi.prototype,"enableKeys",2),ln([w()],bi.prototype,"enableDamping",2),ln([w()],bi.prototype,"dampingFactor",2),ln([w()],bi.prototype,"enableZoom",2),ln([w()],bi.prototype,"minZoom",2),ln([w()],bi.prototype,"maxZoom",2),ln([w()],bi.prototype,"zoomSpeed",2),ln([w()],bi.prototype,"enablePan",2),ln([w(nm)],bi.prototype,"lookAtConstraint",2),ln([w()],bi.prototype,"lookAtConstraint01",2),ln([w()],bi.prototype,"allowInterrupt",2),ln([w()],bi.prototype,"middleClickToFocus",2),ln([w()],bi.prototype,"doubleClickToFocus",2),ln([w()],bi.prototype,"clickBackgroundToFitScene",2),ln([w()],bi.prototype,"targetLerpDuration",2);var qpe=Object.defineProperty,Ype=Object.getOwnPropertyDescriptor,$s=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ype(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&qpe(e,t,s),s},$u=(n=>(n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))($u||{});const _h=te("debugcam"),b8=te("debugscreenpointtoray");var VS;const CA=(VS=class extends Be{constructor(){super(...arguments),d(this,"_nearClipPlane",.1),d(this,"_farClipPlane",1e3),d(this,"orthographic",!1),d(this,"orthographicSize",5),d(this,"ARBackgroundAlpha",0),d(this,"_cullingMask",4294967295),d(this,"_backgroundBlurriness",0),d(this,"_backgroundIntensity",1),d(this,"_backgroundRotation"),d(this,"_environmentIntensity"),d(this,"_targetTexture",null),d(this,"_backgroundColor"),d(this,"_fov"),d(this,"_cam",null),d(this,"_clearFlags",2),d(this,"_skybox"),d(this,"_frustum"),d(this,"_projScreenMatrix",new ve)}get isCamera(){return!0}get aspect(){return this._cam instanceof Lt?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(n){this._cam instanceof Lt&&this._cam.aspect!==n&&(this._cam.aspect=n,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof Lt?this._cam.fov:this._fov}set fieldOfView(n){const e=this.fieldOfView!=n;if(this._fov=n,e&&this._cam&&this._cam instanceof Lt){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(n){const e=this._nearClipPlane!=n;this._nearClipPlane=n,this._cam&&e&&(this._cam.near=n,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(n){const e=this._farClipPlane!=n;this._farClipPlane=n,this._cam&&e&&(this._cam.far=n,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(n){n!==this._clearFlags&&(this._clearFlags=n,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(n){this._cullingMask=n,this._cam&&(this._cam.layers.mask=n)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(n){this.cullingMask=(1<<n|0)>>>0}set backgroundBlurriness(n){n!==this._backgroundBlurriness&&(n===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(n,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(n){n!==this._backgroundIntensity&&(n===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(n,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(n){n!==this._backgroundRotation&&(n===void 0?this._backgroundRotation=void 0:this._backgroundRotation=n,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(n){this._environmentIntensity=n}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(n){if(n){if(this._backgroundColor)this._backgroundColor.copy(n);else{if(!n.clone)return;this._backgroundColor=n.clone()}n.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(n){this._targetTexture=n}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(n,e,t){const r=this.cam,s=CA._origin;s.set(n,e,-1),this.context.input.convertScreenspaceToRaycastSpace(s),b8&&console.log("screenPointToRay",n.toFixed(2),e.toFixed(2),"now:",s.x.toFixed(2),s.y.toFixed(2),"isInXR:"+this.context.isInXR),s.z=-1,s.unproject(r);const o=CA._direction.set(s.x,s.y,s.z),a=Bt(r);return o.sub(a),o.normalize(),t?(t.set(a,o),t):new co(a.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new Yd,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Yd),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(n,e){return e&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),n===this._projScreenMatrix?n:n.copy(this._projScreenMatrix)}awake(){b8&&window.addEventListener("pointerdown",n=>{const e=n.clientX,t=n.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const r=this.screenPointToRay(e,t),s="#"+Math.floor(Math.random()*16777215).toString(16);At.DrawRay(r.origin,r.direction,s,10)})}onEnable(){_h&&console.log(`Camera enabled: "${this.name}". ClearFlags=${$u[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),Kpe(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 n=this.context.renderer;if(n){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,n),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const n=this.gameObject.isCamera;let e=null;if(n?(e=this.gameObject,e?.layers.enableAll(),e instanceof Lt&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof Lt&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new Lt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new Bl(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(n){this.context.mainCameraComponent===this&&this.applyClearFlags(n)}applyClearFlags(n){if(!this._cam){_h&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,_h){const e=`Camera "${this.name}" clear flags: ${$u[this._clearFlags]}`;console.debug(e)}switch(this._clearFlags){case 1:if(CA.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||n?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:_h&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0?this.context.scene.backgroundRotation=this._backgroundRotation:_h&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;CA.backgroundShouldBeTransparent(this.context)&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}else _h&&console.warn(`Camera "${this.name}" has no background color`,this);break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}applySceneSkybox(){this._skybox||(this._skybox=new Jpe(this)),this._skybox.apply()}static backgroundShouldBeTransparent(n){var e,t,r,s;const o=(e=n.renderer.xr)==null?void 0:e.getSession();if(!o)return!1;if(typeof o._transparent=="boolean")return o._transparent;const a=o.environmentBlendMode;_h&&rn("Environment blend mode: "+a+" on "+navigator.userAgent);let l=a==="additive"||a==="alpha-blend";return n.isInAR&&a==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(r=navigator.userAgent)!=null&&r.includes("Mozilla")&&(s=navigator.userAgent)!=null&&s.includes("Mobile WebXRViewer/v2"))&&(l=!0),o._transparent=l,l}},d(VS,"_origin",new C),d(VS,"_direction",new C),VS);let Li=CA;$s([w()],Li.prototype,"aspect",1),$s([w()],Li.prototype,"fieldOfView",1),$s([w()],Li.prototype,"nearClipPlane",1),$s([w()],Li.prototype,"farClipPlane",1),$s([w()],Li.prototype,"clearFlags",1),$s([w()],Li.prototype,"orthographic",2),$s([w()],Li.prototype,"orthographicSize",2),$s([w()],Li.prototype,"ARBackgroundAlpha",2),$s([w()],Li.prototype,"cullingMask",1),$s([w()],Li.prototype,"backgroundBlurriness",1),$s([w()],Li.prototype,"backgroundIntensity",1),$s([w(ii)],Li.prototype,"backgroundRotation",1),$s([w()],Li.prototype,"environmentIntensity",1),$s([w(Si)],Li.prototype,"backgroundColor",1),$s([w(Hg)],Li.prototype,"targetTexture",1);class Jpe{constructor(e){d(this,"_camera"),d(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(_h&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=so,this.context.scene.background=this._skybox):(this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" failed to load/find skybox texture`,this._camera.sourceId,this.context.lightmaps,"Current background: ",this.context.scene.background)),(_h||st())&&Di(`Camera "${this._camera.name}" has no skybox texture`))}}function Kpe(n){te("freecam")&&n.context.mainCameraComponent===n&&ie.getOrAddComponent(n.gameObject,bi)}class ed extends Be{constructor(){super(...arguments),d(this,"_listener",null),d(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new pU),this._listener}onEnable(){Qu.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Qu.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||ie.getComponentInParent(this.gameObject,Li);t!=null&&t.cam?t.cam.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())}}class Zpe extends Sn{constructor(e,t=1,r=16,s=2){const o=new yt,a=r+s*2,l=new Float32Array((a*3+3)*3);o.setAttribute("position",new nt(l,3));const c=new Gi({color:65280}),h=new Gi({color:16776960});super(o,[h,c]),this.audio=e,this.range=t,this.divisionsInnerAngle=r,this.divisionsOuterAngle=s,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,r=this.divisionsInnerAngle,s=this.divisionsOuterAngle,o=ui.degToRad(e.panner.coneInnerAngle),a=ui.degToRad(e.panner.coneOuterAngle),l=o/2,c=a/2;let h=0,u=0,p,m;const f=this.geometry,g=f.attributes.position;f.clearGroups();function v(y,A,_,b){const x=(A-y)/_;for(g.setXYZ(h,0,0,0),u++,p=y;p<A;p+=x)m=h+u,g.setXYZ(m,Math.sin(p)*t,0,Math.cos(p)*t),g.setXYZ(m+1,Math.sin(Math.min(p+x,A))*t,0,Math.cos(Math.min(p+x,A))*t),g.setXYZ(m+2,0,0,0),u+=3;f.addGroup(h,u,b),h+=u,u=0}v(-c,-l,s,0),v(-l,l,r,1),v(l,c,s,0),g.needsUpdate=!0,o===a&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var $pe=Object.defineProperty,eme=Object.getOwnPropertyDescriptor,$l=(n,e,t,r)=>{for(var s=r>1?void 0:r?eme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&$pe(e,t,s),s};const Ms=te("debugaudio"),td=class extends Be{constructor(){super(...arguments),d(this,"clip",""),d(this,"playOnAwake",!1),d(this,"preload",!1),d(this,"_spatialBlend",0),d(this,"_minDistance",1),d(this,"_maxDistance",100),d(this,"_volume",1),d(this,"rollOffMode",0),d(this,"playInBackground",!0),d(this,"_loop",!1),d(this,"sound",null),d(this,"helper",null),d(this,"wasPlaying",!1),d(this,"audioLoader",null),d(this,"shouldPlay",!1),d(this,"_lastClipStartedLoading",null),d(this,"_audioElement",null),d(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||aa())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Ms&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,td.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&td.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),d(this,"onApplicationMuteChanged",()=>{var n,e;this.context.application.muted?(n=this.sound)==null||n.setVolume(0):(e=this.sound)==null||e.setVolume(this.volume)}),d(this,"createAudio",n=>{Ms&&console.log("AudioBuffer finished loading",n);const e=this.Sound;if(!e){Ms&&console.warn("Failed getting sound?",this.name);return}e.isPlaying&&e.stop(),n&&e.setBuffer(n),e.loop=this._loop,this.context.application.muted?e.setVolume(0):e.setVolume(this.volume),e.autoplay=this.shouldPlay&&td.userInteractionRegistered,this.applySpatialDistanceSettings(),e.isPlaying&&e.stop(),td.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),d(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),d(this,"_lastContextTime",0),d(this,"_hasEnded",!0),d(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Qu.userInteractionRegistered}static registerWaitForAllowAudio(n){Qu.registerWaitForAllowAudio(n)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(n){this._loop=n,this.sound&&this.sound.setLoop(n)}get spatialBlend(){return this._spatialBlend}set spatialBlend(n){n!==this._spatialBlend&&(this._spatialBlend=n,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(n){this._minDistance!==n&&(this._minDistance=n,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(n){this._maxDistance!==n&&(this._maxDistance=n,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(n){this._volume=n,this.sound&&!this.context.application.muted&&(Ms&&console.log(this.name,"audio set volume",n),this.sound.setVolume(n))}get Sound(){var n;if(!this.sound&&td.userInteractionRegistered){let e=ie.getComponent(this.context.mainCamera,ed)??ie.findObjectOfType(ed,this.context);!e&&this.context.mainCamera&&(e=ie.addNewComponent(this.context.mainCamera,ed)),e!=null&&e.listener?(this.sound=new fU(e.listener),(n=this.gameObject)==null||n.add(this.sound)):Ms&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var n;return(n=this.sound)==null?void 0:n.context}awake(){Ms&&console.log(this),this.audioLoader=new Nx,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),td.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():td.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(cS.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(cS.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const n=this.sound;if(!n)return;this._needUpdateSpatialDistanceSettings=!1;const e=it.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ms&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+e),n.setRefDistance(e),n.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:n.setDistanceModel("exponential");break;case 1:n.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Ms&&!this.helper&&(this.helper=new Zpe(n,n.getRefDistance()),n.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(n){if(n&&(this.clip=n),typeof n=="string")if(Ms&&console.log(n),n.endsWith(".mp3")||n.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new Nx),this.shouldPlay=!0,this._lastClipStartedLoading===n){Ms&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=n,Ms&&console.log("load audio",n);const e=await this.audioLoader.loadAsync(n).catch(console.error);this._lastClipStartedLoading=null,e&&this.createAudio(e)}else console.warn("Unsupported audio clip type",n);else this.shouldPlay=!0,this.createAudio()}play(n=void 0){var e,t,r;!n&&this.clip&&(n=this.clip),n!==void 0&&typeof n!="string"&&!(n instanceof MediaStream)&&(st()&&console.warn("Called play on AudioSource with unknown argument type:",n+`
5733
- Using the assigned clip instead:`,this.clip),n=this.clip);let s=!this.sound||n&&n!==this.clip;if(typeof n=="string"&&!this.audioLoader&&(s=!0),(n instanceof MediaStream||typeof n=="string")&&(this.clip=n),s){this.shouldPlay=!0,this.onNewClip(n);return}if(this.shouldPlay=!0,this._hasEnded=!1,Ms&&console.log("play",(e=this.sound)==null?void 0:e.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const o=this.context.application.muted;o&&this.sound.setVolume(0),(t=this.gameObject)==null||t.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||(r=this.context.domElement.shadowRoot)==null||r.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(o?.1:0))}}pause(){var n,e;Ms&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(n=this.sound)==null?void 0:n.context.currentTime,this.sound.pause()),(e=this._audioElement)==null||e.remove()}stop(){var n,e;Ms&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(n=this.sound)==null?void 0:n.context.currentTime,Ms&&console.log(this._lastContextTime),this.sound.stop()),(e=this._audioElement)==null||e.remove()}get isPlaying(){var n;return((n=this.sound)==null?void 0:n.isPlaying)??!1}set isPlaying(n){}get time(){var n,e;return(n=this.sound)!=null&&n.source?((e=this.sound.source)==null?void 0:e.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(n){if(this.sound){if(n===this.sound.offset)return;const e=this.isPlaying;this.stop(),this.sound.offset=n,e&&this.play()}}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,Ms&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let Mn=td;$l([w(URL)],Mn.prototype,"clip",2),$l([w()],Mn.prototype,"playOnAwake",2),$l([w()],Mn.prototype,"preload",2),$l([w()],Mn.prototype,"loop",1),$l([w()],Mn.prototype,"spatialBlend",1),$l([w()],Mn.prototype,"minDistance",1),$l([w()],Mn.prototype,"maxDistance",1),$l([w()],Mn.prototype,"volume",1),$l([w()],Mn.prototype,"rollOffMode",2),$l([w()],Mn.prototype,"playInBackground",2);var tme=Object.defineProperty,ime=Object.getOwnPropertyDescriptor,QS=(n,e,t,r)=>{for(var s=r>1?void 0:r?ime(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&tme(e,t,s),s};const nme=te("debugsignals");class EA{constructor(){d(this,"guid")}}QS([w()],EA.prototype,"guid",2);class qg{constructor(){d(this,"signal"),d(this,"reaction")}}QS([w(EA)],qg.prototype,"signal",2),QS([w(Un)],qg.prototype,"reaction",2);var gk;const xh=(gk=class extends Be{constructor(){super(...arguments),d(this,"events")}static invoke(n){if(xh.receivers[n]){const e=xh.receivers[n];if(!e)return;for(const t of e)t.invoke(n)}}awake(){nme&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const n of this.events)xh.receivers[n.signal.guid]||(xh.receivers[n.signal.guid]=[]),xh.receivers[n.signal.guid].push(this)}onDisable(){if(this.events){for(const n of this.events)if(xh.receivers[n.signal.guid]){const e=xh.receivers[n.signal.guid].indexOf(this);e>=0&&xh.receivers[n.signal.guid].splice(e,1)}}}invoke(n){if(!this.events||!Array.isArray(this.events))return;const e=typeof n=="object"?n.guid:n;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(r){console.error(r)}}},d(gk,"receivers",{}),gk);let Yg=xh;QS([w(qg)],Yg.prototype,"events",2);var zo=(n=>(n.Activation="ActivationTrack",n.Animation="AnimationTrack",n.Audio="AudioTrack",n.Control="ControlTrack",n.Marker="MarkerTrack",n.Signal="SignalTrack",n))(zo||{}),ec=(n=>(n[n.None=0]="None",n[n.Hold=1]="Hold",n[n.Loop=2]="Loop",n[n.PingPong=3]="PingPong",n[n.Continue=4]="Continue",n))(ec||{}),vk=(n=>(n.Signal="SignalEmitter",n))(vk||{});const tc=te("debugtimeline");class MA{constructor(){d(this,"director"),d(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let r=this.track.clips.length-1;r>=0;r--)yield this.track.clips[r];else for(const r of this.track.clips)yield r}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,r,s=!0){if(t<0||t>=r.length)return 0;const o=r[t];if(s||e>=o.start&&e<=o.end){let a=1;const l=!1;if(o.easeInDuration>0){const c=Math.min((e-o.start)/o.easeInDuration,1);a*=c}if(o.easeOutDuration>0&&!l){const c=Math.min((o.end-e)/o.easeOutDuration,1);a*=c}return a}return 0}}class rme{constructor(e){d(this,"clip"),d(this,"rootPositionOffset"),d(this,"rootQuaternionOffset"),d(this,"rootStartPosition"),d(this,"rootEndPosition"),d(this,"rootStartQuaternion"),d(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const r=e.getRoot(),s=r.name+".position",o=r.name+".quaternion";tc&&console.log(t.name,t.tracks,s);for(const a of t.tracks)if(!(a.times.length<=0)){if(a.name.endsWith(s))this.rootStartPosition=new C().fromArray(a.values,0),this.rootEndPosition=new C().fromArray(a.values,a.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),tc&&console.log(this.rootPositionOffset);else if(a.name.endsWith(o)&&(this.rootStartQuaternion=new Ce().fromArray(a.values,0),this.rootEndQuaternion=new Ce().fromArray(a.values,a.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),tc)){const l=new ii().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",l)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class HS extends MA{constructor(){super(...arguments),d(this,"models",[]),d(this,"trackOffset"),d(this,"target"),d(this,"mixer"),d(this,"clips",[]),d(this,"actions",[]),d(this,"_actionOffsets",[]),d(this,"_didBind",!1),d(this,"_animator",null),d(this,"_useclipOffsets",!0),d(this,"_totalOffsetPosition",new C),d(this,"_totalOffsetRotation",new Ce),d(this,"_totalOffsetPosition2",new C),d(this,"_totalOffsetRotation2",new Ce),d(this,"_summedPos",new C),d(this,"_tempPos",new C),d(this,"_summedRot",new Ce),d(this,"_tempRot",new Ce),d(this,"_clipRotQuat",new Ce)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&x8(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var r,s;if(((r=t.tracks)==null?void 0:r.length)<=0){console.warn("No tracks in AnimationClip",t);return}const o=t.tracks[0].name.split("."),a=o[o.length-2],l=a+".position",c=a+".quaternion";let h=!1,u=!1;for(const p of t.tracks)p.name.endsWith(l)?(h=!0,this.createPositionInterpolant(t,e,p)):p.name.endsWith(c)&&(u=!0,this.createRotationInterpolant(t,e,p));if(!h||!u){const p=(s=this.mixer)==null?void 0:s.getRoot(),m=t.tracks[0],f=m.name.lastIndexOf("."),g=m.name.substring(0,f),v=g.substring(g.lastIndexOf(".")+1),y=p.getObjectByName(v);if(y)if(h){if(!u){const A=t.tracks[0].name.substring(0,f)+".quaternion";tc&&console.warn("Create quaternion track",v,y);const _=y.quaternion,b=new sa(A,[0,t.duration],[_.x,_.y,_.z,_.w,_.x,_.y,_.z,_.w]);t.tracks.push(b),this.createRotationInterpolant(t,e,b)}}else{const A=g+".position";tc&&console.warn("Create position track",v,y);const _=y.position,b=new kl(A,[0,t.duration],[_.x,_.y,_.z,_.x,_.y,_.z]);t.tracks.push(b),this.createPositionInterpolant(t,e,b)}}}bind(){if(!this._didBind){this._didBind=!0,tc&&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 t=new rme(e);this._actionOffsets.push(t)}this.target&&(this._animator=ie.getComponent(this.target,Wr)??null,this._animator&&x8(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,r=t.position,s=t.rotation;r&&r.x!==void 0&&(r.isVector3||(t.position=new C(r.x,r.y,r.z)),s.isQuaternion||(t.rotation=new Ce(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 C(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new Ce(t.x,t.y,t.z,t.w)))}}evaluate(e){var t,r,s,o,a,l,c;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 h=0,u=0,p=!1,m=!1,f=0;for(let g=0;g<this.clips.length;g++){const v=this.models[g],y=this.actions[g],A=v.asset;y.weight=0;const _=e>=v.start&&e<=v.end,b=v.preExtrapolationMode,x=v.postExtrapolationMode,E=g<this.clips.length-1?this.models[g+1]:null;let I=_,T=!1;if(!I&&!p&&v.end<e&&x!==ec.None?(!E||E.start>e)&&(I=!0,p=!0):g==0&&!I&&!m&&v.start>e&&b!==ec.None&&(!E||E.start<e)&&(I=!0,T=!0,m=!0),I){let R=1;R*=this.evaluateWeight(e,g,this.models,I),R*=this.director.weight;let D=_;if(T)switch(b){case ec.Hold:break;case ec.Loop:e+=v.start,D=!0;break;default:e+=v.start,D=!0;break}let M=this.getClipTime(e,v),P=0;const z=A.duration;if(T&&b===ec.Hold&&(M=0),D){if(A.loop)for(P+=Math.floor(M/(z+1e-6));M>z;)M-=z}else if(!_&&p)switch(x){case ec.Hold:M=this.getClipTime(v.end,v);break;case ec.Loop:M%=z;break;case ec.PingPong:const L=Math.floor(M/z)%2!==0;M%=z,L&&(M=z-M);break}v.reversed===!0?y.time=y.getClip().duration-M:y.time=M,y.timeScale=0;const V=Math.max(0,R);if(y.weight=V,f+=V,y.clampWhenFinished=!1,y.isRunning()||y.play(),this._useclipOffsets){const L=h==0?this._totalOffsetPosition:this._totalOffsetPosition2,H=h==0?this._totalOffsetRotation:this._totalOffsetRotation2;h<1&&(u=1-R),h+=1;const O=this._summedPos.set(0,0,0),F=this._tempPos.set(0,0,0),G=this._summedRot.identity(),J=this._tempRot.identity(),K=A.rotation;K&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(K,R));const oe=this._actionOffsets[g];if(oe.hasOffsets)for(let we=0;we<P;we++)oe.rootPositionOffset?F.copy(oe.rootPositionOffset):F.set(0,0,0),F.applyQuaternion(G),this._clipRotQuat&&F.applyQuaternion(this._clipRotQuat),oe.rootQuaternionOffset&&(J.copy(oe.rootQuaternionOffset),G.multiply(J)),O.add(F);this._clipRotQuat&&H.multiply(this._clipRotQuat),H.multiply(G),A.position&&O.add(A.position),L.add(O)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(tc||st())&&(r=(t=this._animator)==null?void 0:t.runtimeAnimatorController)!=null&&r.mixer&&this.mixer!==((o=(s=this._animator)==null?void 0:s.runtimeAnimatorController)==null?void 0:o.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)),(a=this._animator)!=null&&a.runtimeAnimatorController){const g=Math.max(0,1-f);(c=(l=this._animator)==null?void 0:l.runtimeAnimatorController)==null||c.update(g)}else this.mixer.update(e)}createRotationInterpolant(e,t,r){var s;const o=r.createInterpolant.bind(r),a=new Ce;this.ensureTrackOffsets();const l=(s=this.trackOffset)==null?void 0:s.rotation;r.createInterpolant=()=>{const c=o(),h=c.evaluate.bind(c);return c.evaluate=u=>{var p;const m=h(u);if(a.set(m[0],m[1],m[2],m[3]),a.premultiply(this._totalOffsetRotation),l&&a.premultiply(l),this.director.animationCallbackReceivers)for(const f of this.director.animationCallbackReceivers)(p=f?.onTimelineRotation)==null||p.call(f,this.director,this.target,u,a);return m[0]=a.x,m[1]=a.y,m[2]=a.z,m[3]=a.w,m},c}}createPositionInterpolant(e,t,r){var s,o;const a=r.createInterpolant.bind(r),l=new C;this.ensureTrackOffsets();const c=(s=this.trackOffset)==null?void 0:s.rotation,h=(o=this.trackOffset)==null?void 0:o.position;let u;r.createInterpolant=()=>{const p=a(),m=p.evaluate.bind(p);return p.evaluate=f=>{var g,v,y;const A=m(f);if(l.set(A[0],A[1],A[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(v=(g=this._actionOffsets.find(_=>_.clip===e))==null?void 0:g.rootStartPosition)==null?void 0:v.clone()):u!=null&&u.isVector3&&l.sub(u)),l.applyQuaternion(this._totalOffsetRotation),l.add(this._totalOffsetPosition),c&&l.applyQuaternion(c),h&&(l.x-=h.x,l.y+=h.y,l.z+=h.z),this.director.animationCallbackReceivers)for(const _ of this.director.animationCallbackReceivers)(y=_?.onTimelinePosition)==null||y.call(_,this.director,this.target,f,l);return A[0]=l.x,A[1]=l.y,A[2]=l.z,A},p}}}const sme=te("mutetimeline"),TA=class extends MA{constructor(){super(...arguments),d(this,"models",[]),d(this,"listener"),d(this,"audio",[]),d(this,"audioContextTimeOffset",[]),d(this,"lastTime",0),d(this,"audioSource"),d(this,"_audioLoader",null),d(this,"_playableDirectorResumed",!1)}getAudioFilePath(n){const e=this.director.sourceId;return cu(e,n)}onAllowAudioChanged(n){for(let e=0;e<this.models.length;e++){const t=this.models[e];this.audio[e].setVolume(n?t.asset.volume:0)}}addModel(n){const e=new gI(this.listener);this.audio.push(e);const t=n;t._didTriggerPlay=!1,this.models.push(t)}onDisable(){for(const n of this.audio)n.isPlaying&&n.stop();for(const n of this.models)n._didTriggerPlay=!1}onDestroy(){for(const n of this.audio)n.source&&n?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let n=0;n<this.audio.length;n++){const e=this.audio[n];e!=null&&e.isPlaying&&e.stop()}}stop(){for(let n=0;n<this.audio.length;n++){const e=this.audio[n];e!=null&&e.isPlaying&&e.stop()}for(const n of this.models)n._didTriggerPlay=!1}onPauseChanged(){for(let n=0;n<this.audio.length;n++){const e=this.audio[n];e!=null&&e.isPlaying&&e.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(n){if(sme||this.track.muted||this.director.speed<0)return;const e=this.director.context.application.muted,t=this._playableDirectorResumed;this._playableDirectorResumed=!1;const r=e?.1:0;for(let s=0;s<this.models.length;s++){const o=this.models[s],a=this.audio[s],l=o.asset;if((!a||!a.buffer)&&this.isInTimeRange(o,n-1,n+1)&&this.handleAudioLoading(o,a),Mn.userInteractionRegistered!==!1&&!(a===null||!a.buffer))if(a.playbackRate=this.director.context.time.timeScale*this.director.speed,a.loop=l.loop,n>=o.start&&n<=o.end&&n<this.director.duration){if(!a.isPlaying||!this.director.isPlaying)(t||!o._didTriggerPlay&&this.lastTime<n)&&(o.duration*o.timeScale>.3?a.offset=o.clipIn+(n-o.start)*o.timeScale:a.offset=0,tc&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+o.asset.clip),a.play(r),o._didTriggerPlay=!0);else{const h=o.clipIn+(n-o.start)*o.timeScale,u=a.context.currentTime-a._startedAt+a.offset;Math.abs(h-u)>.3&&(a.offset=h,a.stop(),a.play(r))}let c=l.volume;if(this.track.volume!==void 0&&(c*=this.track.volume),e&&(c=0),o.easeInDuration>0){const h=Math.min((n-o.start)/o.easeInDuration,1);c*=h}if(o.easeOutDuration>0){const h=Math.min((o.end-n)/o.easeOutDuration,1);c*=h}a.setVolume(c*this.director.weight)}else o._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=n}loadAudio(n,e=0,t=0){let r=null;const s=n-t,o=n+e;for(const a of this.models)if(this.isInTimeRange(a,s,o)){const l=this.audio[this.models.indexOf(a)],c=this.handleAudioLoading(a,l);c!==null&&(r===null&&(r=[]),r.push(c))}return r!==null?Promise.all(r):null}isInTimeRange(n,e,t){return e<=n.start&&t>=n.end||e>=n.start&&e<=n.end||t>=n.start&&t<=n.end}static dispose(){TA._audioBuffers.clear()}handleAudioLoading(n,e){this._audioLoader||(this._audioLoader=new Nx);const t=this.getAudioFilePath(n.asset.clip);if(TA._audioBuffers.get(t)){const s=TA._audioBuffers.get(t);return s.then(o=>{o&&e.setBuffer(o)}),s}tc&&console.warn("LOAD audio track",t,this.director.sourceId);const r=new Promise((s,o)=>{this._audioLoader.load(t,a=>{e.setBuffer(a),s(a)},void 0,a=>{console.error("Error loading audio",a),s(null)})});return TA._audioBuffers.set(t,r),r}};let IA=TA;d(IA,"_audioBuffers",new Map);class RA extends MA{constructor(){super(...arguments),d(this,"models",[]),d(this,"didTrigger",[]),d(this,"receivers",[])}evaluate(e){var t;if(this.track.muted)return;const r=this.director.context.time.deltaTime*1.5;for(let s=0;s<this.models.length;s++){const o=this.models[s],a=this.didTrigger[s],l=o.time-e;let c=!1;if(o.retroActive)c=l<=1e-6;else{const h=Math.abs(l);(h===0||h>=1e-5&&h<r)&&(c=!0)}if(c){if(!a)if(tc&&console.log("Trigger signal",e,o.time,o),this.didTrigger[s]=!0,((t=this.receivers)==null?void 0:t.length)<=0)Yg.invoke(o.asset);else for(const h of this.receivers)h&&h.invoke(o.asset)}else o.emitOnce||(this.didTrigger[s]=!1)}}}class WS extends MA{constructor(){super(...arguments),d(this,"models",[]),d(this,"timelines",[]),d(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const r=this.models[t].asset;if(!r.sourceObject||typeof r.sourceObject!="object"){console.log("no source object, removing model",t,r),this.models.splice(t,1);continue}else{const s=ie.getComponent(r.sourceObject,id);this.timelines.push(s),s&&r.updateDirector&&(s.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let r=0;r<this.models.length;r++){const s=this.models[r],o=s.asset;if(e>=s.start&&e<=s.end){this._previousActiveModel=s;const a=this.getClipTime(e,s);if(o.controlActivation){const l=o.sourceObject;l.visible=!0}if(o.updateDirector){const l=this.timelines[r];l&&(l.isPlaying&&l.pause(),l.time=a,l.evaluate())}}else{const a=(t=this._previousActiveModel)==null?void 0:t.asset;if(o.controlActivation){const l=o.sourceObject;a?.sourceObject!==l&&(l.visible=!1)}}}}}var ome=Object.defineProperty,ame=Object.getOwnPropertyDescriptor,_8=(n,e,t,r)=>{for(var s=r>1?void 0:r?ame(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ome(e,t,s),s};const Jg=te("debugtimeline");var yk;const Ak=(yk=class extends Be{constructor(){super(...arguments),d(this,"playableAsset"),d(this,"playOnAwake"),d(this,"extrapolationMode",1),d(this,"waitForAudio",!0),d(this,"_visibilityChangeEvt"),d(this,"_clonedPlayableAsset",!1),d(this,"_speed",1),d(this,"_guidsMap"),d(this,"_isPlaying",!1),d(this,"_internalUpdateRoutine"),d(this,"_isPaused",!1),d(this,"_isStopping",!1),d(this,"_time",0),d(this,"_duration",0),d(this,"_weight",1),d(this,"_animationTracks",[]),d(this,"_audioTracks",[]),d(this,"_signalTracks",[]),d(this,"_controlTracks",[]),d(this,"_customTracks",[]),d(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),d(this,"animationCallbackReceivers",[])}static registerCreateTrack(n,e){this.createTrackFunctions[n]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(n){typeof n=="number"&&!Number.isNaN(n)?this._time=n:(Jg||js())&&console.error("INVALID TIMELINE.TIME VALUE",n,this.name)}get duration(){return this._duration}set duration(n){this._duration=n}get weight(){return this._weight}set weight(n){this._weight=n}get speed(){return this._speed}set speed(n){this._speed=n}awake(){var n,e,t;Jg&&console.log(this,(n=this.playableAsset)==null?void 0:n.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(e=this.playableAsset)==null?void 0:e.tracks,Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this)}onEnable(){var n,e,t;for(const r of this._audioTracks)(n=r.onEnable)==null||n.call(r);for(const r of this._customTracks)(e=r.onEnable)==null||e.call(r);for(const r of this._animationTracks)(t=r.onEnable)==null||t.call(r);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 n,e,t;this.stop();for(const r of this._audioTracks)(n=r.onDisable)==null||n.call(r);for(const r of this._customTracks)(e=r.onDisable)==null||e.call(r);for(const r of this._animationTracks)(t=r.onDisable)==null||t.call(r);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var n;for(const e of this._allTracks)for(const t of e)(n=t.onDestroy)==null||n.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const n=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,n&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const e=[];for(const t of this._audioTracks){const r=t.loadAudio(this._time,1,0);r&&e.push(r)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Mn.userInteractionRegistered&&this.waitForAudio;)await Ll(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Hi.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const t of this._audioTracks)t.stop();const n=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),n&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,n&&!e&&this.invokePauseChangedMethodsOnTracks(),e&&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 n of this._allTracks)for(const e of n)yield e}get audioTracks(){return this._audioTracks}resolveGuids(n){this._guidsMap=n}invokePauseChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onPauseChanged)==null||n.call(e)}invokeStateChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onStateChanged)==null||n.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(n=!1){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}const t=this._time;for(const r of this.playableAsset.tracks)if(!r.muted)switch(r.type){case zo.Activation:if(!n&&!this._isPlaying)continue;for(let s=0;s<r.outputs.length;s++){const o=r.outputs[s];if(typeof o=="object"){let a=!1;if(r.clips)for(const c of r.clips)c.start<=t&&t<=c.end&&(a=!0);const l=o;l.visible!==void 0&&l.visible!==a&&(l.visible=a,Jg&&console.warn(this.name,"set ActivationTrack-"+s,l.name,a,t))}}break}if(!this._isStopping)for(const r of this._animationTracks)r.evaluate(t);for(const r of this._audioTracks)r.evaluate(t);for(const r of this._signalTracks)r.evaluate(t);for(const r of this._controlTracks)r.evaluate(t);for(const r of this._customTracks)r.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Nv(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const n=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let r=e.outputs[t];if(typeof r=="string"){this._guidsMap&&this._guidsMap[r]&&(r=this._guidsMap[r]);const s=ie.findByGuid(r,n);s===null||typeof s!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",r,e.name,e.type)):(Jg&&console.log("Resolved binding",r,"to",s),e.outputs[t]=s)}else if(r===null){if(e.outputs.splice(t,1),Ak.createTrackFunctions[e.type])continue;e.type!==zo.Audio&&e.type!==zo.Control&&e.type!==zo.Marker&&e.type!==zo.Signal&&console.warn("Missing binding",r,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===zo.Control&&e.clips)for(let t=0;t<e.clips.length;t++){const r=e.clips[t];let s=r.asset.sourceObject;if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const o=ie.findByGuid(s,n);o===null||typeof o!="object"?console.warn("Failed to resolve sourceObject binding",s,e.name,r):(Jg&&console.log("Resolved binding",s,"to",o),r.asset.sourceObject=o)}}}}findRoot(n){return n.parent?this.findRoot(n.parent):n}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const n of this.playableAsset.tracks)if(n.muted!==!0){if(n.clips)for(const e of n.clips)e.end>this._duration&&(this._duration=e.end);if(n.markers)for(const e of n.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var n,e,t;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let r=ie.findObjectOfType(ed,this.context);for(const s of this.playableAsset.tracks){const o=s.type,a=Ak.createTrackFunctions[o];if(a!=null){const l=a(this,s);if(typeof l.evaluate=="function"){l.director=this,l.track=s,this._customTracks.push(l);continue}}if(s.type===zo.Animation){if(!s.clips||s.clips.length<=0){Jg&&console.warn("Animation track has no clips",s);continue}for(let l=s.outputs.length-1;l>=0;l--){let c=s.outputs[l];if(c instanceof ye){const u=ie.getOrAddComponent(c,Wr);u&&(c=u)}const h=(n=c?.gameObject)==null?void 0:n.animations;if(h){const u=new HS;u.trackOffset=s.trackOffset,u.director=this,u.track=s;for(let p=0;p<s.clips.length;p++){const m=s.clips[p],f=m.asset;if(!f){console.error(`Timeline ${this.name}: clip #${p} on track "${s.name}" has no animation data`);continue}const g=f.clip;let v=g;if((typeof v=="string"||typeof v=="number")&&(v=h.find(A=>A.name===g)),!v){console.warn("Could not find animationClip for model",m,s.name,this.name,(e=this.playableAsset)==null?void 0:e.name);continue}c instanceof Wr&&c.runtimeAnimatorController&&(c.__internalDidAwakeAndStart||c.initializeRuntimeAnimatorController(),c.runtimeAnimatorController.mixer||c.runtimeAnimatorController.bind(c),u.mixer=c.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new zx(c.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(v),u.mixer.uncacheAction(v),u.createHooks(m.asset,v);const y=u.mixer.clipAction(v);u.actions.push(y),u.models.push(m)}this._animationTracks.push(u)}}}else if(s.type===zo.Audio){if(!s.clips||s.clips.length<=0)continue;const l=new IA;l.director=this,l.track=s,l.audioSource=s.outputs.find(c=>c instanceof Mn),this._audioTracks.push(l),r||(r=(t=this.context.mainCameraComponent)==null?void 0:t.gameObject.addNewComponent(ed)),l.listener=r.listener;for(let c=0;c<s.clips.length;c++){const h=s.clips[c];l.addModel(h)}}else if(s.type===zo.Marker){const l=new RA;if(l.director=this,l.track=s,s.markers)for(const c of s.markers)switch(c.type){case vk.Signal:l.models.push(c),l.didTrigger.push(!1);break}if(l!==null&&l.models.length>0){const c=ie.getComponent(this.gameObject,Yg);c&&(l.receivers.push(c),this._signalTracks.push(l))}}else if(s.type===zo.Signal){const l=new RA;if(l.director=this,l.track=s,s.markers)for(const c of s.markers)l.models.push(c),l.didTrigger.push(!1);for(const c of s.outputs)l.receivers.push(c);this._signalTracks.push(l)}else if(s.type===zo.Control){const l=new WS;if(l.director=this,l.track=s,s.clips)for(const c of s.clips)l.models.push(c);l.resolveSourceObjects(this.context),this._controlTracks.push(l)}}}setAudioTracksAllowPlaying(n){for(const e of this._audioTracks)e.onAllowAudioChanged(n)}registerAnimationCallback(n){this.animationCallbackReceivers.push(n)}unregisterAnimationCallback(n){const e=this.animationCallbackReceivers.indexOf(n);e!==-1&&this.animationCallbackReceivers.splice(e,1)}},d(yk,"createTrackFunctions",{}),yk);let id=Ak;_8([w()],id.prototype,"playOnAwake",2),_8([w()],id.prototype,"extrapolationMode",2);const XS=Symbol("objectIsAnimatedData");function x8(n,e,t){if(!n)return;if(n[XS]===void 0){if(!t)return;n[XS]=new Set}const r=n[XS];t?r.add(e):r.has(e)&&r.delete(e)}function lme(n){if(!n)return!1;const e=n[XS];return e!==void 0&&e.size>0}di.registerCallback(Ci.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&n.files)for(const t of n.files)ie.foreachComponent(t.file.scene,r=>{if(r.enabled!==!1){if(r instanceof Es&&r.playAutomatically||r instanceof Wr||r instanceof id&&r.playOnAwake===!0)return!0;if(r instanceof Es)return r.playAutomatically=!0,!0;if(r instanceof id)return r.playOnAwake=!0,!0}},!0)!==!0&&Bg.assignAnimationsFromFile(t.file,{createAnimationComponent:(r,s)=>gl(r,Es)})});class cme{constructor(){d(this,"_context")}get context(){return this._context??kt.Current}get isStateMachineBehaviour(){return!0}}class PA{constructor(e,t,r,s){d(this,"name"),d(this,"nameHash"),d(this,"normalizedTime"),d(this,"length"),d(this,"speed"),d(this,"action"),d(this,"hasTransitions");var o;this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=r,this.speed=s,this.action=e.motion.action||null,this.hasTransitions=((o=e.transitions)==null?void 0:o.length)>0||!1}}function w8(n,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??ui.generateUUID(),index:-1,clip:new zs(n,0,[])}}var nd=(n=>(n[n.If=1]="If",n[n.IfNot=2]="IfNot",n[n.Greater=3]="Greater",n[n.Less=4]="Less",n[n.Equals=6]="Equals",n[n.NotEqual=7]="NotEqual",n))(nd||{}),bk=(n=>(n[n.Float=1]="Float",n[n.Int=3]="Int",n[n.Bool=4]="Bool",n[n.Trigger=9]="Trigger",n))(bk||{});const Er=te("debuganimatorcontroller"),qS=te("debugrootmotion");class ea{constructor(e){d(this,"_speed",1),d(this,"normalizedStartOffset",0),d(this,"animator"),d(this,"model"),d(this,"_mixer"),d(this,"_activeState"),d(this,"_activeStates",[]),d(this,"_heldActions",[]),d(this,"rootMotionHandler"),this.model=e,Er&&console.log(this)}static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const r=[];for(let o=0;o<e.length;o++){const a=e[o],l=[];if(t.autoTransition!==!1){const h=t.transitionDuration??0,u=h/a.duration;let p=o;(t.autoTransition===void 0||t.autoTransition===!0)&&(p=(o+1)%e.length),l.push({exitTime:1-u,offset:0,duration:h,hasExitTime:!0,destinationState:p,conditions:[]})}const c={name:a.name,hash:o,motion:{name:a.name,clip:a,isLooping:t?.looping??!1},transitions:l,behaviours:[]};r.push(c)}const s={name:"AnimatorController",guid:new Dr(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:r}}]};return new ea(s)}play(e,t=-1,r=Number.NEGATIVE_INFINITY,s=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[t].stateMachine;for(const a of o.states)if(a.name===e||a.hash===e){Er&&console.log("transition to ",a),this.transitionTo(a,s,r);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var r,s;const o=typeof e=="string"?"name":"hash";return(s=(r=this.model)==null?void 0:r.parameters)==null?void 0:s.filter(a=>a[o]===e).forEach(a=>a.value=t)}getBool(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??!1}setFloat(e,t){var r,s;const o=typeof e=="string"?"name":"hash",a=(s=(r=this.model)==null?void 0:r.parameters)==null?void 0:s.filter(l=>l[o]===e);return a.forEach(l=>l.value=t),a?.length>0}getFloat(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??0}setInteger(e,t){var r,s;const o=typeof e=="string"?"name":"hash";return(s=(r=this.model)==null?void 0:r.parameters)==null?void 0:s.filter(a=>a[o]===e).forEach(a=>a.value=t)}getInteger(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??0}setTrigger(e){var t,r;Er&&console.log("SET TRIGGER",e);const s=typeof e=="string"?"name":"hash";return(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.filter(o=>o[s]===e).forEach(o=>o.value=!0)}resetTrigger(e){var t,r;const s=typeof e=="string"?"name":"hash";return(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.filter(o=>o[s]===e).forEach(o=>o.value=!1)}getTrigger(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const r of t.stateMachine.states)if(r.name===e||r.hash==e)return r}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,r=t<=0?0:Math.abs(e.time/t);return new PA(this._activeState,r,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var e;return(e=this.animator)==null?void 0:e.context}get mixer(){return this._mixer}dispose(){var e;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const t of this._activeStates)t.motion.clip&&this.mixer.uncacheAction(t.motion.clip,this.animator.gameObject)}(e=this.context)==null||e.animations.unregisterAnimationMixer(this._mixer)}bind(e){var t,r;e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new zx(this.animator.gameObject),(r=this.context)==null||r.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;Er&&console.warn("AnimatorController clone()",this.model);const e=Nv(this.model,(t,r,s)=>s==null?!0:!(s.type==="Object3D"||s.isObject3D===!0||oz(s)||s.tracks!==void 0||s instanceof ea));return console.assert(e!==this.model),new ea(e)}update(e){var t,r;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const s=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(e)),this._mixer.update(s),this.animator.applyRootMotion&&((r=this.rootMotionHandler)==null||r.onAfterUpdate(e))}get activeState(){return this._activeState}updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const r=this._activeStates[t],s=r.motion;if(!s.action)this._activeStates.splice(t,1),t--;else{const o=s.action;o.weight=e,o.getEffectiveWeight()<=0&&!o.isRunning()&&(Er&&console.debug("REMOVE",r.name,o.getEffectiveWeight(),o.isRunning(),o.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){var e;this.model.layers.length>1&&(Er||st())&&console.warn("Multiple layers are not supported yet "+((e=this.animator)==null?void 0:e.name));for(const t of this.model.layers){const r=t.stateMachine;r.defaultState===void 0&&(Er&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",t),r.defaultState=0);const s=r.states[r.defaultState];this.transitionTo(s,0,this.normalizedStartOffset);break}}evaluateTransitions(){var e;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const r=this._activeState,s=r.motion.action;for(const a of r.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(s){const c=r.motion.clip.duration,h=c<=0?1:Math.abs(s.time/c);let u=a.exitTime;s.timeScale<0&&(u=1-u);let p=!1;if(a.hasExitTime?s.timeScale>0?p=h>=a.exitTime:s.timeScale<0&&(p=1-h>=a.exitTime):p=!0,p){for(const m of a.conditions){const f=this.model.parameters.find(g=>g.name===m.parameter);f?.type===bk.Trigger&&f.value&&(f.value=!1)}if(s.clampWhenFinished=!0,Er){const m=this.getState(a.destinationState,0);console.log(`Transition to ${a.destinationState} / ${m?.name}`,a,`
5732
+ `;var Mpe=Object.defineProperty,Tpe=Object.getOwnPropertyDescriptor,ak=(n,e,t,r)=>{for(var s=r>1?void 0:r?Tpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Mpe(e,t,s),s};class nm extends Be{constructor(){super(...arguments),d(this,"constraintActive",!0),d(this,"locked",!1),d(this,"sources",[])}}ak([w()],nm.prototype,"constraintActive",2),ak([w()],nm.prototype,"locked",2),ak([w(ye)],nm.prototype,"sources",2);function Ipe(n,e){return Nu(n,Ci.ContextCreated,e),()=>zu(n,Ci.ContextCreated)}function Rpe(n,e){return Nu(n,Ci.ContextClearing,e),()=>zu(n,Ci.ContextClearing)}function Ppe(n,e){return Nu(n,Ci.ContextDestroying,e),()=>zu(n,Ci.ContextDestroying)}function fV(n,e){return Nu(n,Hi.Start,e),()=>zu(n,Hi.Start)}function gV(n,e){return Nu(n,Hi.Update,e),()=>zu(n,Hi.Update)}function Bpe(n,e){return Nu(n,Hi.OnBeforeRender,e),()=>zu(n,Hi.OnBeforeRender)}function kpe(n,e){return Nu(n,Hi.OnAfterRender,e),()=>zu(n,Hi.OnAfterRender)}class rm{constructor(){d(this,"bb",null),d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,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(e,t,r,s){return e.prep(4,12),e.writeFloat32(s),e.writeFloat32(r),e.writeFloat32(t),e.offset()}}class vV{constructor(){d(this,"bb",null),d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new rm).__init(this.bb_pos,this.bb)}rotation(e){return(e||new rm).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new rm).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,r,s,o,a,l,c,h,u){return e.prep(4,36),e.prep(4,12),e.writeFloat32(u),e.writeFloat32(h),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(a),e.writeFloat32(o),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(r),e.writeFloat32(t),e.offset()}}class Vh{constructor(){d(this,"bb",null),d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Vh).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+bB),(t||new Vh).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new vV).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var Cr=(n=>(n[n.Average=0]="Average",n[n.Multiply=1]="Multiply",n[n.Minimum=2]="Minimum",n[n.Maximum=3]="Maximum",n))(Cr||{}),LS=(n=>(n[n.Discrete=0]="Discrete",n[n.Continuous=1]="Continuous",n))(LS||{}),Nn=(n=>(n[n.None=0]="None",n[n.FreezePositionX=2]="FreezePositionX",n[n.FreezePositionY=4]="FreezePositionY",n[n.FreezePositionZ=8]="FreezePositionZ",n[n.FreezePosition=14]="FreezePosition",n[n.FreezeRotationX=16]="FreezeRotationX",n[n.FreezeRotationY=32]="FreezeRotationY",n[n.FreezeRotationZ=64]="FreezeRotationZ",n[n.FreezeRotation=112]="FreezeRotation",n[n.FreezeAll=126]="FreezeAll",n))(Nn||{}),Wg=(n=>(n[n.None=0]="None",n[n.X=2]="X",n[n.Y=4]="Y",n[n.Z=8]="Z",n[n.All=-1]="All",n))(Wg||{});const Hr=function(n,e){return function(t,r,s){Dpe(t,r,s,n,e)}};function Dpe(n,e,t,r,s){if(!s&&!r&&!n.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",n,e,t),rn("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Bo.Error);return}let o="";if(typeof e=="string"?o=e:o=e.name,n.__internalAwake){const a=Symbol(o),l=n.__internalAwake;n.__internalAwake=function(){var c;if(!this.onValidate){st()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((c=n.constructor)==null?void 0:c.name)+'"');return}if(this[a]===void 0){this[a]=this[o];const h=this[o];if(h instanceof Z||h instanceof C||h instanceof Ye||h instanceof Ce){const u=this[o];Zx(u,()=>{this.onValidate(o)})}Object.defineProperty(this,o,{set:function(u){var p;if(this[lB]===!0)this[a]=u;else{r?.call(this,u);const m=this[a];this[a]=u,(p=this.onValidate)==null||p.call(this,o,m)}},get:function(){return s?.call(this),this[a]}})}l.call(this)}}}const Ope=function(n){return function(e,t,r){let s="";typeof t=="string"?s=t:s=t.name;const o=n.prototype,a=Object.getOwnPropertyDescriptor(o,s);if(!(a!=null&&a.value)){console.warn("Can not apply prefix: type does not have method named",t,n);return}const l=a.value,c=e[s];Object.defineProperty(o,s,{value:function(...h){const u=c?.call(this,...h);if(u instanceof Promise){u.then(p=>{if(p!==!1)return l.call(this,...h)});return}if(u!==!1)return l.call(this,...h)}})}};var Lpe=Object.defineProperty,Fpe=Object.getOwnPropertyDescriptor,Uo=(n,e,t,r)=>{for(var s=r>1?void 0:r?Fpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Lpe(e,t,s),s};class Upe{constructor(e,t){d(this,"positionChanged",!1),d(this,"rotationChanged",!1),d(this,"position"),d(this,"quaternion"),d(this,"_positionKeys",["x","y","z"]),d(this,"_quaternionKeys",["_x","_y","_z","_w"]),d(this,"mute",!1),d(this,"context"),d(this,"obj"),d(this,"_positionWatch"),d(this,"_rotationWatch"),this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new Nh(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((o,a)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const c=this.position[a];Math.abs(c-o)<1e-5||(this.position[a]=o,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new Nh(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((o,a)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const c=this.quaternion[a];Math.abs(c-o)<1e-5||(this.quaternion[a]=o,this.rotationChanged=!0)}));const r=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),s=new ve;this.obj.matrixWorld.multiplyMatrices=(o,a)=>{var l;return(l=this.context.physics.engine)!=null&&l.isUpdating||this.mute||s.equals(o)||(this.positionChanged=!0,this.rotationChanged=!0,s.copy(o)),r(o,a)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var lk;const ck=(lk=class extends Be{constructor(){super(...arguments),d(this,"autoMass",!0),d(this,"_mass",0),d(this,"useGravity",!0),d(this,"centerOfMass",new C(0,0,0)),d(this,"constraints",Nn.None),d(this,"isKinematic",!1),d(this,"drag",0),d(this,"angularDrag",1),d(this,"detectCollisions",!0),d(this,"sleepThreshold",.01),d(this,"collisionDetectionMode",LS.Discrete),d(this,"_gravityScale",1),d(this,"dominanceGroup",0),d(this,"_propertiesChanged",!1),d(this,"_currentVelocity",new C),d(this,"_smoothedVelocity",new C),d(this,"_smoothedVelocityGetter",new C),d(this,"_lastPosition",new C),d(this,"_watch")}set mass(n){n!==this._mass&&(this._mass=n,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var n,e;return this.autoMass?((e=(n=this.context.physics.engine)==null?void 0:n.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Nn.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Nn.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Nn.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Nn.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Nn.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Nn.FreezeRotationZ)!==0}set lockPositionX(n){n?this.constraints|=Nn.FreezePositionX:this.constraints&=~Nn.FreezePositionX}set lockPositionY(n){n?this.constraints|=Nn.FreezePositionY:this.constraints&=~Nn.FreezePositionY}set lockPositionZ(n){n?this.constraints|=Nn.FreezePositionZ:this.constraints&=~Nn.FreezePositionZ}set lockRotationX(n){n?this.constraints|=Nn.FreezeRotationX:this.constraints&=~Nn.FreezeRotationX}set lockRotationY(n){n?this.constraints|=Nn.FreezeRotationY:this.constraints&=~Nn.FreezeRotationY}set lockRotationZ(n){n?this.constraints|=Nn.FreezeRotationZ:this.constraints&=~Nn.FreezeRotationZ}set gravityScale(n){this._gravityScale=n}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new Upe(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Hi.LateUpdate)}onDisable(){var n,e;(n=this._watch)==null||n.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var n;(n=this.context.physics.engine)==null||n.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var n,e,t,r;;)this._propertiesChanged&&(this._propertiesChanged=!1,(n=this.context.physics.engine)==null||n.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(r=this._watch)==null||r.syncValues(),this.captureVelocity(),yield}teleport(n,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(n.x,n.y,n.z):this.setWorldPosition(n.x,n.y,n.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(n=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,n)}resetTorques(n=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,n)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var n;(n=this.context.physics.engine)==null||n.wakeup(this)}get isSleeping(){var n;return(n=this.context.physics.engine)==null?void 0:n.isSleeping(this)}updateProperties(){var n;return this._propertiesChanged=!1,(n=this.context.physics.engine)==null?void 0:n.updateProperties(this)}applyForce(n,e,t=!0){var r;this._propertiesChanged&&this.updateProperties(),(r=this.context.physics.engine)==null||r.addForce(this,n,t)}applyImpulse(n,e=!0){var t;this._propertiesChanged&&this.updateProperties(),(t=this.context.physics.engine)==null||t.applyImpulse(this,n,e)}setForce(n,e,t,r=!0){var s,o,a;(s=this.context.physics.engine)==null||s.resetForces(this,r),typeof n=="number"?(e??(e=0),t??(t=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:n,y:e,z:t},r)):(a=this.context.physics.engine)==null||a.addForce(this,n,r)}getVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,r=!0){var s,o;if(n instanceof C){const a=n;(s=this.context.physics.engine)==null||s.setLinearVelocity(this,a,r);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:n,y:e,z:t},r)}getAngularVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,r=!0){var s,o;if(n instanceof C){const a=n;(s=this.context.physics.engine)==null||s.setAngularVelocity(this,a,r);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:n,y:e,z:t},r)}setTorque(n,e,t){this.setAngularVelocity(n,e,t)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(n=null){}captureVelocity(){const n=Bt(this.gameObject);ck.tempPosition.copy(n);const e=n.sub(this._lastPosition);this._lastPosition.copy(ck.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},d(lk,"tempPosition",new C),lk);let Oi=ck;Uo([Hr()],Oi.prototype,"autoMass",2),Uo([w()],Oi.prototype,"mass",1),Uo([Hr(),w()],Oi.prototype,"useGravity",2),Uo([w(C)],Oi.prototype,"centerOfMass",2),Uo([Hr(),w()],Oi.prototype,"constraints",2),Uo([Hr(),w()],Oi.prototype,"isKinematic",2),Uo([Hr(),w()],Oi.prototype,"drag",2),Uo([Hr(),w()],Oi.prototype,"angularDrag",2),Uo([Hr(),w()],Oi.prototype,"detectCollisions",2),Uo([Hr(),w()],Oi.prototype,"sleepThreshold",2),Uo([Hr(),w()],Oi.prototype,"collisionDetectionMode",2),Uo([Hr()],Oi.prototype,"_gravityScale",2),Uo([Hr()],Oi.prototype,"dominanceGroup",2);const Ju=te("debugsync"),AA="STRS";wB(AA,Vh.getRootAsSyncedTransformModel);const Zl=new s_;function yV(n,e,t=!0){Zl.clear();const r=Zl.createString(n);Vh.startSyncedTransformModel(Zl),Vh.addGuid(Zl,r),Vh.addFast(Zl,t);const s=e.worldPosition,o=e.worldEuler,a=e.gameObject.scale;Vh.addTransform(Zl,vV.createTransform(Zl,s.x,s.y,s.z,o.x,o.y,o.z,a.x,a.y,a.z));const l=Vh.endSyncedTransformModel(Zl);return Zl.finish(l,AA),Zl.asUint8Array()}let hk=0,bA=0;gV(n=>{var e;const t=(e=n.connection.currentServerUrl)!=null&&e.includes("glitch")?10:40;bA=Math.floor(hk/t),hk=0,Ju&&bA>0&&console.log("Sync Transform Fast Interval",bA)});class Ku extends Be{constructor(){super(...arguments),d(this,"overridePhysics",!0),d(this,"interpolatePosition",!0),d(this,"interpolateRotation",!0),d(this,"fastMode",!1),d(this,"syncDestroy",!1),d(this,"_model",null),d(this,"_needsUpdate",!0),d(this,"rb",null),d(this,"_wasKinematic",!1),d(this,"_receivedDataBefore",!1),d(this,"_targetPosition"),d(this,"_targetRotation"),d(this,"_receivedFastUpdate",!1),d(this,"_shouldRequestOwnership",!1),d(this,"joinedRoomCallback",null),d(this,"receivedDataCallback",null),d(this,"tempEuler",new ii),d(this,"receivedUpdate",!1),d(this,"lastWorldPos"),d(this,"lastWorldRotation")}requestOwnership(){Ju&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}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(){Ju&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new C,this._targetRotation=new Ce,this.lastWorldPos=new C,this.lastWorldRotation=new Ce,this.rb=ie.getComponentInChildren(this.gameObject,Oi),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new jB(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Vt.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(AA,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&$B(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Vt.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(AA,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Ju&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const r=e.transform();if(r){Qa.markDirty(this.gameObject,!0);const s=r.position();s&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(s.x(),s.y(),s.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(s.x(),s.y(),s.z()));const o=r.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&ER(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),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){Ju&&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,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=e.distanceTo(this.lastWorldPos),a=t.angleTo(this.lastWorldRotation),l=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>l||a>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(Ju&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),Qa.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const o=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,o),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,o),this.worldQuaternion=l,a=!0}a&&Qa.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Ju&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const r=10,s=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%r===0||s)){if(hk++,s&&bA>0&&this.context.time.frameCount%bA!==0)return;Ju&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const o=yV(this.guid,this,!!s);this.context.connection.sendBinary(o)}}}const Npe=te("debugshadowcomponents");pR.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};const Ma=Symbol("shadowDomOwner");class Va extends Be{constructor(){super(...arguments),d(this,"_shadowComponent",null),d(this,"_controlsChildLayout",!0),d(this,"_root"),d(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(){Ta.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=ie.getComponentInParent(this.gameObject,_A)),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,t){var r;if(!e)return;this.removeShadowComponent();const s=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=ie.getComponentInParent(s,Va),!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[Ma]=this,this.setShadowComponentOwner(e);let o=!1;if(((r=this.Root)==null?void 0:r.gameObject)===this.gameObject)this.gameObject.add(e);else{const a=this._parentComponent.shadowComponent;a&&(a?.add(e),o=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Wy&&e.add(new Po(.5)),this.onAfterAddedToScene(),o&&YN(),Npe&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Ma]===void 0||e[Ma]===this)&&(e[Ma]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,r){if(e&&e[Ma]===t){r(e);for(const s of e.children)this.traverseOwnedShadowComponents(s,t,r)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class _A extends Va{awake(){super.awake()}}class q0{constructor(e,t){d(this,"event"),d(this,"button"),d(this,"buttonName"),d(this,"_used",!1),d(this,"_propagationStopped",!1),d(this,"z__pointer_ctured",!1),d(this,"z__pointer_cture_rleased",!1),d(this,"inputSource"),d(this,"object"),d(this,"point"),d(this,"normal"),d(this,"face"),d(this,"distance"),d(this,"instanceId"),d(this,"intersection"),d(this,"isDown"),d(this,"isUp"),d(this,"isPressed"),d(this,"isClick"),d(this,"isDoubleClick"),d(this,"input"),this.event=t,this.input=e,this.button=t.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(),this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId))}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 e=new q0(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function uk(n,e){return ie.foreachComponent(n,t=>{if(!t.enabled)return;const r=t;if(e)switch(e){case"pointerdown":if(r.onPointerDown)return!0;break;case"pointerup":if(r.onPointerUp||r.onPointerClick)return!0;break;case"pointermove":if(r.onPointerEnter||r.onPointerExit||r.onPointerMove)return!0;break}else if(r.onPointerDown||r.onPointerUp||r.onPointerEnter||r.onPointerExit||r.onPointerClick)return!0},!1)===!0}var zpe=Object.defineProperty,jpe=Object.getOwnPropertyDescriptor,Gpe=(n,e,t,r)=>{for(var s=r>1?void 0:r?jpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&zpe(e,t,s),s};class xA extends Be{awake(){Ta.createIfNoneExists(this.context)}onEnable(){var e;(e=Ta.get(this.context))==null||e.register(this)}onDisable(){var e;(e=Ta.get(this.context))==null||e.unregister(this)}}class No extends xA{constructor(){super(...arguments),d(this,"targets",null),d(this,"raycastHits",[]),d(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new ml),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=s=>s instanceof uo?"continue in children":t?t(s):!0);const r=this.context.physics.raycast(e);return e.testObject=t,r}}Gpe([w()],No.prototype,"ignoreSkinnedMeshes",2);class FS extends No{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class wA extends xA{performRaycast(e){if(!wt.active||!(e!=null&&e.ray))return null;const t=e.ray.origin,r=.01;return this.context.physics.sphereOverlap(t,r)}}class US{static getObject(e){const t=e[Ma];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const r=this.tryFindCanvasGroup(e);if(r?.isCanvasGroup===!0&&(t&&(t.canvasGroup=r),r.blocksRaycasts===!1||r.interactable===!1))return!1;const s=Kp(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&s?.isGraphic===!0&&(t.graphic=s),!(s?.raycastTarget===!1||s?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Kp(e,r=>{const s=r;if(s.blocksRaycasts!==void 0&&s.interactable!==void 0)return s},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function dk(n){return n[Ma]||(n.parent?dk(n.parent):null)}function Vpe(n){return n.isUI===!0||typeof n[Ma]=="object"}function NS(n,e){if(!n)return;const t=n.material;if(t?.isMaterial===!0){const r=n.parent;r&&r.isText,t.side=e.doubleSided??!0?yi:nr,t.shadowSide=e.doubleSided?yi:nr,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const r of n.children)NS(r,e)}function Xg(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const r=Proxy.revocable(n[e],{set(a,l,c,h){const u=a[l],p=Reflect.set(a,l,c,h);return t(c,u),p}}),s=r.revoke,o=n[e];return r.revoke=()=>{n[e]=o,s()},n[e]=r.proxy,r}const AV=Symbol("Scheduled action");function Qpe(n,e,t=Hi.OnBeforeRender){let r=n[AV];r||(r=n[AV]={});const s=e.name;r[t]||(r[t]={});const o=r[t];if(o[s])return;function*a(){e?.call(n),o[s]=null}const l=n.startCoroutine(a(),t);o[s]=l}const Ah=te("debugeventsystem");var pk=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))(pk||{});const bh=class extends Be{constructor(){super(),d(this,"raycaster",[]),d(this,"_handleInputFn"),d(this,"pressedByID",new Map),d(this,"hoveredByID",new Map),d(this,"_sortedHits",[]),d(this,"_testObjectsCache",new Map),d(this,"_currentlyActiveRaycaster",null),d(this,"_currentPointerEventName",null),d(this,"shouldRaycastObject",n=>{var e;let t=null;if(Vpe(n)&&(t=(e=n[Ma])==null?void 0:e.gameObject),this._testObjectsCache.has(n)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(n)===!1?"continue in children":!0;{let r=uk(n,this._currentPointerEventName);if(!r&&t&&(r=uk(t,this._currentPointerEventName)),r){this._testObjectsCache.set(n,!0);for(const s of n.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(n,!1),"continue in children"}}),d(this,"_sortingBuffer",[]),d(this,"_noDepthTestingResults",[]),d(this,"out",{}),d(this,"_capturedPointer",{}),d(this,"pointerEnterSymbol",Symbol("pointerEnter")),d(this,"pointerExitSymbol",Symbol("pointerExit")),d(this,"currentActiveMeshUIComponents",[]),bh.systems.push(this)}static createIfNoneExists(n){this.didSearchEventSystem||(this.didSearchEventSystem=!0,bh.systems.length<=0&&bh.systems.push(...ie.findObjectsOfType(bh,n)));for(const t of bh.systems)if(t.context===n)return;const e=new ye;ie.addNewComponent(e,bh),n.scene.add(e)}static get systems(){const n=kt.Current;return this._eventSystemMap.has(n)||this._eventSystemMap.set(n,[]),this._eventSystemMap.get(n)}static get(n){const e=this._eventSystemMap.get(n);return e&&e.length>0?e[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(n,e,t=!1){Zu.update(n,e,t)}static markUIDirty(n){Zu.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){bh.systems.splice(bh.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!ie.findObjectOfType(xA,this.context)){const n=ie.addNewComponent(this.context.scene,No);this.raycaster.push(n),(st()||Ah)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(n){var e;n&&this.raycaster&&!this.raycaster.includes(n)&&((e=this.raycaster)==null||e.push(n))}unregister(n){var e,t;const r=(e=this.raycaster)==null?void 0:e.indexOf(n);r!==void 0&&r!==-1&&((t=this.raycaster)==null||t.splice(r,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(an.PointerDown,this._handleInputFn),this.context.input.addEventListener(an.PointerUp,this._handleInputFn),this.context.input.addEventListener(an.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(an.PointerDown,this._handleInputFn),this.context.input.removeEventListener(an.PointerUp,this._handleInputFn),this.context.input.removeEventListener(an.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(n){if(n===void 0||n.propagationStopped)return;const e=new q0(this.context.input,n);this._currentPointerEventName=n.type,e.inputSource=this.context.input,e.isClick=n.isClick,e.isDoubleClick=n.isDoubleClick,e.isDown=n.type==an.PointerDown,e.isUp=n.type==an.PointerUp,e.isPressed=this.context.input.getPointerPressed(n.pointerId),Ah&&(e.isDown?console.log("DOWN",e.pointerId):e.isUp&&console.log("UP",e.pointerId),e.isClick&&console.log("CLICK",e.pointerId));const t=new ml;n.hasRay?t.ray=n.ray:t.screenPoint=this.context.input.getPointerPositionRC(n.pointerId);const r=this.performRaycast(t);if(r){for(const o of r)o.event=n,n.intersections.push(o);n.origin.onPointerHits&&n.origin.onPointerHits({sender:this,event:n,hits:r})}Ah&&e.isClick&&rn("EventSystem: "+e.pointerId+" - "+this.context.time.frame+" - Up:"+e.isUp+", Down:"+e.isDown);const s={sender:this,args:e,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),this.handleIntersections(r,e),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))}shouldRaycastObject_AddToYesCache(n){this._testObjectsCache.set(n,!0);for(const e of n.children)this.shouldRaycastObject_AddToYesCache(e)}performRaycast(n){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,n||(n=new ml),n.testObject=this.shouldRaycastObject;for(const e of this.raycaster){if(!e.activeAndEnabled)continue;this._currentlyActiveRaycaster=e;const t=e.performRaycast(n);this._currentlyActiveRaycaster=null,t&&t.length>0&&this._sortedHits.push(...t)}return this._sortedHits.sort((e,t)=>e.distance-t.distance),this._sortedHits}assignHitInformation(n,e){e?(n.intersection=e,n.point=e.point,n.normal=e.normal,n.face=e.face,n.distance=e.distance,n.instanceId=e.instanceId):(n.intersection=void 0,n.point=void 0,n.normal=void 0,n.face=void 0,n.distance=void 0,n.instanceId=void 0)}handleIntersections(n,e){var t;if(n!=null&&n.length){n=this.sortCandidates(n);for(const s of n){if(e.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(e,s),this.handleEventOnObject(s.object,e))return!0}}this.assignHitInformation(e,n?.[0]),this.invokePointerCapture(e);const r=this.hoveredByID.get(e.pointerId);return r&&this.propagatePointerExit(r.obj,r.data,null),this.hoveredByID.delete(e.pointerId),e.isUp&&((t=this.pressedByID.get(e.pointerId))==null||t.handlers.forEach(s=>this.invokeOnPointerUp(e,s)),this.pressedByID.delete(e.pointerId)),!1}sortCandidates(n){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let e=0;e<n.length;e++){const t=n[e],r=t.object;if(r.material&&r.material.depthTest===!1){this._noDepthTestingResults.push(t);continue}this._sortingBuffer.push(t)}for(const e of this._sortingBuffer)this._noDepthTestingResults.push(e);return this._noDepthTestingResults}handleEventOnObject(n,e){if(!this.testIsVisible(n))return e.isClick&&Ah&&console.log("not allowed",n),!1;if(e.pointerId===void 0)return Ah&&console.error("Event without pointer can't be handled",e),!1;e.object=n;const t=n.parent,r=e.isClick??!1;let s=null;if(t&&t.isUI){const c=(e.isPressed||e.isClick)??!1;if(t[Ma]){const h=t[Ma].gameObject;if(h){if(!US.isInteractable(h,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(n,c),n=h}}}r&&Ah&&console.log(this.context.time.frame,n);const o=this.hoveredByID.get(e.pointerId),a=o?.obj;a!==n&&a&&this.propagatePointerExit(a,o.data,n);const l=this.hoveredByID.get(e.pointerId);if(l?(l.obj=n,l.data=e):this.hoveredByID.set(e.pointerId,{obj:n,data:e}),e.isDown){const c=this.pressedByID.get(e.pointerId);c?(c.obj=n,c.data=e):this.pressedByID.set(e.pointerId,{obj:n,data:e,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(n,e,a??null),!0}propagate(n,e){for(;n;)ie.foreachComponent(n,t=>{e(t)},!1),n=n.parent}handleMainInteraction(n,e,t){const r=this.pressedByID.get(e.pointerId),s=t!==n;let o=!0;switch(e.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(e.pointerId),l=this.context.input.getPointerPosition(e.pointerId);o=a&&!it.approximately(a,l);break}this.propagate(n,a=>{var l;const c=a;c.interactable!==!1&&(!c.activeAndEnabled||!c.enabled||(c.onPointerEnter&&s&&this.handlePointerEnter(c,e),e.isDown&&c.onPointerDown&&(c.onPointerDown(e),r?.handlers.add(c),this.handlePointerCapture(e,c)),c.onPointerMove&&(o&&c.onPointerMove(e),this.handlePointerCapture(e,c)),e.isUp&&(c.onPointerUp&&(this.invokeOnPointerUp(e,c),r?.handlers.delete(c)),c.onPointerExit&&((l=e.event)==null?void 0:l.pointerType)===q1.Touch&&(this.handlePointerExit(c,e),this.hoveredByID.delete(e.pointerId))),e.isClick&&c.onPointerClick&&c.onPointerClick(e)))}),e.isUp&&(r?.handlers.forEach(a=>{this.invokeOnPointerUp(e,a)}),this.pressedByID.delete(e.pointerId))}propagatePointerExit(n,e,t){this.propagate(n,r=>{if(!r.gameObject||r.destroyed)return;const s=r;if(s.onPointerExit){if(t&&this.isChild(t,r.gameObject))return;this.handlePointerExit(s,e)}})}invokeOnPointerUp(n,e){var t;(t=e.onPointerUp)==null||t.call(e,n),this.releasePointerCapture(n,e)}handlePointerEnter(n,e){n.onPointerEnter&&this.updatePointerState(n,e.pointerId,this.pointerEnterSymbol,!0)&&n.onPointerEnter(e),this.updatePointerState(n,e.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(n,e){n.onPointerExit&&this.updatePointerState(n,e.pointerId,this.pointerExitSymbol,!0)&&n.onPointerExit(e),this.updatePointerState(n,e.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(n,e,t,r){let s=n[t];if(r)return s&&s.includes(e)?!1:(s=s||[],s.push(e),n[t]=s,!0);{if(!s||!s.includes(e))return!1;const o=s.indexOf(e);return o!==-1&&s.splice(o,1),!0}}handlePointerCapture(n,e){if(n.z__pointer_ctured){n.z__pointer_ctured=!1;const t=n.pointerId;if(e.onPointerMove){const r=this._capturedPointer[t]||[];r.push(e),this._capturedPointer[t]=r}else st()&&!e.z__warned_no_pointermove&&(e.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 n.z__pointer_cture_rleased&&(n.z__pointer_cture_rleased=!1,this.releasePointerCapture(n,e))}releasePointerCapture(n,e){const t=n.pointerId;if(this._capturedPointer[t]){const r=this._capturedPointer[t].indexOf(e);r!==-1&&(this._capturedPointer[t].splice(r,1),Ah&&console.log("released pointer capture",t,e,this._capturedPointer))}}invokePointerCapture(n){var e;if(n.event.type===an.PointerMove){const t=n.pointerId,r=this._capturedPointer[t];if(r){Ah&&console.log("Captured",t,r);for(let s=0;s<r.length;s++){const o=r[s];if(o.destroyed){r.splice(s,1),s--;continue}(e=o.onPointerMove)==null||e.call(o,n)}}}}isChild(n,e){return!n||!e?!1:n===e?!0:n.parent?this.isChild(n.parent,e):!1}handleMeshUiObjectWithoutShadowDom(n,e){return!n||!n.isUI?!0:this.handleMeshUIIntersection(n,e)}handleMeshUIIntersection(n,e){const t=Zu.updateState(n,e);return t&&this.currentActiveMeshUIComponents.push(t),t!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Zu.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let n=0;n<this.currentActiveMeshUIComponents.length;n++){const e=this.currentActiveMeshUIComponents[n];Zu.resetState(e)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(n){return n?ie.isActiveSelf(n)?this.testIsVisible(n.parent):!1:!0}};let Ta=bh;d(Ta,"_eventSystemMap",new Map),d(Ta,"didSearchEventSystem",!1);class Zu{static markDirty(){this.needsUpdate=!0}static update(e,t,r=!1){if(r){e.update();return}const s=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(s===o.frame)return;o.frame=s;let a=this.needsUpdate||s<1;o.nextUpdate===t.time.frameCount&&(a=!0),a&&(Ah&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:s,nextUpdate:s}],e.update()}static updateState(e,t){let r=null;if(e&&(r=this.findBlockInParent(e),r&&r!==this.lastSelected)){if(r.interactable===!1)return null;this.needsUpdate=!0}return r}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockInParent(e){return e?e.isBlock?e:this.findBlockInParent(e.parent):null}}d(Zu,"lastSelected",null),d(Zu,"lastUpdateFrame",[]),d(Zu,"needsUpdate",!1);var Hpe=Object.defineProperty,Wpe=Object.getOwnPropertyDescriptor,ln=(n,e,t,r)=>{for(var s=r>1?void 0:r?Wpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Hpe(e,t,s),s};const mk=te("debugorbit"),zS=te("freecam"),jS=te("debugcamerafit"),GS=te("smoothcam"),Xpe={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let fk;class SA extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class bi extends Be{constructor(){super(...arguments),d(this,"autoTarget",!0),d(this,"autoFit",!1),d(this,"enableRotate",!0),d(this,"autoRotate",!1),d(this,"autoRotateSpeed",1),d(this,"minAzimuthAngle",1/0),d(this,"maxAzimuthAngle",1/0),d(this,"minPolarAngle",0),d(this,"maxPolarAngle",Math.PI),d(this,"enableKeys",!0),d(this,"enableDamping",!0),d(this,"dampingFactor",.1),d(this,"enableZoom",!0),d(this,"minZoom",0),d(this,"maxZoom",1/0),d(this,"zoomSpeed",1),d(this,"zoomToCursor",!1),d(this,"enablePan",!0),d(this,"lookAtConstraint",null),d(this,"lookAtConstraint01",1),d(this,"allowInterrupt",!0),d(this,"middleClickToFocus",!0),d(this,"doubleClickToFocus",!0),d(this,"clickBackgroundToFitScene",2),d(this,"debugLog",!1),d(this,"targetLerpDuration",1),d(this,"_controls",null),d(this,"_cameraObject",null),d(this,"_lookTargetLerpActive",!1),d(this,"_lookTargetStartPosition",new C),d(this,"_lookTargetEndPosition",new C),d(this,"_lookTargetLerp01",0),d(this,"_lookTargetLerpDuration",0),d(this,"_cameraLerpActive",!1),d(this,"_cameraStartPosition",new C),d(this,"_cameraEndPosition",new C),d(this,"_cameraLerp01",0),d(this,"_cameraLerpDuration",0),d(this,"_inputs",0),d(this,"_enableTime",0),d(this,"_startedListeningToKeyEvents",!1),d(this,"_eventSystem"),d(this,"_afterHandleInputFn"),d(this,"_camera",null),d(this,"_syncedTransform"),d(this,"_didSetTarget",0),d(this,"targetElement",null),d(this,"_lastTimeClickOnBackground",-1),d(this,"_clickOnBackgroundCount",0),d(this,"_onPointerDown",e=>{if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}mk&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),d(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),d(this,"_shouldDisable",!1),d(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(this.scene.children,{centerCamera:"y",immediate:!0}))}),d(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Ta.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(pk.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(pk.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=ie.getComponent(this.gameObject,Li);this._camera=e;let t=e?.cam;if(!t&&this.gameObject instanceof Lt&&(t=this.gameObject),t&&vR(t,this,!0),!this._controls&&t instanceof Lt){this._cameraObject=t;const r=this.targetElement??this.context.renderer.domElement,s=t?.quaternion.clone();this._controls=new pV(t,r),t?.quaternion.copy(s),fk===void 0&&(fk={...this._controls.keys})}this._controls&&(zS&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,aa()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),t?.type==="PerspectiveCamera"?zS||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):zS||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=ie.getComponent(this.gameObject,Ku)??void 0,this.context.input.addEventListener("pointerup",this._onPointerDown),this.context.pre_render_callbacks.push(this.__onPreRender)}onDisable(){var e;(e=this._camera)!=null&&e.cam&&vR(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted)),this.context.input.removeEventListener("pointerup",this._onPointerDown)}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 e,t;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)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.length()||0>.1)&&(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 s=ie.getComponent(this.gameObject,Li);if(s&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const o=Bt(s.cam),a=Math.max(.01,o.length()),l=new C(0,0,-a).applyMatrix4(s.cam.matrixWorld);this.setLookTargetPosition(l,!0)}if(!this.setLookTargetFromConstraint()){const o=new ml;o.screenPoint=new Z(0,0),o.lineThreshold=.1;const a=this.context.physics.raycast(o);a.length>0&&this.setLookTargetPosition(a[0].point,!0),jS&&console.log("OrbitControls hits",...a)}}let r=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(r||(r=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),r&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive){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 SA(this,"camera"));else{const s=it.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,s)}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 SA(this,"lookat"));else{const s=it.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,s)}}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._controls.keys=this.enableKeys?fk:Xpe,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,typeof GS=="number"||GS===!0){this._controls.enableDamping=!0;const s=typeof GS=="number"?GS:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,s))}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||(!zS&&(t=this.lookAtConstraint)!=null&&t.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),mk&&At.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(e){if(!e||!(e instanceof ye))return;const t=Bt(e),r=SR(e);this.setTargetFromRaycast(new co(t,r)),this.setCameraTargetPosition(t)}setCameraTargetPosition(e,t=!1){var r,s;e&&(e instanceof ye&&(e=Bt(e)),this._cameraEndPosition||(this._cameraEndPosition=new C),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,(r=this.controllerObject)==null||r.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof ye&&(e=Bt(e)),this._lookTargetEndPosition.copy(e),mk&&(console.warn("OrbitControls: setLookTargetPosition",e,t),At.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var r;if(!this._controls)return!1;const s=(r=this.lookAtConstraint)==null?void 0:r.sources;if(s&&s.length>0){const o=s[e];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e){if(!this.controls)return;const t=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const r of t)if(r.distance>0&&ie.isActiveInHierarchy(r.object)){const s=dk(r.object);if(s){const o=s.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(r.point);break}}fitCamera(e,t={fitOffset:void 0,immediate:!1}){if(this.context.isInXR)return;const{immediate:r=!1,centerCamera:s}=t;let{fitOffset:o}=t;o==null&&(o=1.1);const a=this._cameraObject,l=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),e.length<=0){console.warn("No objects to fit camera to...");return}if(!a||!l){console.warn("No camera or controls found to fit camera to objects...");return}const c=new C,h=new C,u=Ul(e,void 0);a.updateMatrixWorld(),a.updateProjectionMatrix(),u.getCenter(h);const p=new C;if(u.getSize(p),u.applyMatrix4(a.matrixWorldInverse),u.getSize(c),u.setFromCenterAndSize(h,c),Number.isNaN(c.x)||Number.isNaN(c.y)||Number.isNaN(c.z)){console.warn("Camera fit size resultet in NaN",a,u,[...e]);return}if(c.length()<=1e-10){jS&&console.warn("Camera fit size is zero",u,[...e]);return}const m=a.fov,f=2*Math.atan(Math.tan(m*Math.PI/360/2)*a.aspect)/Math.PI*360,g=c.y/(2*Math.atan(Math.PI*m/360)),v=c.x/(2*Math.atan(Math.PI*f/360)),y=o*Math.max(g,v)+c.z/2;jS&&console.log("Fit camera to objects",g,v,"distance",y),l.maxDistance=y*10,l.minDistance=y*.01;const A=.05,_=h.clone();_.y-=c.y*A,this.setLookTargetPosition(_,r),this.autoTarget=!1;const b=ie.findObjectOfType(Yu),x=b?b.radius:0,E=Math.max(p.x,p.y,p.z,x);a.near=y/100,a.far=E+y*10,a.updateMatrixWorld(),a.updateProjectionMatrix();const I=Bt(a),T=h.clone();if(T.sub(I),s==="y"&&(T.y=0),T.normalize(),T.multiplyScalar(y),s==="y"&&(T.y+=-A*4*c.y),a.parent){const R=a.parent.worldToLocal(h.clone().sub(T));this.setCameraTargetPosition(R,r)}else console.error(`Can not fit camera ${a.name} because it has no parent`);if(jS){const R=new wI(u);this.context.scene.add(R),MR(R,Wv(a)),setTimeout(()=>{this.context.scene.remove(R)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",D=>{D.code==="KeyF"&&this.fitCamera(e,{fitOffset:o,immediate:r})}))}l.update()}}ln([w()],bi.prototype,"autoTarget",2),ln([w()],bi.prototype,"autoFit",2),ln([w()],bi.prototype,"enableRotate",2),ln([w()],bi.prototype,"autoRotate",2),ln([w()],bi.prototype,"autoRotateSpeed",2),ln([w()],bi.prototype,"minAzimuthAngle",2),ln([w()],bi.prototype,"maxAzimuthAngle",2),ln([w()],bi.prototype,"minPolarAngle",2),ln([w()],bi.prototype,"maxPolarAngle",2),ln([w()],bi.prototype,"enableKeys",2),ln([w()],bi.prototype,"enableDamping",2),ln([w()],bi.prototype,"dampingFactor",2),ln([w()],bi.prototype,"enableZoom",2),ln([w()],bi.prototype,"minZoom",2),ln([w()],bi.prototype,"maxZoom",2),ln([w()],bi.prototype,"zoomSpeed",2),ln([w()],bi.prototype,"enablePan",2),ln([w(nm)],bi.prototype,"lookAtConstraint",2),ln([w()],bi.prototype,"lookAtConstraint01",2),ln([w()],bi.prototype,"allowInterrupt",2),ln([w()],bi.prototype,"middleClickToFocus",2),ln([w()],bi.prototype,"doubleClickToFocus",2),ln([w()],bi.prototype,"clickBackgroundToFitScene",2),ln([w()],bi.prototype,"targetLerpDuration",2);var qpe=Object.defineProperty,Ype=Object.getOwnPropertyDescriptor,$s=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ype(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&qpe(e,t,s),s},$u=(n=>(n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))($u||{});const _h=te("debugcam"),bV=te("debugscreenpointtoray");var VS;const CA=(VS=class extends Be{constructor(){super(...arguments),d(this,"_nearClipPlane",.1),d(this,"_farClipPlane",1e3),d(this,"orthographic",!1),d(this,"orthographicSize",5),d(this,"ARBackgroundAlpha",0),d(this,"_cullingMask",4294967295),d(this,"_backgroundBlurriness",0),d(this,"_backgroundIntensity",1),d(this,"_backgroundRotation"),d(this,"_environmentIntensity"),d(this,"_targetTexture",null),d(this,"_backgroundColor"),d(this,"_fov"),d(this,"_cam",null),d(this,"_clearFlags",2),d(this,"_skybox"),d(this,"_frustum"),d(this,"_projScreenMatrix",new ve)}get isCamera(){return!0}get aspect(){return this._cam instanceof Lt?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(n){this._cam instanceof Lt&&this._cam.aspect!==n&&(this._cam.aspect=n,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof Lt?this._cam.fov:this._fov}set fieldOfView(n){const e=this.fieldOfView!=n;if(this._fov=n,e&&this._cam&&this._cam instanceof Lt){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(n){const e=this._nearClipPlane!=n;this._nearClipPlane=n,this._cam&&e&&(this._cam.near=n,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(n){const e=this._farClipPlane!=n;this._farClipPlane=n,this._cam&&e&&(this._cam.far=n,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(n){n!==this._clearFlags&&(this._clearFlags=n,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(n){this._cullingMask=n,this._cam&&(this._cam.layers.mask=n)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(n){this.cullingMask=(1<<n|0)>>>0}set backgroundBlurriness(n){n!==this._backgroundBlurriness&&(n===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(n,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(n){n!==this._backgroundIntensity&&(n===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(n,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(n){n!==this._backgroundRotation&&(n===void 0?this._backgroundRotation=void 0:this._backgroundRotation=n,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(n){this._environmentIntensity=n}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(n){if(n){if(this._backgroundColor)this._backgroundColor.copy(n);else{if(!n.clone)return;this._backgroundColor=n.clone()}n.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(n){this._targetTexture=n}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(n,e,t){const r=this.cam,s=CA._origin;s.set(n,e,-1),this.context.input.convertScreenspaceToRaycastSpace(s),bV&&console.log("screenPointToRay",n.toFixed(2),e.toFixed(2),"now:",s.x.toFixed(2),s.y.toFixed(2),"isInXR:"+this.context.isInXR),s.z=-1,s.unproject(r);const o=CA._direction.set(s.x,s.y,s.z),a=Bt(r);return o.sub(a),o.normalize(),t?(t.set(a,o),t):new co(a.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new Yd,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Yd),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(n,e){return e&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),n===this._projScreenMatrix?n:n.copy(this._projScreenMatrix)}awake(){bV&&window.addEventListener("pointerdown",n=>{const e=n.clientX,t=n.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const r=this.screenPointToRay(e,t),s="#"+Math.floor(Math.random()*16777215).toString(16);At.DrawRay(r.origin,r.direction,s,10)})}onEnable(){_h&&console.log(`Camera enabled: "${this.name}". ClearFlags=${$u[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),Kpe(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 n=this.context.renderer;if(n){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,n),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const n=this.gameObject.isCamera;let e=null;if(n?(e=this.gameObject,e?.layers.enableAll(),e instanceof Lt&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof Lt&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new Lt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new Bl(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(n){this.context.mainCameraComponent===this&&this.applyClearFlags(n)}applyClearFlags(n){if(!this._cam){_h&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,_h){const e=`Camera "${this.name}" clear flags: ${$u[this._clearFlags]}`;console.debug(e)}switch(this._clearFlags){case 1:if(CA.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||n?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:_h&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0?this.context.scene.backgroundRotation=this._backgroundRotation:_h&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;CA.backgroundShouldBeTransparent(this.context)&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}else _h&&console.warn(`Camera "${this.name}" has no background color`,this);break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}applySceneSkybox(){this._skybox||(this._skybox=new Jpe(this)),this._skybox.apply()}static backgroundShouldBeTransparent(n){var e,t,r,s;const o=(e=n.renderer.xr)==null?void 0:e.getSession();if(!o)return!1;if(typeof o._transparent=="boolean")return o._transparent;const a=o.environmentBlendMode;_h&&rn("Environment blend mode: "+a+" on "+navigator.userAgent);let l=a==="additive"||a==="alpha-blend";return n.isInAR&&a==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(r=navigator.userAgent)!=null&&r.includes("Mozilla")&&(s=navigator.userAgent)!=null&&s.includes("Mobile WebXRViewer/v2"))&&(l=!0),o._transparent=l,l}},d(VS,"_origin",new C),d(VS,"_direction",new C),VS);let Li=CA;$s([w()],Li.prototype,"aspect",1),$s([w()],Li.prototype,"fieldOfView",1),$s([w()],Li.prototype,"nearClipPlane",1),$s([w()],Li.prototype,"farClipPlane",1),$s([w()],Li.prototype,"clearFlags",1),$s([w()],Li.prototype,"orthographic",2),$s([w()],Li.prototype,"orthographicSize",2),$s([w()],Li.prototype,"ARBackgroundAlpha",2),$s([w()],Li.prototype,"cullingMask",1),$s([w()],Li.prototype,"backgroundBlurriness",1),$s([w()],Li.prototype,"backgroundIntensity",1),$s([w(ii)],Li.prototype,"backgroundRotation",1),$s([w()],Li.prototype,"environmentIntensity",1),$s([w(Si)],Li.prototype,"backgroundColor",1),$s([w(Hg)],Li.prototype,"targetTexture",1);class Jpe{constructor(e){d(this,"_camera"),d(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(_h&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=so,this.context.scene.background=this._skybox):(this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" failed to load/find skybox texture`,this._camera.sourceId,this.context.lightmaps,"Current background: ",this.context.scene.background)),(_h||st())&&Di(`Camera "${this._camera.name}" has no skybox texture`))}}function Kpe(n){te("freecam")&&n.context.mainCameraComponent===n&&ie.getOrAddComponent(n.gameObject,bi)}class ed extends Be{constructor(){super(...arguments),d(this,"_listener",null),d(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new pU),this._listener}onEnable(){Qu.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Qu.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||ie.getComponentInParent(this.gameObject,Li);t!=null&&t.cam?t.cam.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())}}class Zpe extends Sn{constructor(e,t=1,r=16,s=2){const o=new yt,a=r+s*2,l=new Float32Array((a*3+3)*3);o.setAttribute("position",new nt(l,3));const c=new Gi({color:65280}),h=new Gi({color:16776960});super(o,[h,c]),this.audio=e,this.range=t,this.divisionsInnerAngle=r,this.divisionsOuterAngle=s,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,r=this.divisionsInnerAngle,s=this.divisionsOuterAngle,o=ui.degToRad(e.panner.coneInnerAngle),a=ui.degToRad(e.panner.coneOuterAngle),l=o/2,c=a/2;let h=0,u=0,p,m;const f=this.geometry,g=f.attributes.position;f.clearGroups();function v(y,A,_,b){const x=(A-y)/_;for(g.setXYZ(h,0,0,0),u++,p=y;p<A;p+=x)m=h+u,g.setXYZ(m,Math.sin(p)*t,0,Math.cos(p)*t),g.setXYZ(m+1,Math.sin(Math.min(p+x,A))*t,0,Math.cos(Math.min(p+x,A))*t),g.setXYZ(m+2,0,0,0),u+=3;f.addGroup(h,u,b),h+=u,u=0}v(-c,-l,s,0),v(-l,l,r,1),v(l,c,s,0),g.needsUpdate=!0,o===a&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var $pe=Object.defineProperty,eme=Object.getOwnPropertyDescriptor,$l=(n,e,t,r)=>{for(var s=r>1?void 0:r?eme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&$pe(e,t,s),s};const Ms=te("debugaudio"),td=class extends Be{constructor(){super(...arguments),d(this,"clip",""),d(this,"playOnAwake",!1),d(this,"preload",!1),d(this,"_spatialBlend",0),d(this,"_minDistance",1),d(this,"_maxDistance",100),d(this,"_volume",1),d(this,"rollOffMode",0),d(this,"playInBackground",!0),d(this,"_loop",!1),d(this,"sound",null),d(this,"helper",null),d(this,"wasPlaying",!1),d(this,"audioLoader",null),d(this,"shouldPlay",!1),d(this,"_lastClipStartedLoading",null),d(this,"_audioElement",null),d(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||aa())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Ms&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,td.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&td.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),d(this,"onApplicationMuteChanged",()=>{var n,e;this.context.application.muted?(n=this.sound)==null||n.setVolume(0):(e=this.sound)==null||e.setVolume(this.volume)}),d(this,"createAudio",n=>{Ms&&console.log("AudioBuffer finished loading",n);const e=this.Sound;if(!e){Ms&&console.warn("Failed getting sound?",this.name);return}e.isPlaying&&e.stop(),n&&e.setBuffer(n),e.loop=this._loop,this.context.application.muted?e.setVolume(0):e.setVolume(this.volume),e.autoplay=this.shouldPlay&&td.userInteractionRegistered,this.applySpatialDistanceSettings(),e.isPlaying&&e.stop(),td.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),d(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),d(this,"_lastContextTime",0),d(this,"_hasEnded",!0),d(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Qu.userInteractionRegistered}static registerWaitForAllowAudio(n){Qu.registerWaitForAllowAudio(n)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(n){this._loop=n,this.sound&&this.sound.setLoop(n)}get spatialBlend(){return this._spatialBlend}set spatialBlend(n){n!==this._spatialBlend&&(this._spatialBlend=n,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(n){this._minDistance!==n&&(this._minDistance=n,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(n){this._maxDistance!==n&&(this._maxDistance=n,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(n){this._volume=n,this.sound&&!this.context.application.muted&&(Ms&&console.log(this.name,"audio set volume",n),this.sound.setVolume(n))}get Sound(){var n;if(!this.sound&&td.userInteractionRegistered){let e=ie.getComponent(this.context.mainCamera,ed)??ie.findObjectOfType(ed,this.context);!e&&this.context.mainCamera&&(e=ie.addNewComponent(this.context.mainCamera,ed)),e!=null&&e.listener?(this.sound=new fU(e.listener),(n=this.gameObject)==null||n.add(this.sound)):Ms&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var n;return(n=this.sound)==null?void 0:n.context}awake(){Ms&&console.log(this),this.audioLoader=new Nx,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),td.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():td.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(cS.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(cS.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const n=this.sound;if(!n)return;this._needUpdateSpatialDistanceSettings=!1;const e=it.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ms&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+e),n.setRefDistance(e),n.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:n.setDistanceModel("exponential");break;case 1:n.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Ms&&!this.helper&&(this.helper=new Zpe(n,n.getRefDistance()),n.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(n){if(n&&(this.clip=n),typeof n=="string")if(Ms&&console.log(n),n.endsWith(".mp3")||n.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new Nx),this.shouldPlay=!0,this._lastClipStartedLoading===n){Ms&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=n,Ms&&console.log("load audio",n);const e=await this.audioLoader.loadAsync(n).catch(console.error);this._lastClipStartedLoading=null,e&&this.createAudio(e)}else console.warn("Unsupported audio clip type",n);else this.shouldPlay=!0,this.createAudio()}play(n=void 0){var e,t,r;!n&&this.clip&&(n=this.clip),n!==void 0&&typeof n!="string"&&!(n instanceof MediaStream)&&(st()&&console.warn("Called play on AudioSource with unknown argument type:",n+`
5733
+ Using the assigned clip instead:`,this.clip),n=this.clip);let s=!this.sound||n&&n!==this.clip;if(typeof n=="string"&&!this.audioLoader&&(s=!0),(n instanceof MediaStream||typeof n=="string")&&(this.clip=n),s){this.shouldPlay=!0,this.onNewClip(n);return}if(this.shouldPlay=!0,this._hasEnded=!1,Ms&&console.log("play",(e=this.sound)==null?void 0:e.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const o=this.context.application.muted;o&&this.sound.setVolume(0),(t=this.gameObject)==null||t.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||(r=this.context.domElement.shadowRoot)==null||r.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(o?.1:0))}}pause(){var n,e;Ms&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(n=this.sound)==null?void 0:n.context.currentTime,this.sound.pause()),(e=this._audioElement)==null||e.remove()}stop(){var n,e;Ms&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(n=this.sound)==null?void 0:n.context.currentTime,Ms&&console.log(this._lastContextTime),this.sound.stop()),(e=this._audioElement)==null||e.remove()}get isPlaying(){var n;return((n=this.sound)==null?void 0:n.isPlaying)??!1}set isPlaying(n){}get time(){var n,e;return(n=this.sound)!=null&&n.source?((e=this.sound.source)==null?void 0:e.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(n){if(this.sound){if(n===this.sound.offset)return;const e=this.isPlaying;this.stop(),this.sound.offset=n,e&&this.play()}}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,Ms&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let Mn=td;$l([w(URL)],Mn.prototype,"clip",2),$l([w()],Mn.prototype,"playOnAwake",2),$l([w()],Mn.prototype,"preload",2),$l([w()],Mn.prototype,"loop",1),$l([w()],Mn.prototype,"spatialBlend",1),$l([w()],Mn.prototype,"minDistance",1),$l([w()],Mn.prototype,"maxDistance",1),$l([w()],Mn.prototype,"volume",1),$l([w()],Mn.prototype,"rollOffMode",2),$l([w()],Mn.prototype,"playInBackground",2);var tme=Object.defineProperty,ime=Object.getOwnPropertyDescriptor,QS=(n,e,t,r)=>{for(var s=r>1?void 0:r?ime(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&tme(e,t,s),s};const nme=te("debugsignals");class EA{constructor(){d(this,"guid")}}QS([w()],EA.prototype,"guid",2);class qg{constructor(){d(this,"signal"),d(this,"reaction")}}QS([w(EA)],qg.prototype,"signal",2),QS([w(Un)],qg.prototype,"reaction",2);var gk;const xh=(gk=class extends Be{constructor(){super(...arguments),d(this,"events")}static invoke(n){if(xh.receivers[n]){const e=xh.receivers[n];if(!e)return;for(const t of e)t.invoke(n)}}awake(){nme&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const n of this.events)xh.receivers[n.signal.guid]||(xh.receivers[n.signal.guid]=[]),xh.receivers[n.signal.guid].push(this)}onDisable(){if(this.events){for(const n of this.events)if(xh.receivers[n.signal.guid]){const e=xh.receivers[n.signal.guid].indexOf(this);e>=0&&xh.receivers[n.signal.guid].splice(e,1)}}}invoke(n){if(!this.events||!Array.isArray(this.events))return;const e=typeof n=="object"?n.guid:n;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(r){console.error(r)}}},d(gk,"receivers",{}),gk);let Yg=xh;QS([w(qg)],Yg.prototype,"events",2);var zo=(n=>(n.Activation="ActivationTrack",n.Animation="AnimationTrack",n.Audio="AudioTrack",n.Control="ControlTrack",n.Marker="MarkerTrack",n.Signal="SignalTrack",n))(zo||{}),ec=(n=>(n[n.None=0]="None",n[n.Hold=1]="Hold",n[n.Loop=2]="Loop",n[n.PingPong=3]="PingPong",n[n.Continue=4]="Continue",n))(ec||{}),vk=(n=>(n.Signal="SignalEmitter",n))(vk||{});const tc=te("debugtimeline");class MA{constructor(){d(this,"director"),d(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let r=this.track.clips.length-1;r>=0;r--)yield this.track.clips[r];else for(const r of this.track.clips)yield r}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,r,s=!0){if(t<0||t>=r.length)return 0;const o=r[t];if(s||e>=o.start&&e<=o.end){let a=1;const l=!1;if(o.easeInDuration>0){const c=Math.min((e-o.start)/o.easeInDuration,1);a*=c}if(o.easeOutDuration>0&&!l){const c=Math.min((o.end-e)/o.easeOutDuration,1);a*=c}return a}return 0}}class rme{constructor(e){d(this,"clip"),d(this,"rootPositionOffset"),d(this,"rootQuaternionOffset"),d(this,"rootStartPosition"),d(this,"rootEndPosition"),d(this,"rootStartQuaternion"),d(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const r=e.getRoot(),s=r.name+".position",o=r.name+".quaternion";tc&&console.log(t.name,t.tracks,s);for(const a of t.tracks)if(!(a.times.length<=0)){if(a.name.endsWith(s))this.rootStartPosition=new C().fromArray(a.values,0),this.rootEndPosition=new C().fromArray(a.values,a.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),tc&&console.log(this.rootPositionOffset);else if(a.name.endsWith(o)&&(this.rootStartQuaternion=new Ce().fromArray(a.values,0),this.rootEndQuaternion=new Ce().fromArray(a.values,a.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),tc)){const l=new ii().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",l)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class HS extends MA{constructor(){super(...arguments),d(this,"models",[]),d(this,"trackOffset"),d(this,"target"),d(this,"mixer"),d(this,"clips",[]),d(this,"actions",[]),d(this,"_actionOffsets",[]),d(this,"_didBind",!1),d(this,"_animator",null),d(this,"_useclipOffsets",!0),d(this,"_totalOffsetPosition",new C),d(this,"_totalOffsetRotation",new Ce),d(this,"_totalOffsetPosition2",new C),d(this,"_totalOffsetRotation2",new Ce),d(this,"_summedPos",new C),d(this,"_tempPos",new C),d(this,"_summedRot",new Ce),d(this,"_tempRot",new Ce),d(this,"_clipRotQuat",new Ce)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&xV(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var r,s;if(((r=t.tracks)==null?void 0:r.length)<=0){console.warn("No tracks in AnimationClip",t);return}const o=t.tracks[0].name.split("."),a=o[o.length-2],l=a+".position",c=a+".quaternion";let h=!1,u=!1;for(const p of t.tracks)p.name.endsWith(l)?(h=!0,this.createPositionInterpolant(t,e,p)):p.name.endsWith(c)&&(u=!0,this.createRotationInterpolant(t,e,p));if(!h||!u){const p=(s=this.mixer)==null?void 0:s.getRoot(),m=t.tracks[0],f=m.name.lastIndexOf("."),g=m.name.substring(0,f),v=g.substring(g.lastIndexOf(".")+1),y=p.getObjectByName(v);if(y)if(h){if(!u){const A=t.tracks[0].name.substring(0,f)+".quaternion";tc&&console.warn("Create quaternion track",v,y);const _=y.quaternion,b=new sa(A,[0,t.duration],[_.x,_.y,_.z,_.w,_.x,_.y,_.z,_.w]);t.tracks.push(b),this.createRotationInterpolant(t,e,b)}}else{const A=g+".position";tc&&console.warn("Create position track",v,y);const _=y.position,b=new kl(A,[0,t.duration],[_.x,_.y,_.z,_.x,_.y,_.z]);t.tracks.push(b),this.createPositionInterpolant(t,e,b)}}}bind(){if(!this._didBind){this._didBind=!0,tc&&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 t=new rme(e);this._actionOffsets.push(t)}this.target&&(this._animator=ie.getComponent(this.target,Wr)??null,this._animator&&xV(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,r=t.position,s=t.rotation;r&&r.x!==void 0&&(r.isVector3||(t.position=new C(r.x,r.y,r.z)),s.isQuaternion||(t.rotation=new Ce(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 C(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new Ce(t.x,t.y,t.z,t.w)))}}evaluate(e){var t,r,s,o,a,l,c;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 h=0,u=0,p=!1,m=!1,f=0;for(let g=0;g<this.clips.length;g++){const v=this.models[g],y=this.actions[g],A=v.asset;y.weight=0;const _=e>=v.start&&e<=v.end,b=v.preExtrapolationMode,x=v.postExtrapolationMode,E=g<this.clips.length-1?this.models[g+1]:null;let I=_,T=!1;if(!I&&!p&&v.end<e&&x!==ec.None?(!E||E.start>e)&&(I=!0,p=!0):g==0&&!I&&!m&&v.start>e&&b!==ec.None&&(!E||E.start<e)&&(I=!0,T=!0,m=!0),I){let R=1;R*=this.evaluateWeight(e,g,this.models,I),R*=this.director.weight;let D=_;if(T)switch(b){case ec.Hold:break;case ec.Loop:e+=v.start,D=!0;break;default:e+=v.start,D=!0;break}let M=this.getClipTime(e,v),P=0;const z=A.duration;if(T&&b===ec.Hold&&(M=0),D){if(A.loop)for(P+=Math.floor(M/(z+1e-6));M>z;)M-=z}else if(!_&&p)switch(x){case ec.Hold:M=this.getClipTime(v.end,v);break;case ec.Loop:M%=z;break;case ec.PingPong:const L=Math.floor(M/z)%2!==0;M%=z,L&&(M=z-M);break}v.reversed===!0?y.time=y.getClip().duration-M:y.time=M,y.timeScale=0;const V=Math.max(0,R);if(y.weight=V,f+=V,y.clampWhenFinished=!1,y.isRunning()||y.play(),this._useclipOffsets){const L=h==0?this._totalOffsetPosition:this._totalOffsetPosition2,H=h==0?this._totalOffsetRotation:this._totalOffsetRotation2;h<1&&(u=1-R),h+=1;const O=this._summedPos.set(0,0,0),F=this._tempPos.set(0,0,0),G=this._summedRot.identity(),J=this._tempRot.identity(),K=A.rotation;K&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(K,R));const oe=this._actionOffsets[g];if(oe.hasOffsets)for(let we=0;we<P;we++)oe.rootPositionOffset?F.copy(oe.rootPositionOffset):F.set(0,0,0),F.applyQuaternion(G),this._clipRotQuat&&F.applyQuaternion(this._clipRotQuat),oe.rootQuaternionOffset&&(J.copy(oe.rootQuaternionOffset),G.multiply(J)),O.add(F);this._clipRotQuat&&H.multiply(this._clipRotQuat),H.multiply(G),A.position&&O.add(A.position),L.add(O)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(tc||st())&&(r=(t=this._animator)==null?void 0:t.runtimeAnimatorController)!=null&&r.mixer&&this.mixer!==((o=(s=this._animator)==null?void 0:s.runtimeAnimatorController)==null?void 0:o.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)),(a=this._animator)!=null&&a.runtimeAnimatorController){const g=Math.max(0,1-f);(c=(l=this._animator)==null?void 0:l.runtimeAnimatorController)==null||c.update(g)}else this.mixer.update(e)}createRotationInterpolant(e,t,r){var s;const o=r.createInterpolant.bind(r),a=new Ce;this.ensureTrackOffsets();const l=(s=this.trackOffset)==null?void 0:s.rotation;r.createInterpolant=()=>{const c=o(),h=c.evaluate.bind(c);return c.evaluate=u=>{var p;const m=h(u);if(a.set(m[0],m[1],m[2],m[3]),a.premultiply(this._totalOffsetRotation),l&&a.premultiply(l),this.director.animationCallbackReceivers)for(const f of this.director.animationCallbackReceivers)(p=f?.onTimelineRotation)==null||p.call(f,this.director,this.target,u,a);return m[0]=a.x,m[1]=a.y,m[2]=a.z,m[3]=a.w,m},c}}createPositionInterpolant(e,t,r){var s,o;const a=r.createInterpolant.bind(r),l=new C;this.ensureTrackOffsets();const c=(s=this.trackOffset)==null?void 0:s.rotation,h=(o=this.trackOffset)==null?void 0:o.position;let u;r.createInterpolant=()=>{const p=a(),m=p.evaluate.bind(p);return p.evaluate=f=>{var g,v,y;const A=m(f);if(l.set(A[0],A[1],A[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(v=(g=this._actionOffsets.find(_=>_.clip===e))==null?void 0:g.rootStartPosition)==null?void 0:v.clone()):u!=null&&u.isVector3&&l.sub(u)),l.applyQuaternion(this._totalOffsetRotation),l.add(this._totalOffsetPosition),c&&l.applyQuaternion(c),h&&(l.x-=h.x,l.y+=h.y,l.z+=h.z),this.director.animationCallbackReceivers)for(const _ of this.director.animationCallbackReceivers)(y=_?.onTimelinePosition)==null||y.call(_,this.director,this.target,f,l);return A[0]=l.x,A[1]=l.y,A[2]=l.z,A},p}}}const sme=te("mutetimeline"),TA=class extends MA{constructor(){super(...arguments),d(this,"models",[]),d(this,"listener"),d(this,"audio",[]),d(this,"audioContextTimeOffset",[]),d(this,"lastTime",0),d(this,"audioSource"),d(this,"_audioLoader",null),d(this,"_playableDirectorResumed",!1)}getAudioFilePath(n){const e=this.director.sourceId;return cu(e,n)}onAllowAudioChanged(n){for(let e=0;e<this.models.length;e++){const t=this.models[e];this.audio[e].setVolume(n?t.asset.volume:0)}}addModel(n){const e=new gI(this.listener);this.audio.push(e);const t=n;t._didTriggerPlay=!1,this.models.push(t)}onDisable(){for(const n of this.audio)n.isPlaying&&n.stop();for(const n of this.models)n._didTriggerPlay=!1}onDestroy(){for(const n of this.audio)n.source&&n?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let n=0;n<this.audio.length;n++){const e=this.audio[n];e!=null&&e.isPlaying&&e.stop()}}stop(){for(let n=0;n<this.audio.length;n++){const e=this.audio[n];e!=null&&e.isPlaying&&e.stop()}for(const n of this.models)n._didTriggerPlay=!1}onPauseChanged(){for(let n=0;n<this.audio.length;n++){const e=this.audio[n];e!=null&&e.isPlaying&&e.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(n){if(sme||this.track.muted||this.director.speed<0)return;const e=this.director.context.application.muted,t=this._playableDirectorResumed;this._playableDirectorResumed=!1;const r=e?.1:0;for(let s=0;s<this.models.length;s++){const o=this.models[s],a=this.audio[s],l=o.asset;if((!a||!a.buffer)&&this.isInTimeRange(o,n-1,n+1)&&this.handleAudioLoading(o,a),Mn.userInteractionRegistered!==!1&&!(a===null||!a.buffer))if(a.playbackRate=this.director.context.time.timeScale*this.director.speed,a.loop=l.loop,n>=o.start&&n<=o.end&&n<this.director.duration){if(!a.isPlaying||!this.director.isPlaying)(t||!o._didTriggerPlay&&this.lastTime<n)&&(o.duration*o.timeScale>.3?a.offset=o.clipIn+(n-o.start)*o.timeScale:a.offset=0,tc&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+o.asset.clip),a.play(r),o._didTriggerPlay=!0);else{const h=o.clipIn+(n-o.start)*o.timeScale,u=a.context.currentTime-a._startedAt+a.offset;Math.abs(h-u)>.3&&(a.offset=h,a.stop(),a.play(r))}let c=l.volume;if(this.track.volume!==void 0&&(c*=this.track.volume),e&&(c=0),o.easeInDuration>0){const h=Math.min((n-o.start)/o.easeInDuration,1);c*=h}if(o.easeOutDuration>0){const h=Math.min((o.end-n)/o.easeOutDuration,1);c*=h}a.setVolume(c*this.director.weight)}else o._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=n}loadAudio(n,e=0,t=0){let r=null;const s=n-t,o=n+e;for(const a of this.models)if(this.isInTimeRange(a,s,o)){const l=this.audio[this.models.indexOf(a)],c=this.handleAudioLoading(a,l);c!==null&&(r===null&&(r=[]),r.push(c))}return r!==null?Promise.all(r):null}isInTimeRange(n,e,t){return e<=n.start&&t>=n.end||e>=n.start&&e<=n.end||t>=n.start&&t<=n.end}static dispose(){TA._audioBuffers.clear()}handleAudioLoading(n,e){this._audioLoader||(this._audioLoader=new Nx);const t=this.getAudioFilePath(n.asset.clip);if(TA._audioBuffers.get(t)){const s=TA._audioBuffers.get(t);return s.then(o=>{o&&e.setBuffer(o)}),s}tc&&console.warn("LOAD audio track",t,this.director.sourceId);const r=new Promise((s,o)=>{this._audioLoader.load(t,a=>{e.setBuffer(a),s(a)},void 0,a=>{console.error("Error loading audio",a),s(null)})});return TA._audioBuffers.set(t,r),r}};let IA=TA;d(IA,"_audioBuffers",new Map);class RA extends MA{constructor(){super(...arguments),d(this,"models",[]),d(this,"didTrigger",[]),d(this,"receivers",[])}evaluate(e){var t;if(this.track.muted)return;const r=this.director.context.time.deltaTime*1.5;for(let s=0;s<this.models.length;s++){const o=this.models[s],a=this.didTrigger[s],l=o.time-e;let c=!1;if(o.retroActive)c=l<=1e-6;else{const h=Math.abs(l);(h===0||h>=1e-5&&h<r)&&(c=!0)}if(c){if(!a)if(tc&&console.log("Trigger signal",e,o.time,o),this.didTrigger[s]=!0,((t=this.receivers)==null?void 0:t.length)<=0)Yg.invoke(o.asset);else for(const h of this.receivers)h&&h.invoke(o.asset)}else o.emitOnce||(this.didTrigger[s]=!1)}}}class WS extends MA{constructor(){super(...arguments),d(this,"models",[]),d(this,"timelines",[]),d(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const r=this.models[t].asset;if(!r.sourceObject||typeof r.sourceObject!="object"){console.log("no source object, removing model",t,r),this.models.splice(t,1);continue}else{const s=ie.getComponent(r.sourceObject,id);this.timelines.push(s),s&&r.updateDirector&&(s.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let r=0;r<this.models.length;r++){const s=this.models[r],o=s.asset;if(e>=s.start&&e<=s.end){this._previousActiveModel=s;const a=this.getClipTime(e,s);if(o.controlActivation){const l=o.sourceObject;l.visible=!0}if(o.updateDirector){const l=this.timelines[r];l&&(l.isPlaying&&l.pause(),l.time=a,l.evaluate())}}else{const a=(t=this._previousActiveModel)==null?void 0:t.asset;if(o.controlActivation){const l=o.sourceObject;a?.sourceObject!==l&&(l.visible=!1)}}}}}var ome=Object.defineProperty,ame=Object.getOwnPropertyDescriptor,_V=(n,e,t,r)=>{for(var s=r>1?void 0:r?ame(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ome(e,t,s),s};const Jg=te("debugtimeline");var yk;const Ak=(yk=class extends Be{constructor(){super(...arguments),d(this,"playableAsset"),d(this,"playOnAwake"),d(this,"extrapolationMode",1),d(this,"waitForAudio",!0),d(this,"_visibilityChangeEvt"),d(this,"_clonedPlayableAsset",!1),d(this,"_speed",1),d(this,"_guidsMap"),d(this,"_isPlaying",!1),d(this,"_internalUpdateRoutine"),d(this,"_isPaused",!1),d(this,"_isStopping",!1),d(this,"_time",0),d(this,"_duration",0),d(this,"_weight",1),d(this,"_animationTracks",[]),d(this,"_audioTracks",[]),d(this,"_signalTracks",[]),d(this,"_controlTracks",[]),d(this,"_customTracks",[]),d(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),d(this,"animationCallbackReceivers",[])}static registerCreateTrack(n,e){this.createTrackFunctions[n]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(n){typeof n=="number"&&!Number.isNaN(n)?this._time=n:(Jg||js())&&console.error("INVALID TIMELINE.TIME VALUE",n,this.name)}get duration(){return this._duration}set duration(n){this._duration=n}get weight(){return this._weight}set weight(n){this._weight=n}get speed(){return this._speed}set speed(n){this._speed=n}awake(){var n,e,t;Jg&&console.log(this,(n=this.playableAsset)==null?void 0:n.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(e=this.playableAsset)==null?void 0:e.tracks,Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this)}onEnable(){var n,e,t;for(const r of this._audioTracks)(n=r.onEnable)==null||n.call(r);for(const r of this._customTracks)(e=r.onEnable)==null||e.call(r);for(const r of this._animationTracks)(t=r.onEnable)==null||t.call(r);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 n,e,t;this.stop();for(const r of this._audioTracks)(n=r.onDisable)==null||n.call(r);for(const r of this._customTracks)(e=r.onDisable)==null||e.call(r);for(const r of this._animationTracks)(t=r.onDisable)==null||t.call(r);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var n;for(const e of this._allTracks)for(const t of e)(n=t.onDestroy)==null||n.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const n=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,n&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const e=[];for(const t of this._audioTracks){const r=t.loadAudio(this._time,1,0);r&&e.push(r)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Mn.userInteractionRegistered&&this.waitForAudio;)await Ll(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Hi.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const t of this._audioTracks)t.stop();const n=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),n&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,n&&!e&&this.invokePauseChangedMethodsOnTracks(),e&&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 n of this._allTracks)for(const e of n)yield e}get audioTracks(){return this._audioTracks}resolveGuids(n){this._guidsMap=n}invokePauseChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onPauseChanged)==null||n.call(e)}invokeStateChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onStateChanged)==null||n.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(n=!1){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}const t=this._time;for(const r of this.playableAsset.tracks)if(!r.muted)switch(r.type){case zo.Activation:if(!n&&!this._isPlaying)continue;for(let s=0;s<r.outputs.length;s++){const o=r.outputs[s];if(typeof o=="object"){let a=!1;if(r.clips)for(const c of r.clips)c.start<=t&&t<=c.end&&(a=!0);const l=o;l.visible!==void 0&&l.visible!==a&&(l.visible=a,Jg&&console.warn(this.name,"set ActivationTrack-"+s,l.name,a,t))}}break}if(!this._isStopping)for(const r of this._animationTracks)r.evaluate(t);for(const r of this._audioTracks)r.evaluate(t);for(const r of this._signalTracks)r.evaluate(t);for(const r of this._controlTracks)r.evaluate(t);for(const r of this._customTracks)r.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Nv(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const n=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let r=e.outputs[t];if(typeof r=="string"){this._guidsMap&&this._guidsMap[r]&&(r=this._guidsMap[r]);const s=ie.findByGuid(r,n);s===null||typeof s!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",r,e.name,e.type)):(Jg&&console.log("Resolved binding",r,"to",s),e.outputs[t]=s)}else if(r===null){if(e.outputs.splice(t,1),Ak.createTrackFunctions[e.type])continue;e.type!==zo.Audio&&e.type!==zo.Control&&e.type!==zo.Marker&&e.type!==zo.Signal&&console.warn("Missing binding",r,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===zo.Control&&e.clips)for(let t=0;t<e.clips.length;t++){const r=e.clips[t];let s=r.asset.sourceObject;if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const o=ie.findByGuid(s,n);o===null||typeof o!="object"?console.warn("Failed to resolve sourceObject binding",s,e.name,r):(Jg&&console.log("Resolved binding",s,"to",o),r.asset.sourceObject=o)}}}}findRoot(n){return n.parent?this.findRoot(n.parent):n}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const n of this.playableAsset.tracks)if(n.muted!==!0){if(n.clips)for(const e of n.clips)e.end>this._duration&&(this._duration=e.end);if(n.markers)for(const e of n.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var n,e,t;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let r=ie.findObjectOfType(ed,this.context);for(const s of this.playableAsset.tracks){const o=s.type,a=Ak.createTrackFunctions[o];if(a!=null){const l=a(this,s);if(typeof l.evaluate=="function"){l.director=this,l.track=s,this._customTracks.push(l);continue}}if(s.type===zo.Animation){if(!s.clips||s.clips.length<=0){Jg&&console.warn("Animation track has no clips",s);continue}for(let l=s.outputs.length-1;l>=0;l--){let c=s.outputs[l];if(c instanceof ye){const u=ie.getOrAddComponent(c,Wr);u&&(c=u)}const h=(n=c?.gameObject)==null?void 0:n.animations;if(h){const u=new HS;u.trackOffset=s.trackOffset,u.director=this,u.track=s;for(let p=0;p<s.clips.length;p++){const m=s.clips[p],f=m.asset;if(!f){console.error(`Timeline ${this.name}: clip #${p} on track "${s.name}" has no animation data`);continue}const g=f.clip;let v=g;if((typeof v=="string"||typeof v=="number")&&(v=h.find(A=>A.name===g)),!v){console.warn("Could not find animationClip for model",m,s.name,this.name,(e=this.playableAsset)==null?void 0:e.name);continue}c instanceof Wr&&c.runtimeAnimatorController&&(c.__internalDidAwakeAndStart||c.initializeRuntimeAnimatorController(),c.runtimeAnimatorController.mixer||c.runtimeAnimatorController.bind(c),u.mixer=c.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new zx(c.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(v),u.mixer.uncacheAction(v),u.createHooks(m.asset,v);const y=u.mixer.clipAction(v);u.actions.push(y),u.models.push(m)}this._animationTracks.push(u)}}}else if(s.type===zo.Audio){if(!s.clips||s.clips.length<=0)continue;const l=new IA;l.director=this,l.track=s,l.audioSource=s.outputs.find(c=>c instanceof Mn),this._audioTracks.push(l),r||(r=(t=this.context.mainCameraComponent)==null?void 0:t.gameObject.addNewComponent(ed)),l.listener=r.listener;for(let c=0;c<s.clips.length;c++){const h=s.clips[c];l.addModel(h)}}else if(s.type===zo.Marker){const l=new RA;if(l.director=this,l.track=s,s.markers)for(const c of s.markers)switch(c.type){case vk.Signal:l.models.push(c),l.didTrigger.push(!1);break}if(l!==null&&l.models.length>0){const c=ie.getComponent(this.gameObject,Yg);c&&(l.receivers.push(c),this._signalTracks.push(l))}}else if(s.type===zo.Signal){const l=new RA;if(l.director=this,l.track=s,s.markers)for(const c of s.markers)l.models.push(c),l.didTrigger.push(!1);for(const c of s.outputs)l.receivers.push(c);this._signalTracks.push(l)}else if(s.type===zo.Control){const l=new WS;if(l.director=this,l.track=s,s.clips)for(const c of s.clips)l.models.push(c);l.resolveSourceObjects(this.context),this._controlTracks.push(l)}}}setAudioTracksAllowPlaying(n){for(const e of this._audioTracks)e.onAllowAudioChanged(n)}registerAnimationCallback(n){this.animationCallbackReceivers.push(n)}unregisterAnimationCallback(n){const e=this.animationCallbackReceivers.indexOf(n);e!==-1&&this.animationCallbackReceivers.splice(e,1)}},d(yk,"createTrackFunctions",{}),yk);let id=Ak;_V([w()],id.prototype,"playOnAwake",2),_V([w()],id.prototype,"extrapolationMode",2);const XS=Symbol("objectIsAnimatedData");function xV(n,e,t){if(!n)return;if(n[XS]===void 0){if(!t)return;n[XS]=new Set}const r=n[XS];t?r.add(e):r.has(e)&&r.delete(e)}function lme(n){if(!n)return!1;const e=n[XS];return e!==void 0&&e.size>0}di.registerCallback(Ci.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&n.files)for(const t of n.files)ie.foreachComponent(t.file.scene,r=>{if(r.enabled!==!1){if(r instanceof Es&&r.playAutomatically||r instanceof Wr||r instanceof id&&r.playOnAwake===!0)return!0;if(r instanceof Es)return r.playAutomatically=!0,!0;if(r instanceof id)return r.playOnAwake=!0,!0}},!0)!==!0&&Bg.assignAnimationsFromFile(t.file,{createAnimationComponent:(r,s)=>gl(r,Es)})});class cme{constructor(){d(this,"_context")}get context(){return this._context??kt.Current}get isStateMachineBehaviour(){return!0}}class PA{constructor(e,t,r,s){d(this,"name"),d(this,"nameHash"),d(this,"normalizedTime"),d(this,"length"),d(this,"speed"),d(this,"action"),d(this,"hasTransitions");var o;this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=r,this.speed=s,this.action=e.motion.action||null,this.hasTransitions=((o=e.transitions)==null?void 0:o.length)>0||!1}}function wV(n,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??ui.generateUUID(),index:-1,clip:new zs(n,0,[])}}var nd=(n=>(n[n.If=1]="If",n[n.IfNot=2]="IfNot",n[n.Greater=3]="Greater",n[n.Less=4]="Less",n[n.Equals=6]="Equals",n[n.NotEqual=7]="NotEqual",n))(nd||{}),bk=(n=>(n[n.Float=1]="Float",n[n.Int=3]="Int",n[n.Bool=4]="Bool",n[n.Trigger=9]="Trigger",n))(bk||{});const Er=te("debuganimatorcontroller"),qS=te("debugrootmotion");class ea{constructor(e){d(this,"_speed",1),d(this,"normalizedStartOffset",0),d(this,"animator"),d(this,"model"),d(this,"_mixer"),d(this,"_activeState"),d(this,"_activeStates",[]),d(this,"_heldActions",[]),d(this,"rootMotionHandler"),this.model=e,Er&&console.log(this)}static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const r=[];for(let o=0;o<e.length;o++){const a=e[o],l=[];if(t.autoTransition!==!1){const h=t.transitionDuration??0,u=h/a.duration;let p=o;(t.autoTransition===void 0||t.autoTransition===!0)&&(p=(o+1)%e.length),l.push({exitTime:1-u,offset:0,duration:h,hasExitTime:!0,destinationState:p,conditions:[]})}const c={name:a.name,hash:o,motion:{name:a.name,clip:a,isLooping:t?.looping??!1},transitions:l,behaviours:[]};r.push(c)}const s={name:"AnimatorController",guid:new Dr(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:r}}]};return new ea(s)}play(e,t=-1,r=Number.NEGATIVE_INFINITY,s=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[t].stateMachine;for(const a of o.states)if(a.name===e||a.hash===e){Er&&console.log("transition to ",a),this.transitionTo(a,s,r);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var r,s;const o=typeof e=="string"?"name":"hash";return(s=(r=this.model)==null?void 0:r.parameters)==null?void 0:s.filter(a=>a[o]===e).forEach(a=>a.value=t)}getBool(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??!1}setFloat(e,t){var r,s;const o=typeof e=="string"?"name":"hash",a=(s=(r=this.model)==null?void 0:r.parameters)==null?void 0:s.filter(l=>l[o]===e);return a.forEach(l=>l.value=t),a?.length>0}getFloat(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??0}setInteger(e,t){var r,s;const o=typeof e=="string"?"name":"hash";return(s=(r=this.model)==null?void 0:r.parameters)==null?void 0:s.filter(a=>a[o]===e).forEach(a=>a.value=t)}getInteger(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??0}setTrigger(e){var t,r;Er&&console.log("SET TRIGGER",e);const s=typeof e=="string"?"name":"hash";return(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.filter(o=>o[s]===e).forEach(o=>o.value=!0)}resetTrigger(e){var t,r;const s=typeof e=="string"?"name":"hash";return(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.filter(o=>o[s]===e).forEach(o=>o.value=!1)}getTrigger(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const r of t.stateMachine.states)if(r.name===e||r.hash==e)return r}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,r=t<=0?0:Math.abs(e.time/t);return new PA(this._activeState,r,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var e;return(e=this.animator)==null?void 0:e.context}get mixer(){return this._mixer}dispose(){var e;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const t of this._activeStates)t.motion.clip&&this.mixer.uncacheAction(t.motion.clip,this.animator.gameObject)}(e=this.context)==null||e.animations.unregisterAnimationMixer(this._mixer)}bind(e){var t,r;e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new zx(this.animator.gameObject),(r=this.context)==null||r.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;Er&&console.warn("AnimatorController clone()",this.model);const e=Nv(this.model,(t,r,s)=>s==null?!0:!(s.type==="Object3D"||s.isObject3D===!0||oz(s)||s.tracks!==void 0||s instanceof ea));return console.assert(e!==this.model),new ea(e)}update(e){var t,r;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const s=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(e)),this._mixer.update(s),this.animator.applyRootMotion&&((r=this.rootMotionHandler)==null||r.onAfterUpdate(e))}get activeState(){return this._activeState}updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const r=this._activeStates[t],s=r.motion;if(!s.action)this._activeStates.splice(t,1),t--;else{const o=s.action;o.weight=e,o.getEffectiveWeight()<=0&&!o.isRunning()&&(Er&&console.debug("REMOVE",r.name,o.getEffectiveWeight(),o.isRunning(),o.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){var e;this.model.layers.length>1&&(Er||st())&&console.warn("Multiple layers are not supported yet "+((e=this.animator)==null?void 0:e.name));for(const t of this.model.layers){const r=t.stateMachine;r.defaultState===void 0&&(Er&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",t),r.defaultState=0);const s=r.states[r.defaultState];this.transitionTo(s,0,this.normalizedStartOffset);break}}evaluateTransitions(){var e;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const r=this._activeState,s=r.motion.action;for(const a of r.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(s){const c=r.motion.clip.duration,h=c<=0?1:Math.abs(s.time/c);let u=a.exitTime;s.timeScale<0&&(u=1-u);let p=!1;if(a.hasExitTime?s.timeScale>0?p=h>=a.exitTime:s.timeScale<0&&(p=1-h>=a.exitTime):p=!0,p){for(const m of a.conditions){const f=this.model.parameters.find(g=>g.name===m.parameter);f?.type===bk.Trigger&&f.value&&(f.value=!1)}if(s.clampWhenFinished=!0,Er){const m=this.getState(a.destinationState,0);console.log(`Transition to ${a.destinationState} / ${m?.name}`,a,`
5734
5734
  Timescale: `+s.timeScale,`
5735
5735
  Normalized time: `+h.toFixed(3),`
5736
- Exit Time: `+u,a.hasExitTime)}this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}}s&&this.setTimescale(s,r);let o=!1;if(r.motion.isLooping&&s&&(s.time>=s.getClip().duration?(o=!0,s.reset(),s.time=0,s.play()):s.time<=0&&s.timeScale<0&&(o=!0,s.reset(),s.time=s.getClip().duration,s.play())),!o&&r&&!t&&s&&this.animator&&r.behaviours){const a=s?.getClip().duration,l=s.time/a,c=new PA(this._activeState,l,a,this._speed);for(const h of r.behaviours)h.instance&&((e=h.instance.onStateUpdate)==null||e.call(h.instance,this.animator,c,0))}}setTimescale(e,t){let r=t.speed??1;t.speedParameter&&(r*=this.getFloat(t.speedParameter)),r!==void 0&&(e.timeScale=r*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(Er&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}releaseHeldActions(e){for(const t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,r){var s,o,a,l,c,h,u,p;if(!this.animator)return;const m=0;if(e=this.getState(e,m),!(e!=null&&e.motion)||!e.motion.clip||!(e.motion.clip instanceof zs))return;const f=this._activeState===e;if(f){const _=e.motion;if(!_.action_loopback&&_.clip){const b=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(_.clip,this.animator.gameObject),b&&b.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),_.action_loopback=this.createAction(_.clip)}}if((s=this._activeState)!=null&&s.behaviours&&this._activeState.motion.action){const _=(o=this._activeState)==null?void 0:o.motion.clip.duration,b=this._activeState.motion.action.time/_,x=new PA(this._activeState,b,_,this._speed);for(const E of this._activeState.behaviours)(l=(a=E.instance)==null?void 0:a.onStateExit)==null||l.call(E.instance,this.animator,x,m)}const g=(c=this._activeState)==null?void 0:c.motion.action;f&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=g);const v=this._activeState;this._activeState=e;const y=(h=e.motion)==null?void 0:h.action,A=e.motion.clip;if(A?.duration<=0&&A.tracks.length<=0?g&&this._heldActions.push(g):g&&(g.fadeOut(t),this.releaseHeldActions(t)),y){if(r=Math.max(0,Math.min(1,r)),e.cycleOffsetParameter){let b=this.getFloat(e.cycleOffsetParameter);typeof b=="number"?(b<0&&(b+=1),r+=b,r%=1):Er&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(r+=e.cycleOffset,r%=1);y.isRunning()&&y.stop(),y.reset(),y.enabled=!0,this.setTimescale(y,e);const _=e.motion.clip.duration;if(y.time=f?0:r*_,y.timeScale<0&&(y.time=_-y.time),y.clampWhenFinished=!0,y.setLoop(nv,0),t>0?y.fadeIn(t):y.weight=1,y.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(y),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const b=new PA(e,r,_,this._speed);for(const x of this._activeState.behaviours)(p=(u=x.instance)==null?void 0:u.onStateEnter)==null||p.call(x.instance,this.animator,b,m)}}else Er&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));Er&&console.log("TRANSITION FROM "+v?.name+" TO "+e.name,t,g,y,y?.getEffectiveTimeScale(),y?.getEffectiveWeight(),y?.isRunning(),y?.isScheduled(),y?.paused)}createAction(e){var t,r;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(t=this.animator)==null?void 0:t.gameObject),(r=this.animator)!=null&&r.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new hme(this));const s=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,s,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(r=>r.name===e.parameter);if(!t)return!1;switch(e.mode){case nd.If:return t.value===!0;case nd.IfNot:return t.value===!1;case nd.Greater:return t.value>e.threshold;case nd.Less:return t.value<e.threshold;case nd.Equals:return t.value===e.threshold;case nd.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,r,s,o;Er&&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||(Er&&console.warn("No motion",h),h.motion=w8(h.name)),this.animator&&h.motion.clips){const u=(t=h.motion.clips)==null?void 0:t.find(p=>{var m,f;return p.node.name===((f=(m=this.animator)==null?void 0:m.gameObject)==null?void 0:f.name)});u?h.motion.clip=u.clip:(Er||st())&&console.warn('Could not find clip for animator "'+((s=(r=this.animator)==null?void 0:r.gameObject)==null?void 0:s.name)+'"',h.motion.clips.map(p=>p.node.name))}if(!h.motion.clip){Er&&console.warn("No clip assigned to state",h);const u=new zs(void 0,void 0,[]);h.motion.clip=u}if((o=h.motion)!=null&&o.clip){const u=h.motion.clip;if(u instanceof zs){const p=this.createAction(u);h.motion.action=p}else(Er||st())&&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 p=q.get(u.typeName),m=new p;m.isStateMachineBehaviour&&(m._context=this.context??void 0,Rg(m,u.properties),u.instance=m),Er&&console.log("Created animator controller behaviour",h.name,u.typeName,u.properties,m)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let r=0;r<t.states.length;r++){const s=t.states[r];s!=null&&s.motion&&(s.motion.action&&(yield s.motion.action),s.motion.action_loopback&&(yield s.motion.action_loopback))}}}}class S8{constructor(e,t){d(this,"track"),d(this,"createdInterpolant"),d(this,"originalEvaluate"),d(this,"customEvaluate"),this.track=e;const r=e,s=r.createInterpolant.bind(e);r.createInterpolant=()=>(r.createInterpolant=s,this.createdInterpolant=s(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=o=>{if(!this.originalEvaluate)return;const a=this.originalEvaluate(o);return t(o,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 Mr=class{constructor(n,e,t,r,s){if(d(this,"_action"),d(this,"root"),d(this,"clip"),d(this,"positionWrapper",null),d(this,"rotationWrapper",null),d(this,"context"),d(this,"positionChange",new C),d(this,"rotationChange",new Ce),d(this,"_prevTime",0),this.context=n,this.root=e,this.clip=t,Mr.firstKeyframeRotation[this.cacheId]||(Mr.firstKeyframeRotation[this.cacheId]=new Ce),s){const o=s.values;Mr.firstKeyframeRotation[this.cacheId].set(o[0],o[1],o[2],o[3])}Mr.spaceRotation[this.cacheId]||(Mr.spaceRotation[this.cacheId]=new Ce),Mr.effectiveSpaceRotation[this.cacheId]||(Mr.effectiveSpaceRotation[this.cacheId]=new Ce),Mr.clipOffsetRotation[this.cacheId]=new Ce,s&&Mr.clipOffsetRotation[this.cacheId].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(t,r),this.handleRotation(t,s)}set action(n){this._action=n}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(n){if(n.getClip()!==this.clip)return;Mr.lastObjRotation[this.cacheId]||(Mr.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const e=Mr.lastObjRotation[this.cacheId];if(Mr.spaceRotation[this.cacheId].copy(e),qS){const t=new ii().setFromQuaternion(e);console.log("START",this.clip.name,it.toDegrees(t.y),this.root.position.z)}}getClipRotationOffset(){return Mr.clipOffsetRotation[this.cacheId]}handlePosition(n,e){if(e){const t=this.root;qS&&t.add(new Po),Mr.lastObjPosition[this.cacheId]||(Mr.lastObjPosition[this.cacheId]=this.root.position.clone());const r=new C,s=new C;this.positionWrapper=new S8(e,(o,a)=>{const l=this.action.getEffectiveWeight();return qS&&t.position.length()>8&&t.position.set(0,t.position.y,0),o>this._prevTime&&(r.set(a[0],a[1],a[2]),r.sub(s),r.multiplyScalar(l),r.applyQuaternion(this.getClipRotationOffset()),r.applyQuaternion(t.quaternion),this.positionChange.copy(r)),s.fromArray(a),this._prevTime=o,a[0]=0,a[1]=0,a[2]=0,a})}}handleRotation(n,e){if(e){if(qS){const o=e.values,a=new ii().setFromQuaternion(new Ce(o[0],o[1],o[2],o[3]));console.log(n.name,e.name,"FIRST ROTATION IN TRACK",it.toDegrees(a.y));const l=e.values.length-4,c=new Ce().set(o[l],o[l+1],o[l+2],o[l+3]),h=new ii().setFromQuaternion(c);console.log(n.name,e.name,"LAST ROTATION IN TRACK",it.toDegrees(h.y))}let t=0;const r=new Ce,s=new Ce;this.rotationWrapper=new S8(e,(o,a)=>(o>t&&(s.set(a[0],a[1],a[2],a[3]),r.invert(),s.multiply(r),this.rotationChange.copy(s)),r.fromArray(a),t=o,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(n){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(n){return!this.action||(n*=this.action.getEffectiveWeight(),n<=0)?!1:(this.positionChange.multiplyScalar(n),this.rotationChange.slerp(Mr.identityQuaternion,1-n),!0)}};let rd=Mr;d(rd,"lastObjPosition",{}),d(rd,"lastObjRotation",{}),d(rd,"firstKeyframeRotation",{}),d(rd,"spaceRotation",{}),d(rd,"effectiveSpaceRotation",{}),d(rd,"clipOffsetRotation",{}),d(rd,"identityQuaternion",new Ce);class hme{constructor(e){d(this,"controller"),d(this,"handler",[]),d(this,"root"),d(this,"basePosition",new C),d(this,"baseQuaternion",new Ce),d(this,"baseRotation",new ii),d(this,"summedPosition",new C),d(this,"summedRotation",new Ce),this.controller=e}createClip(e,t,r){this.root=t,t&&"name"in t&&t.name;const s=this.findRootTrack(r,".position"),o=this.findRootTrack(r,".quaternion"),a=new rd(this.controller.context,t,r,s,o);this.handler.push(a);const l=e.clipAction(r);return a.action=l,l}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}onAfterUpdate(e){if(!(e<=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 t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const r=e.tracks;if(!r)return null;for(const s of r)if(s.name.endsWith(t))return s;return null}}class ume extends wa{onSerialize(e,t){}onDeserialize(e,t){if(t.type===ea&&e?.__type==="AnimatorController")return new ea(e)}}new ume(ea);var dme=Object.defineProperty,pme=Object.getOwnPropertyDescriptor,YS=(n,e,t,r)=>{for(var s=r>1?void 0:r?pme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&dme(e,t,s),s};const Ia=te("debuganimator");class Wr extends Be{constructor(){super(...arguments),d(this,"applyRootMotion",!1),d(this,"hasRootMotion",!1),d(this,"keepAnimatorControllerStateOnDisable",!1),d(this,"_parametersAreDirty",!1),d(this,"_isDirty",!1),d(this,"_speed",1),d(this,"_normalizedStartOffset",0),d(this,"_animatorController",null),d(this,"_initializeWithRuntimeAnimatorController")}get isAnimationComponent(){return!0}set runtimeAnimatorController(e){var t;this._animatorController&&this._animatorController.model===e||(e?e instanceof ea?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(t=e.model)==null?void 0:t.name),e.model||console.error("AnimatorController has no model"),e=new ea(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Ia&&console.log("Assign animator controller",e,this),this._animatorController=new ea(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,t=-1,r=Number.NEGATIVE_INFINITY,s=0){this.play(e,t,r,s)}play(e,t=-1,r=Number.NEGATIVE_INFINITY,s=0){var o;(o=this.runtimeAnimatorController)==null||o.play(e,t,r,s),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var r,s;Ia&&console.log("setBool",e,t),((r=this.runtimeAnimatorController)==null?void 0:r.getBool(e))!==t&&(this._parametersAreDirty=!0),(s=this.runtimeAnimatorController)==null||s.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var t;const r=((t=this.runtimeAnimatorController)==null?void 0:t.getBool(e))??!1;return Ia&&console.log("getBool",e,r),r}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var r,s;((r=this.runtimeAnimatorController)==null?void 0:r.getFloat(e))!==t&&(this._parametersAreDirty=!0),Ia&&console.log("setFloat",e,t),(s=this.runtimeAnimatorController)==null||s.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var t;const r=((t=this.runtimeAnimatorController)==null?void 0:t.getFloat(e))??-1;return Ia&&console.log("getFloat",e,r),r}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var r,s;((r=this.runtimeAnimatorController)==null?void 0:r.getInteger(e))!==t&&(this._parametersAreDirty=!0),Ia&&console.log("setInteger",e,t),(s=this.runtimeAnimatorController)==null||s.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var t;const r=((t=this.runtimeAnimatorController)==null?void 0:t.getInteger(e))??-1;return Ia&&console.log("getInteger",e,r),r}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;this._parametersAreDirty=!0,Ia&&console.log("setTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;this._parametersAreDirty=!0,Ia&&console.log("resetTrigger",e),(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var t;const r=(t=this.runtimeAnimatorController)==null?void 0:t.getTrigger(e);return Ia&&console.log("getTrigger",e,r),r}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 t;e!==this._speed&&(Ia&&console.log("setSpeed",e),this._speed=e,((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){var t;this._speed=it.lerp(e.x,e.y,Math.random()),((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){var t;this._normalizedStartOffset=it.lerp(e.x,e.y,Math.random()),((t=this.runtimeAnimatorController)==null?void 0:t.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){Ia&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const r=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=r,r?(console.assert(this.runtimeAnimatorController!==r),this.runtimeAnimatorController=r,console.assert(this.runtimeAnimatorController===r),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,!lme(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}YS([w()],Wr.prototype,"applyRootMotion",2),YS([w()],Wr.prototype,"hasRootMotion",2),YS([w()],Wr.prototype,"keepAnimatorControllerStateOnDisable",2),YS([w()],Wr.prototype,"runtimeAnimatorController",1);const ic=te("debugusdzanimation"),_k=te("debugusdzanimationserialization");class JS{constructor(e,t,r){d(this,"_start"),d(this,"ext"),d(this,"root"),d(this,"clip"),d(this,"speed"),this.ext=e,this.root=t,this.clip=r}get start(){return this._start===void 0&&(this._start=this.ext.getStartTime01(this.root,this.clip)),this._start}get duration(){var e;return((e=this.clip)==null?void 0:e.duration)??Tr.restPoseClipDuration}}const C8=class{constructor(n,e,t){d(this,"clip"),d(this,"pos"),d(this,"rot"),d(this,"scale"),d(this,"root"),d(this,"target"),d(this,"duration",0),d(this,"useRootMotion",!1),this.root=n,this.target=e,this.clip=t,t?this.duration=t.duration:this.duration=C8.restPoseClipDuration;const r=ie.getComponent(n,Wr);r&&(this.useRootMotion=r.applyRootMotion)}get frameRate(){return 60}addTrack(n){var e,t;if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it \u2013 this is likely a bug");return}n.name.endsWith("position")?this.pos=n:n.name.endsWith("quaternion")?this.rot=n:n.name.endsWith("scale")?this.scale=n:(n.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+n.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: "+n.name+" on "+(((t=this.root)==null?void 0:t.name)??this.target.name)+". Only .position, .rotation, .scale are supported."),st()&&Di("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){var n,e,t,r,s,o;return this.clip?Math.max(((e=(n=this.pos)==null?void 0:n.times)==null?void 0:e.length)??0,((r=(t=this.rot)==null?void 0:t.times)==null?void 0:r.length)??0,((o=(s=this.scale)==null?void 0:s.times)==null?void 0:o.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(n=!0,e=!0,t=!0){var r,s,o;if(!this.clip)return[0,this.duration];const a=(r=this.pos)==null?void 0:r.times,l=(s=this.rot)==null?void 0:s.times,c=(o=this.scale)==null?void 0:o.times,h=[];if(n&&a)for(const u of a)h.push(u);if(e&&l)for(const u of l)h.push(u);if(t&&c)for(const u of c)h.push(u);return h.includes(0)||h.push(0),h.sort((u,p)=>u-p),[...new Set(h)]}*getValues(n,e=!0,t=!0,r=!0){var s,o,a;const l=new C,c=new Ce,h=new C(1,1,1),u=this.target,p=e?(s=this.pos)==null?void 0:s.createInterpolant():void 0,m=t?(o=this.rot)==null?void 0:o.createInterpolant():void 0,f=r?(a=this.scale)==null?void 0:a.createInterpolant():void 0;p||l.set(u.position.x,u.position.y,u.position.z),m||c.set(u.quaternion.x,u.quaternion.y,u.quaternion.z,u.quaternion.w),f||h.set(u.scale.x,u.scale.y,u.scale.z);for(let g=0;g<n.length;g++){const v=n[g];if(p){const y=p.evaluate(v);l.set(y[0],y[1],y[2])}if(m){const y=m.evaluate(v);c.set(y[0],y[1],y[2],y[3])}if(f){const y=f.evaluate(v);h.set(y[0],y[1],y[2])}if(this.useRootMotion&&u===this.root){const y=new ve;y.compose(l,c,h),y.multiply(u.matrix),y.decompose(l,c,h)}yield{time:v,translation:l,rotation:c,scale:h,index:g}}}};let Tr=C8;d(Tr,"animationDurationPadding",1/60),d(Tr,"restPoseClipDuration",1/60);class BA{constructor(e){d(this,"dict",new Map),d(this,"rootTargetMap",new Map),d(this,"rootAndClipToRegisteredAnimationMap",new Map),d(this,"rootToRegisteredClip",new Map),d(this,"serializers",[]),d(this,"injectRestPoses",!1),d(this,"injectImplicitBehaviours",!1),this.injectRestPoses=e,this.injectImplicitBehaviours=e}get extensionName(){return"animation"}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Tr.restPoseClipDuration+Tr.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,r]of this.rootAndClipToRegisteredAnimationMap){const s=r.start+r.duration;s>e&&(e=s)}return e*60}getClipCount(e){var t;return((t=this.rootToRegisteredClip.get(e))==null?void 0:t.length)??0??0}getStartTime01(e,t){if(!t)return 0;const r=this.rootTargetMap.get(e);if(!r)return 0;const s=this.dict.get(r[0]);if(!s)return console.error("Trying to get start time for root that has no animation data",e,t,...this.dict),0;let o=0;for(let a=0;a<s.length&&s[a].clip!==t;a++)o+=s[a].getDuration()+Tr.animationDurationPadding;return o}registerAnimation(e,t){var r;if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const s=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(s))return this.rootAndClipToRegisteredAnimationMap.get(s);ic&&console.log("registerAnimation",e,t);const o=this.injectRestPoses?1:0,a=(((r=this.rootToRegisteredClip.get(e))==null?void 0:r.length)??0)+o,l=this.rootTargetMap.get(e),c=new Set(l);if(t&&t.tracks)for(const u of t.tracks){const p=Xt.parseTrackName(u.name),m=Xt.findNode(e,p.nodeName);if(!m){console.warn("no object found for track",u.name,"using "+e.name+" instead");continue}this.dict.has(m)||this.dict.set(m,[]);const f=this.dict.get(m);if(!f){console.warn("no transform data found for target ",m,"at slot "+a+", this is likely a bug");continue}c.delete(m),this.injectRestPoses&&!f[0]&&(f[0]=new Tr(null,m,null));let g=f[a];g||(g=new Tr(e,m,t),f[a]=g),g.addTrack(u),l!=null&&l.includes(m)||l==null||l.push(m)}ic&&console.log("Unregistered nodes for this clip",c,"clip",t,"at slot",a,"for root",e,"targets",l);for(const u of c){const p=this.dict.get(u);if(!p)continue;if(this.injectRestPoses&&!p[0]){console.warn("Adding rest pose for ",u,t,"at slot",a,"This is likely a bug, should have been added earlier.");const f=new Tr(null,u,null);p[0]=f}let m=p[a];m||(ic&&console.log("Adding padding clip for ",u,t,"at slot",a),m=new Tr(e,u,t),p[a]=m)}const h=new JS(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(s,h),ic&&console.log({root:e,clip:t,info:h}),t){const u=this.rootToRegisteredClip.get(e);u?u.push(t):this.rootToRegisteredClip.set(e,[t])}return h}onAfterHierarchy(e){ic&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){var t,r;ic&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const s of this.rootTargetMap.keys()){const o=this.rootTargetMap.get(s);if(!o)continue;let a;const l=[];for(const c of o){const h=this.dict.get(c);if(!h){console.error("No data found for target on USDZ export \u2013 please report a bug!",c);continue}a===void 0&&(a=h?.length),a!==h?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",h);for(let u=0;u<h.length;u++){let p=h[u];if(!p){const f=u-(this.injectRestPoses?1:0);h[u]=new Tr(null,c,this.rootToRegisteredClip.get(s)[f]),p=h[u]}const m=p.getDuration();if(l[u]===void 0)l[u]=m;else if(l[u]!==m){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:h,target:c}),l[u]=m;continue}}}}for(const s of this.serializers){const o=(t=s.model)==null?void 0:t.parent,a=o?.isDynamic===!0;_k&&console.log(a,(r=s.model)==null?void 0:r.parent),a&&s.registerCallback(o)}}onExportObject(e,t,r){ie.foreachComponent(e,o=>{const a=o;typeof a.createAnimation=="function"&&a.createAnimation(this,t,r)},!1);const s=new mme(e,this.dict);this.serializers.push(s),s.registerCallback(t)}}class mme{constructor(e,t){d(this,"object"),d(this,"dict"),d(this,"model"),d(this,"callback"),this.object=e,this.dict=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),_k&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t){var r;const s=this.model,o=this.dict;if(s&&s.skinnedMesh){let a=function(P){const z=[];for(const[V,L]of P){let H=`${V} : [`;const O=[];for(const F of L)O.push(`(${yr(F.x)}, ${yr(F.y)}, ${yr(F.z)})`);H=H.concat(O.join(", ")),H=H.concat("],"),z.push(H)}return z},l=function(P){const z=[];for(const[V,L]of P){let H=`${V} : [`;const O=[];for(const F of L)O.push(`(${yr(F.w)}, ${yr(F.x)}, ${yr(F.y)}, ${yr(F.z)})`);H=H.concat(O.join(", ")),H=H.concat("],"),z.push(H)}return z},c=function(P){let z,V=!0;const L=new Map;for(const[O,F]of P){z===void 0&&(z=F.length),z!==F.length&&(V=!1);let G=0;for(const J of F)G++,J||(L.has(O)||L.set(O,[]),L.get(O).push(G))}ic&&console.log("Bone count: ",P.size,"TransformData entries per bone: ",z,"Undefined bone entries: ",L),console.assert(V,"All bones should have the same number of TransformData entries",P),console.assert(L.size===0,"All TransformData entries should be set",L);const H=[];for(const[O,F]of P){const G=new Array;let J=0;for(let K=0;K<F.length;K++)G.push(J),J+=F[K].getDuration()+Tr.animationDurationPadding;for(let K=0;K<F.length;K++){const oe=F[K],we=G[K];H.length<=K&&H.push({pos:[],rot:[],scale:[],timeOffset:we});const De=H[K];De.pos.push(...oe.getSortedTimesArray(!0,!1,!1)),De.rot.push(...oe.getSortedTimesArray(!1,!0,!1)),De.scale.push(...oe.getSortedTimesArray(!1,!1,!0))}}for(const O of H)O.pos.sort((F,G)=>F-G),O.rot.sort((F,G)=>F-G),O.scale.sort((F,G)=>F-G),O.pos=[...new Set(O.pos)],O.rot=[...new Set(O.rot)],O.scale=[...new Set(O.scale)];return H},h=function(P,z,V){const L=new Map,H=new Map,O=new Map,F=z.length;for(const G of V){const J=P.get(G);let K;J?console.assert(J.length===F,"We should have the same number of TransformData entries for each bone",J,z):K=new Tr(null,G,null);for(let oe=0;oe<F;oe++){const we=J?J[oe]:K,De=z[oe];for(const{time:se,translation:be}of we.getValues(De.pos,!0,!1,!1)){const Ie=(se+De.timeOffset)*60;L.has(Ie)||L.set(Ie,new Array),L.get(Ie).push(be.clone())}for(const{time:se,rotation:be}of we.getValues(De.rot,!1,!0,!1)){const Ie=(se+De.timeOffset)*60;H.has(Ie)||H.set(Ie,new Array),H.get(Ie).push(be.clone())}for(const{time:se,scale:be}of we.getValues(De.scale,!1,!1,!0)){const Ie=(se+De.timeOffset)*60;O.has(Ie)||O.set(Ie,new Array),O.get(Ie).push(be.clone())}}}return{position:L.size==0?void 0:L,quaternion:H.size==0?void 0:H,scale:O.size==0?void 0:O}},u=function(P){const z=[];for(const V of P)z.push(`(${yr(V.x)}, ${yr(V.y)}, ${yr(V.z)})`);return z.join(", ")},p=function(P){const z=[];for(const V of P)z.push(`(${yr(V.w)}, ${yr(V.x)}, ${yr(V.y)}, ${yr(V.z)})`);return z.join(", ")},m=function(P){const z=new Map;if(ic){const V=new Array;for(const[L,H]of o)V.push(L.uuid+": "+H.length+" "+H.map(O=>{var F;return(F=O.clip)==null?void 0:F.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
5736
+ Exit Time: `+u,a.hasExitTime)}this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}}s&&this.setTimescale(s,r);let o=!1;if(r.motion.isLooping&&s&&(s.time>=s.getClip().duration?(o=!0,s.reset(),s.time=0,s.play()):s.time<=0&&s.timeScale<0&&(o=!0,s.reset(),s.time=s.getClip().duration,s.play())),!o&&r&&!t&&s&&this.animator&&r.behaviours){const a=s?.getClip().duration,l=s.time/a,c=new PA(this._activeState,l,a,this._speed);for(const h of r.behaviours)h.instance&&((e=h.instance.onStateUpdate)==null||e.call(h.instance,this.animator,c,0))}}setTimescale(e,t){let r=t.speed??1;t.speedParameter&&(r*=this.getFloat(t.speedParameter)),r!==void 0&&(e.timeScale=r*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(Er&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}releaseHeldActions(e){for(const t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,r){var s,o,a,l,c,h,u,p;if(!this.animator)return;const m=0;if(e=this.getState(e,m),!(e!=null&&e.motion)||!e.motion.clip||!(e.motion.clip instanceof zs))return;const f=this._activeState===e;if(f){const _=e.motion;if(!_.action_loopback&&_.clip){const b=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(_.clip,this.animator.gameObject),b&&b.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),_.action_loopback=this.createAction(_.clip)}}if((s=this._activeState)!=null&&s.behaviours&&this._activeState.motion.action){const _=(o=this._activeState)==null?void 0:o.motion.clip.duration,b=this._activeState.motion.action.time/_,x=new PA(this._activeState,b,_,this._speed);for(const E of this._activeState.behaviours)(l=(a=E.instance)==null?void 0:a.onStateExit)==null||l.call(E.instance,this.animator,x,m)}const g=(c=this._activeState)==null?void 0:c.motion.action;f&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=g);const v=this._activeState;this._activeState=e;const y=(h=e.motion)==null?void 0:h.action,A=e.motion.clip;if(A?.duration<=0&&A.tracks.length<=0?g&&this._heldActions.push(g):g&&(g.fadeOut(t),this.releaseHeldActions(t)),y){if(r=Math.max(0,Math.min(1,r)),e.cycleOffsetParameter){let b=this.getFloat(e.cycleOffsetParameter);typeof b=="number"?(b<0&&(b+=1),r+=b,r%=1):Er&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(r+=e.cycleOffset,r%=1);y.isRunning()&&y.stop(),y.reset(),y.enabled=!0,this.setTimescale(y,e);const _=e.motion.clip.duration;if(y.time=f?0:r*_,y.timeScale<0&&(y.time=_-y.time),y.clampWhenFinished=!0,y.setLoop(nv,0),t>0?y.fadeIn(t):y.weight=1,y.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(y),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const b=new PA(e,r,_,this._speed);for(const x of this._activeState.behaviours)(p=(u=x.instance)==null?void 0:u.onStateEnter)==null||p.call(x.instance,this.animator,b,m)}}else Er&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));Er&&console.log("TRANSITION FROM "+v?.name+" TO "+e.name,t,g,y,y?.getEffectiveTimeScale(),y?.getEffectiveWeight(),y?.isRunning(),y?.isScheduled(),y?.paused)}createAction(e){var t,r;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(t=this.animator)==null?void 0:t.gameObject),(r=this.animator)!=null&&r.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new hme(this));const s=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,s,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(r=>r.name===e.parameter);if(!t)return!1;switch(e.mode){case nd.If:return t.value===!0;case nd.IfNot:return t.value===!1;case nd.Greater:return t.value>e.threshold;case nd.Less:return t.value<e.threshold;case nd.Equals:return t.value===e.threshold;case nd.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,r,s,o;Er&&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||(Er&&console.warn("No motion",h),h.motion=wV(h.name)),this.animator&&h.motion.clips){const u=(t=h.motion.clips)==null?void 0:t.find(p=>{var m,f;return p.node.name===((f=(m=this.animator)==null?void 0:m.gameObject)==null?void 0:f.name)});u?h.motion.clip=u.clip:(Er||st())&&console.warn('Could not find clip for animator "'+((s=(r=this.animator)==null?void 0:r.gameObject)==null?void 0:s.name)+'"',h.motion.clips.map(p=>p.node.name))}if(!h.motion.clip){Er&&console.warn("No clip assigned to state",h);const u=new zs(void 0,void 0,[]);h.motion.clip=u}if((o=h.motion)!=null&&o.clip){const u=h.motion.clip;if(u instanceof zs){const p=this.createAction(u);h.motion.action=p}else(Er||st())&&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 p=q.get(u.typeName),m=new p;m.isStateMachineBehaviour&&(m._context=this.context??void 0,Rg(m,u.properties),u.instance=m),Er&&console.log("Created animator controller behaviour",h.name,u.typeName,u.properties,m)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let r=0;r<t.states.length;r++){const s=t.states[r];s!=null&&s.motion&&(s.motion.action&&(yield s.motion.action),s.motion.action_loopback&&(yield s.motion.action_loopback))}}}}class SV{constructor(e,t){d(this,"track"),d(this,"createdInterpolant"),d(this,"originalEvaluate"),d(this,"customEvaluate"),this.track=e;const r=e,s=r.createInterpolant.bind(e);r.createInterpolant=()=>(r.createInterpolant=s,this.createdInterpolant=s(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=o=>{if(!this.originalEvaluate)return;const a=this.originalEvaluate(o);return t(o,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 Mr=class{constructor(n,e,t,r,s){if(d(this,"_action"),d(this,"root"),d(this,"clip"),d(this,"positionWrapper",null),d(this,"rotationWrapper",null),d(this,"context"),d(this,"positionChange",new C),d(this,"rotationChange",new Ce),d(this,"_prevTime",0),this.context=n,this.root=e,this.clip=t,Mr.firstKeyframeRotation[this.cacheId]||(Mr.firstKeyframeRotation[this.cacheId]=new Ce),s){const o=s.values;Mr.firstKeyframeRotation[this.cacheId].set(o[0],o[1],o[2],o[3])}Mr.spaceRotation[this.cacheId]||(Mr.spaceRotation[this.cacheId]=new Ce),Mr.effectiveSpaceRotation[this.cacheId]||(Mr.effectiveSpaceRotation[this.cacheId]=new Ce),Mr.clipOffsetRotation[this.cacheId]=new Ce,s&&Mr.clipOffsetRotation[this.cacheId].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(t,r),this.handleRotation(t,s)}set action(n){this._action=n}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(n){if(n.getClip()!==this.clip)return;Mr.lastObjRotation[this.cacheId]||(Mr.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const e=Mr.lastObjRotation[this.cacheId];if(Mr.spaceRotation[this.cacheId].copy(e),qS){const t=new ii().setFromQuaternion(e);console.log("START",this.clip.name,it.toDegrees(t.y),this.root.position.z)}}getClipRotationOffset(){return Mr.clipOffsetRotation[this.cacheId]}handlePosition(n,e){if(e){const t=this.root;qS&&t.add(new Po),Mr.lastObjPosition[this.cacheId]||(Mr.lastObjPosition[this.cacheId]=this.root.position.clone());const r=new C,s=new C;this.positionWrapper=new SV(e,(o,a)=>{const l=this.action.getEffectiveWeight();return qS&&t.position.length()>8&&t.position.set(0,t.position.y,0),o>this._prevTime&&(r.set(a[0],a[1],a[2]),r.sub(s),r.multiplyScalar(l),r.applyQuaternion(this.getClipRotationOffset()),r.applyQuaternion(t.quaternion),this.positionChange.copy(r)),s.fromArray(a),this._prevTime=o,a[0]=0,a[1]=0,a[2]=0,a})}}handleRotation(n,e){if(e){if(qS){const o=e.values,a=new ii().setFromQuaternion(new Ce(o[0],o[1],o[2],o[3]));console.log(n.name,e.name,"FIRST ROTATION IN TRACK",it.toDegrees(a.y));const l=e.values.length-4,c=new Ce().set(o[l],o[l+1],o[l+2],o[l+3]),h=new ii().setFromQuaternion(c);console.log(n.name,e.name,"LAST ROTATION IN TRACK",it.toDegrees(h.y))}let t=0;const r=new Ce,s=new Ce;this.rotationWrapper=new SV(e,(o,a)=>(o>t&&(s.set(a[0],a[1],a[2],a[3]),r.invert(),s.multiply(r),this.rotationChange.copy(s)),r.fromArray(a),t=o,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(n){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(n){return!this.action||(n*=this.action.getEffectiveWeight(),n<=0)?!1:(this.positionChange.multiplyScalar(n),this.rotationChange.slerp(Mr.identityQuaternion,1-n),!0)}};let rd=Mr;d(rd,"lastObjPosition",{}),d(rd,"lastObjRotation",{}),d(rd,"firstKeyframeRotation",{}),d(rd,"spaceRotation",{}),d(rd,"effectiveSpaceRotation",{}),d(rd,"clipOffsetRotation",{}),d(rd,"identityQuaternion",new Ce);class hme{constructor(e){d(this,"controller"),d(this,"handler",[]),d(this,"root"),d(this,"basePosition",new C),d(this,"baseQuaternion",new Ce),d(this,"baseRotation",new ii),d(this,"summedPosition",new C),d(this,"summedRotation",new Ce),this.controller=e}createClip(e,t,r){this.root=t,t&&"name"in t&&t.name;const s=this.findRootTrack(r,".position"),o=this.findRootTrack(r,".quaternion"),a=new rd(this.controller.context,t,r,s,o);this.handler.push(a);const l=e.clipAction(r);return a.action=l,l}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}onAfterUpdate(e){if(!(e<=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 t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const r=e.tracks;if(!r)return null;for(const s of r)if(s.name.endsWith(t))return s;return null}}class ume extends wa{onSerialize(e,t){}onDeserialize(e,t){if(t.type===ea&&e?.__type==="AnimatorController")return new ea(e)}}new ume(ea);var dme=Object.defineProperty,pme=Object.getOwnPropertyDescriptor,YS=(n,e,t,r)=>{for(var s=r>1?void 0:r?pme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&dme(e,t,s),s};const Ia=te("debuganimator");class Wr extends Be{constructor(){super(...arguments),d(this,"applyRootMotion",!1),d(this,"hasRootMotion",!1),d(this,"keepAnimatorControllerStateOnDisable",!1),d(this,"_parametersAreDirty",!1),d(this,"_isDirty",!1),d(this,"_speed",1),d(this,"_normalizedStartOffset",0),d(this,"_animatorController",null),d(this,"_initializeWithRuntimeAnimatorController")}get isAnimationComponent(){return!0}set runtimeAnimatorController(e){var t;this._animatorController&&this._animatorController.model===e||(e?e instanceof ea?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(t=e.model)==null?void 0:t.name),e.model||console.error("AnimatorController has no model"),e=new ea(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Ia&&console.log("Assign animator controller",e,this),this._animatorController=new ea(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,t=-1,r=Number.NEGATIVE_INFINITY,s=0){this.play(e,t,r,s)}play(e,t=-1,r=Number.NEGATIVE_INFINITY,s=0){var o;(o=this.runtimeAnimatorController)==null||o.play(e,t,r,s),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var r,s;Ia&&console.log("setBool",e,t),((r=this.runtimeAnimatorController)==null?void 0:r.getBool(e))!==t&&(this._parametersAreDirty=!0),(s=this.runtimeAnimatorController)==null||s.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var t;const r=((t=this.runtimeAnimatorController)==null?void 0:t.getBool(e))??!1;return Ia&&console.log("getBool",e,r),r}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var r,s;((r=this.runtimeAnimatorController)==null?void 0:r.getFloat(e))!==t&&(this._parametersAreDirty=!0),Ia&&console.log("setFloat",e,t),(s=this.runtimeAnimatorController)==null||s.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var t;const r=((t=this.runtimeAnimatorController)==null?void 0:t.getFloat(e))??-1;return Ia&&console.log("getFloat",e,r),r}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var r,s;((r=this.runtimeAnimatorController)==null?void 0:r.getInteger(e))!==t&&(this._parametersAreDirty=!0),Ia&&console.log("setInteger",e,t),(s=this.runtimeAnimatorController)==null||s.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var t;const r=((t=this.runtimeAnimatorController)==null?void 0:t.getInteger(e))??-1;return Ia&&console.log("getInteger",e,r),r}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;this._parametersAreDirty=!0,Ia&&console.log("setTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;this._parametersAreDirty=!0,Ia&&console.log("resetTrigger",e),(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var t;const r=(t=this.runtimeAnimatorController)==null?void 0:t.getTrigger(e);return Ia&&console.log("getTrigger",e,r),r}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 t;e!==this._speed&&(Ia&&console.log("setSpeed",e),this._speed=e,((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){var t;this._speed=it.lerp(e.x,e.y,Math.random()),((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){var t;this._normalizedStartOffset=it.lerp(e.x,e.y,Math.random()),((t=this.runtimeAnimatorController)==null?void 0:t.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){Ia&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const r=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=r,r?(console.assert(this.runtimeAnimatorController!==r),this.runtimeAnimatorController=r,console.assert(this.runtimeAnimatorController===r),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,!lme(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}YS([w()],Wr.prototype,"applyRootMotion",2),YS([w()],Wr.prototype,"hasRootMotion",2),YS([w()],Wr.prototype,"keepAnimatorControllerStateOnDisable",2),YS([w()],Wr.prototype,"runtimeAnimatorController",1);const ic=te("debugusdzanimation"),_k=te("debugusdzanimationserialization");class JS{constructor(e,t,r){d(this,"_start"),d(this,"ext"),d(this,"root"),d(this,"clip"),d(this,"speed"),this.ext=e,this.root=t,this.clip=r}get start(){return this._start===void 0&&(this._start=this.ext.getStartTime01(this.root,this.clip)),this._start}get duration(){var e;return((e=this.clip)==null?void 0:e.duration)??Tr.restPoseClipDuration}}const CV=class{constructor(n,e,t){d(this,"clip"),d(this,"pos"),d(this,"rot"),d(this,"scale"),d(this,"root"),d(this,"target"),d(this,"duration",0),d(this,"useRootMotion",!1),this.root=n,this.target=e,this.clip=t,t?this.duration=t.duration:this.duration=CV.restPoseClipDuration;const r=ie.getComponent(n,Wr);r&&(this.useRootMotion=r.applyRootMotion)}get frameRate(){return 60}addTrack(n){var e,t;if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it \u2013 this is likely a bug");return}n.name.endsWith("position")?this.pos=n:n.name.endsWith("quaternion")?this.rot=n:n.name.endsWith("scale")?this.scale=n:(n.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+n.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: "+n.name+" on "+(((t=this.root)==null?void 0:t.name)??this.target.name)+". Only .position, .rotation, .scale are supported."),st()&&Di("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){var n,e,t,r,s,o;return this.clip?Math.max(((e=(n=this.pos)==null?void 0:n.times)==null?void 0:e.length)??0,((r=(t=this.rot)==null?void 0:t.times)==null?void 0:r.length)??0,((o=(s=this.scale)==null?void 0:s.times)==null?void 0:o.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(n=!0,e=!0,t=!0){var r,s,o;if(!this.clip)return[0,this.duration];const a=(r=this.pos)==null?void 0:r.times,l=(s=this.rot)==null?void 0:s.times,c=(o=this.scale)==null?void 0:o.times,h=[];if(n&&a)for(const u of a)h.push(u);if(e&&l)for(const u of l)h.push(u);if(t&&c)for(const u of c)h.push(u);return h.includes(0)||h.push(0),h.sort((u,p)=>u-p),[...new Set(h)]}*getValues(n,e=!0,t=!0,r=!0){var s,o,a;const l=new C,c=new Ce,h=new C(1,1,1),u=this.target,p=e?(s=this.pos)==null?void 0:s.createInterpolant():void 0,m=t?(o=this.rot)==null?void 0:o.createInterpolant():void 0,f=r?(a=this.scale)==null?void 0:a.createInterpolant():void 0;p||l.set(u.position.x,u.position.y,u.position.z),m||c.set(u.quaternion.x,u.quaternion.y,u.quaternion.z,u.quaternion.w),f||h.set(u.scale.x,u.scale.y,u.scale.z);for(let g=0;g<n.length;g++){const v=n[g];if(p){const y=p.evaluate(v);l.set(y[0],y[1],y[2])}if(m){const y=m.evaluate(v);c.set(y[0],y[1],y[2],y[3])}if(f){const y=f.evaluate(v);h.set(y[0],y[1],y[2])}if(this.useRootMotion&&u===this.root){const y=new ve;y.compose(l,c,h),y.multiply(u.matrix),y.decompose(l,c,h)}yield{time:v,translation:l,rotation:c,scale:h,index:g}}}};let Tr=CV;d(Tr,"animationDurationPadding",1/60),d(Tr,"restPoseClipDuration",1/60);class BA{constructor(e){d(this,"dict",new Map),d(this,"rootTargetMap",new Map),d(this,"rootAndClipToRegisteredAnimationMap",new Map),d(this,"rootToRegisteredClip",new Map),d(this,"serializers",[]),d(this,"injectRestPoses",!1),d(this,"injectImplicitBehaviours",!1),this.injectRestPoses=e,this.injectImplicitBehaviours=e}get extensionName(){return"animation"}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Tr.restPoseClipDuration+Tr.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,r]of this.rootAndClipToRegisteredAnimationMap){const s=r.start+r.duration;s>e&&(e=s)}return e*60}getClipCount(e){var t;return((t=this.rootToRegisteredClip.get(e))==null?void 0:t.length)??0??0}getStartTime01(e,t){if(!t)return 0;const r=this.rootTargetMap.get(e);if(!r)return 0;const s=this.dict.get(r[0]);if(!s)return console.error("Trying to get start time for root that has no animation data",e,t,...this.dict),0;let o=0;for(let a=0;a<s.length&&s[a].clip!==t;a++)o+=s[a].getDuration()+Tr.animationDurationPadding;return o}registerAnimation(e,t){var r;if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const s=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(s))return this.rootAndClipToRegisteredAnimationMap.get(s);ic&&console.log("registerAnimation",e,t);const o=this.injectRestPoses?1:0,a=(((r=this.rootToRegisteredClip.get(e))==null?void 0:r.length)??0)+o,l=this.rootTargetMap.get(e),c=new Set(l);if(t&&t.tracks)for(const u of t.tracks){const p=Xt.parseTrackName(u.name),m=Xt.findNode(e,p.nodeName);if(!m){console.warn("no object found for track",u.name,"using "+e.name+" instead");continue}this.dict.has(m)||this.dict.set(m,[]);const f=this.dict.get(m);if(!f){console.warn("no transform data found for target ",m,"at slot "+a+", this is likely a bug");continue}c.delete(m),this.injectRestPoses&&!f[0]&&(f[0]=new Tr(null,m,null));let g=f[a];g||(g=new Tr(e,m,t),f[a]=g),g.addTrack(u),l!=null&&l.includes(m)||l==null||l.push(m)}ic&&console.log("Unregistered nodes for this clip",c,"clip",t,"at slot",a,"for root",e,"targets",l);for(const u of c){const p=this.dict.get(u);if(!p)continue;if(this.injectRestPoses&&!p[0]){console.warn("Adding rest pose for ",u,t,"at slot",a,"This is likely a bug, should have been added earlier.");const f=new Tr(null,u,null);p[0]=f}let m=p[a];m||(ic&&console.log("Adding padding clip for ",u,t,"at slot",a),m=new Tr(e,u,t),p[a]=m)}const h=new JS(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(s,h),ic&&console.log({root:e,clip:t,info:h}),t){const u=this.rootToRegisteredClip.get(e);u?u.push(t):this.rootToRegisteredClip.set(e,[t])}return h}onAfterHierarchy(e){ic&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){var t,r;ic&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const s of this.rootTargetMap.keys()){const o=this.rootTargetMap.get(s);if(!o)continue;let a;const l=[];for(const c of o){const h=this.dict.get(c);if(!h){console.error("No data found for target on USDZ export \u2013 please report a bug!",c);continue}a===void 0&&(a=h?.length),a!==h?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",h);for(let u=0;u<h.length;u++){let p=h[u];if(!p){const f=u-(this.injectRestPoses?1:0);h[u]=new Tr(null,c,this.rootToRegisteredClip.get(s)[f]),p=h[u]}const m=p.getDuration();if(l[u]===void 0)l[u]=m;else if(l[u]!==m){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:h,target:c}),l[u]=m;continue}}}}for(const s of this.serializers){const o=(t=s.model)==null?void 0:t.parent,a=o?.isDynamic===!0;_k&&console.log(a,(r=s.model)==null?void 0:r.parent),a&&s.registerCallback(o)}}onExportObject(e,t,r){ie.foreachComponent(e,o=>{const a=o;typeof a.createAnimation=="function"&&a.createAnimation(this,t,r)},!1);const s=new mme(e,this.dict);this.serializers.push(s),s.registerCallback(t)}}class mme{constructor(e,t){d(this,"object"),d(this,"dict"),d(this,"model"),d(this,"callback"),this.object=e,this.dict=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),_k&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t){var r;const s=this.model,o=this.dict;if(s&&s.skinnedMesh){let a=function(P){const z=[];for(const[V,L]of P){let H=`${V} : [`;const O=[];for(const F of L)O.push(`(${yr(F.x)}, ${yr(F.y)}, ${yr(F.z)})`);H=H.concat(O.join(", ")),H=H.concat("],"),z.push(H)}return z},l=function(P){const z=[];for(const[V,L]of P){let H=`${V} : [`;const O=[];for(const F of L)O.push(`(${yr(F.w)}, ${yr(F.x)}, ${yr(F.y)}, ${yr(F.z)})`);H=H.concat(O.join(", ")),H=H.concat("],"),z.push(H)}return z},c=function(P){let z,V=!0;const L=new Map;for(const[O,F]of P){z===void 0&&(z=F.length),z!==F.length&&(V=!1);let G=0;for(const J of F)G++,J||(L.has(O)||L.set(O,[]),L.get(O).push(G))}ic&&console.log("Bone count: ",P.size,"TransformData entries per bone: ",z,"Undefined bone entries: ",L),console.assert(V,"All bones should have the same number of TransformData entries",P),console.assert(L.size===0,"All TransformData entries should be set",L);const H=[];for(const[O,F]of P){const G=new Array;let J=0;for(let K=0;K<F.length;K++)G.push(J),J+=F[K].getDuration()+Tr.animationDurationPadding;for(let K=0;K<F.length;K++){const oe=F[K],we=G[K];H.length<=K&&H.push({pos:[],rot:[],scale:[],timeOffset:we});const De=H[K];De.pos.push(...oe.getSortedTimesArray(!0,!1,!1)),De.rot.push(...oe.getSortedTimesArray(!1,!0,!1)),De.scale.push(...oe.getSortedTimesArray(!1,!1,!0))}}for(const O of H)O.pos.sort((F,G)=>F-G),O.rot.sort((F,G)=>F-G),O.scale.sort((F,G)=>F-G),O.pos=[...new Set(O.pos)],O.rot=[...new Set(O.rot)],O.scale=[...new Set(O.scale)];return H},h=function(P,z,V){const L=new Map,H=new Map,O=new Map,F=z.length;for(const G of V){const J=P.get(G);let K;J?console.assert(J.length===F,"We should have the same number of TransformData entries for each bone",J,z):K=new Tr(null,G,null);for(let oe=0;oe<F;oe++){const we=J?J[oe]:K,De=z[oe];for(const{time:se,translation:be}of we.getValues(De.pos,!0,!1,!1)){const Ie=(se+De.timeOffset)*60;L.has(Ie)||L.set(Ie,new Array),L.get(Ie).push(be.clone())}for(const{time:se,rotation:be}of we.getValues(De.rot,!1,!0,!1)){const Ie=(se+De.timeOffset)*60;H.has(Ie)||H.set(Ie,new Array),H.get(Ie).push(be.clone())}for(const{time:se,scale:be}of we.getValues(De.scale,!1,!1,!0)){const Ie=(se+De.timeOffset)*60;O.has(Ie)||O.set(Ie,new Array),O.get(Ie).push(be.clone())}}}return{position:L.size==0?void 0:L,quaternion:H.size==0?void 0:H,scale:O.size==0?void 0:O}},u=function(P){const z=[];for(const V of P)z.push(`(${yr(V.x)}, ${yr(V.y)}, ${yr(V.z)})`);return z.join(", ")},p=function(P){const z=[];for(const V of P)z.push(`(${yr(V.w)}, ${yr(V.x)}, ${yr(V.y)}, ${yr(V.z)})`);return z.join(", ")},m=function(P){const z=new Map;if(ic){const V=new Array;for(const[L,H]of o)V.push(L.uuid+": "+H.length+" "+H.map(O=>{var F;return(F=O.clip)==null?void 0:F.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
5737
5737
  `+V.join(`
5738
- `))}for(const V of P){const L=o.get(V);L&&z.set(V,L)}return z},f=function(P){const z=m(P),V=c(z);return h(z,V,P)};const g=s.skinnedMesh.skeleton,v=new Array,y=[],A=[];for(const P of g.bones)if(P.parent.type!=="Bone"){y.push(P);const z=g.boneInverses[g.bones.indexOf(P)];v.push({bone:P,inverse:z}),A.push(P.uuid)}for(;A.length<g.bones.length;)for(const P of y){const z=P.children;for(const V of z)if(A.indexOf(V.uuid)===-1&&g.bones.indexOf(V)!==-1){y.push(V);const L=g.boneInverses[g.bones.indexOf(V)];v.push({bone:V,inverse:L}),A.push(V.uuid)}}for(const P of $j(g.bones))v.push({bone:P,inverse:P.matrixWorld.clone().invert()});const _=v[0].bone.parent;_||console.error("No bone parent found for skinned mesh during USDZ export",s.skinnedMesh),v.sort((P,z)=>xg(P.bone,_)>xg(z.bone,_)?1:-1);const b=t.quickLookCompatible,x=[],E=[],I=[],T=[];for(const{bone:P}of v){if(b){const z=P.scale;z.x==0&&(z.x=1e-5),z.y==0&&(z.y=1e-5),z.z==0&&(z.z=1e-5),x.push(new ve().compose(P.position,P.quaternion,P.scale))}else x.push(P.matrix.clone());E.push(P.position),I.push(P.quaternion),T.push(P.scale)}const R=v.map(P=>'"'+xg(P.bone,_)+'"').join(", "),D=v.map(P=>wg(P.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${D}]`),e.appendLine(`uniform token[] joints = [${R}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${x.map(P=>wg(P)).join(", ")}]`),e.appendLine(`matrix4d xformOp:transform = ${wg(new ve)}`),e.appendLine('uniform token[] xformOpOrder = ["xformOp:transform"]');const M=f(v.map(P=>P.bone));if(ic){let P=1e7,z=0;for(const V of((r=M.position)==null?void 0:r.keys())??[])P=Math.min(P,V),z=Math.max(z,V);console.log("Time samples",P,z,M)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${R}]`),e.appendLine(`quatf[] rotations = [${p(I)}]`),M&&M.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const P=l(M.quaternion);for(const z of P)e.appendLine(z);e.closeBlock()}if(e.appendLine(`half3[] scales = [${u(T)}]`),M&&M.scale){e.beginBlock("half3[] scales.timeSamples = {","");const P=a(M.scale);for(const z of P)e.appendLine(z);e.closeBlock()}if(e.appendLine(`float3[] translations = [${u(E)}]`),M&&M.position){e.beginBlock("float3[] translations.timeSamples = {","");const P=a(M.position);for(const z of P)e.appendLine(z);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){var r;if(!this.model)return;const s=this.dict.get(this.object);if(s)for(let p=0;p<s.length;p++)s[p]===void 0&&(s[p]=new Tr(null,this.object,null));this.skinnedMeshExport(e,t);const o=this.object,a=this.dict.get(o);if(!a||o.isSkinnedMesh)return;_k&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=new ve;e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;const c=new Array;let h=0;for(let p=0;p<a.length;p++){if(c.push(h),a[p]===void 0){console.error("Got an undefined transform data, this is likely a bug.",o,a);continue}h+=a[p].getDuration()+Tr.animationDurationPadding}const u=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});for(let p=0;p<a.length;p++){const m=a[p];if(!m)continue;const f=c[p];{const g=m.getSortedTimesArray();if(!g||g.length===0){console.error("got an animated object but no time values?",o,m);continue}{const v=((r=m.clip)==null?void 0:r.name)??"rest",y=m.getDuration();ic&&console.log("Write .timeSamples:",v,f,y,a),e.appendLine("# "+v+": start="+u.format(f*m.frameRate)+", length="+u.format(y*m.frameRate)+", frames="+m.getFrames())}for(const{time:v,translation:y,rotation:A,scale:_}of m.getValues(g)){l.compose(y,A,_);const b=`${u.format((f+v)*m.frameRate)}: ${wg(l)},`;e.appendLine(b)}}}e.indent--,e.appendLine("}")}}const fme=te("debugpost");let xk=null;function gme(n){xk=n}function E8(n){let e=n.gameObject;for(;e;){for(const t of TS(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function vme(n){let e=E8(n);if(!e)if(xk){fme&&console.warn("Adding postprocessing manager to the scene.");const t=n.scene;e=gl(t,xk)}else st()&&console.warn("No post processing manager found");return e}var yme=Object.defineProperty,Ame=Object.getOwnPropertyDescriptor,M8=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ame(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&yme(e,t,s),s};const bme=te("debugpost");class qe{constructor(e){d(this,"isVolumeParameter",!0),d(this,"_isInitialized",!1),d(this,"_active",!0),d(this,"_value"),d(this,"_valueRaw"),d(this,"_defaultValue"),d(this,"valueProcessor"),d(this,"onValueChanged"),e!==void 0&&this.initialize(e)}get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const r=this._value;bme&&typeof r=="number"&&typeof e=="number"&&(r?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,r,this)}testIfValueChanged(e){return this._valueRaw!==e}}M8([w()],qe.prototype,"overrideState",1),M8([w()],qe.prototype,"value",1);class _me extends wa{constructor(){super([qe])}onSerialize(e,t){}onDeserialize(e,t){const r=t.target,s=t.path;let o;if(r&&s&&(o=r[s]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new qe),typeof e=="object"&&"value"in e){const a=e.value;o.initialize(a),o.overrideState=e.overrideState}else o.value=e;return o}}new _me;var xme=Object.defineProperty,wme=Object.getOwnPropertyDescriptor,Sme=(n,e,t,r)=>{for(var s=r>1?void 0:r?wme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&xme(e,t,s),s};const Cme=te("debugpost");class Xr extends Be{constructor(e=void 0){if(super(),d(this,"active",!0),d(this,"_manager",null),d(this,"_result"),d(this,"_postprocessingContext",null),e)for(const t of Object.keys(e)){const r=e[t],s=this[t];s instanceof qe?s.initialize(r):s!==void 0&&(this[t]=r)}}get isPostProcessingEffect(){return!0}onEnable(){this.onEffectEnabled(),this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){var e;(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){var t;e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=vme(this)),(t=this._manager)==null||t.addEffect(this)}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var t;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(t=this.onCreateEffect)==null?void 0:t.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Cme&&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 t of e){const r=this[t];r instanceof qe&&r.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof qe){const r=e.value;return this[t].value=r,!0}}}Sme([w()],Xr.prototype,"active",2);var Eme=Object.defineProperty,Mme=Object.getOwnPropertyDescriptor,Tme=(n,e,t,r)=>{for(var s=r>1?void 0:r?Mme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Eme(e,t,s),s};const Ime=te("debugpost"),wk={};function Ra(n,e){wk[n]=e}function Rme(n){return n.__type in wk?wk[n.__type]:(Ime&&n.__type&&console.warn("Unknown postprocessing type",n.__type,n),Xr)}class kA{constructor(){d(this,"components",[])}init(){var e;(e=this.components)==null||e.forEach(t=>t.init())}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}Tme([Eg([n=>Rme(n),Xr])],kA.prototype,"components",2);var Pme=Object.defineProperty,Bme=Object.getOwnPropertyDescriptor,kme=(n,e,t,r)=>{for(var s=r>1?void 0:r?Bme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Pme(e,t,s),s};class DA extends Xr{constructor(){super(...arguments),d(this,"preset",new qe(Wp.HIGH))}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new s6({preset:Wp.HIGH,edgeDetectionMode:eB.DEPTH});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}kme([w(qe)],DA.prototype,"preset",2),Ra("Antialiasing",DA);const Dme=te("debugusdz");class Pd{constructor(){d(this,"files",new Array)}static getName(e){var t;const r=e.split(".").pop();let s=(t=e.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:t.replace(".","_");return s||(s="Audio_"+Math.random().toString(36).substring(2,15)),ul(s)+"."+r}get extensionName(){return"Audio"}onExportObject(e,t,r){const s=ie.getComponents(e,Mn);if(s.length)for(const o of s){if(!o.clip||typeof o.clip!="string"||!o.playOnAwake)continue;const a=o.clip.split("/").pop()||"Audio",l=Pd.getName(o.clip),c=ul(l);if(!this.files.some(h=>h.path===o.clip)){this.files.push({path:o.clip,name:l});const h=l.toLowerCase();r.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+o.clip+" from "+o.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}r.quickLookCompatible||t.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 = "${o.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${o.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${o.volume}`),h.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const r="audio/"+t.name;if(e.files[r]){Dme&&console.warn("Audio file with name "+r+" already exists in the context. Skipping.");continue}const s=await(await(await fetch(t.path)).blob()).arrayBuffer(),o=new Uint8Array(s);e.files[r]=o}}}const T8=Symbol("customVisibilityFlag");function sd(n,e){n.layers[T8]=e}const I8=Symbol("DidPatchLayers");function Ome(){const n=ds.prototype;if(n[I8])return;n[I8]=!0;const e=n.test;n.test=function(t){return this[T8]===!1?!1:e.call(this,t)}}Ome();const sm=te("debugautosync"),Sk=Symbol("syncerId");class Lme{constructor(){d(this,"_syncers",{})}getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new Fme(e);return t[Sk]=e.guid,this._syncers[t[Sk]]=t,t}removeSyncer(e){delete this._syncers[e[Sk]]}}const Ck=new Lme;class Fme{constructor(e){d(this,"comp"),d(this,"hasChanges",!1),d(this,"changedProperties",{}),d(this,"data",{}),d(this,"_isReceiving",!1),d(this,"_isInit",!1),d(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const t=this.comp.context.connection;if(!t||!t.isConnected||!t.isInRoom){for(const r in this.changedProperties)delete this.changedProperties[r];return}for(const r in this.data)delete this.data[r];this.data.guid=this.comp.guid;for(const r in this.changedProperties){const s=this.changedProperties[r];delete this.changedProperties[r],this.data[r]=s}t.send(this.networkingKey,this.data,dl.Queued)}),d(this,"onHandleReceiving",t=>{if(sm&&console.log("RECEIVE",this.comp.name,this.comp.guid,t),!this._isInit||!this.comp)return;const r=t.guid;if(!(r&&r!==this.comp.guid)){sm&&console.log("RECEIVED",this.comp.name,this.comp.guid,t);try{this._isReceiving=!0;for(const s in t){if(s==="guid")continue;const o=t[s];this.comp[s]=o,sm&&console.log("SET",s,o)}}catch(s){console.error(s)}finally{this._isReceiving=!1}}}),this.comp=e}get networkingKey(){return this.comp.guid}init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}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(e,t){this._isReceiving||(sm&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}}function Ume(n,e){let t=e!==n;return!t&&n&&e&&(Array.isArray(n)&&Array.isArray(e)||typeof n=="object"&&typeof e=="object")&&(t=!0),t}const OA=Symbol("AutoSyncHandler");function Nme(n){if(n[OA])return n[OA];const e=Ck.getOrCreateSyncer(n);return e?.init(n),n[OA]=e,e}function zme(n){const e=n[OA];e&&(Ck.removeSyncer(e),e.destroy(),delete n[OA])}const Ek=function(n){return function(e,t){var r;let s="";typeof t=="string"?s=t:s=t.name;let o=null,a;typeof n=="string"?a=e[n]:typeof n=="function"&&(a=n);const l=e,c=l.__internalAwake;if(typeof c!="function"){(sm||st())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((r=e?.constructor)==null?void 0:r.name)+'" is not supported',e);return}sm&&console.log(s);const h=Symbol(s);l.__internalAwake=function(){if(this[h]!==void 0)return;this[h]=this[s],o=Ck.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,s);if(p?.set===void 0){let m=!1;Object.defineProperty(this,s,{set:function(f){var g;const v=this[h];if(this[h]=f,m){st()&&console.warn("Recursive call detected",s);return}m=!0;try{const y=Ume(f,v);sm&&console.log("SyncField assignment",s,"changed?",y,f),y&&a?.call(this,f,v)!==!1&&((g=Nme(this))==null||g.notifyChanged(s,f))}finally{m=!1}},get:function(){return this[h]},configurable:!0,enumerable:!0})}o?.init(this),c.call(this)};const u=l.__internalDestroy;l.__internalDestroy=function(){zme(this),u.call(this)}}};var jme=Object.defineProperty,Gme=Object.getOwnPropertyDescriptor,KS=(n,e,t,r)=>{for(var s=r>1?void 0:r?Gme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&jme(e,t,s),s};const jo=te("debugplayersync");class Kg extends Be{constructor(){super(...arguments),d(this,"autoSync",!0),d(this,"asset"),d(this,"onPlayerSpawned"),d(this,"_localInstance"),d(this,"onJoinedRoom",()=>{jo&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),d(this,"destroyInstance",()=>{var e;(e=this._localInstance)==null||e.then(t=>{jo&&console.log("PlayerSync.destroyInstance",t),hA(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new Un)}onEnable(){this.context.connection.beginListen(Vt.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Vt.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.LeftRoom,this.destroyInstance)}async getInstance(){var e,t,r,s,o,a;if(this._localInstance)return this._localInstance;if(jo&&console.log("PlayerSync.createInstance",(e=this.asset)==null?void 0:e.uri),!((t=this.asset)!=null&&t.asset)&&!((r=this.asset)!=null&&r.uri))return console.error('PlayerSync: can not create an instance because "asset" is not set!'),null;this._localInstance=(s=this.asset)==null?void 0:s.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const l=await this._localInstance;if(l){const c=ie.getComponentsInChildren(l,Pa);if(c!=null&&c.length){for(const h of c)h.owner=this.context.connection.connectionId;(o=this.onPlayerSpawned)==null||o.invoke(l)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((a=this.asset)==null?void 0:a.uri)+"</strong>: please make sure the asset has a PlayerState component!"),ie.destroySynced(l)}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 t=Pa.all.length-1;t>=0;t--){const r=Pa.all[t];(!r.owner||!this.context.connection.userIsInRoom(r.owner))&&r.doDestroy()}})}}KS([w()],Kg.prototype,"autoSync",2),KS([w(ti)],Kg.prototype,"asset",2),KS([w(Un)],Kg.prototype,"onPlayerSpawned",2);var R8=(n=>(n.OwnerChanged="ownerChanged",n))(R8||{}),LA;const qr=(LA=class extends Be{constructor(){super(...arguments),d(this,"onOwnerChangeEvent",new Un),d(this,"onFirstOwnerChangeEvent",new Un),d(this,"hasOwner",!1),d(this,"owner"),d(this,"dontDestroy",!1),d(this,"onUserLeftRoom",n=>{if(n.userId===this.owner){jo&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return qr._all}static get local(){return qr._local}static getFor(n){if(n instanceof ye)return ie.getComponentInParent(n,qr);if(n instanceof Be)return ie.getComponentInParent(n.gameObject,qr)}static isLocalPlayer(n){const e=qr.getFor(n);return e?.isLocalPlayer??!1}static addEventListener(n,e){return this._callbacks[n]||(this._callbacks[n]=[]),this._callbacks[n].push(e),e}static removeEventListener(n,e){if(!this._callbacks[n])return;const t=this._callbacks[n].indexOf(e);t>=0&&this._callbacks[n].splice(t,1)}static dispatchEvent(n,e){if(this._callbacks[n])for(const t of this._callbacks[n])t(e)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(n,e){var t,r;jo&&console.log("PlayerSync.onOwnerChange",this,"newOwner",n,"oldOwner",e);const s=qr._local.indexOf(this);s>=0&&qr._local.splice(s,1);const o={playerState:this,oldValue:e,newValue:n};if(this.hasOwner||(this.hasOwner=!0,(t=this.onFirstOwnerChangeEvent)==null||t.invoke(o)),(r=this.onOwnerChangeEvent)==null||r.invoke(o),this.owner===this.context.connection.connectionId){qr._local.push(this);const l=new CustomEvent("local-owner-changed",{detail:o});this.dispatchEvent(l)}const a=new CustomEvent("owner-changed",{detail:o});this.dispatchEvent(a),qr.dispatchEvent("ownerChanged",a)}awake(){qr.all.push(this),jo&&console.log("Registered new PlayerState",this.guid,qr.all.length-1,qr.all),this.context.connection.beginListen(Vt.UserLeftRoom,this.onUserLeftRoom)}async start(){jo&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Ll(300),this.context.connection.userIsInRoom(this.owner)==!1&&(jo&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(jo&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?jo&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(jo&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):jo&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){jo&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),hA(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(this.context.connection.stopListen(Vt.UserLeftRoom,this.onUserLeftRoom),qr.all.splice(qr.all.indexOf(this),1),this.isLocalPlayer){const n=qr._local.indexOf(this);n>=0&&qr._local.splice(n,1)}}},d(LA,"_all",[]),d(LA,"_local",[]),d(LA,"_callbacks",{}),LA);let Pa=qr;KS([Ek(Pa.prototype.onOwnerChange)],Pa.prototype,"owner",2);const Vme=te("debugavatar"),nc=class extends Be{constructor(){super(...arguments),d(this,"connectionId"),d(this,"avatar")}static getAvatar(n){return n>=0&&n<nc.instances.length?nc.instances[n]:null}static onAvatarMarkerCreated(n){return nc._onNewAvatarMarkerAdded.push(n),n}static onAvatarMarkerDestroyed(n){return nc._onAvatarMarkerDestroyed.push(n),n}awake(){nc.instances.push(this),Vme&&console.log(this);for(const n of nc._onNewAvatarMarkerAdded)n({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){nc.instances.splice(nc.instances.indexOf(this),1);for(const n of nc._onAvatarMarkerDestroyed)n({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let Yr=nc;d(Yr,"instances",[]),d(Yr,"_onNewAvatarMarkerAdded",[]),d(Yr,"_onAvatarMarkerDestroyed",[]);var Qme=Object.defineProperty,Hme=Object.getOwnPropertyDescriptor,Wme=(n,e,t,r)=>{for(var s=r>1?void 0:r?Hme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Qme(e,t,s),s};const Zg=te("debugxrflags"),P8=te("disablexrflags");P8&&console.warn("XRFlags are disabled");var rc=(n=>(n[n.Never=0]="Never",n[n.Browser=1]="Browser",n[n.AR=2]="AR",n[n.VR=4]="VR",n[n.FirstPerson=8]="FirstPerson",n[n.ThirdPerson=16]="ThirdPerson",n[n.All=4294967295]="All",n))(rc||{});const B8=class{constructor(){d(this,"Mask",17)}Has(n){return(this.Mask&n)!==0}Set(n){Zg&&console.warn("Set XR flag state to",n),this.Mask=n,Go.Apply()}Enable(n){this.Mask|=n,Go.Apply()}Disable(n){this.Mask&=~n,Go.Apply()}Toggle(n){this.Mask^=n,Go.Apply()}EnableAll(){this.Mask=-1,Go.Apply()}DisableAll(){this.Mask=0,Go.Apply()}};let eo=B8;d(eo,"Global",new B8);var FA;const wh=(FA=class extends Be{constructor(){super(...arguments),d(this,"visibleIn")}static Apply(){for(const n of this.registry)n.UpdateVisible(eo.Global)}awake(){wh.registry.push(this)}onEnable(){wh.firstApply?this.UpdateVisible(eo.Global):(wh.firstApply=!0,wh.Apply())}onDestroy(){const n=wh.registry.indexOf(this);n>=0&&wh.registry.splice(n,1)}get isOn(){return this.gameObject.visible}UpdateVisible(n=null){if(P8)return;let e;const t=n;if(t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),Zg&&console.log(t),wh.buffer.Mask=t,n=wh.buffer),n instanceof eo?(Zg&&console.warn(this.name,"use passed in mask",n.Mask,this.visibleIn),e=n.Has(this.visibleIn)):(Zg&&console.log(this.name,"use global mask"),eo.Global.Has(this.visibleIn)),e!==void 0)if(e)Zg&&console.log(this.name,"is visible",this.gameObject.uuid),ie.setActive(this.gameObject,!0);else{if(Zg&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},d(FA,"registry",[]),d(FA,"firstApply"),d(FA,"buffer",new eo),FA);let Go=wh;Wme([w()],Go.prototype,"visibleIn",2);var Xme=Object.defineProperty,qme=Object.getOwnPropertyDescriptor,Mk=(n,e,t,r)=>{for(var s=r>1?void 0:r?qme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Xme(e,t,s),s};const UA=te("debugwebxr"),k8=new Ce().setFromAxisAngle(new C(0,1,0),Math.PI);class od extends Be{constructor(){super(...arguments),d(this,"head"),d(this,"leftHand"),d(this,"rightHand"),d(this,"_leftHandMeshes"),d(this,"_rightHandMeshes"),d(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;UA&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Pa.getFor(this);if(t!=null&&t.owner){const r=this.gameObject.addComponent(Yr);r.avatar=this.gameObject,r.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Yr);t&&t.destroy()}onUpdateXR(e){var t,r;if(!this.activeAndEnabled)return;const s=Pa.isLocalPlayer(this);if(!s)return;const o=e.xr;if(o.rig&&o.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),o.rig.gameObject.add(this.gameObject)),this._syncTransforms&&s)for(const u of this._syncTransforms)u.fastMode=!0,u.isOwned()||u.requestOwnership();if(this.head&&this.context.mainCamera){const u=this.head.asset;if(u.position.copy(this.context.mainCamera.position),u.position.z*=-1,u.quaternion.copy(this.context.mainCamera.quaternion),u.quaternion.x*=-1,this.context.time.frameCount%10===0){const p=ie.getComponentsInChildren(this.head.asset,Go);for(const m of p)m.enabled=!1,m.gameObject.visible=!1}}const a=e.xr.leftController,l=(t=this.leftHand)==null?void 0:t.asset;a&&l?(l.position.copy(a.gripPosition),l.quaternion.copy(a.gripQuaternion),l.quaternion.multiply(k8),l.visible=a.isTracking,this.updateHandVisibility(a,l,this._leftHandMeshes)):l&&l.visible&&(l.visible=!1);const c=e.xr.rightController,h=(r=this.rightHand)==null?void 0:r.asset;c&&h?(h.position.copy(c.gripPosition),h.quaternion.copy(c.gripQuaternion),h.quaternion.multiply(k8),h.visible=c.isTracking,this.updateHandVisibility(c,h,this._rightHandMeshes)):h&&h.visible&&(h.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,r){if(r){const s=e.model&&e.model.visible&&e.model!==t;r.forEach(o=>{sd(o,!s)})}}updateRemoteAvatarVisibility(){var e,t,r;if(this.context.connection.isConnected){const s=Pa.getFor(this);if(s&&s.isLocalPlayer==!1){const o=wt.getXRSync(this.context);if(o&&o.hasState(s.owner)){this.tryFindAvatarObjectsIfMissing();const a=(e=this.leftHand)==null?void 0:e.asset;a&&(a.visible=o?.isTracking(s.owner,"left")??!1);const l=(t=this.rightHand)==null?void 0:t.asset;l&&(l.visible=o?.isTracking(s.owner,"right")??!1)}if((r=this.head)!=null&&r.asset){const a=ie.getComponentsInChildren(this.head.asset,Go);for(const l of a)l.enabled=!1,l.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};uV.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(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof ye&&(this.head=new ti("",this.sourceId,this.head));else{const e=new ye;e.name="Head";const t=sA.createPrimitive(Yp.Cube);e.add(t),this.gameObject.add(e),this.head=new ti("",this.sourceId,e),UA&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof ye&&(this.rightHand=new ti("",this.sourceId,this.rightHand));else{const e=new ye;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ti("",this.sourceId,e),UA&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof ye&&(this.leftHand=new ti("",this.sourceId,this.leftHand));else{const e=new ye;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ti("",this.sourceId,e),UA&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset.traverse(e=>{e!=null&&e.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset.traverse(e=>{e!=null&&e.isMesh&&this._rightHandMeshes.push(e)}),Pa.isLocalPlayer(this.gameObject)&&(this._syncTransforms=ie.getComponentsInChildren(this.gameObject,Ku))}async loadAvatarObjects(e,t,r){const s=e.loadAssetAsync(),o=t.loadAssetAsync(),a=r.loadAssetAsync(),l=new Array;s&&l.push(s),o&&l.push(o),a&&l.push(a);const c=await tw(l);UA&&console.log("Avatar loaded results:",c)}}Mk([w(ti)],od.prototype,"head",2),Mk([w(ti)],od.prototype,"leftHand",2),Mk([w(ti)],od.prototype,"rightHand",2);class sc{static Add(e,t,r=null){if(t){for(const s of this.Pois)if(s.obj===t)return;this.Pois.push({obj:t,avatar:r}),this.LastChangeTime=e.time.time}}static Remove(e,t){var r;if(t){for(const s of this.Pois)if(s.obj===t){this.Pois.splice(this.Pois.indexOf(s),1),this.LastChangeTime=e?.time.time??((r=kt.Current)==null?void 0:r.time.time);return}}}}d(sc,"Pois",[]),d(sc,"LastChangeTime",0);class Yme{constructor(){d(this,"guid"),d(this,"position",new C)}}class NA extends Be{constructor(){super(...arguments),d(this,"target",null),d(this,"avatar",null),d(this,"_model",null),d(this,"_targetModel",new Yme),d(this,"_currentTargetObject",null),d(this,"_lastUpdateTime",0),d(this,"_lookDuration",0),d(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=q.get("MoveRandom");if(t&&this.target){const r=ie.getComponent(this.target,t);r&&r.destroy()}}awake(){if(this.avatar=ie.getComponentInParent(this.gameObject,Yr),this.avatar){const e=ie.getComponentInParent(this.gameObject,Yr);this._model=new jB(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&&lr(this.target,e.position)})}update(){var e;if((!this.context.connection.isConnected||(e=this._model)!=null&&e.hasOwnership)&&(sc.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=sc.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=Bt(this._currentTargetObject);lr(this.target,t),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(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=sc.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}const $g=te("debugnetworkingstreams");var oc=(n=>(n.Connected="peer-user-connected",n.StreamReceived="receive-stream",n.StreamEnded="call-ended",n.Disconnected="peer-user-disconnected",n.UserJoined="user-joined",n))(oc||{});class D8{constructor(e,t){d(this,"type","call-ended"),d(this,"userId"),d(this,"direction"),this.userId=e,this.direction=t}}class O8{constructor(e,t){d(this,"type","receive-stream"),d(this,"stream"),d(this,"target"),this.stream=e,this.target=t}}class Jme{constructor(e,t){d(this,"guid"),d(this,"peerId"),d(this,"dontSave",!0),this.guid=e.id,this.peerId=t}}var L8=(n=>(n.Incoming="incoming",n.Outgoing="outgoing",n))(L8||{});class Kme extends mr{constructor(e,t,r){super(),d(this,"userId"),d(this,"direction"),d(this,"call"),d(this,"_stream",null),d(this,"_isDisposed",!1),this.userId=e,this.call=t,this.direction=r,this._stream=null,t.on("stream",s=>{if($g&&console.log("Receive video",s.getAudioTracks(),s.getVideoTracks()),this._stream=s,r==="incoming"){const o=new O8(s,this);this.dispatchEvent(o)}}),t.on("close",()=>{this.dispatchEvent(new D8(e,r))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Sh(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}}const zA=class extends mr{constructor(n,e){super(),d(this,"id"),d(this,"context"),d(this,"_peer"),d(this,"_incomingCalls",[]),d(this,"_outgoingCalls",[]),d(this,"_enabled",!1),d(this,"_enabledPeer",!1),d(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),d(this,"onPeerConnectFn",this.onPeerConnect.bind(this)),d(this,"onPeerReceiveCallFn",this.onPeerReceivingCall.bind(this)),this.context=n,this.id=e,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(n,e){if(zA.instances.has(e))return zA.instances.get(e);const t=new zA(n,e);return zA.instances.set(e,t),t}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(n){return this.id+"-"+n}getUserIdFromPeerId(n){return n.substring(this.id.length+1)}makeCall(n,e){var t;const r={metadata:{userId:this.context.connection.connectionId}},s=(t=this._peer)==null?void 0:t.call(n,e,r);if(s)return this.registerCall(s,"outgoing")}get peer(){return this._peer}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(Vt.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(Vt.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const n=this.getMyPeerId();n?this._peer=$G(n):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.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnectFn),this._peer.off("call",this.onPeerReceiveCallFn))}onPeerConnect(n){$g&&console.log("Peer connected as",n),this.context.connection.send("peer-user-connected",new Jme(this,n))}onPeerReceivingCall(n){n.answer(),this.registerCall(n,"incoming")}registerCall(n,e){const t=n.metadata;(!t||!t.userId)&&console.error("Missing call metadata",n);const r=t.userId;e==="incoming"&&$g?console.log("Receive call from",n.metadata):$g&&console.log("Make call to",n.metadata);const s=e==="incoming"?this._incomingCalls:this._outgoingCalls,o=new Kme(r,n,e);return s.push(o),n.on("error",a=>{console.error("Call error",a)}),n.on("close",()=>{$g&&console.log("Call ended",n.metadata),n.close();const a=s.indexOf(o);a!==-1&&s.splice(a,1)}),o.addEventListener("call-ended",a=>{this.dispatchEvent(a)}),e==="incoming"&&(o.addEventListener("receive-stream",a=>{this.dispatchEvent(a)}),n.on("stream",()=>{let a=0;const l=setInterval(()=>{const c=a===0;!o.isOpen&&c&&(a+=1,clearInterval(l),o.close())},2e3)})),o}};let ZS=zA;d(ZS,"instances",new Map);class o_ extends mr{constructor(e,t){super(),d(this,"context"),d(this,"peer"),d(this,"_sendingStreams",new Map),d(this,"debug",!1),d(this,"onJoinedRoom",r=>{this.debug&&console.log(`${r.userId} joined room and I'm currently sending ${this._sendingStreams.size} streams`),this._sendingStreams.size>0&&this.updateSendingCalls()}),d(this,"onReceiveStream",r=>{this.debug&&console.log("RECEIVE STREAM",r),this.dispatchEvent({type:"receive-stream",target:this,stream:r.stream,userId:r.userId})}),d(this,"onCallEnded",r=>{this.dispatchEvent(r)}),d(this,"onUserConnected",r=>{if(this.peer.id===r.guid){this.debug&&console.log("USER CONNECTED",r.guid,r);const s=this._sendingStreams.keys().next().value;this.peer.makeCall(r.peerId,s)}}),d(this,"onUserLeft",r=>{this.stopCallsToUsersThatAreNotInTheRoomAnymore()}),this.context=e,this.peer=t,$g&&(this.debug=!0)}static create(e){const t=ZS.getOrCreate(e.context,e.context.connection.connectionId);return new o_(e.context,t)}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 t=this._sendingStreams.get(e);if(t){this.debug&&console.log("Closing calls",t);for(const r of t)r.close()}this._sendingStreams.delete(e),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}}enable(){this.peer.enable(),this.peer.addEventListener("receive-stream",this.onReceiveStream),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.UserLeftRoom,this.onUserLeft)}disable(){this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onReceiveStream),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.UserLeftRoom,this.onUserLeft)}updateSendingCalls(){var e;let t=!1;const r=this.context.connection.connectionId;for(const s of this._sendingStreams.keys()){const o=this._sendingStreams.get(s)||[];for(const a of this.context.connection.usersInRoom()){if(a===r)continue;const l=o.find(c=>c.userId===a);if(!l||((e=l.stream)==null?void 0:e.active)===!1){this.debug&&console.log("Starting call to",a,r);const c=this.peer.makeCall(this.peer.getPeerIdFromUserId(a),s);c&&(t=!0,o.push(c))}}this._sendingStreams.set(s,o)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let r=t.length-1;r>=0;r--){const s=t[r];this.context.connection.userIsInRoom(s.userId)||(s.close(),t.splice(r,1))}}}}function Sh(n){if(n&&n instanceof MediaStream)for(const e of n.getTracks())e.stop()}var Zme=Object.defineProperty,$me=Object.getOwnPropertyDescriptor,F8=(n,e,t,r)=>{for(var s=r>1?void 0:r?$me(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Zme(e,t,s),s};const efe="noVoip",tfe=te("debugvoip");class om extends Be{constructor(){super(...arguments),d(this,"autoConnect",!0),d(this,"runInBackground",!0),d(this,"debug",!1),d(this,"_net"),d(this,"_outputStream",null),d(this,"onJoinedRoom",async()=>{this.debug&&console.log("VOIP: Joined room"),await Ll(300),this.autoConnect&&!this.isSending&&this.connect()}),d(this,"_incomingStreams",new Map),d(this,"onReceiveStream",e=>{const t=e.target.userId,r=e.stream,s=this._incomingStreams.get(t);if(s)s.srcObject=r,s.setAttribute("autoplay","true");else{const o=new Audio;this._incomingStreams.set(t,o),o.setAttribute("autoplay","true"),o.srcObject=r}}),d(this,"onStreamEnded",e=>{const t=this._incomingStreams.get(e.userId);Sh(t?.srcObject),this._incomingStreams.delete(e.userId)}),d(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}}),d(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const r=t[1];r.muted=e}})}awake(){tfe&&(this.debug=!0),this.debug&&window.addEventListener("keydown",async e=>{e.key==="v"&&(console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted))})}onEnable(){this._net||(this._net=o_.create(this)),this._net.addEventListener(oc.StreamReceived,this.onReceiveStream),this._net.addEventListener(oc.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&(this.context.connection.isConnected?this.connect():this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom)),this.onEnabledChanged(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(oc.StreamReceived,this.onReceiveStream),this._net.removeEventListener(oc.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable(),this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.onEnabledChanged(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(this.context.connection.isConnected){if(!await BI())return console.error("Cannot connect to voice chat - microphone permissions not granted"),!1}else return console.error("Cannot connect to voice chat - not connected to server"),!1;return this._net.stopSendingStream(this._outputStream),Sh(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net.startSendingStream(this._outputStream),!0):(await BI()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):IR("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||st())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(){this._net.stopSendingStream(this._outputStream),Sh(this._outputStream),this._outputStream=null}setMuted(e){var t;const r=(t=this._outputStream)==null?void 0:t.getAudioTracks();if(r)for(const s of r)s.enabled=!e}get isMuted(){var e;if(this._outputStream===null)return!1;const t=(e=this._outputStream)==null?void 0:e.getAudioTracks();if(t){for(const r of t)if(!r.enabled)return!0}return!1}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,st()&&Di("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){return navigator.mediaDevices.getUserMedia?await navigator.mediaDevices.getUserMedia({audio:e??!0,video:!1}).catch(t=>(console.warn("VOIP failed getting audio stream",t),null)):(console.error("No getDisplayMedia support"),null)}}F8([w()],om.prototype,"autoConnect",2),F8([w()],om.prototype,"runInBackground",2);var ife=Object.defineProperty,nfe=Object.getOwnPropertyDescriptor,U8=(n,e,t,r)=>{for(var s=r>1?void 0:r?nfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ife(e,t,s),s};const rfe=te("debugmouth");class jA extends Be{constructor(){super(...arguments),d(this,"idle",[]),d(this,"talking",[]),d(this,"marker",null),d(this,"voip",null),d(this,"lastMouthChangeTime",0),d(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=ie.findObjectOfType(om,this.context),this.marker||(this.marker=ie.getComponentInParent(this.gameObject,Yr))},3e3)}update(){var e;if(!this.voip||this.context.time.frameCount%10!==0)return;let t=((e=this.marker)==null?void 0:e.connectionId)??null;if(!t){rfe&&(t=null);return}const r=this.voip.getFrequency(t)??0;this.updateLips(r)}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 t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(r=>r.visible=!1):this.talking.map(r=>r.visible=!1);for(let r=0;r<e.length;r++){const s=e[r];s&&(s.visible=r===t)}}}}U8([w(ye)],jA.prototype,"idle",2),U8([w(ye)],jA.prototype,"talking",2);class Tk extends Be{constructor(){super(...arguments),d(this,"voip",null),d(this,"marker",null),d(this,"_startPosition",null)}awake(){this.voip=ie.findObjectOfType(om,this.context),this.marker=ie.getComponentInParent(this.gameObject,Yr)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const r=t/100;this.gameObject.position.y=this._startPosition.y+r*.07}}var sfe=Object.defineProperty,ofe=Object.getOwnPropertyDescriptor,$S=(n,e,t,r)=>{for(var s=r>1?void 0:r?ofe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&sfe(e,t,s),s};class am extends Be{constructor(){super(...arguments),d(this,"eyes",[]),d(this,"lastBlinkTime",0),d(this,"blinkLength",0),d(this,"eyesOpen",!0),d(this,"state",null)}awake(){this.state=ie.getComponentInParent(this.gameObject,Go)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&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 e of this.eyes)e&&(e.visible=this.eyesOpen)}}}$S([w(ye)],am.prototype,"eyes",2),$S([w()],am.prototype,"lastBlinkTime",2),$S([w()],am.prototype,"blinkLength",2),$S([w()],am.prototype,"eyesOpen",2);var afe=Object.defineProperty,lfe=Object.getOwnPropertyDescriptor,Ik=(n,e,t,r)=>{for(var s=r>1?void 0:r?lfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&afe(e,t,s),s},Rk;const N8=(Rk=class extends Be{constructor(){super(...arguments),d(this,"head",null),d(this,"eyes",null),d(this,"target",null),d(this,"brain",null),d(this,"vec",new C),d(this,"currentTargetPoint",new C)}awake(){this.brain||(this.brain=ie.getComponentInParent(this.gameObject,NA)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=ie.addNewComponent(this.gameObject,NA)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const n=this.target;if(n&&this.head){const e=this.eyes;if(e){const t=Bt(n);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const r=Bt(this.head),s=this.vec.copy(this.currentTargetPoint).sub(r).normalize();if(s.length()<.1)return;const o=N8.forward;if(o.set(0,0,1),o.applyQuaternion(Mi(this.head)),o.dot(s)>.45)for(let a=0;a<e.length;a++)e[a].lookAt(this.currentTargetPoint)}}}},d(Rk,"forward",new C(0,0,1)),Rk);let e0=N8;Ik([w(ye)],e0.prototype,"head",2),Ik([w(ye)],e0.prototype,"eyes",2),Ik([w(ye)],e0.prototype,"target",2);const GA=te("debugavatar");class eC{constructor(e,t,r,s){d(this,"root"),d(this,"head"),d(this,"leftHand"),d(this,"rigthHand");var o;this.root=e,this.head=t,this.leftHand=r,this.rigthHand=s,(o=this.root)==null||o.traverse(a=>a.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Pk{constructor(){d(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let r=null;if(typeof t=="string"){if(r=await this.loadAvatar(e,t),!r){const o=new Ml;r=ie.instantiate(Df(t,e.scene),o)}}else r=t;if(!r)return null;const s=this.findAvatar(r);return s.isValid?(GA&&console.log("[Custom Avatar] valid config",t,GA?s:""),s):(console.warn("[Custom Avatar] config isn't valid",t,GA?s:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(GA&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const s=await fetch("./"+t);let o=null;if(s.ok){const l=await s.blob();l&&(o=await l.arrayBuffer())}if(!o&&(o=await dB(t,t,0,"no url here go away",!0),!o))return null;const a=await Ka().parseSync(e,o,null,0);return a?.scene??null}const r=new Ru;return u1(r,e),new Promise((s,o)=>{const a=this.avatarRegistryUrl+"/"+t;r.load(a,async l=>{await Ka().createBuiltinComponents(e,a,l,null,void 0),s(l.scene)},l=>{GA&&console.log("[Custom Avatar] "+l.loaded/l.total*100+"% loaded of "+l.total/1024+"kB")},l=>{console.error("[Custom Avatar] Error when loading: "+l),s(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let r=t;r.children.length==1&&(r=e.children[0]);let s=this.findAvatarPart(r,["head"]);const o=this.findAvatarPart(r,["left","hand"]),a=this.findAvatarPart(r,["right","hand"]);if(!s){s=t;const l=new C;new xi().setFromObject(s).getSize(l);const c=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+c+" meters! Should be < 0.3m"),c>.3&&s.scale.multiplyScalar(1/c*.3)}return new eC(t,s,o,a)}findAvatarPart(e,t){const r=e.name.toLowerCase();let s=!0;for(const o of t){if(!s)break;r.indexOf(o)===-1&&(s=!1)}if(s)return e;if(e.children)for(const o of e.children){const a=this.findAvatarPart(o,t);if(a)return a}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}var cfe=Object.defineProperty,hfe=Object.getOwnPropertyDescriptor,Bk=(n,e,t,r)=>{for(var s=r>1?void 0:r?hfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&cfe(e,t,s),s};class t0 extends Be{constructor(){super(...arguments),d(this,"length",1),d(this,"depthTest",!0),d(this,"isGizmo",!0),d(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Wy)return;this._axes||(this._axes=new Po(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)}}Bk([w()],t0.prototype,"length",2),Bk([w()],t0.prototype,"depthTest",2),Bk([w()],t0.prototype,"isGizmo",2);class kk extends Be{constructor(){super(...arguments),d(this,"from"),d(this,"to"),d(this,"hint"),d(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=Bt(this.to).clone(),t=Bt(this.from).clone(),r=e.distanceTo(t),s=e.clone();s.sub(t);const o=t.clone();o.add(e),o.multiplyScalar(.5);const a=Bt(this.hint).clone();a.sub(o);const l=new C;l.crossVectors(a,s),l.crossVectors(s,l),l.normalize();const c=r*.5,h=Math.max(this.desiredDistance,c),u=Math.sqrt(h*h-c*c),p=l.clone();p.multiplyScalar(u),p.add(o),lr(this.gameObject,p);const m=o.clone();m.sub(l),this.gameObject.lookAt(m)}}const Dk=te("debugusdzbehaviours");class tC{constructor(){d(this,"behaviours",[]),d(this,"behaviourComponents",[]),d(this,"behaviourComponentsCopy",[]),d(this,"audioClips",[]),d(this,"audioClipsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+Pd.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(r=>{ie.foreachComponent(r,s=>{var o;const a=s;if(typeof a.createBehaviours=="function"||typeof a.beforeCreateDocument=="function"||typeof a.afterCreateDocument=="function"||typeof a.afterSerialize=="function"){this.behaviourComponents.push(a);const l=(o=a.beforeCreateDocument)==null?void 0:o.call(a,this,e);l instanceof Promise&&t.push(l)}},!1)}),Dk&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,r){var s;for(const o of this.behaviourComponents)Dk&&console.log("onExportObject: createBehaviours",o),(s=o.createBehaviours)==null||s.call(o,this,t,r)}onAfterBuildDocument(e){for(const t of this.behaviourComponents)typeof t.afterCreateDocument=="function"&&t.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0}onAfterHierarchy(e,t){var r;if((r=this.behaviours)!=null&&r.length){t.beginBlock('def Scope "Behaviors"');for(const s of this.behaviours)s.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Dk&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:r}of this.audioClipsCopy){if(e.files[r])return;const s=await(await(await fetch(t)).blob()).arrayBuffer(),o=new Uint8Array(s);e.files[r]=o}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}var ufe=Object.defineProperty,dfe=Object.getOwnPropertyDescriptor,Ok=(n,e,t,r)=>{for(var s=r>1?void 0:r?dfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ufe(e,t,s),s},Lk;const z8=(Lk=class extends Xr{constructor(){super(...arguments),d(this,"threshold",new qe(.9)),d(this,"intensity",new qe(1)),d(this,"scatter",new qe(.3)),d(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=n=>n,this.intensity.valueProcessor=n=>n,this.scatter.valueProcessor=n=>n}onCreateEffect(){let n;if(this.selectiveBloom==null&&(this.selectiveBloom=z8.useSelectiveBloom),this.selectiveBloom){const e=n=new i6(this.context.scene,this.context.mainCamera,{blendFunction:jt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});e.inverted=!0}else n=new $P({blendFunction:jt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=e=>{n.intensity=e},this.threshold.onValueChanged=e=>{n.luminanceMaterial.threshold=Math.pow(e,2.2)},this.scatter.onValueChanged=e=>{n.luminancePass.enabled=!0,n.luminanceMaterial.smoothing=e,n.mipmapBlurPass&&(n.mipmapBlurPass.radius=ui.lerp(.1,.9,e))},n}},d(Lk,"useSelectiveBloom",!1),Lk);let lm=z8;Ok([w(qe)],lm.prototype,"threshold",2),Ok([w(qe)],lm.prototype,"intensity",2),Ok([w(qe)],lm.prototype,"scatter",2),Ra("Bloom",lm);var pfe=Object.defineProperty,mfe=Object.getOwnPropertyDescriptor,bo=(n,e,t,r)=>{for(var s=r>1?void 0:r?mfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&pfe(e,t,s),s};class Vo extends Be{constructor(){super(...arguments),d(this,"attachedRigidbody",null),d(this,"isTrigger",!1),d(this,"sharedMaterial"),d(this,"membership",[0]),d(this,"filter"),d(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(Oi))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Oi))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Oi))}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)}}bo([w(Oi)],Vo.prototype,"attachedRigidbody",2),bo([w()],Vo.prototype,"isTrigger",2),bo([w()],Vo.prototype,"sharedMaterial",2),bo([w()],Vo.prototype,"membership",2),bo([w()],Vo.prototype,"filter",2);class i0 extends Vo{constructor(){super(...arguments),d(this,"radius",.5),d(this,"center",new C(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this),Zx(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),PI(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}bo([Hr(),w()],i0.prototype,"radius",2),bo([w(C)],i0.prototype,"center",2);class n0 extends Vo{constructor(){super(...arguments),d(this,"size",new C(1,1,1)),d(this,"center",new C(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.size),Zx(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),PI(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}bo([Hr(),w(C)],n0.prototype,"size",2),bo([w(C)],n0.prototype,"center",2);class cm extends Vo{constructor(){super(...arguments),d(this,"sharedMesh"),d(this,"convex",!1)}onEnable(){var e,t,r;if(super.onEnable(),!this.context.physics.engine)return;(e=this.sharedMesh)!=null&&e.isMesh||this.gameObject instanceof me&&(this.sharedMesh=this.gameObject);const s=0;if((t=this.sharedMesh)!=null&&t.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex,Vi(this.gameObject)),fi.assignMeshLOD(this.sharedMesh,s).then(o=>{o&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=o,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex,Vi(this.gameObject)))});else{const o=this.sharedMesh;if(o!=null&&o.isGroup){console.warn(`MeshCollider mesh is a group "${((r=this.sharedMesh)==null?void 0:r.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 a=new Array;for(const l in o.children){const c=o.children[l];c.isMesh&&(this.context.physics.engine.addMeshCollider(this,c,this.convex,Vi(this.gameObject)),a.push(fi.assignMeshLOD(c,s)))}Promise.all(a).then(l=>{var c,h;if(l.some(p=>p)==!1)return;(c=this.context.physics.engine)==null||c.removeBody(this);const u=new me;for(const p of l)p&&this.activeAndEnabled&&(u.geometry=p,(h=this.context.physics.engine)==null||h.addMeshCollider(this,u,this.convex,Vi(this.gameObject)))})}}}}bo([w(me)],cm.prototype,"sharedMesh",2),bo([w()],cm.prototype,"convex",2);class Ch extends Vo{constructor(){super(...arguments),d(this,"center",new C(0,0,0)),d(this,"radius",.5),d(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.height,this.radius)}}bo([w(C)],Ch.prototype,"center",2),bo([w()],Ch.prototype,"radius",2),bo([w()],Ch.prototype,"height",2);var ffe=Object.defineProperty,gfe=Object.getOwnPropertyDescriptor,Fk=(n,e,t,r)=>{for(var s=r>1?void 0:r?gfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ffe(e,t,s),s};class hm extends Be{constructor(){super(...arguments),d(this,"objectBounds",!1),d(this,"color"),d(this,"isGizmo",!0),d(this,"_gizmoObject",null),d(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!Wy||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new xI(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=fB(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Hi.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var e;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}Fk([w()],hm.prototype,"objectBounds",2),Fk([w(xe)],hm.prototype,"color",2),Fk([w()],hm.prototype,"isGizmo",2);const vfe=te("gizmos"),yfe=te("debugboxhelper"),vl=class extends Be{constructor(){super(...arguments),d(this,"box",null),d(this,"_lastMatrixUpdateFrame",-1),d(this,"_helper",null),d(this,"_color",null)}isInBox(n,e){var t;if(!n)return;if(this.box||(this.box=new xi),n.type==="Mesh")vl.testBox.setFromObject(n);else if(n.type==="Group"){if(vl.testBox.makeEmpty(),n.children.length>0)for(let s=0;s<n.children.length;s++)n.children[s].type==="Mesh"&&vl.testBox.expandByObject(n)}else{const s=Bt(n,vl._position),o=Vi(n,vl._size);e!==void 0&&o.multiplyScalar(e),vl.testBox.setFromCenterAndSize(s,o)}this.updateBox();const r=(t=this.box)==null?void 0:t.intersectsBox(vl.testBox);return r&&yfe&&At.DrawWireBox3(vl.testBox,16711680,5),r}intersects(n){return n?this.updateBox(!1).intersectsBox(n):!1}updateBox(n=!1){if(this.box||(this.box=new xi),n||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const e=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const t=e,r=Bt(this.gameObject,vl._position,t),s=Vi(this.gameObject,vl._size);this.box.setFromCenterAndSize(r,s)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(n=null,e=!1){var t;if(!(!vfe&&!e)){if(this._helper){n&&((t=this._color)==null||t.set(n)),this.gameObject.add(this._helper);return}this._helper=fB(n),this.gameObject.add(this._helper)}}};let ac=vl;d(ac,"testBox",new xi),d(ac,"_position",new C),d(ac,"_size",new C(.01,.01,.01));class Afe extends qN{constructor(e,t={}){super(e),e._simpleState__activeStates=[],e._simpleState__normalStyles={},e._simpleState__states=t,e._simpleState__statesProperties={};for(const r in t)for(const s in t[r])e._simpleState__statesProperties[s]||(e._simpleState__statesProperties[s]=[]),e._simpleState__statesProperties[s].push(r);for(const r of e._components)e._simpleState__statesProperties[r.id]&&(e._simpleState__normalStyles[r.id]=r.inline?r.inline:r._value);e.__overridedSet=e.set,e.set=this.storeSet.bind(e),e.renderStates=this.renderStates.bind(e),e.setupState=this.setupState.bind(e),e.setState=this.setState.bind(e),e.activatePseudoState=this.activatePseudoState.bind(e),e.deactivatePseudoState=this.deactivatePseudoState.bind(e),e.togglePseudoState=this.togglePseudoState.bind(e)}act(){}attach(){}detach(){}setupState(e,t){this._simpleState__states[e]=t;const r=[];for(const s in t)this._simpleState__statesProperties[s]||(this._simpleState__statesProperties[s]=[],r.push(s)),this._simpleState__statesProperties[s].push(e);for(const s of this._components)r.indexOf(s.id)>-1&&(this._simpleState__normalStyles[s.id]=s.inline?s.inline:s._value)}renderStates(){let e={...this._simpleState__normalStyles};for(const t in this._simpleState__states)this._simpleState__activeStates.indexOf(t)>-1&&(e={...e,...this._simpleState__states[t]});this.set(e,!1)}storeSet(e,t=!0){if(t)for(const r in e)this._simpleState__statesProperties[r]&&(this._simpleState__normalStyles[r]=e[r]);this.__overridedSet(e)}activatePseudoState(e){this._simpleState__activeStates.indexOf(e)===-1&&(this._simpleState__activeStates.push(e),this.renderStates())}deactivatePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1&&(this._simpleState__activeStates.splice(t,1),this.renderStates())}togglePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1?this._simpleState__activeStates.splice(t,1):this._simpleState__activeStates.push(e),this.renderStates()}setState(e){Array.isArray(e)?this._simpleState__activeStates=e:this._simpleState__activeStates=[e],this.renderStates()}}var bfe=Object.defineProperty,_fe=Object.getOwnPropertyDescriptor,j8=(n,e,t,r)=>{for(var s=r>1?void 0:r?_fe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&bfe(e,t,s),s};class r0 extends Be{constructor(){super(...arguments),d(this,"effectColor"),d(this,"effectDistance")}}j8([w(Si)],r0.prototype,"effectColor",2),j8([w(Z)],r0.prototype,"effectDistance",2);var xfe=Object.defineProperty,wfe=Object.getOwnPropertyDescriptor,VA=(n,e,t,r)=>{for(var s=r>1?void 0:r?wfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&xfe(e,t,s),s};const Uk=te("debugui"),Nk=te("debuguilayout");class zk{constructor(){d(this,"width"),d(this,"height")}}class jk{constructor(){d(this,"x"),d(this,"y"),d(this,"width"),d(this,"height")}}const yl=new C,QA=new ve,iC=new Ce,G8=class extends Va{constructor(){super(...arguments),d(this,"_anchoredPosition"),d(this,"sizeDelta",new Z(100,100)),d(this,"pivot",new Z(.5,.5)),d(this,"anchorMin",new Z(0,0)),d(this,"anchorMax",new Z(1,1)),d(this,"minWidth"),d(this,"minHeight"),d(this,"lastMatrix"),d(this,"rectBlock"),d(this,"_transformNeedsUpdate",!1),d(this,"_initialPosition"),d(this,"_parentRectTransform"),d(this,"_lastUpdateFrame",-1),d(this,"_lastAnchoring"),d(this,"_createdBlocks",[]),d(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 Z),this._anchoredPosition}set anchoredPosition(n){this._anchoredPosition=n}get width(){let n=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const e=this._parentRectTransform.width,t=this.anchorMax.x-this.anchorMin.x;n=e*t,n+=this.sizeDelta.x}return this.minWidth!==void 0&&n<this.minWidth?this.minWidth:n}get height(){let n=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const e=this._parentRectTransform.height,t=this.anchorMax.y-this.anchorMin.y;n=e*t,n+=this.sizeDelta.y}return this.minHeight!==void 0&&n<this.minHeight?this.minHeight:n}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new Z),this.lastMatrix=new ve,this.rectBlock=new ye,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,Xg(this,"_anchoredPosition",()=>{this.markDirty()}),Xg(this,"sizeDelta",()=>{this.markDirty()}),Xg(this,"pivot",()=>{this.markDirty()}),Xg(this,"anchorMin",()=>{this.markDirty()}),Xg(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var n;super.onEnable(),this.rectBlock||(this.rectBlock=new ye),this.lastMatrix||(this.lastMatrix=new ve),this._lastAnchoring||(this._lastAnchoring=new Z),this._initialPosition||(this._initialPosition=new C),this._anchoredPosition||(this._anchoredPosition=new Z),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(n=this.canvas)==null||n.registerTransform(this)}onDisable(){var n;super.onDisable(),this.removeShadowComponent(),(n=this.canvas)==null||n.unregisterTransform(this)}onParentRectTransformChanged(n){this._transformNeedsUpdate||this.onApplyTransform(Nk?`${n.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(Nk&&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(n){var e;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=ie.getComponentInParent(this.gameObject.parent,G8):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,Nk&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+n),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,yl.set(0,0,0),this.applyPivot(yl),t.matrix.setPosition(yl.x,yl.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(iC.copy(this.gameObject.quaternion),iC.x*=-1,iC.z*=-1,QA.makeRotationFromQuaternion(iC),t.matrix.premultiply(QA)),yl.set(0,0,0),this.applyAnchoring(yl),(e=this.canvas)!=null&&e.screenspace?yl.z+=.1:yl.z+=.01,QA.identity(),QA.setPosition(yl.x,yl.y,yl.z),t.matrix.premultiply(QA),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const r=!0;for(const s of TS(this.gameObject,Va,r,1)){if(s===this||!s.activeAndEnabled)continue;const o=s;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}applyAnchoring(n){this._lastAnchoring||(this._lastAnchoring=new Z);const e=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=e.x,this.gameObject.position.y+=e.y,this._lastAnchoring.copy(this._anchoredPosition),n.x+=this._initialPosition.x-this.gameObject.position.x,n.y+=this._initialPosition.y-this.gameObject.position.y,n.z+=this._initialPosition.z-this.gameObject.position.z;const t=this._parentRectTransform;if(t){let r=0;const s=1-this.anchorMax.y-this.anchorMin.y;r-=t.height*.5*s,n.y+=r;let o=0;const a=1-this.anchorMax.x-this.anchorMin.x;o-=t.width*.5*a,n.x+=o}}applyPivot(n){if(this.pivot&&!this.isRoot()){const e=this.pivot.x-.5;n.x-=e*this.sizeDelta.x*this.gameObject.scale.x;const t=this.pivot.y-.5;n.y-=t*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const n={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(n),n}ensureValidSize(n,e=1e-4){return n.width<=0&&(n.width=e),n.height<=0&&(n.height=1e-4),n}createNewBlock(n){n={...this.getBasicOptions(),...n},Uk&&console.log(this.name,n);const e=new pR(n);return this._createdBlocks.push(e),e}createNewText(n){Uk&&console.log(n),n={...this.getBasicOptions(),...n},Uk&&console.log(this.name,n);const e=new fR(n);return this._createdTextBlocks.push(e),e}};let Ts=G8;VA([w(Z)],Ts.prototype,"anchoredPosition",1),VA([w(Z)],Ts.prototype,"sizeDelta",2),VA([w(Z)],Ts.prototype,"pivot",2),VA([w(Z)],Ts.prototype,"anchorMin",2),VA([w(Z)],Ts.prototype,"anchorMax",2);var Sfe=Object.defineProperty,Cfe=Object.getOwnPropertyDescriptor,V8=(n,e,t,r)=>{for(var s=r>1?void 0:r?Cfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Sfe(e,t,s),s};const nC={backgroundColor:new xe(1,1,1),backgroundOpacity:1,borderColor:new xe(1,1,1),borderOpacity:1};var Gk;const HA=(Gk=class extends Va{constructor(){super(...arguments),d(this,"_alphaFactor",1),d(this,"sRGBColor",new xe(1,0,1)),d(this,"raycastTarget",!0),d(this,"uiObject",null),d(this,"_color",null),d(this,"_rect",null),d(this,"_stateManager",null),d(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new Si(1,1,1,1)),this._color}set color(n){(!this._color||this._color.r!==n.r||this._color.g!==n.g||this._color.b!==n.b||this._color.alpha!==n.alpha)&&(this._color||(this._color=new Si(1,1,1,1)),this._color.copy(n),this.onColorChanged())}setAlphaFactor(n){this._alphaFactor=n,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),nC.backgroundColor=this.sRGBColor,nC.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(nC,this._alphaFactor),this.uiObject.set(nC),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=ie.getComponent(this.gameObject,Ts)),!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 n;(n=this.uiObject)==null||n.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(n){return super.__internalNewInstanceCreated(n),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone()),this}setState(n){this.makePanel(),this.uiObject&&(this.uiObject.setState(n),this==null||this.markDirty())}setupState(n){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new Afe(this.uiObject)),this.uiObject.setupState(n.state,n.attributes))}setOptions(n){this.makePanel(),this.uiObject&&this.uiObject.set(n)}awake(){super.awake(),this.makePanel(),Xg(this,"_color",()=>Qpe(this,this.onColorChanged))}onEnable(){var n;super.onEnable(),this.uiObject&&((n=this.rectTransform.shadowComponent)==null||n.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 n=.015,e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:n};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(n){}onCreate(n){this.uiObject=this.rectTransform.createNewBlock(n),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(n,e=1){var t;const r=(t=this.gameObject)==null?void 0:t.getComponent(r0);r&&(r.effectDistance&&(n.borderWidth=Math.max(Math.abs(r.effectDistance.x),Math.abs(r.effectDistance.y))),r.effectColor&&(n.borderColor=r.effectColor,n.borderOpacity=r.effectColor.alpha*e))}async setTexture(n){if(this.setOptions({backgroundOpacity:0}),n){if(HA.textureCache.has(n))n=HA.textureCache.get(n);else if(!n.isRenderTargetTexture){const e=n.clone();e.colorSpace=Ri,HA.textureCache.set(n,e),n=e}this.setOptions({backgroundImage:n,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),fi.assignTextureLOD(n,0).then(e=>{e instanceof zt&&(n&&HA.textureCache.set(n,e),this.setOptions({backgroundImage:e}),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)}},d(Gk,"textureCache",new Map),Gk);let um=HA;V8([w(Si)],um.prototype,"color",1),V8([w()],um.prototype,"raycastTarget",2);class WA extends um{constructor(){super(...arguments),d(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var Efe=Object.defineProperty,Mfe=Object.getOwnPropertyDescriptor,rC=(n,e,t,r)=>{for(var s=r>1?void 0:r?Mfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Efe(e,t,s),s};let Vk=class{constructor(){d(this,"texture",null),d(this,"rect")}};rC([w(zt)],Vk.prototype,"texture",2);let s0=class extends WA{constructor(){super(...arguments),d(this,"_sprite"),d(this,"pixelsPerUnitMultiplier",1)}set image(n){this.sprite||(this.sprite=new Vk),this.sprite.texture=n,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(n){this._sprite!==n&&(this._sprite=n,this.onAfterCreated())}isBuiltinSprite(){var n,e,t,r,s,o,a;const l=this.sprite;switch((n=l?.texture)==null?void 0:n.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((t=(e=l?.texture)==null?void 0:e.name)!=null&&t.length)&&((s=(r=l?.texture)==null?void 0:r.image)==null?void 0:s.width)===32&&((a=(o=l?.texture)==null?void 0:o.image)==null?void 0:a.height)===32}onBeforeCreate(n){var e,t;super.onBeforeCreate(n),this.isBuiltinSprite()&&(n.borderRadius=5/this.pixelsPerUnitMultiplier,((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name)==="Knob"&&(n.borderRadius=999))}onAfterCreated(){var n;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((n=this.sprite)==null?void 0:n.texture))}};rC([w(Vk)],s0.prototype,"sprite",1),rC([w()],s0.prototype,"pixelsPerUnitMultiplier",2);class sC extends WA{constructor(){super(...arguments),d(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))}}rC([w(zt)],sC.prototype,"mainTexture",1);var Tfe=Object.defineProperty,Ife=Object.getOwnPropertyDescriptor,Qo=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ife(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Tfe(e,t,s),s};const dm=te("debugbutton");class ad{constructor(){d(this,"colorMultiplier"),d(this,"disabledColor"),d(this,"fadeDuration"),d(this,"highlightedColor"),d(this,"normalColor"),d(this,"pressedColor"),d(this,"selectedColor")}}Qo([w()],ad.prototype,"colorMultiplier",2),Qo([w(Si)],ad.prototype,"disabledColor",2),Qo([w()],ad.prototype,"fadeDuration",2),Qo([w(Si)],ad.prototype,"highlightedColor",2),Qo([w(Si)],ad.prototype,"normalColor",2),Qo([w(Si)],ad.prototype,"pressedColor",2),Qo([w(Si)],ad.prototype,"selectedColor",2);class Rfe{constructor(){d(this,"disabledTrigger"),d(this,"highlightedTrigger"),d(this,"normalTrigger"),d(this,"pressedTrigger"),d(this,"selectedTrigger")}}class Eh extends Be{constructor(){super(...arguments),d(this,"onClick"),d(this,"_isHovered",0),d(this,"colors"),d(this,"transition"),d(this,"animationTriggers"),d(this,"animator"),d(this,"_interactable",!0),d(this,"_requestedAnimatorTrigger"),d(this,"_isInit",!1),d(this,"_image")}onPointerEnter(e){var t,r;const s=e.event.pointerType==="mouse"&&e.button===0;s&&(this._isHovered+=1),dm&&console.warn("Button Enter",s,this._isHovered,(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((r=this._image)==null||r.setState("hovered")),s&&this.context.input.setCursorPointer())}onPointerExit(){var e,t;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),dm&&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&&((t=this._image)==null||t.setState("normal")),this.context.input.setCursorNormal()))}onPointerDown(e){var t,r;dm&&console.log("Button Down",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((r=this._image)==null||r.setState("pressed")))}onPointerUp(e){var t,r;dm&&console.warn("Button Up",(t=this.animationTriggers)==null?void 0:t.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&&((r=this._image)==null||r.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===q1.Mouse)&&(dm&&(console.warn("Button Click",this.onClick),rn("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),dm))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),At.DrawLabel(t,"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(),dm&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable),this.gameObject.getComponentInParent(xA)||this.gameObject.addComponent(FS)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.setCursorNormal()}*setAnimatorTriggerAtEndOfFrame(e){var t;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((t=this.animator)==null||t.SetTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=ie.getComponent(this.gameObject,s0),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var t,r,s,o,a;e.setInteractable(this.interactable);const l=this.getFinalColor(e.color,(t=this.colors)==null?void 0:t.normalColor),c={state:"normal",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);const h=this.getFinalColor(e.color,(r=this.colors)==null?void 0:r.highlightedColor),u={state:"hovered",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(u);const p=this.getFinalColor(e.color,(s=this.colors)==null?void 0:s.pressedColor),m={state:"pressed",attributes:{backgroundColor:p,backgroundOpacity:p.alpha}};e.setupState(m);const f=this.getFinalColor(e.color,(o=this.colors)==null?void 0:o.selectedColor),g={state:"selected",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(g);const v=this.getFinalColor(e.color,(a=this.colors)==null?void 0:a.disabledColor),y={state:"disabled",attributes:{backgroundColor:v,backgroundOpacity:v.alpha}};e.setupState(y)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}Qo([w(Un)],Eh.prototype,"onClick",2),Qo([w(ad)],Eh.prototype,"colors",2),Qo([w()],Eh.prototype,"transition",2),Qo([w(Rfe)],Eh.prototype,"animationTriggers",2),Qo([w(Wr)],Eh.prototype,"animator",2),Qo([w()],Eh.prototype,"interactable",1);var Pfe=Object.defineProperty,Bfe=Object.getOwnPropertyDescriptor,Jn=(n,e,t,r)=>{for(var s=r>1?void 0:r?Bfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Pfe(e,t,s),s};const Q8=te("debuguilayout");class ld{constructor(){d(this,"left",0),d(this,"right",0),d(this,"top",0),d(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Jn([w()],ld.prototype,"left",2),Jn([w()],ld.prototype,"right",2),Jn([w()],ld.prototype,"top",2),Jn([w()],ld.prototype,"bottom",2);class Ho extends Be{constructor(){super(...arguments),d(this,"_rectTransform",null),d(this,"_needsUpdate",!1),d(this,"childAlignment",0),d(this,"reverseArrangement",!1),d(this,"spacing",0),d(this,"padding"),d(this,"minWidth",0),d(this,"minHeight",0),d(this,"flexibleHeight",0),d(this,"flexibleWidth",0),d(this,"preferredHeight",0),d(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&&(Q8&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){Q8&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ts);const e=this.gameObject.getComponentInParent(Jr);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Jr);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Jn([w()],Ho.prototype,"childAlignment",2),Jn([w()],Ho.prototype,"reverseArrangement",2),Jn([w()],Ho.prototype,"spacing",2),Jn([w(ld)],Ho.prototype,"padding",2),Jn([w()],Ho.prototype,"minWidth",2),Jn([w()],Ho.prototype,"minHeight",2),Jn([w()],Ho.prototype,"flexibleHeight",2),Jn([w()],Ho.prototype,"flexibleWidth",2),Jn([w()],Ho.prototype,"preferredHeight",2),Jn([w()],Ho.prototype,"preferredWidth",2);class cd extends Ho{constructor(){super(...arguments),d(this,"childControlHeight",!0),d(this,"childControlWidth",!0),d(this,"childForceExpandHeight",!1),d(this,"childForceExpandWidth",!1),d(this,"childScaleHeight",!1),d(this,"childScaleWidth",!1)}onCalculateLayout(e){var t;const r=this.primaryAxis,s=e.width;let o=s;const a=e.height;let l=a;o-=this.padding.horizontal,l-=this.padding.vertical,r==="x"?this.padding.horizontal:this.padding.vertical;const c=r==="x",h=c?"y":"x",u=c?this.childControlWidth:this.childControlHeight,p=c?this.childControlHeight:this.childControlWidth,m=c?this.childForceExpandWidth:this.childForceExpandHeight,f=c?this.childForceExpandHeight:this.childForceExpandWidth,g=c?l:o,v=c?s:a,y=.5*(c?this.childAlignment%3:Math.floor(this.childAlignment/3));let A=0;c?A+=this.padding.left:A+=this.padding.top;let _=0,b=0;for(let R=0;R<this.gameObject.children.length;R++){const D=this.gameObject.children[R],M=ie.getComponent(D,Ts);M!=null&&M.activeAndEnabled&&(b+=1,c?_+=M.width:_+=M.height)}let x=0;const E=this.spacing*(b-1);if(m||u){let R=0;c?R=o-=E:R=l-=E,b>0&&(x=R/b)}let I=0;I+=this.padding.left,I-=this.padding.right,y!==0&&(A=v-_,A*=y,A-=E*y,c?(A-=this.padding.right*y,A+=this.padding.left*(1-y),A<this.padding.left&&(A=this.padding.left)):(A-=this.padding.bottom*y,A+=this.padding.top*(1-y),A<this.padding.top&&(A=this.padding.top)));let T=1;for(let R=0;R<this.gameObject.children.length;R++){const D=this.gameObject.children[R],M=ie.getComponent(D,Ts);if(M!=null&&M.activeAndEnabled){(t=M.pivot)==null||t.set(.5,.5),M.anchorMin.set(0,1),M.anchorMax.set(0,1);const P=s*.5+I*.5;M.anchoredPosition.x!==P&&(M.anchoredPosition.x=P);const z=a*-.5;M.anchoredPosition.y!==z&&(M.anchoredPosition.y=z),f&&p&&M.sizeDelta[h]!==g&&(M.sizeDelta[h]=g),m&&u&&M.sizeDelta[r]!==x&&(M.sizeDelta[r]=x);const V=c?M.width:M.height,L=V*.5;if(A+=L,m){const O=x*T-x*.5;O>A&&(A=O-x*.5+V+this.padding.left,A-=L)}let H=A;r==="y"&&(H=-H),M.anchoredPosition[r]!==H&&(M.anchoredPosition[r]=H),A+=L,A+=this.spacing,T+=1}}}}Jn([w()],cd.prototype,"childControlHeight",2),Jn([w()],cd.prototype,"childControlWidth",2),Jn([w()],cd.prototype,"childForceExpandHeight",2),Jn([w()],cd.prototype,"childForceExpandWidth",2),Jn([w()],cd.prototype,"childScaleHeight",2),Jn([w()],cd.prototype,"childScaleWidth",2);class Qk extends cd{get primaryAxis(){return"y"}}class Hk extends cd{get primaryAxis(){return"x"}}class Wk extends Ho{onCalculateLayout(){}}var kfe=Object.defineProperty,Dfe=Object.getOwnPropertyDescriptor,lc=(n,e,t,r)=>{for(var s=r>1?void 0:r?Dfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&kfe(e,t,s),s},H8=(n=>(n[n.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",n[n.ScreenSpaceCamera=1]="ScreenSpaceCamera",n[n.WorldSpace=2]="WorldSpace",n[n.Undefined=-1]="Undefined",n))(H8||{});const Xk=te("debuguilayout"),W8=class extends _A{constructor(){super(...arguments),d(this,"_renderOnTop"),d(this,"_depthWrite",!1),d(this,"_doubleSided",!0),d(this,"_castShadows",!1),d(this,"_receiveShadows",!1),d(this,"_renderMode",-1),d(this,"_rootCanvas"),d(this,"_scaleFactor",1),d(this,"worldCamera"),d(this,"planeDistance",-1),d(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),d(this,"previousParent",null),d(this,"_lastMatrixWorld",null),d(this,"_rectTransforms",[]),d(this,"_layoutGroups",new Map),d(this,"_receivers",[]),d(this,"onBeforeRenderRoutine",()=>{var n,e,t,r;if(this.previousParent=this.gameObject.parent,((n=this.context.xr)!=null&&n.isVR||(e=this.context.xr)!=null&&e.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(t=this.shadowComponent)==null||t.updateMatrixWorld(!0),(r=this.shadowComponent)==null||r.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),Ta.ensureUpdateMeshUI(JN,this.context))}),d(this,"onAfterRenderRoutine",()=>{var n,e,t,r,s;if(((n=this.context.xr)!=null&&n.isVR||(e=this.context.xr)!=null&&e.isPassThrough)&&this.screenspace){(t=this.previousParent)==null||t.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const l=this.context.mainCamera;l?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const o=this.context.renderer.autoClear,a=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(r=this.shadowComponent)==null||r.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),Ta.ensureUpdateMeshUI(JN,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=o,this.context.renderer.autoClearColor=a,this.previousParent.add(this.gameObject)}(s=this._lastMatrixWorld)==null||s.copy(this.gameObject.matrixWorld)}),d(this,"_updateRenderSettingsRoutine"),d(this,"_activeRenderMode",-1),d(this,"_lastWidth",-1),d(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(n){n!==this._renderOnTop&&(this._renderOnTop=n,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(n){this._depthWrite!==n&&(this._depthWrite=n,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(n){this._doubleSided!==n&&(this._doubleSided=n,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(n){this._castShadows!==n&&(this._castShadows=n,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(n){this._receiveShadows!==n&&(this._receiveShadows=n,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(n){this._renderMode!==n&&(this._renderMode=n,this.onRenderSettingsChanged())}set rootCanvas(n){this._rootCanvas instanceof W8||(this._rootCanvas=n)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(n){this._scaleFactor=n}awake(){var n;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,Xk&&console.log("Canvas.Awake()",((n=this.previousParent)==null?void 0:n.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ve,this.onUpdateRenderMode(),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 n=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);n!==-1&&this.context.pre_render_callbacks.splice(n,1);const e=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);e!==-1&&this.context.post_render_callbacks.splice(e,1)}registerTransform(n){this._rectTransforms.push(n)}unregisterTransform(n){const e=this._rectTransforms.indexOf(n);e!==-1&&this._rectTransforms.splice(e,1)}registerLayoutGroup(n){const e=n.gameObject;this._layoutGroups.set(e,n)}unregisterLayoutGroup(n){const e=n.gameObject;this._layoutGroups.delete(e)}registerEventReceiver(n){this._receivers.push(n)}unregisterEventReceiver(n){const e=this._receivers.indexOf(n);e!==-1&&this._receivers.splice(e,1)}async onEnterXR(n){this.screenspace?(n.xr.isVR||n.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await NU(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(n){this.screenspace&&(n.xr.isVR||n.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var n;for(const e of this._receivers)(n=e.onBeforeCanvasRender)==null||n.call(e,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ve);const n=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);Xk&&n&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const e=!1;for(const t of this._rectTransforms){n&&t.markDirty();let r=this._layoutGroups.get(t.gameObject);t.isDirty&&!r&&(r=t.gameObject.getComponentInParent(Ho)),(t.isDirty||r!=null&&r.isDirty)&&(Xk&&!e&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),r?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Hi.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),NS(this.shadowComponent,this);for(const n of ie.getComponentsInChildren(this.gameObject,Va))NS(n.shadowComponent,this)}}onUpdateRenderMode(n=!1){if(!n&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let e=this.context.mainCameraComponent,t=10;switch(e&&e.nearClipPlane>0&&e.farClipPlane>0&&(t=it.lerp(e.nearClipPlane,e.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(e=this.worldCamera),this.planeDistance>0&&(t=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!e)return;const r=t+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-r,this.gameObject.quaternion.identity();const s=this.gameObject.getComponent(Ts);let o=!1;s.sizeDelta.x!==this.context.domWidth&&(o=!0),s.sizeDelta.y!==this.context.domHeight&&(o=!0);const a=e.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(r);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,o&&(s.sizeDelta.x=this.context.domWidth,s.sizeDelta.y=this.context.domHeight,s?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let Jr=W8;lc([w()],Jr.prototype,"renderOnTop",1),lc([w()],Jr.prototype,"depthWrite",1),lc([w()],Jr.prototype,"doubleSided",1),lc([w()],Jr.prototype,"castShadows",1),lc([w()],Jr.prototype,"receiveShadows",1),lc([w()],Jr.prototype,"renderMode",1),lc([w(Jr)],Jr.prototype,"rootCanvas",1),lc([w()],Jr.prototype,"scaleFactor",1),lc([w(Li)],Jr.prototype,"worldCamera",2),lc([w()],Jr.prototype,"planeDistance",2);var Ofe=Object.defineProperty,Lfe=Object.getOwnPropertyDescriptor,qk=(n,e,t,r)=>{for(var s=r>1?void 0:r?Lfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Ofe(e,t,s),s};class hd extends Be{constructor(){super(...arguments),d(this,"_alpha",1),d(this,"interactable",!0),d(this,"blocksRaycasts",!0),d(this,"_isDirty",!1),d(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(),Hi.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of ie.getComponentsInChildren(this.gameObject,Va,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}qk([w()],hd.prototype,"alpha",1),qk([w()],hd.prototype,"interactable",2),qk([w()],hd.prototype,"blocksRaycasts",2);var Ffe=Object.defineProperty,Ufe=Object.getOwnPropertyDescriptor,mn=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ufe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Ffe(e,t,s),s};const X8=te("debugusdzbehaviours");function XA(n){n&&(n.getComponentInParent(xA)||(st()&&console.warn("Create Raycaster on "+n.name+" because no raycaster was found in the hierarchy"),n.addNewComponent(No)))}class pm extends Be{constructor(){super(...arguments),d(this,"object"),d(this,"target"),d(this,"duration",1),d(this,"relativeMotion",!1),d(this,"coroutine",null),d(this,"targetPos",new C),d(this,"targetRot",new Ce),d(this,"targetScale",new C)}start(){XA(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=Bt(this.object).clone(),t=Bt(this.target).clone(),r=Mi(this.object).clone(),s=Mi(this.target).clone(),o=Vi(this.object).clone(),a=Vi(this.target).clone(),l=e.distanceTo(t),c=r.angleTo(s),h=o.distanceTo(a);if(l<.01&&c<.01&&h<.01){lr(this.object,t),ca(this.object,s),Uf(this.object,a),this.coroutine=null;return}let u=0,p=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),p=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(e,t,p),this.targetRot.slerpQuaternions(r,s,p),this.targetScale.lerpVectors(o,a,p),lr(this.object,this.targetPos),ca(this.object,this.targetRot),Uf(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),r=this.object.scale.clone(),s=this.target.position.clone(),o=this.target.quaternion.clone(),a=this.target.scale.clone();s.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(s),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(a);let l=0,c=0;for(;l<1;)l+=this.context.time.deltaTime/this.duration,l>1&&(l=1),c=l<.5?4*l*l*l:1-Math.pow(-2*l+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,c),this.object.quaternion.slerpQuaternions(t,this.targetRot,c),this.object.scale.lerpVectors(r,this.targetScale,c),yield;this.coroutine=null}beforeCreateDocument(e){var t;if(this.target&&this.object&&this.gameObject){const r=new Ar("Move to "+((t=this.target)==null?void 0:t.name),br.tapTrigger(this.gameObject),gi.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(r)}}}mn([w(ye)],pm.prototype,"object",2),mn([w(ye)],pm.prototype,"target",2),mn([w()],pm.prototype,"duration",2),mn([w()],pm.prototype,"relativeMotion",2);var oC;const cc=(oC=class extends Be{constructor(){super(...arguments),d(this,"materialToSwitch"),d(this,"variantMaterial"),d(this,"fadeDuration",0),d(this,"_objectsWithThisMaterial",null),d(this,"selfModel"),d(this,"targetModels")}start(){var n;this._objectsWithThisMaterial=this.objectsWithThisMaterial,XA(this.gameObject),st()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((n=this.materialToSwitch)==null?void 0:n.name)+'"')}onPointerEnter(n){this.context.input.setCursorPointer()}onPointerExit(n){this.context.input.setCursorNormal()}onPointerClick(n){if(n.use(),!!this.variantMaterial)for(let e=0;e<this.objectsWithThisMaterial.length;e++){const t=this.objectsWithThisMaterial[e];t.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(n=>{if(n instanceof me)if(Array.isArray(n.material)){for(const e of n.material)if(e===this.materialToSwitch){this.objectsWithThisMaterial.push(n);break}}else n.material===this.materialToSwitch?this.objectsWithThisMaterial.push(n):p6(n.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(n)}),this._objectsWithThisMaterial)}async beforeCreateDocument(n,e){this.targetModels=[],cc._materialTriggersPerId={},cc.variantSwitchIndex=0,this.materialToSwitch&&await fi.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await fi.assignTextureLOD(this.variantMaterial,0)}createBehaviours(n,e,t){this.objectsWithThisMaterial.find(r=>r.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(cc._materialTriggersPerId[this.materialToSwitch.uuid]||(cc._materialTriggersPerId[this.materialToSwitch.uuid]=[]),cc._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(n,e){if(!this.materialToSwitch)return;const t=cc._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const r={};for(const s of t){const o=s.createVariants();o&&o.length>0&&(r[s.selfModel.uuid]=o)}for(const s of t){const o=[];for(const a in r)a!==s.selfModel.uuid&&o.push(...r[a]);s.createAndAttachBehaviors(n,r[s.selfModel.uuid],o)}}delete cc._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(n,e,t){const r=[],s=[],o=Math.max(0,this.fadeDuration);s.push(gi.fadeAction([...this.targetModels,...t],o,!1)),r.push(gi.fadeAction(e,o,!1)),s.push(gi.fadeAction(e,o,!0)),n.addBehavior(new Ar("Select_"+this.selfModel.name,br.tapTrigger(this.selfModel),gi.parallel(...s))),n.addBehavior(new Ar("StartHidden_"+this.selfModel.name,br.sceneStartTrigger(),gi.parallel(...r)))}static getMaterialName(n){return ul(n.name||"Material")+"_"+n.id}createVariants(){if(!this.variantMaterial)return null;const n=[];for(const e of this.targetModels){const t=e.clone();t.name+="_Variant_"+cc.variantSwitchIndex+++"_"+cc.getMaterialName(this.variantMaterial),t.displayName=t.displayName+": Variant with material "+this.variantMaterial.name,t.material=this.variantMaterial,t.geometry=e.geometry,t.matrix=e.matrix,(!e.parent||!e.parent.isEmpty())&&Ws.createEmptyParent(e),e.parent&&e.parent.add(t),n.push(t)}return n}},d(oC,"_materialTriggersPerId",{}),d(oC,"variantSwitchIndex",0),oC);let o0=cc;mn([w(Ot)],o0.prototype,"materialToSwitch",2),mn([w(Ot)],o0.prototype,"variantMaterial",2),mn([w()],o0.prototype,"fadeDuration",2);var a0;const fn=(a0=class extends Be{constructor(){super(...arguments),d(this,"target"),d(this,"toggleOnClick",!1),d(this,"targetState",!0),d(this,"hideSelf",!0),d(this,"selfModel"),d(this,"selfModelClone"),d(this,"targetModel"),d(this,"toggleModel"),d(this,"stateBeforeCreatingDocument",!1),d(this,"targetStateBeforeCreatingDocument",!1)}start(){XA(this.gameObject)}onPointerClick(n){n.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(n,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e,this.selfModelClone=e.clone())}beforeCreateDocument(){this.target&&(this.gameObject[fn.wasVisible]===void 0&&(this.gameObject[fn.wasVisible]=this.gameObject.activeSelf),this.target[fn.wasVisible]===void 0&&(this.target[fn.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[fn.wasVisible],this.targetStateBeforeCreatingDocument=this.target[fn.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(n,e){if(!this.target)return;this.targetModel=e.document.findById(this.target.uuid);const t=this.selfModel;if(this.selfModel&&this.targetModel){let r=this.selfModel,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&e5.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[fn.toggleClone]){const l=this.selfModelClone.clone();l.matrix.identity(),l.name+="_toggle"+fn.clonedToggleIndex++,t.add(l),this.gameObject[fn.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[fn.toggleClone];if(!this.gameObject[fn.reverseToggleClone]){const l=this.selfModelClone.clone();l.matrix.identity(),l.name+="_toggleReverse"+fn.clonedToggleIndex++,t.add(l),this.gameObject[fn.reverseToggleClone]=l}this.toggleModel=this.gameObject[fn.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,t.geometry),r=a,t.geometry=null,t.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(gi.fadeAction(r,0,!1)),a.push(gi.fadeAction(this.toggleModel,0,!0)),a.push(gi.fadeAction(this.targetModel,0,s)),n.addBehavior(new Ar("Toggle_"+r.name+"_toggleTo"+(s?"On":"Off"),br.tapTrigger(r),gi.parallel(...a)));const l=[];l.push(gi.fadeAction(this.toggleModel,0,!1)),l.push(gi.fadeAction(r,0,!0)),l.push(gi.fadeAction(this.targetModel,0,!s)),n.addBehavior(new Ar("Toggle_"+r.name+"_toggleTo"+(s?"Off":"On"),br.tapTrigger(this.toggleModel),gi.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(gi.fadeAction(r,0,!1)),a.push(gi.fadeAction(this.targetModel,0,s)),n.addBehavior(new Ar("Toggle_"+r.name+"_toggleTo"+(s?"On":"Off"),br.tapTrigger(r),gi.parallel(...a)))}const o=new Array;this.targetStateBeforeCreatingDocument||o.push(this.targetModel),this.stateBeforeCreatingDocument||o.push(t),this.toggleModel&&o.push(this.toggleModel),n.addBehavior(new Ar("HideOnStart_"+this.gameObject.name,br.sceneStartTrigger(),gi.fadeAction(o,0,!1)))}}afterSerialize(n,e){this.gameObject[fn.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[fn.wasVisible],delete this.gameObject[fn.wasVisible]),this.target&&this.target[fn.wasVisible]!==void 0&&(this.target.visible=this.target[fn.wasVisible],delete this.target[fn.wasVisible]),delete this.gameObject[fn.toggleClone],delete this.gameObject[fn.reverseToggleClone]}},d(a0,"clonedToggleIndex",0),d(a0,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),d(a0,"toggleClone",Symbol("clone for toggling")),d(a0,"reverseToggleClone",Symbol("clone for reverse toggling")),a0);let mm=fn;mn([w(ye)],mm.prototype,"target",2),mn([w()],mm.prototype,"toggleOnClick",2),mn([w()],mm.prototype,"targetState",2),mn([w()],mm.prototype,"hideSelf",2);class Yk extends Be{constructor(){super(...arguments),d(this,"wasVisible",!1)}start(){ie.setActive(this.gameObject,!1)}createBehaviours(e,t,r){t.uuid===this.gameObject.uuid&&(this.wasVisible||e.addBehavior(new Ar("HideOnStart_"+this.gameObject.name,br.sceneStartTrigger(),gi.fadeAction(t,0,!1))))}beforeCreateDocument(){this.wasVisible=ie.isActiveSelf(this.gameObject)}}class l0 extends Be{constructor(){super(...arguments),d(this,"target"),d(this,"duration",.5),d(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(e,t,r){if(this.target&&t.uuid===this.gameObject.uuid){const s=new Ar("emphasize "+this.name,br.tapTrigger(this.gameObject),gi.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(s)}}afterCreateDocument(e,t){}}mn([w()],l0.prototype,"target",2),mn([w()],l0.prototype,"duration",2),mn([w()],l0.prototype,"motionType",2);class ud extends Be{constructor(){super(...arguments),d(this,"target"),d(this,"clip",""),d(this,"toggleOnClick",!1),d(this,"trigger","tap")}start(){XA(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addNewComponent(Mn);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){var t;e.use(),!(!((t=this.target)!=null&&t.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,t,r){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const s=this.clip?this.clip:this.target?this.target.clip:void 0;if(!s||typeof s!="string")return;const o=this.target?this.target.gameObject:this.gameObject;Pd.getName(s);const a=this.target?this.target.volume:1,l=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let c=!1;this.gameObject.traverse(m=>{m instanceof me&&m.visible&&(c=!0)}),c=!0;const h=e.addAudioClip(s);let u=gi.playAudioAction(o,h,"play",a,l);this.target&&this.target.loop&&(u=gi.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(c&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const m=new Ar("playAudio"+p,br.tapTrigger(t),u);e.addBehavior(m)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(c&&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 m=new Ar("playAudioOnStart"+p,br.sceneStartTrigger(),u);e.addBehavior(m)}}}}mn([w(Mn)],ud.prototype,"target",2),mn([w(URL)],ud.prototype,"clip",2),mn([w()],ud.prototype,"toggleOnClick",2);var aC;const hc=(aC=class extends Be{constructor(){super(...arguments),d(this,"animator"),d(this,"stateName"),d(this,"trigger","tap"),d(this,"animation"),d(this,"selfModel"),d(this,"stateAnimationModel"),d(this,"animationSequence",new Array),d(this,"animationLoopAfterSequence",new Array)}get target(){var n,e;return((n=this.animator)==null?void 0:n.gameObject)||((e=this.animation)==null?void 0:e.gameObject)}start(){XA(this.gameObject)}onPointerClick(n){var e;n.use(),this.target&&this.stateName&&((e=this.animator)==null||e.play(this.stateName,0,0,.1))}createBehaviours(n,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}afterSerialize(){if(hc.rootsWithExclusivePlayback.size>1){const n='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.';st()&&Di(n),console.warn(n,...hc.rootsWithExclusivePlayback)}hc.animationActions=[],hc.rootsWithExclusivePlayback=new Set}afterCreateDocument(n,e){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const t=e.document,r=e.extensions.find(a=>a instanceof BA);if(!r)return;const s=r.getClipCount(this.target)>1;s&&(st()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+r.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),hc.rootsWithExclusivePlayback.add(this.target));const o=this.name?this.name:"";t.traverse(a=>{var l,c;if(a.uuid===((l=this.target)==null?void 0:l.uuid)){const h=hc.getActionForSequences(a,this.animationSequence,this.animationLoopAfterSequence),u=new Ar(this.trigger+"_"+o+"_toPlayAnimation_"+this.stateName+"_on_"+((c=this.target)==null?void 0:c.name),this.trigger=="tap"?br.tapTrigger(this.selfModel):br.sceneStartTrigger(),h);s&&u.makeExclusive(!0),n.addBehavior(u)}})}static getActionForSequences(n,e,t){const r=(o,a)=>{let l=hc.animationActions.find(c=>c.affectedObjects==o&&c.start==a.start&&c.duration==a.duration&&c.animationSpeed==a.speed);return l||(l=gi.startAnimationAction(o,a.start,a.duration,a.speed),hc.animationActions.push(l)),l},s=gi.sequence();if(e&&e.length>0)for(const o of e)s.addAction(r(n,o));if(t&&t.length>0){const o=s.actions.length==0?s:gi.sequence();for(const a of t)o.addAction(r(n,a));o.makeLooping(),s!==o&&s.addAction(o)}return s}static getAndRegisterAnimationSequences(n,e,t){var r,s,o,a,l;if(!e)return;const c=e.getComponent(Wr),h=e.getComponent(Es);if(!c&&!h)return;if(c&&!t)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+c.name+" on "+e.name);let u=[],p=[];if(h){const A=n.registerAnimation(e,h.clip);return A&&(h.loop?p.push(A):u.push(A)),{animationSequence:u,animationLoopAfterSequence:p}}const m=c?.runtimeAnimatorController;let f=m?.findState(t),g=[],v=[];if(m&&f){const A=new Array;A.push(f);let _=!1;for(;A.length<100;){if(!f||f===null||!f.transitions||f.transitions.length===0){(r=f.motion)!=null&&r.isLooping&&(_=!0);break}const b=f.transitions.find(E=>E.conditions.length===0),x=b?m.getState(b.destinationState,0):null;if(x&&A.includes(x)){f=x,_=!0;break}else if(b){if(f=x,!f)break;A.push(f)}else{_=((s=f.motion)==null?void 0:s.isLooping)??!1;break}}if(_&&f){const b=A.indexOf(f);g=A.slice(0,b),v=A.slice(b),X8&&console.log("found loop from "+t,"states until loop",g,"states looping",v)}else g=A,v=[],X8&&console.log("found no loop from "+t,"states",g)}if(g.length===1&&(!((o=g[0].motion)!=null&&o.clip)||((l=(a=g[0].motion)==null?void 0:a.clip.tracks)==null?void 0:l.length)===0)){u=new Array;const A=n.registerAnimation(e,null);A&&u.push(A);return}if(g=g.filter(A=>{var _,b,x;return((_=A.motion)==null?void 0:_.clip)&&((x=(b=A.motion)==null?void 0:b.clip.tracks)==null?void 0:x.length)>0}),v=v.filter(A=>{var _,b,x;return((_=A.motion)==null?void 0:_.clip)&&((x=(b=A.motion)==null?void 0:b.clip.tracks)==null?void 0:x.length)>0}),g.length===0&&v.length===0){console.warn("No clips found for state "+t+" on "+c?.name+", can't export animation data");return}const y=(A,_)=>{if(!e)return;const b=n.registerAnimation(e,A.motion.clip??null);b?(b.speed=A.speed,_.push(b)):console.warn("Couldn't register animation for state "+A.name+" on "+c?.name)};if(g.length>0){u=new Array;for(const A of g)y(A,u)}if(v.length>0){p=new Array;for(const A of v)y(A,p)}return{animationSequence:u,animationLoopAfterSequence:p}}createAnimation(n,e,t){if(!this.target||!this.animator&&!this.animation)return;const r=hc.getAndRegisterAnimationSequences(n,this.target,this.stateName);r&&(this.animationSequence=r.animationSequence,this.animationLoopAfterSequence=r.animationLoopAfterSequence,this.stateAnimationModel=e)}},d(aC,"animationActions",[]),d(aC,"rootsWithExclusivePlayback",new Set),aC);let fm=hc;mn([w(Wr)],fm.prototype,"animator",2),mn([w()],fm.prototype,"stateName",2);class c0 extends Be{constructor(){super(...arguments),d(this,"target")}getType(){}getDuration(){}}mn([w(ye)],c0.prototype,"target",2);class qA extends Be{constructor(){super(...arguments),d(this,"target")}}mn([w(c0)],qA.prototype,"target",2);class YA extends c0{constructor(){super(...arguments),d(this,"type",1),d(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}mn([w()],YA.prototype,"type",2),mn([w()],YA.prototype,"duration",2);class Jk extends qA{}var Nfe=Object.defineProperty,zfe=Object.getOwnPropertyDescriptor,Mh=(n,e,t,r)=>{for(var s=r>1?void 0:r?zfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Nfe(e,t,s),s};const q8=te("debugcharactercontroller");class gm extends Be{constructor(){super(...arguments),d(this,"center",new C(0,0,0)),d(this,"radius",.5),d(this,"height",2),d(this,"_rigidbody",null),d(this,"_activeGroundCollisions"),d(this,"_contactVelocity",new C)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Oi),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(Oi)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Ch);t||(t=this.gameObject.addNewComponent(Ch)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const r=new C(0,0,1),s=new C(1,0,0),o=new C(0,1,0),a=this.gameObject.getWorldDirection(new C);a.y=0;const l=s.dot(a)<0?-1:1,c=r.angleTo(a)*l;this.gameObject.setRotationFromAxisAngle(o,c),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(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),q8&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),q8&&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 t of this._activeGroundCollisions){const r=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(t.collider);r&&(this._contactVelocity.x+=r.x,this._contactVelocity.y+=r.y,this._contactVelocity.z+=r.z)}return this._contactVelocity}}Mh([w(C)],gm.prototype,"center",2),Mh([w()],gm.prototype,"radius",2),Mh([w()],gm.prototype,"height",2);class Th extends Be{constructor(){super(...arguments),d(this,"controller"),d(this,"movementSpeed",2),d(this,"rotationSpeed",2),d(this,"jumpForce",1),d(this,"doubleJumpForce",2),d(this,"animator"),d(this,"lookForward",!0),d(this,"lookInput",new Z(0,0)),d(this,"moveInput",new Z(0,0)),d(this,"jumpInput",!1),d(this,"_currentSpeed",new C(0,0,0)),d(this,"_currentAngularSpeed",new C(0,0,0)),d(this,"_temp",new C(0,0,0)),d(this,"_jumpCount",0),d(this,"_currentRotation"),d(this,"_raycastOptions",new ml)}awake(){this._currentRotation=new Ce}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,t,r){var s,o,a,l,c,h,u,p,m,f,g;if((s=this.controller)!=null&&s.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((o=this.animator)==null||o.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(a=this.animator)==null||a.setBool("running",e.length()>.01),(c=this.animator)==null||c.setBool("jumping",((l=this.controller)==null?void 0:l.isGrounded)===!0&&r),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+=it.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const v=this.context.mainCameraComponent.forward;v.y=0,v.normalize(),this._currentRotation.setFromUnitVectors(new C(0,0,1),v),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&&r&&this.jumpForce>0){let v=(h=this.controller)==null?void 0:h.isGrounded;if(this.doubleJumpForce>0&&!((u=this.controller)!=null&&u.isGrounded)&&this._jumpCount===1&&(v=!0,(p=this.animator)==null||p.setBool("doubleJump",!0)),v){this._jumpCount+=1;const y=this.controller.rigidbody,A=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;y.applyImpulse(new C(0,1,0).multiplyScalar(A))}}if(this.controller){const v=(m=this.controller)==null?void 0:m.rigidbody.getVelocity().y;if(v<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new co),this._raycastOptions.ray.origin.copy(Bt(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const y=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const A=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(y),(A.length&&A[0].distance>2||v<-10)&&((f=this.animator)==null||f.setBool("falling",!0))}else(g=this.animator)==null||g.setBool("falling",!1)}}}Mh([w(gm)],Th.prototype,"controller",2),Mh([w()],Th.prototype,"movementSpeed",2),Mh([w()],Th.prototype,"rotationSpeed",2),Mh([w()],Th.prototype,"jumpForce",2),Mh([w()],Th.prototype,"doubleJumpForce",2),Mh([w(Wr)],Th.prototype,"animator",2);var jfe=Object.defineProperty,Gfe=Object.getOwnPropertyDescriptor,Vfe=(n,e,t,r)=>{for(var s=r>1?void 0:r?Gfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&jfe(e,t,s),s};class JA extends Xr{constructor(){super(...arguments),d(this,"intensity",new qe(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new J5;return e.offset=new Z(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}Vfe([w(qe)],JA.prototype,"intensity",2),Ra("ChromaticAberration",JA);var Qfe=Object.defineProperty,Hfe=Object.getOwnPropertyDescriptor,Y8=(n,e,t,r)=>{for(var s=r>1?void 0:r?Hfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Qfe(e,t,s),s};const J8=te("debugpost");var lC=(n=>(n[n.None=0]="None",n[n.Neutral=1]="Neutral",n[n.ACES=2]="ACES",n[n.AgX=3]="AgX",n[n.KhronosNeutral=4]="KhronosNeutral",n))(lC||{});function Kk(n){switch(n){case 0:return Xm;case 1:return tv;case 2:return iv;case 3:return qm;case 4:return Ud;default:return Ud}}function Wfe(n){switch(n){case Xm:return 0;case iv:return 2;case qm:return 3;case Ud:return 1;case tv:return 1;default:return 0}}function K8(n){switch(n){case Xm:return _r.LINEAR;case iv:return _r.ACES_FILMIC;case qm:return _r.AGX;case Ud:return _r.NEUTRAL;case tv:return _r.REINHARD;default:return _r.LINEAR}}const Z8=class extends Xr{constructor(){super(...arguments),d(this,"mode",new qe(void 0)),d(this,"exposure",new qe(1))}get typeName(){return"ToneMapping"}setMode(n){const e=lC[n];return e===void 0?(console.error("Invalid ToneMapping mode",n),this):(this.mode.value=e,this)}get isToneMapping(){return!0}onEffectEnabled(){const n=E8(this);n&&super.onEffectEnabled(n)}onCreateEffect(){if(this.postprocessingContext)for(const t of this.postprocessingContext.components){if(t===this)break;if(t!=this&&t instanceof Z8){console.warn("Multiple tonemapping effects found in the same postprocessing stack: Please check your scene setup.",{activeEffect:t,ignoredEffect:this});return}}if(this.mode.isInitialized==!1){const t=Wfe(this.context.renderer.toneMapping);this.mode.initialize(t)}const n=Kk(this.mode.value),e=new U1({mode:K8(n)});return this.mode.onValueChanged=t=>{const r=Kk(t);e.mode=K8(r),J8&&console.log("ToneMapping mode changed to",lC[t],r,e.mode)},J8&&console.log("Use ToneMapping",lC[this.mode.value],n,e.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),this.exposure.onValueChanged=t=>{this.context.renderer.toneMappingExposure=t},e}onBeforeRender(){this.mode.overrideState&&(this.context.renderer.toneMapping=Kk(this.mode.value)),this.exposure.overrideState&&(this.context.renderer.toneMappingExposure=this.exposure.value)}};let dd=Z8;Y8([w(qe)],dd.prototype,"mode",2),Y8([w(qe)],dd.prototype,"exposure",2),Ra("Tonemapping",dd);var Xfe=Object.defineProperty,qfe=Object.getOwnPropertyDescriptor,cC=(n,e,t,r)=>{for(var s=r>1?void 0:r?qfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Xfe(e,t,s),s};class pd extends Xr{constructor(){super(...arguments),d(this,"postExposure",new qe(0)),d(this,"contrast",new qe(0)),d(this,"hueShift",new qe(0)),d(this,"saturation",new qe(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(e=Math.pow(2,e),e),this.contrast.valueProcessor=e=>{let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>Math.PI*e/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>e<0?e/100:e/(100*Math.PI),this.saturation.defaultValue=0}onCreateEffect(){var e,t;const r=[];this.context.renderer.toneMapping!==Ls&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=Ls);let s=(e=this.postprocessingContext)==null?void 0:e.components.find(l=>l instanceof dd);s||(s=new dd,(t=this.postprocessingContext)==null||t.components.push(s)),this.postExposure.onValueChanged=l=>{this.postExposure.overrideState&&(s.exposure.value=l)};const o=new Y5;this.contrast.onValueChanged=l=>o.contrast=l;const a=new e6;return r.push(o),r.push(a),this.hueShift.onValueChanged=l=>a.hue=l,this.saturation.onValueChanged=l=>a.saturation=l,r}}cC([w(qe)],pd.prototype,"postExposure",2),cC([w(qe)],pd.prototype,"contrast",2),cC([w(qe)],pd.prototype,"hueShift",2),cC([w(qe)],pd.prototype,"saturation",2),Ra("ColorAdjustments",pd);const Yfe=(Math.sqrt(5)-1)/4,Kr=(5-Math.sqrt(5))/20,hC=n=>Math.floor(n)|0,uC=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);function Jfe(n=Math.random){const e=Kfe(n),t=new Float64Array(e).map(a=>uC[a%32*4]),r=new Float64Array(e).map(a=>uC[a%32*4+1]),s=new Float64Array(e).map(a=>uC[a%32*4+2]),o=new Float64Array(e).map(a=>uC[a%32*4+3]);return function(a,l,c,h){let u,p,m,f,g;const v=(a+l+c+h)*Yfe,y=hC(a+v),A=hC(l+v),_=hC(c+v),b=hC(h+v),x=(y+A+_+b)*Kr,E=y-x,I=A-x,T=_-x,R=b-x,D=a-E,M=l-I,P=c-T,z=h-R;let V=0,L=0,H=0,O=0;D>M?V++:L++,D>P?V++:H++,D>z?V++:O++,M>P?L++:H++,M>z?L++:O++,P>z?H++:O++;const F=V>=3?1:0,G=L>=3?1:0,J=H>=3?1:0,K=O>=3?1:0,oe=V>=2?1:0,we=L>=2?1:0,De=H>=2?1:0,se=O>=2?1:0,be=V>=1?1:0,Ie=L>=1?1:0,Je=H>=1?1:0,$e=O>=1?1:0,Oe=D-F+Kr,lt=M-G+Kr,fe=P-J+Kr,X=z-K+Kr,ze=D-oe+2*Kr,Te=M-we+2*Kr,Me=P-De+2*Kr,Qe=z-se+2*Kr,Ae=D-be+3*Kr,et=M-Ie+3*Kr,ct=P-Je+3*Kr,Tt=z-$e+3*Kr,Q=D-1+4*Kr,k=M-1+4*Kr,he=P-1+4*Kr,Ee=z-1+4*Kr,Le=y&255,Pe=A&255,vt=_&255,ht=b&255;let je=.6-D*D-M*M-P*P-z*z;if(je<0)u=0;else{const Fe=Le+e[Pe+e[vt+e[ht]]];je*=je,u=je*je*(t[Fe]*D+r[Fe]*M+s[Fe]*P+o[Fe]*z)}let Ve=.6-Oe*Oe-lt*lt-fe*fe-X*X;if(Ve<0)p=0;else{const Fe=Le+F+e[Pe+G+e[vt+J+e[ht+K]]];Ve*=Ve,p=Ve*Ve*(t[Fe]*Oe+r[Fe]*lt+s[Fe]*fe+o[Fe]*X)}let St=.6-ze*ze-Te*Te-Me*Me-Qe*Qe;if(St<0)m=0;else{const Fe=Le+oe+e[Pe+we+e[vt+De+e[ht+se]]];St*=St,m=St*St*(t[Fe]*ze+r[Fe]*Te+s[Fe]*Me+o[Fe]*Qe)}let Ue=.6-Ae*Ae-et*et-ct*ct-Tt*Tt;if(Ue<0)f=0;else{const Fe=Le+be+e[Pe+Ie+e[vt+Je+e[ht+$e]]];Ue*=Ue,f=Ue*Ue*(t[Fe]*Ae+r[Fe]*et+s[Fe]*ct+o[Fe]*Tt)}let qt=.6-Q*Q-k*k-he*he-Ee*Ee;if(qt<0)g=0;else{const Fe=Le+1+e[Pe+1+e[vt+1+e[ht+1]]];qt*=qt,g=qt*qt*(t[Fe]*Q+r[Fe]*k+s[Fe]*he+o[Fe]*Ee)}return 27*(u+p+m+f+g)}}function Kfe(n){const e=new Uint8Array(512);for(let t=0;t<512/2;t++)e[t]=t;for(let t=0;t<512/2-1;t++){const r=t+~~(n()*(256-t)),s=e[t];e[t]=e[r],e[r]=s}for(let t=256;t<512;t++)e[t]=e[t-256];return e}const Zk=te("debugstencil");function Zfe(n,e){return(n&1<<e.layer)!=0}const $fe=Symbol("stencils"),h0=class{constructor(n,e){d(this,"parser"),d(this,"source"),this.parser=n,this.source=e}get name(){return"NEEDLE_render_objects"}static applyStencil(n){if(!n)return;const e=n.sourceId;if(Zk&&console.log(e,h0.stencils),!e)return;const t=h0.stencils[e];if(t)for(let r=t.length-1;r>=0;r--){const s=t[r];if(Zfe(s.layer,n)){Zk&&console.log(s),setTimeout(()=>{js()&&CS(n.gameObject)&&(Di("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",n))},500);for(let o=0;o<n.sharedMaterials.length;o++){let a=n.sharedMaterials[o];a&&(a=a.clone(),a[$fe]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=s.value,a.stencilFunc=s.compareFunc,a.stencilZPass=s.passOp,a.stencilFail=s.failOp,a.stencilZFail=s.zFailOp,n.sharedMaterials[o]=a)}n.gameObject.renderOrder=s.event*1e3+s.index*50;break}}}afterRoot(n){const e=this.parser.json.extensions;if(e){const t=e[tge];if(t){Zk&&console.log(t);const r=t.stencil;if(r&&Array.isArray(r))for(const s of r){const o={...s};o.compareFunc=ege(o.compareFunc),o.passOp=eD(o.passOp),o.failOp=eD(o.failOp),o.zFailOp=eD(o.zFailOp),h0.stencils[this.source]||(h0.stencils[this.source]=[]),h0.stencils[this.source].push(o)}}}return null}};let $k=h0;d($k,"stencils",{});function eD(n){switch(n){case 0:return Kh;case 1:return jL;case 2:return GL;case 3:return VL;case 4:return QL;case 6:return HL;case 7:return WL;case 5:return XL}return 0}function ege(n){switch(n){case 1:return YM;case 2:return qL;case 3:return YL;case 4:return JL;case 5:return KL;case 6:return ZL;case 7:return $L;case 8:return B_}return YM}const tge="NEEDLE_render_objects";var ige=Object.defineProperty,nge=Object.getOwnPropertyDescriptor,$8=(n,e,t,r)=>{for(var s=r>1?void 0:r?nge(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ige(e,t,s),s};const KA=te("debugreflectionprobe"),eQ=te("noreflectionprobe"),rge=Symbol("reflectionProbeKey"),sge=Symbol("original material");var dC;const Ih=(dC=class extends Be{constructor(){var n;super(),d(this,"_texture"),d(this,"center"),d(this,"size"),d(this,"_boxHelper"),Ih._probes.has(this.context)||Ih._probes.set(this.context,[]),(n=Ih._probes.get(this.context))==null||n.push(this)}static get(n,e,t,r){if(!n||n.isObject3D!==!0||eQ)return null;const s=Ih._probes.get(e);if(s){for(const o of s)if(o.__didAwake||o.__internalAwake(),o.enabled){if(r){if(o.gameObject===r)return o}else if(o.isInBox(n,void 0))return KA&&console.log("Found reflection probe",n.name,o.name),o}}return KA&&console.debug("Did not find reflection probe",n.name,t,n),null}set texture(n){if(n&&!(n instanceof zt)){console.error("ReflectionProbe.texture must be a Texture",n);return}this._texture=n,n&&(n.mapping=so,n.colorSpace=ft,n.needsUpdate=!0)}get texture(){return this._texture}isInBox(n,e){var t;return(t=this._boxHelper)==null?void 0:t.isInBox(n,e)}awake(){this._boxHelper=this.gameObject.addNewComponent(ac),this._boxHelper.updateBox(!0),KA&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=so,this.texture.colorSpace=ft,this.texture.needsUpdate=!0)}onDestroy(){const n=Ih._probes.get(this.context);if(n){const e=n.indexOf(this);e>=0&&n.splice(e,1)}}onSet(n){var e;if(eQ||!this.enabled||((e=n.sharedMaterials)==null?void 0:e.length)<=0||!this.texture)return;let t=Ih._rendererMaterialsCache.get(n);t||(t=[],Ih._rendererMaterialsCache.set(n,t));for(let r=0;r<n.sharedMaterials.length;r++){const s=n.sharedMaterials[r];if(!s||s.envMap===void 0||s instanceof $t)continue;let o=t[r];const a=s===o?.copy,l=!o||o.material.uuid!==s.uuid||o.copy.version!==s.version;if(!a&&l){if(KA){let u="";o?o.material!==s?u="reference changed; cached instance?: "+a:o.copy.version!==s.version&&(u="version changed"):u="not cached",console.warn("Cloning material",s.name,s.version,"Reason:",u,`
5738
+ `))}for(const V of P){const L=o.get(V);L&&z.set(V,L)}return z},f=function(P){const z=m(P),V=c(z);return h(z,V,P)};const g=s.skinnedMesh.skeleton,v=new Array,y=[],A=[];for(const P of g.bones)if(P.parent.type!=="Bone"){y.push(P);const z=g.boneInverses[g.bones.indexOf(P)];v.push({bone:P,inverse:z}),A.push(P.uuid)}for(;A.length<g.bones.length;)for(const P of y){const z=P.children;for(const V of z)if(A.indexOf(V.uuid)===-1&&g.bones.indexOf(V)!==-1){y.push(V);const L=g.boneInverses[g.bones.indexOf(V)];v.push({bone:V,inverse:L}),A.push(V.uuid)}}for(const P of $j(g.bones))v.push({bone:P,inverse:P.matrixWorld.clone().invert()});const _=v[0].bone.parent;_||console.error("No bone parent found for skinned mesh during USDZ export",s.skinnedMesh),v.sort((P,z)=>xg(P.bone,_)>xg(z.bone,_)?1:-1);const b=t.quickLookCompatible,x=[],E=[],I=[],T=[];for(const{bone:P}of v){if(b){const z=P.scale;z.x==0&&(z.x=1e-5),z.y==0&&(z.y=1e-5),z.z==0&&(z.z=1e-5),x.push(new ve().compose(P.position,P.quaternion,P.scale))}else x.push(P.matrix.clone());E.push(P.position),I.push(P.quaternion),T.push(P.scale)}const R=v.map(P=>'"'+xg(P.bone,_)+'"').join(", "),D=v.map(P=>wg(P.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${D}]`),e.appendLine(`uniform token[] joints = [${R}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${x.map(P=>wg(P)).join(", ")}]`),e.appendLine(`matrix4d xformOp:transform = ${wg(new ve)}`),e.appendLine('uniform token[] xformOpOrder = ["xformOp:transform"]');const M=f(v.map(P=>P.bone));if(ic){let P=1e7,z=0;for(const V of((r=M.position)==null?void 0:r.keys())??[])P=Math.min(P,V),z=Math.max(z,V);console.log("Time samples",P,z,M)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${R}]`),e.appendLine(`quatf[] rotations = [${p(I)}]`),M&&M.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const P=l(M.quaternion);for(const z of P)e.appendLine(z);e.closeBlock()}if(e.appendLine(`half3[] scales = [${u(T)}]`),M&&M.scale){e.beginBlock("half3[] scales.timeSamples = {","");const P=a(M.scale);for(const z of P)e.appendLine(z);e.closeBlock()}if(e.appendLine(`float3[] translations = [${u(E)}]`),M&&M.position){e.beginBlock("float3[] translations.timeSamples = {","");const P=a(M.position);for(const z of P)e.appendLine(z);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){var r;if(!this.model)return;const s=this.dict.get(this.object);if(s)for(let p=0;p<s.length;p++)s[p]===void 0&&(s[p]=new Tr(null,this.object,null));this.skinnedMeshExport(e,t);const o=this.object,a=this.dict.get(o);if(!a||o.isSkinnedMesh)return;_k&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=new ve;e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;const c=new Array;let h=0;for(let p=0;p<a.length;p++){if(c.push(h),a[p]===void 0){console.error("Got an undefined transform data, this is likely a bug.",o,a);continue}h+=a[p].getDuration()+Tr.animationDurationPadding}const u=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});for(let p=0;p<a.length;p++){const m=a[p];if(!m)continue;const f=c[p];{const g=m.getSortedTimesArray();if(!g||g.length===0){console.error("got an animated object but no time values?",o,m);continue}{const v=((r=m.clip)==null?void 0:r.name)??"rest",y=m.getDuration();ic&&console.log("Write .timeSamples:",v,f,y,a),e.appendLine("# "+v+": start="+u.format(f*m.frameRate)+", length="+u.format(y*m.frameRate)+", frames="+m.getFrames())}for(const{time:v,translation:y,rotation:A,scale:_}of m.getValues(g)){l.compose(y,A,_);const b=`${u.format((f+v)*m.frameRate)}: ${wg(l)},`;e.appendLine(b)}}}e.indent--,e.appendLine("}")}}const fme=te("debugpost");let xk=null;function gme(n){xk=n}function EV(n){let e=n.gameObject;for(;e;){for(const t of TS(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function vme(n){let e=EV(n);if(!e)if(xk){fme&&console.warn("Adding postprocessing manager to the scene.");const t=n.scene;e=gl(t,xk)}else st()&&console.warn("No post processing manager found");return e}var yme=Object.defineProperty,Ame=Object.getOwnPropertyDescriptor,MV=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ame(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&yme(e,t,s),s};const bme=te("debugpost");class qe{constructor(e){d(this,"isVolumeParameter",!0),d(this,"_isInitialized",!1),d(this,"_active",!0),d(this,"_value"),d(this,"_valueRaw"),d(this,"_defaultValue"),d(this,"valueProcessor"),d(this,"onValueChanged"),e!==void 0&&this.initialize(e)}get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const r=this._value;bme&&typeof r=="number"&&typeof e=="number"&&(r?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,r,this)}testIfValueChanged(e){return this._valueRaw!==e}}MV([w()],qe.prototype,"overrideState",1),MV([w()],qe.prototype,"value",1);class _me extends wa{constructor(){super([qe])}onSerialize(e,t){}onDeserialize(e,t){const r=t.target,s=t.path;let o;if(r&&s&&(o=r[s]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new qe),typeof e=="object"&&"value"in e){const a=e.value;o.initialize(a),o.overrideState=e.overrideState}else o.value=e;return o}}new _me;var xme=Object.defineProperty,wme=Object.getOwnPropertyDescriptor,Sme=(n,e,t,r)=>{for(var s=r>1?void 0:r?wme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&xme(e,t,s),s};const Cme=te("debugpost");class Xr extends Be{constructor(e=void 0){if(super(),d(this,"active",!0),d(this,"_manager",null),d(this,"_result"),d(this,"_postprocessingContext",null),e)for(const t of Object.keys(e)){const r=e[t],s=this[t];s instanceof qe?s.initialize(r):s!==void 0&&(this[t]=r)}}get isPostProcessingEffect(){return!0}onEnable(){this.onEffectEnabled(),this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){var e;(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){var t;e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=vme(this)),(t=this._manager)==null||t.addEffect(this)}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var t;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(t=this.onCreateEffect)==null?void 0:t.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Cme&&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 t of e){const r=this[t];r instanceof qe&&r.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof qe){const r=e.value;return this[t].value=r,!0}}}Sme([w()],Xr.prototype,"active",2);var Eme=Object.defineProperty,Mme=Object.getOwnPropertyDescriptor,Tme=(n,e,t,r)=>{for(var s=r>1?void 0:r?Mme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Eme(e,t,s),s};const Ime=te("debugpost"),wk={};function Ra(n,e){wk[n]=e}function Rme(n){return n.__type in wk?wk[n.__type]:(Ime&&n.__type&&console.warn("Unknown postprocessing type",n.__type,n),Xr)}class kA{constructor(){d(this,"components",[])}init(){var e;(e=this.components)==null||e.forEach(t=>t.init())}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}Tme([Eg([n=>Rme(n),Xr])],kA.prototype,"components",2);var Pme=Object.defineProperty,Bme=Object.getOwnPropertyDescriptor,kme=(n,e,t,r)=>{for(var s=r>1?void 0:r?Bme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Pme(e,t,s),s};class DA extends Xr{constructor(){super(...arguments),d(this,"preset",new qe(Wp.HIGH))}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new s6({preset:Wp.HIGH,edgeDetectionMode:eB.DEPTH});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}kme([w(qe)],DA.prototype,"preset",2),Ra("Antialiasing",DA);const Dme=te("debugusdz");class Pd{constructor(){d(this,"files",new Array)}static getName(e){var t;const r=e.split(".").pop();let s=(t=e.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:t.replace(".","_");return s||(s="Audio_"+Math.random().toString(36).substring(2,15)),ul(s)+"."+r}get extensionName(){return"Audio"}onExportObject(e,t,r){const s=ie.getComponents(e,Mn);if(s.length)for(const o of s){if(!o.clip||typeof o.clip!="string"||!o.playOnAwake)continue;const a=o.clip.split("/").pop()||"Audio",l=Pd.getName(o.clip),c=ul(l);if(!this.files.some(h=>h.path===o.clip)){this.files.push({path:o.clip,name:l});const h=l.toLowerCase();r.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+o.clip+" from "+o.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}r.quickLookCompatible||t.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 = "${o.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${o.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${o.volume}`),h.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const r="audio/"+t.name;if(e.files[r]){Dme&&console.warn("Audio file with name "+r+" already exists in the context. Skipping.");continue}const s=await(await(await fetch(t.path)).blob()).arrayBuffer(),o=new Uint8Array(s);e.files[r]=o}}}const TV=Symbol("customVisibilityFlag");function sd(n,e){n.layers[TV]=e}const IV=Symbol("DidPatchLayers");function Ome(){const n=ds.prototype;if(n[IV])return;n[IV]=!0;const e=n.test;n.test=function(t){return this[TV]===!1?!1:e.call(this,t)}}Ome();const sm=te("debugautosync"),Sk=Symbol("syncerId");class Lme{constructor(){d(this,"_syncers",{})}getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new Fme(e);return t[Sk]=e.guid,this._syncers[t[Sk]]=t,t}removeSyncer(e){delete this._syncers[e[Sk]]}}const Ck=new Lme;class Fme{constructor(e){d(this,"comp"),d(this,"hasChanges",!1),d(this,"changedProperties",{}),d(this,"data",{}),d(this,"_isReceiving",!1),d(this,"_isInit",!1),d(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const t=this.comp.context.connection;if(!t||!t.isConnected||!t.isInRoom){for(const r in this.changedProperties)delete this.changedProperties[r];return}for(const r in this.data)delete this.data[r];this.data.guid=this.comp.guid;for(const r in this.changedProperties){const s=this.changedProperties[r];delete this.changedProperties[r],this.data[r]=s}t.send(this.networkingKey,this.data,dl.Queued)}),d(this,"onHandleReceiving",t=>{if(sm&&console.log("RECEIVE",this.comp.name,this.comp.guid,t),!this._isInit||!this.comp)return;const r=t.guid;if(!(r&&r!==this.comp.guid)){sm&&console.log("RECEIVED",this.comp.name,this.comp.guid,t);try{this._isReceiving=!0;for(const s in t){if(s==="guid")continue;const o=t[s];this.comp[s]=o,sm&&console.log("SET",s,o)}}catch(s){console.error(s)}finally{this._isReceiving=!1}}}),this.comp=e}get networkingKey(){return this.comp.guid}init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}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(e,t){this._isReceiving||(sm&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}}function Ume(n,e){let t=e!==n;return!t&&n&&e&&(Array.isArray(n)&&Array.isArray(e)||typeof n=="object"&&typeof e=="object")&&(t=!0),t}const OA=Symbol("AutoSyncHandler");function Nme(n){if(n[OA])return n[OA];const e=Ck.getOrCreateSyncer(n);return e?.init(n),n[OA]=e,e}function zme(n){const e=n[OA];e&&(Ck.removeSyncer(e),e.destroy(),delete n[OA])}const Ek=function(n){return function(e,t){var r;let s="";typeof t=="string"?s=t:s=t.name;let o=null,a;typeof n=="string"?a=e[n]:typeof n=="function"&&(a=n);const l=e,c=l.__internalAwake;if(typeof c!="function"){(sm||st())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((r=e?.constructor)==null?void 0:r.name)+'" is not supported',e);return}sm&&console.log(s);const h=Symbol(s);l.__internalAwake=function(){if(this[h]!==void 0)return;this[h]=this[s],o=Ck.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,s);if(p?.set===void 0){let m=!1;Object.defineProperty(this,s,{set:function(f){var g;const v=this[h];if(this[h]=f,m){st()&&console.warn("Recursive call detected",s);return}m=!0;try{const y=Ume(f,v);sm&&console.log("SyncField assignment",s,"changed?",y,f),y&&a?.call(this,f,v)!==!1&&((g=Nme(this))==null||g.notifyChanged(s,f))}finally{m=!1}},get:function(){return this[h]},configurable:!0,enumerable:!0})}o?.init(this),c.call(this)};const u=l.__internalDestroy;l.__internalDestroy=function(){zme(this),u.call(this)}}};var jme=Object.defineProperty,Gme=Object.getOwnPropertyDescriptor,KS=(n,e,t,r)=>{for(var s=r>1?void 0:r?Gme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&jme(e,t,s),s};const jo=te("debugplayersync");class Kg extends Be{constructor(){super(...arguments),d(this,"autoSync",!0),d(this,"asset"),d(this,"onPlayerSpawned"),d(this,"_localInstance"),d(this,"onJoinedRoom",()=>{jo&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),d(this,"destroyInstance",()=>{var e;(e=this._localInstance)==null||e.then(t=>{jo&&console.log("PlayerSync.destroyInstance",t),hA(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new Un)}onEnable(){this.context.connection.beginListen(Vt.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Vt.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.LeftRoom,this.destroyInstance)}async getInstance(){var e,t,r,s,o,a;if(this._localInstance)return this._localInstance;if(jo&&console.log("PlayerSync.createInstance",(e=this.asset)==null?void 0:e.uri),!((t=this.asset)!=null&&t.asset)&&!((r=this.asset)!=null&&r.uri))return console.error('PlayerSync: can not create an instance because "asset" is not set!'),null;this._localInstance=(s=this.asset)==null?void 0:s.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const l=await this._localInstance;if(l){const c=ie.getComponentsInChildren(l,Pa);if(c!=null&&c.length){for(const h of c)h.owner=this.context.connection.connectionId;(o=this.onPlayerSpawned)==null||o.invoke(l)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((a=this.asset)==null?void 0:a.uri)+"</strong>: please make sure the asset has a PlayerState component!"),ie.destroySynced(l)}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 t=Pa.all.length-1;t>=0;t--){const r=Pa.all[t];(!r.owner||!this.context.connection.userIsInRoom(r.owner))&&r.doDestroy()}})}}KS([w()],Kg.prototype,"autoSync",2),KS([w(ti)],Kg.prototype,"asset",2),KS([w(Un)],Kg.prototype,"onPlayerSpawned",2);var RV=(n=>(n.OwnerChanged="ownerChanged",n))(RV||{}),LA;const qr=(LA=class extends Be{constructor(){super(...arguments),d(this,"onOwnerChangeEvent",new Un),d(this,"onFirstOwnerChangeEvent",new Un),d(this,"hasOwner",!1),d(this,"owner"),d(this,"dontDestroy",!1),d(this,"onUserLeftRoom",n=>{if(n.userId===this.owner){jo&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return qr._all}static get local(){return qr._local}static getFor(n){if(n instanceof ye)return ie.getComponentInParent(n,qr);if(n instanceof Be)return ie.getComponentInParent(n.gameObject,qr)}static isLocalPlayer(n){const e=qr.getFor(n);return e?.isLocalPlayer??!1}static addEventListener(n,e){return this._callbacks[n]||(this._callbacks[n]=[]),this._callbacks[n].push(e),e}static removeEventListener(n,e){if(!this._callbacks[n])return;const t=this._callbacks[n].indexOf(e);t>=0&&this._callbacks[n].splice(t,1)}static dispatchEvent(n,e){if(this._callbacks[n])for(const t of this._callbacks[n])t(e)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(n,e){var t,r;jo&&console.log("PlayerSync.onOwnerChange",this,"newOwner",n,"oldOwner",e);const s=qr._local.indexOf(this);s>=0&&qr._local.splice(s,1);const o={playerState:this,oldValue:e,newValue:n};if(this.hasOwner||(this.hasOwner=!0,(t=this.onFirstOwnerChangeEvent)==null||t.invoke(o)),(r=this.onOwnerChangeEvent)==null||r.invoke(o),this.owner===this.context.connection.connectionId){qr._local.push(this);const l=new CustomEvent("local-owner-changed",{detail:o});this.dispatchEvent(l)}const a=new CustomEvent("owner-changed",{detail:o});this.dispatchEvent(a),qr.dispatchEvent("ownerChanged",a)}awake(){qr.all.push(this),jo&&console.log("Registered new PlayerState",this.guid,qr.all.length-1,qr.all),this.context.connection.beginListen(Vt.UserLeftRoom,this.onUserLeftRoom)}async start(){jo&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Ll(300),this.context.connection.userIsInRoom(this.owner)==!1&&(jo&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(jo&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?jo&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(jo&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):jo&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){jo&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),hA(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(this.context.connection.stopListen(Vt.UserLeftRoom,this.onUserLeftRoom),qr.all.splice(qr.all.indexOf(this),1),this.isLocalPlayer){const n=qr._local.indexOf(this);n>=0&&qr._local.splice(n,1)}}},d(LA,"_all",[]),d(LA,"_local",[]),d(LA,"_callbacks",{}),LA);let Pa=qr;KS([Ek(Pa.prototype.onOwnerChange)],Pa.prototype,"owner",2);const Vme=te("debugavatar"),nc=class extends Be{constructor(){super(...arguments),d(this,"connectionId"),d(this,"avatar")}static getAvatar(n){return n>=0&&n<nc.instances.length?nc.instances[n]:null}static onAvatarMarkerCreated(n){return nc._onNewAvatarMarkerAdded.push(n),n}static onAvatarMarkerDestroyed(n){return nc._onAvatarMarkerDestroyed.push(n),n}awake(){nc.instances.push(this),Vme&&console.log(this);for(const n of nc._onNewAvatarMarkerAdded)n({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){nc.instances.splice(nc.instances.indexOf(this),1);for(const n of nc._onAvatarMarkerDestroyed)n({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let Yr=nc;d(Yr,"instances",[]),d(Yr,"_onNewAvatarMarkerAdded",[]),d(Yr,"_onAvatarMarkerDestroyed",[]);var Qme=Object.defineProperty,Hme=Object.getOwnPropertyDescriptor,Wme=(n,e,t,r)=>{for(var s=r>1?void 0:r?Hme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Qme(e,t,s),s};const Zg=te("debugxrflags"),PV=te("disablexrflags");PV&&console.warn("XRFlags are disabled");var rc=(n=>(n[n.Never=0]="Never",n[n.Browser=1]="Browser",n[n.AR=2]="AR",n[n.VR=4]="VR",n[n.FirstPerson=8]="FirstPerson",n[n.ThirdPerson=16]="ThirdPerson",n[n.All=4294967295]="All",n))(rc||{});const BV=class{constructor(){d(this,"Mask",17)}Has(n){return(this.Mask&n)!==0}Set(n){Zg&&console.warn("Set XR flag state to",n),this.Mask=n,Go.Apply()}Enable(n){this.Mask|=n,Go.Apply()}Disable(n){this.Mask&=~n,Go.Apply()}Toggle(n){this.Mask^=n,Go.Apply()}EnableAll(){this.Mask=-1,Go.Apply()}DisableAll(){this.Mask=0,Go.Apply()}};let eo=BV;d(eo,"Global",new BV);var FA;const wh=(FA=class extends Be{constructor(){super(...arguments),d(this,"visibleIn")}static Apply(){for(const n of this.registry)n.UpdateVisible(eo.Global)}awake(){wh.registry.push(this)}onEnable(){wh.firstApply?this.UpdateVisible(eo.Global):(wh.firstApply=!0,wh.Apply())}onDestroy(){const n=wh.registry.indexOf(this);n>=0&&wh.registry.splice(n,1)}get isOn(){return this.gameObject.visible}UpdateVisible(n=null){if(PV)return;let e;const t=n;if(t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),Zg&&console.log(t),wh.buffer.Mask=t,n=wh.buffer),n instanceof eo?(Zg&&console.warn(this.name,"use passed in mask",n.Mask,this.visibleIn),e=n.Has(this.visibleIn)):(Zg&&console.log(this.name,"use global mask"),eo.Global.Has(this.visibleIn)),e!==void 0)if(e)Zg&&console.log(this.name,"is visible",this.gameObject.uuid),ie.setActive(this.gameObject,!0);else{if(Zg&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},d(FA,"registry",[]),d(FA,"firstApply"),d(FA,"buffer",new eo),FA);let Go=wh;Wme([w()],Go.prototype,"visibleIn",2);var Xme=Object.defineProperty,qme=Object.getOwnPropertyDescriptor,Mk=(n,e,t,r)=>{for(var s=r>1?void 0:r?qme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Xme(e,t,s),s};const UA=te("debugwebxr"),kV=new Ce().setFromAxisAngle(new C(0,1,0),Math.PI);class od extends Be{constructor(){super(...arguments),d(this,"head"),d(this,"leftHand"),d(this,"rightHand"),d(this,"_leftHandMeshes"),d(this,"_rightHandMeshes"),d(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;UA&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Pa.getFor(this);if(t!=null&&t.owner){const r=this.gameObject.addComponent(Yr);r.avatar=this.gameObject,r.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Yr);t&&t.destroy()}onUpdateXR(e){var t,r;if(!this.activeAndEnabled)return;const s=Pa.isLocalPlayer(this);if(!s)return;const o=e.xr;if(o.rig&&o.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),o.rig.gameObject.add(this.gameObject)),this._syncTransforms&&s)for(const u of this._syncTransforms)u.fastMode=!0,u.isOwned()||u.requestOwnership();if(this.head&&this.context.mainCamera){const u=this.head.asset;if(u.position.copy(this.context.mainCamera.position),u.position.z*=-1,u.quaternion.copy(this.context.mainCamera.quaternion),u.quaternion.x*=-1,this.context.time.frameCount%10===0){const p=ie.getComponentsInChildren(this.head.asset,Go);for(const m of p)m.enabled=!1,m.gameObject.visible=!1}}const a=e.xr.leftController,l=(t=this.leftHand)==null?void 0:t.asset;a&&l?(l.position.copy(a.gripPosition),l.quaternion.copy(a.gripQuaternion),l.quaternion.multiply(kV),l.visible=a.isTracking,this.updateHandVisibility(a,l,this._leftHandMeshes)):l&&l.visible&&(l.visible=!1);const c=e.xr.rightController,h=(r=this.rightHand)==null?void 0:r.asset;c&&h?(h.position.copy(c.gripPosition),h.quaternion.copy(c.gripQuaternion),h.quaternion.multiply(kV),h.visible=c.isTracking,this.updateHandVisibility(c,h,this._rightHandMeshes)):h&&h.visible&&(h.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,r){if(r){const s=e.model&&e.model.visible&&e.model!==t;r.forEach(o=>{sd(o,!s)})}}updateRemoteAvatarVisibility(){var e,t,r;if(this.context.connection.isConnected){const s=Pa.getFor(this);if(s&&s.isLocalPlayer==!1){const o=wt.getXRSync(this.context);if(o&&o.hasState(s.owner)){this.tryFindAvatarObjectsIfMissing();const a=(e=this.leftHand)==null?void 0:e.asset;a&&(a.visible=o?.isTracking(s.owner,"left")??!1);const l=(t=this.rightHand)==null?void 0:t.asset;l&&(l.visible=o?.isTracking(s.owner,"right")??!1)}if((r=this.head)!=null&&r.asset){const a=ie.getComponentsInChildren(this.head.asset,Go);for(const l of a)l.enabled=!1,l.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};u8.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(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof ye&&(this.head=new ti("",this.sourceId,this.head));else{const e=new ye;e.name="Head";const t=sA.createPrimitive(Yp.Cube);e.add(t),this.gameObject.add(e),this.head=new ti("",this.sourceId,e),UA&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof ye&&(this.rightHand=new ti("",this.sourceId,this.rightHand));else{const e=new ye;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ti("",this.sourceId,e),UA&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof ye&&(this.leftHand=new ti("",this.sourceId,this.leftHand));else{const e=new ye;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ti("",this.sourceId,e),UA&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset.traverse(e=>{e!=null&&e.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset.traverse(e=>{e!=null&&e.isMesh&&this._rightHandMeshes.push(e)}),Pa.isLocalPlayer(this.gameObject)&&(this._syncTransforms=ie.getComponentsInChildren(this.gameObject,Ku))}async loadAvatarObjects(e,t,r){const s=e.loadAssetAsync(),o=t.loadAssetAsync(),a=r.loadAssetAsync(),l=new Array;s&&l.push(s),o&&l.push(o),a&&l.push(a);const c=await tw(l);UA&&console.log("Avatar loaded results:",c)}}Mk([w(ti)],od.prototype,"head",2),Mk([w(ti)],od.prototype,"leftHand",2),Mk([w(ti)],od.prototype,"rightHand",2);class sc{static Add(e,t,r=null){if(t){for(const s of this.Pois)if(s.obj===t)return;this.Pois.push({obj:t,avatar:r}),this.LastChangeTime=e.time.time}}static Remove(e,t){var r;if(t){for(const s of this.Pois)if(s.obj===t){this.Pois.splice(this.Pois.indexOf(s),1),this.LastChangeTime=e?.time.time??((r=kt.Current)==null?void 0:r.time.time);return}}}}d(sc,"Pois",[]),d(sc,"LastChangeTime",0);class Yme{constructor(){d(this,"guid"),d(this,"position",new C)}}class NA extends Be{constructor(){super(...arguments),d(this,"target",null),d(this,"avatar",null),d(this,"_model",null),d(this,"_targetModel",new Yme),d(this,"_currentTargetObject",null),d(this,"_lastUpdateTime",0),d(this,"_lookDuration",0),d(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=q.get("MoveRandom");if(t&&this.target){const r=ie.getComponent(this.target,t);r&&r.destroy()}}awake(){if(this.avatar=ie.getComponentInParent(this.gameObject,Yr),this.avatar){const e=ie.getComponentInParent(this.gameObject,Yr);this._model=new jB(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&&lr(this.target,e.position)})}update(){var e;if((!this.context.connection.isConnected||(e=this._model)!=null&&e.hasOwnership)&&(sc.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=sc.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=Bt(this._currentTargetObject);lr(this.target,t),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(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=sc.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}const $g=te("debugnetworkingstreams");var oc=(n=>(n.Connected="peer-user-connected",n.StreamReceived="receive-stream",n.StreamEnded="call-ended",n.Disconnected="peer-user-disconnected",n.UserJoined="user-joined",n))(oc||{});class DV{constructor(e,t){d(this,"type","call-ended"),d(this,"userId"),d(this,"direction"),this.userId=e,this.direction=t}}class OV{constructor(e,t){d(this,"type","receive-stream"),d(this,"stream"),d(this,"target"),this.stream=e,this.target=t}}class Jme{constructor(e,t){d(this,"guid"),d(this,"peerId"),d(this,"dontSave",!0),this.guid=e.id,this.peerId=t}}var LV=(n=>(n.Incoming="incoming",n.Outgoing="outgoing",n))(LV||{});class Kme extends mr{constructor(e,t,r){super(),d(this,"userId"),d(this,"direction"),d(this,"call"),d(this,"_stream",null),d(this,"_isDisposed",!1),this.userId=e,this.call=t,this.direction=r,this._stream=null,t.on("stream",s=>{if($g&&console.log("Receive video",s.getAudioTracks(),s.getVideoTracks()),this._stream=s,r==="incoming"){const o=new OV(s,this);this.dispatchEvent(o)}}),t.on("close",()=>{this.dispatchEvent(new DV(e,r))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Sh(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}}const zA=class extends mr{constructor(n,e){super(),d(this,"id"),d(this,"context"),d(this,"_peer"),d(this,"_incomingCalls",[]),d(this,"_outgoingCalls",[]),d(this,"_enabled",!1),d(this,"_enabledPeer",!1),d(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),d(this,"onPeerConnectFn",this.onPeerConnect.bind(this)),d(this,"onPeerReceiveCallFn",this.onPeerReceivingCall.bind(this)),this.context=n,this.id=e,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(n,e){if(zA.instances.has(e))return zA.instances.get(e);const t=new zA(n,e);return zA.instances.set(e,t),t}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(n){return this.id+"-"+n}getUserIdFromPeerId(n){return n.substring(this.id.length+1)}makeCall(n,e){var t;const r={metadata:{userId:this.context.connection.connectionId}},s=(t=this._peer)==null?void 0:t.call(n,e,r);if(s)return this.registerCall(s,"outgoing")}get peer(){return this._peer}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(Vt.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(Vt.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const n=this.getMyPeerId();n?this._peer=$G(n):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.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnectFn),this._peer.off("call",this.onPeerReceiveCallFn))}onPeerConnect(n){$g&&console.log("Peer connected as",n),this.context.connection.send("peer-user-connected",new Jme(this,n))}onPeerReceivingCall(n){n.answer(),this.registerCall(n,"incoming")}registerCall(n,e){const t=n.metadata;(!t||!t.userId)&&console.error("Missing call metadata",n);const r=t.userId;e==="incoming"&&$g?console.log("Receive call from",n.metadata):$g&&console.log("Make call to",n.metadata);const s=e==="incoming"?this._incomingCalls:this._outgoingCalls,o=new Kme(r,n,e);return s.push(o),n.on("error",a=>{console.error("Call error",a)}),n.on("close",()=>{$g&&console.log("Call ended",n.metadata),n.close();const a=s.indexOf(o);a!==-1&&s.splice(a,1)}),o.addEventListener("call-ended",a=>{this.dispatchEvent(a)}),e==="incoming"&&(o.addEventListener("receive-stream",a=>{this.dispatchEvent(a)}),n.on("stream",()=>{let a=0;const l=setInterval(()=>{const c=a===0;!o.isOpen&&c&&(a+=1,clearInterval(l),o.close())},2e3)})),o}};let ZS=zA;d(ZS,"instances",new Map);class o_ extends mr{constructor(e,t){super(),d(this,"context"),d(this,"peer"),d(this,"_sendingStreams",new Map),d(this,"debug",!1),d(this,"onJoinedRoom",r=>{this.debug&&console.log(`${r.userId} joined room and I'm currently sending ${this._sendingStreams.size} streams`),this._sendingStreams.size>0&&this.updateSendingCalls()}),d(this,"onReceiveStream",r=>{this.debug&&console.log("RECEIVE STREAM",r),this.dispatchEvent({type:"receive-stream",target:this,stream:r.stream,userId:r.userId})}),d(this,"onCallEnded",r=>{this.dispatchEvent(r)}),d(this,"onUserConnected",r=>{if(this.peer.id===r.guid){this.debug&&console.log("USER CONNECTED",r.guid,r);const s=this._sendingStreams.keys().next().value;this.peer.makeCall(r.peerId,s)}}),d(this,"onUserLeft",r=>{this.stopCallsToUsersThatAreNotInTheRoomAnymore()}),this.context=e,this.peer=t,$g&&(this.debug=!0)}static create(e){const t=ZS.getOrCreate(e.context,e.context.connection.connectionId);return new o_(e.context,t)}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 t=this._sendingStreams.get(e);if(t){this.debug&&console.log("Closing calls",t);for(const r of t)r.close()}this._sendingStreams.delete(e),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}}enable(){this.peer.enable(),this.peer.addEventListener("receive-stream",this.onReceiveStream),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.UserLeftRoom,this.onUserLeft)}disable(){this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onReceiveStream),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.UserLeftRoom,this.onUserLeft)}updateSendingCalls(){var e;let t=!1;const r=this.context.connection.connectionId;for(const s of this._sendingStreams.keys()){const o=this._sendingStreams.get(s)||[];for(const a of this.context.connection.usersInRoom()){if(a===r)continue;const l=o.find(c=>c.userId===a);if(!l||((e=l.stream)==null?void 0:e.active)===!1){this.debug&&console.log("Starting call to",a,r);const c=this.peer.makeCall(this.peer.getPeerIdFromUserId(a),s);c&&(t=!0,o.push(c))}}this._sendingStreams.set(s,o)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let r=t.length-1;r>=0;r--){const s=t[r];this.context.connection.userIsInRoom(s.userId)||(s.close(),t.splice(r,1))}}}}function Sh(n){if(n&&n instanceof MediaStream)for(const e of n.getTracks())e.stop()}var Zme=Object.defineProperty,$me=Object.getOwnPropertyDescriptor,FV=(n,e,t,r)=>{for(var s=r>1?void 0:r?$me(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Zme(e,t,s),s};const efe="noVoip",tfe=te("debugvoip");class om extends Be{constructor(){super(...arguments),d(this,"autoConnect",!0),d(this,"runInBackground",!0),d(this,"debug",!1),d(this,"_net"),d(this,"_outputStream",null),d(this,"onJoinedRoom",async()=>{this.debug&&console.log("VOIP: Joined room"),await Ll(300),this.autoConnect&&!this.isSending&&this.connect()}),d(this,"_incomingStreams",new Map),d(this,"onReceiveStream",e=>{const t=e.target.userId,r=e.stream,s=this._incomingStreams.get(t);if(s)s.srcObject=r,s.setAttribute("autoplay","true");else{const o=new Audio;this._incomingStreams.set(t,o),o.setAttribute("autoplay","true"),o.srcObject=r}}),d(this,"onStreamEnded",e=>{const t=this._incomingStreams.get(e.userId);Sh(t?.srcObject),this._incomingStreams.delete(e.userId)}),d(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}}),d(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const r=t[1];r.muted=e}})}awake(){tfe&&(this.debug=!0),this.debug&&window.addEventListener("keydown",async e=>{e.key==="v"&&(console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted))})}onEnable(){this._net||(this._net=o_.create(this)),this._net.addEventListener(oc.StreamReceived,this.onReceiveStream),this._net.addEventListener(oc.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&(this.context.connection.isConnected?this.connect():this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom)),this.onEnabledChanged(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(oc.StreamReceived,this.onReceiveStream),this._net.removeEventListener(oc.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable(),this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.onEnabledChanged(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(this.context.connection.isConnected){if(!await BI())return console.error("Cannot connect to voice chat - microphone permissions not granted"),!1}else return console.error("Cannot connect to voice chat - not connected to server"),!1;return this._net.stopSendingStream(this._outputStream),Sh(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net.startSendingStream(this._outputStream),!0):(await BI()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):IR("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||st())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(){this._net.stopSendingStream(this._outputStream),Sh(this._outputStream),this._outputStream=null}setMuted(e){var t;const r=(t=this._outputStream)==null?void 0:t.getAudioTracks();if(r)for(const s of r)s.enabled=!e}get isMuted(){var e;if(this._outputStream===null)return!1;const t=(e=this._outputStream)==null?void 0:e.getAudioTracks();if(t){for(const r of t)if(!r.enabled)return!0}return!1}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,st()&&Di("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){return navigator.mediaDevices.getUserMedia?await navigator.mediaDevices.getUserMedia({audio:e??!0,video:!1}).catch(t=>(console.warn("VOIP failed getting audio stream",t),null)):(console.error("No getDisplayMedia support"),null)}}FV([w()],om.prototype,"autoConnect",2),FV([w()],om.prototype,"runInBackground",2);var ife=Object.defineProperty,nfe=Object.getOwnPropertyDescriptor,UV=(n,e,t,r)=>{for(var s=r>1?void 0:r?nfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ife(e,t,s),s};const rfe=te("debugmouth");class jA extends Be{constructor(){super(...arguments),d(this,"idle",[]),d(this,"talking",[]),d(this,"marker",null),d(this,"voip",null),d(this,"lastMouthChangeTime",0),d(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=ie.findObjectOfType(om,this.context),this.marker||(this.marker=ie.getComponentInParent(this.gameObject,Yr))},3e3)}update(){var e;if(!this.voip||this.context.time.frameCount%10!==0)return;let t=((e=this.marker)==null?void 0:e.connectionId)??null;if(!t){rfe&&(t=null);return}const r=this.voip.getFrequency(t)??0;this.updateLips(r)}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 t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(r=>r.visible=!1):this.talking.map(r=>r.visible=!1);for(let r=0;r<e.length;r++){const s=e[r];s&&(s.visible=r===t)}}}}UV([w(ye)],jA.prototype,"idle",2),UV([w(ye)],jA.prototype,"talking",2);class Tk extends Be{constructor(){super(...arguments),d(this,"voip",null),d(this,"marker",null),d(this,"_startPosition",null)}awake(){this.voip=ie.findObjectOfType(om,this.context),this.marker=ie.getComponentInParent(this.gameObject,Yr)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const r=t/100;this.gameObject.position.y=this._startPosition.y+r*.07}}var sfe=Object.defineProperty,ofe=Object.getOwnPropertyDescriptor,$S=(n,e,t,r)=>{for(var s=r>1?void 0:r?ofe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&sfe(e,t,s),s};class am extends Be{constructor(){super(...arguments),d(this,"eyes",[]),d(this,"lastBlinkTime",0),d(this,"blinkLength",0),d(this,"eyesOpen",!0),d(this,"state",null)}awake(){this.state=ie.getComponentInParent(this.gameObject,Go)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&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 e of this.eyes)e&&(e.visible=this.eyesOpen)}}}$S([w(ye)],am.prototype,"eyes",2),$S([w()],am.prototype,"lastBlinkTime",2),$S([w()],am.prototype,"blinkLength",2),$S([w()],am.prototype,"eyesOpen",2);var afe=Object.defineProperty,lfe=Object.getOwnPropertyDescriptor,Ik=(n,e,t,r)=>{for(var s=r>1?void 0:r?lfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&afe(e,t,s),s},Rk;const NV=(Rk=class extends Be{constructor(){super(...arguments),d(this,"head",null),d(this,"eyes",null),d(this,"target",null),d(this,"brain",null),d(this,"vec",new C),d(this,"currentTargetPoint",new C)}awake(){this.brain||(this.brain=ie.getComponentInParent(this.gameObject,NA)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=ie.addNewComponent(this.gameObject,NA)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const n=this.target;if(n&&this.head){const e=this.eyes;if(e){const t=Bt(n);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const r=Bt(this.head),s=this.vec.copy(this.currentTargetPoint).sub(r).normalize();if(s.length()<.1)return;const o=NV.forward;if(o.set(0,0,1),o.applyQuaternion(Mi(this.head)),o.dot(s)>.45)for(let a=0;a<e.length;a++)e[a].lookAt(this.currentTargetPoint)}}}},d(Rk,"forward",new C(0,0,1)),Rk);let e0=NV;Ik([w(ye)],e0.prototype,"head",2),Ik([w(ye)],e0.prototype,"eyes",2),Ik([w(ye)],e0.prototype,"target",2);const GA=te("debugavatar");class eC{constructor(e,t,r,s){d(this,"root"),d(this,"head"),d(this,"leftHand"),d(this,"rigthHand");var o;this.root=e,this.head=t,this.leftHand=r,this.rigthHand=s,(o=this.root)==null||o.traverse(a=>a.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Pk{constructor(){d(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let r=null;if(typeof t=="string"){if(r=await this.loadAvatar(e,t),!r){const o=new Ml;r=ie.instantiate(Df(t,e.scene),o)}}else r=t;if(!r)return null;const s=this.findAvatar(r);return s.isValid?(GA&&console.log("[Custom Avatar] valid config",t,GA?s:""),s):(console.warn("[Custom Avatar] config isn't valid",t,GA?s:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(GA&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const s=await fetch("./"+t);let o=null;if(s.ok){const l=await s.blob();l&&(o=await l.arrayBuffer())}if(!o&&(o=await dB(t,t,0,"no url here go away",!0),!o))return null;const a=await Ka().parseSync(e,o,null,0);return a?.scene??null}const r=new Ru;return u1(r,e),new Promise((s,o)=>{const a=this.avatarRegistryUrl+"/"+t;r.load(a,async l=>{await Ka().createBuiltinComponents(e,a,l,null,void 0),s(l.scene)},l=>{GA&&console.log("[Custom Avatar] "+l.loaded/l.total*100+"% loaded of "+l.total/1024+"kB")},l=>{console.error("[Custom Avatar] Error when loading: "+l),s(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let r=t;r.children.length==1&&(r=e.children[0]);let s=this.findAvatarPart(r,["head"]);const o=this.findAvatarPart(r,["left","hand"]),a=this.findAvatarPart(r,["right","hand"]);if(!s){s=t;const l=new C;new xi().setFromObject(s).getSize(l);const c=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+c+" meters! Should be < 0.3m"),c>.3&&s.scale.multiplyScalar(1/c*.3)}return new eC(t,s,o,a)}findAvatarPart(e,t){const r=e.name.toLowerCase();let s=!0;for(const o of t){if(!s)break;r.indexOf(o)===-1&&(s=!1)}if(s)return e;if(e.children)for(const o of e.children){const a=this.findAvatarPart(o,t);if(a)return a}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}var cfe=Object.defineProperty,hfe=Object.getOwnPropertyDescriptor,Bk=(n,e,t,r)=>{for(var s=r>1?void 0:r?hfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&cfe(e,t,s),s};class t0 extends Be{constructor(){super(...arguments),d(this,"length",1),d(this,"depthTest",!0),d(this,"isGizmo",!0),d(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Wy)return;this._axes||(this._axes=new Po(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)}}Bk([w()],t0.prototype,"length",2),Bk([w()],t0.prototype,"depthTest",2),Bk([w()],t0.prototype,"isGizmo",2);class kk extends Be{constructor(){super(...arguments),d(this,"from"),d(this,"to"),d(this,"hint"),d(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=Bt(this.to).clone(),t=Bt(this.from).clone(),r=e.distanceTo(t),s=e.clone();s.sub(t);const o=t.clone();o.add(e),o.multiplyScalar(.5);const a=Bt(this.hint).clone();a.sub(o);const l=new C;l.crossVectors(a,s),l.crossVectors(s,l),l.normalize();const c=r*.5,h=Math.max(this.desiredDistance,c),u=Math.sqrt(h*h-c*c),p=l.clone();p.multiplyScalar(u),p.add(o),lr(this.gameObject,p);const m=o.clone();m.sub(l),this.gameObject.lookAt(m)}}const Dk=te("debugusdzbehaviours");class tC{constructor(){d(this,"behaviours",[]),d(this,"behaviourComponents",[]),d(this,"behaviourComponentsCopy",[]),d(this,"audioClips",[]),d(this,"audioClipsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+Pd.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(r=>{ie.foreachComponent(r,s=>{var o;const a=s;if(typeof a.createBehaviours=="function"||typeof a.beforeCreateDocument=="function"||typeof a.afterCreateDocument=="function"||typeof a.afterSerialize=="function"){this.behaviourComponents.push(a);const l=(o=a.beforeCreateDocument)==null?void 0:o.call(a,this,e);l instanceof Promise&&t.push(l)}},!1)}),Dk&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,r){var s;for(const o of this.behaviourComponents)Dk&&console.log("onExportObject: createBehaviours",o),(s=o.createBehaviours)==null||s.call(o,this,t,r)}onAfterBuildDocument(e){for(const t of this.behaviourComponents)typeof t.afterCreateDocument=="function"&&t.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0}onAfterHierarchy(e,t){var r;if((r=this.behaviours)!=null&&r.length){t.beginBlock('def Scope "Behaviors"');for(const s of this.behaviours)s.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Dk&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:r}of this.audioClipsCopy){if(e.files[r])return;const s=await(await(await fetch(t)).blob()).arrayBuffer(),o=new Uint8Array(s);e.files[r]=o}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}var ufe=Object.defineProperty,dfe=Object.getOwnPropertyDescriptor,Ok=(n,e,t,r)=>{for(var s=r>1?void 0:r?dfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ufe(e,t,s),s},Lk;const zV=(Lk=class extends Xr{constructor(){super(...arguments),d(this,"threshold",new qe(.9)),d(this,"intensity",new qe(1)),d(this,"scatter",new qe(.3)),d(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=n=>n,this.intensity.valueProcessor=n=>n,this.scatter.valueProcessor=n=>n}onCreateEffect(){let n;if(this.selectiveBloom==null&&(this.selectiveBloom=zV.useSelectiveBloom),this.selectiveBloom){const e=n=new i6(this.context.scene,this.context.mainCamera,{blendFunction:jt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});e.inverted=!0}else n=new $P({blendFunction:jt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=e=>{n.intensity=e},this.threshold.onValueChanged=e=>{n.luminanceMaterial.threshold=Math.pow(e,2.2)},this.scatter.onValueChanged=e=>{n.luminancePass.enabled=!0,n.luminanceMaterial.smoothing=e,n.mipmapBlurPass&&(n.mipmapBlurPass.radius=ui.lerp(.1,.9,e))},n}},d(Lk,"useSelectiveBloom",!1),Lk);let lm=zV;Ok([w(qe)],lm.prototype,"threshold",2),Ok([w(qe)],lm.prototype,"intensity",2),Ok([w(qe)],lm.prototype,"scatter",2),Ra("Bloom",lm);var pfe=Object.defineProperty,mfe=Object.getOwnPropertyDescriptor,bo=(n,e,t,r)=>{for(var s=r>1?void 0:r?mfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&pfe(e,t,s),s};class Vo extends Be{constructor(){super(...arguments),d(this,"attachedRigidbody",null),d(this,"isTrigger",!1),d(this,"sharedMaterial"),d(this,"membership",[0]),d(this,"filter"),d(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(Oi))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Oi))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Oi))}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)}}bo([w(Oi)],Vo.prototype,"attachedRigidbody",2),bo([w()],Vo.prototype,"isTrigger",2),bo([w()],Vo.prototype,"sharedMaterial",2),bo([w()],Vo.prototype,"membership",2),bo([w()],Vo.prototype,"filter",2);class i0 extends Vo{constructor(){super(...arguments),d(this,"radius",.5),d(this,"center",new C(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this),Zx(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),PI(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}bo([Hr(),w()],i0.prototype,"radius",2),bo([w(C)],i0.prototype,"center",2);class n0 extends Vo{constructor(){super(...arguments),d(this,"size",new C(1,1,1)),d(this,"center",new C(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.size),Zx(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),PI(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}bo([Hr(),w(C)],n0.prototype,"size",2),bo([w(C)],n0.prototype,"center",2);class cm extends Vo{constructor(){super(...arguments),d(this,"sharedMesh"),d(this,"convex",!1)}onEnable(){var e,t,r;if(super.onEnable(),!this.context.physics.engine)return;(e=this.sharedMesh)!=null&&e.isMesh||this.gameObject instanceof me&&(this.sharedMesh=this.gameObject);const s=0;if((t=this.sharedMesh)!=null&&t.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex,Vi(this.gameObject)),fi.assignMeshLOD(this.sharedMesh,s).then(o=>{o&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=o,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex,Vi(this.gameObject)))});else{const o=this.sharedMesh;if(o!=null&&o.isGroup){console.warn(`MeshCollider mesh is a group "${((r=this.sharedMesh)==null?void 0:r.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 a=new Array;for(const l in o.children){const c=o.children[l];c.isMesh&&(this.context.physics.engine.addMeshCollider(this,c,this.convex,Vi(this.gameObject)),a.push(fi.assignMeshLOD(c,s)))}Promise.all(a).then(l=>{var c,h;if(l.some(p=>p)==!1)return;(c=this.context.physics.engine)==null||c.removeBody(this);const u=new me;for(const p of l)p&&this.activeAndEnabled&&(u.geometry=p,(h=this.context.physics.engine)==null||h.addMeshCollider(this,u,this.convex,Vi(this.gameObject)))})}}}}bo([w(me)],cm.prototype,"sharedMesh",2),bo([w()],cm.prototype,"convex",2);class Ch extends Vo{constructor(){super(...arguments),d(this,"center",new C(0,0,0)),d(this,"radius",.5),d(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.height,this.radius)}}bo([w(C)],Ch.prototype,"center",2),bo([w()],Ch.prototype,"radius",2),bo([w()],Ch.prototype,"height",2);var ffe=Object.defineProperty,gfe=Object.getOwnPropertyDescriptor,Fk=(n,e,t,r)=>{for(var s=r>1?void 0:r?gfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ffe(e,t,s),s};class hm extends Be{constructor(){super(...arguments),d(this,"objectBounds",!1),d(this,"color"),d(this,"isGizmo",!0),d(this,"_gizmoObject",null),d(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!Wy||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new xI(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=fB(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Hi.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var e;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}Fk([w()],hm.prototype,"objectBounds",2),Fk([w(xe)],hm.prototype,"color",2),Fk([w()],hm.prototype,"isGizmo",2);const vfe=te("gizmos"),yfe=te("debugboxhelper"),vl=class extends Be{constructor(){super(...arguments),d(this,"box",null),d(this,"_lastMatrixUpdateFrame",-1),d(this,"_helper",null),d(this,"_color",null)}isInBox(n,e){var t;if(!n)return;if(this.box||(this.box=new xi),n.type==="Mesh")vl.testBox.setFromObject(n);else if(n.type==="Group"){if(vl.testBox.makeEmpty(),n.children.length>0)for(let s=0;s<n.children.length;s++)n.children[s].type==="Mesh"&&vl.testBox.expandByObject(n)}else{const s=Bt(n,vl._position),o=Vi(n,vl._size);e!==void 0&&o.multiplyScalar(e),vl.testBox.setFromCenterAndSize(s,o)}this.updateBox();const r=(t=this.box)==null?void 0:t.intersectsBox(vl.testBox);return r&&yfe&&At.DrawWireBox3(vl.testBox,16711680,5),r}intersects(n){return n?this.updateBox(!1).intersectsBox(n):!1}updateBox(n=!1){if(this.box||(this.box=new xi),n||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const e=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const t=e,r=Bt(this.gameObject,vl._position,t),s=Vi(this.gameObject,vl._size);this.box.setFromCenterAndSize(r,s)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(n=null,e=!1){var t;if(!(!vfe&&!e)){if(this._helper){n&&((t=this._color)==null||t.set(n)),this.gameObject.add(this._helper);return}this._helper=fB(n),this.gameObject.add(this._helper)}}};let ac=vl;d(ac,"testBox",new xi),d(ac,"_position",new C),d(ac,"_size",new C(.01,.01,.01));class Afe extends qN{constructor(e,t={}){super(e),e._simpleState__activeStates=[],e._simpleState__normalStyles={},e._simpleState__states=t,e._simpleState__statesProperties={};for(const r in t)for(const s in t[r])e._simpleState__statesProperties[s]||(e._simpleState__statesProperties[s]=[]),e._simpleState__statesProperties[s].push(r);for(const r of e._components)e._simpleState__statesProperties[r.id]&&(e._simpleState__normalStyles[r.id]=r.inline?r.inline:r._value);e.__overridedSet=e.set,e.set=this.storeSet.bind(e),e.renderStates=this.renderStates.bind(e),e.setupState=this.setupState.bind(e),e.setState=this.setState.bind(e),e.activatePseudoState=this.activatePseudoState.bind(e),e.deactivatePseudoState=this.deactivatePseudoState.bind(e),e.togglePseudoState=this.togglePseudoState.bind(e)}act(){}attach(){}detach(){}setupState(e,t){this._simpleState__states[e]=t;const r=[];for(const s in t)this._simpleState__statesProperties[s]||(this._simpleState__statesProperties[s]=[],r.push(s)),this._simpleState__statesProperties[s].push(e);for(const s of this._components)r.indexOf(s.id)>-1&&(this._simpleState__normalStyles[s.id]=s.inline?s.inline:s._value)}renderStates(){let e={...this._simpleState__normalStyles};for(const t in this._simpleState__states)this._simpleState__activeStates.indexOf(t)>-1&&(e={...e,...this._simpleState__states[t]});this.set(e,!1)}storeSet(e,t=!0){if(t)for(const r in e)this._simpleState__statesProperties[r]&&(this._simpleState__normalStyles[r]=e[r]);this.__overridedSet(e)}activatePseudoState(e){this._simpleState__activeStates.indexOf(e)===-1&&(this._simpleState__activeStates.push(e),this.renderStates())}deactivatePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1&&(this._simpleState__activeStates.splice(t,1),this.renderStates())}togglePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1?this._simpleState__activeStates.splice(t,1):this._simpleState__activeStates.push(e),this.renderStates()}setState(e){Array.isArray(e)?this._simpleState__activeStates=e:this._simpleState__activeStates=[e],this.renderStates()}}var bfe=Object.defineProperty,_fe=Object.getOwnPropertyDescriptor,jV=(n,e,t,r)=>{for(var s=r>1?void 0:r?_fe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&bfe(e,t,s),s};class r0 extends Be{constructor(){super(...arguments),d(this,"effectColor"),d(this,"effectDistance")}}jV([w(Si)],r0.prototype,"effectColor",2),jV([w(Z)],r0.prototype,"effectDistance",2);var xfe=Object.defineProperty,wfe=Object.getOwnPropertyDescriptor,VA=(n,e,t,r)=>{for(var s=r>1?void 0:r?wfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&xfe(e,t,s),s};const Uk=te("debugui"),Nk=te("debuguilayout");class zk{constructor(){d(this,"width"),d(this,"height")}}class jk{constructor(){d(this,"x"),d(this,"y"),d(this,"width"),d(this,"height")}}const yl=new C,QA=new ve,iC=new Ce,GV=class extends Va{constructor(){super(...arguments),d(this,"_anchoredPosition"),d(this,"sizeDelta",new Z(100,100)),d(this,"pivot",new Z(.5,.5)),d(this,"anchorMin",new Z(0,0)),d(this,"anchorMax",new Z(1,1)),d(this,"minWidth"),d(this,"minHeight"),d(this,"lastMatrix"),d(this,"rectBlock"),d(this,"_transformNeedsUpdate",!1),d(this,"_initialPosition"),d(this,"_parentRectTransform"),d(this,"_lastUpdateFrame",-1),d(this,"_lastAnchoring"),d(this,"_createdBlocks",[]),d(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 Z),this._anchoredPosition}set anchoredPosition(n){this._anchoredPosition=n}get width(){let n=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const e=this._parentRectTransform.width,t=this.anchorMax.x-this.anchorMin.x;n=e*t,n+=this.sizeDelta.x}return this.minWidth!==void 0&&n<this.minWidth?this.minWidth:n}get height(){let n=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const e=this._parentRectTransform.height,t=this.anchorMax.y-this.anchorMin.y;n=e*t,n+=this.sizeDelta.y}return this.minHeight!==void 0&&n<this.minHeight?this.minHeight:n}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new Z),this.lastMatrix=new ve,this.rectBlock=new ye,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,Xg(this,"_anchoredPosition",()=>{this.markDirty()}),Xg(this,"sizeDelta",()=>{this.markDirty()}),Xg(this,"pivot",()=>{this.markDirty()}),Xg(this,"anchorMin",()=>{this.markDirty()}),Xg(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var n;super.onEnable(),this.rectBlock||(this.rectBlock=new ye),this.lastMatrix||(this.lastMatrix=new ve),this._lastAnchoring||(this._lastAnchoring=new Z),this._initialPosition||(this._initialPosition=new C),this._anchoredPosition||(this._anchoredPosition=new Z),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(n=this.canvas)==null||n.registerTransform(this)}onDisable(){var n;super.onDisable(),this.removeShadowComponent(),(n=this.canvas)==null||n.unregisterTransform(this)}onParentRectTransformChanged(n){this._transformNeedsUpdate||this.onApplyTransform(Nk?`${n.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(Nk&&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(n){var e;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=ie.getComponentInParent(this.gameObject.parent,GV):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,Nk&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+n),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,yl.set(0,0,0),this.applyPivot(yl),t.matrix.setPosition(yl.x,yl.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(iC.copy(this.gameObject.quaternion),iC.x*=-1,iC.z*=-1,QA.makeRotationFromQuaternion(iC),t.matrix.premultiply(QA)),yl.set(0,0,0),this.applyAnchoring(yl),(e=this.canvas)!=null&&e.screenspace?yl.z+=.1:yl.z+=.01,QA.identity(),QA.setPosition(yl.x,yl.y,yl.z),t.matrix.premultiply(QA),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const r=!0;for(const s of TS(this.gameObject,Va,r,1)){if(s===this||!s.activeAndEnabled)continue;const o=s;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}applyAnchoring(n){this._lastAnchoring||(this._lastAnchoring=new Z);const e=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=e.x,this.gameObject.position.y+=e.y,this._lastAnchoring.copy(this._anchoredPosition),n.x+=this._initialPosition.x-this.gameObject.position.x,n.y+=this._initialPosition.y-this.gameObject.position.y,n.z+=this._initialPosition.z-this.gameObject.position.z;const t=this._parentRectTransform;if(t){let r=0;const s=1-this.anchorMax.y-this.anchorMin.y;r-=t.height*.5*s,n.y+=r;let o=0;const a=1-this.anchorMax.x-this.anchorMin.x;o-=t.width*.5*a,n.x+=o}}applyPivot(n){if(this.pivot&&!this.isRoot()){const e=this.pivot.x-.5;n.x-=e*this.sizeDelta.x*this.gameObject.scale.x;const t=this.pivot.y-.5;n.y-=t*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const n={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(n),n}ensureValidSize(n,e=1e-4){return n.width<=0&&(n.width=e),n.height<=0&&(n.height=1e-4),n}createNewBlock(n){n={...this.getBasicOptions(),...n},Uk&&console.log(this.name,n);const e=new pR(n);return this._createdBlocks.push(e),e}createNewText(n){Uk&&console.log(n),n={...this.getBasicOptions(),...n},Uk&&console.log(this.name,n);const e=new fR(n);return this._createdTextBlocks.push(e),e}};let Ts=GV;VA([w(Z)],Ts.prototype,"anchoredPosition",1),VA([w(Z)],Ts.prototype,"sizeDelta",2),VA([w(Z)],Ts.prototype,"pivot",2),VA([w(Z)],Ts.prototype,"anchorMin",2),VA([w(Z)],Ts.prototype,"anchorMax",2);var Sfe=Object.defineProperty,Cfe=Object.getOwnPropertyDescriptor,VV=(n,e,t,r)=>{for(var s=r>1?void 0:r?Cfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Sfe(e,t,s),s};const nC={backgroundColor:new xe(1,1,1),backgroundOpacity:1,borderColor:new xe(1,1,1),borderOpacity:1};var Gk;const HA=(Gk=class extends Va{constructor(){super(...arguments),d(this,"_alphaFactor",1),d(this,"sRGBColor",new xe(1,0,1)),d(this,"raycastTarget",!0),d(this,"uiObject",null),d(this,"_color",null),d(this,"_rect",null),d(this,"_stateManager",null),d(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new Si(1,1,1,1)),this._color}set color(n){(!this._color||this._color.r!==n.r||this._color.g!==n.g||this._color.b!==n.b||this._color.alpha!==n.alpha)&&(this._color||(this._color=new Si(1,1,1,1)),this._color.copy(n),this.onColorChanged())}setAlphaFactor(n){this._alphaFactor=n,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),nC.backgroundColor=this.sRGBColor,nC.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(nC,this._alphaFactor),this.uiObject.set(nC),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=ie.getComponent(this.gameObject,Ts)),!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 n;(n=this.uiObject)==null||n.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(n){return super.__internalNewInstanceCreated(n),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone()),this}setState(n){this.makePanel(),this.uiObject&&(this.uiObject.setState(n),this==null||this.markDirty())}setupState(n){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new Afe(this.uiObject)),this.uiObject.setupState(n.state,n.attributes))}setOptions(n){this.makePanel(),this.uiObject&&this.uiObject.set(n)}awake(){super.awake(),this.makePanel(),Xg(this,"_color",()=>Qpe(this,this.onColorChanged))}onEnable(){var n;super.onEnable(),this.uiObject&&((n=this.rectTransform.shadowComponent)==null||n.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 n=.015,e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:n};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(n){}onCreate(n){this.uiObject=this.rectTransform.createNewBlock(n),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(n,e=1){var t;const r=(t=this.gameObject)==null?void 0:t.getComponent(r0);r&&(r.effectDistance&&(n.borderWidth=Math.max(Math.abs(r.effectDistance.x),Math.abs(r.effectDistance.y))),r.effectColor&&(n.borderColor=r.effectColor,n.borderOpacity=r.effectColor.alpha*e))}async setTexture(n){if(this.setOptions({backgroundOpacity:0}),n){if(HA.textureCache.has(n))n=HA.textureCache.get(n);else if(!n.isRenderTargetTexture){const e=n.clone();e.colorSpace=Ri,HA.textureCache.set(n,e),n=e}this.setOptions({backgroundImage:n,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),fi.assignTextureLOD(n,0).then(e=>{e instanceof zt&&(n&&HA.textureCache.set(n,e),this.setOptions({backgroundImage:e}),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)}},d(Gk,"textureCache",new Map),Gk);let um=HA;VV([w(Si)],um.prototype,"color",1),VV([w()],um.prototype,"raycastTarget",2);class WA extends um{constructor(){super(...arguments),d(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var Efe=Object.defineProperty,Mfe=Object.getOwnPropertyDescriptor,rC=(n,e,t,r)=>{for(var s=r>1?void 0:r?Mfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Efe(e,t,s),s};let Vk=class{constructor(){d(this,"texture",null),d(this,"rect")}};rC([w(zt)],Vk.prototype,"texture",2);let s0=class extends WA{constructor(){super(...arguments),d(this,"_sprite"),d(this,"pixelsPerUnitMultiplier",1)}set image(n){this.sprite||(this.sprite=new Vk),this.sprite.texture=n,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(n){this._sprite!==n&&(this._sprite=n,this.onAfterCreated())}isBuiltinSprite(){var n,e,t,r,s,o,a;const l=this.sprite;switch((n=l?.texture)==null?void 0:n.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((t=(e=l?.texture)==null?void 0:e.name)!=null&&t.length)&&((s=(r=l?.texture)==null?void 0:r.image)==null?void 0:s.width)===32&&((a=(o=l?.texture)==null?void 0:o.image)==null?void 0:a.height)===32}onBeforeCreate(n){var e,t;super.onBeforeCreate(n),this.isBuiltinSprite()&&(n.borderRadius=5/this.pixelsPerUnitMultiplier,((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name)==="Knob"&&(n.borderRadius=999))}onAfterCreated(){var n;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((n=this.sprite)==null?void 0:n.texture))}};rC([w(Vk)],s0.prototype,"sprite",1),rC([w()],s0.prototype,"pixelsPerUnitMultiplier",2);class sC extends WA{constructor(){super(...arguments),d(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))}}rC([w(zt)],sC.prototype,"mainTexture",1);var Tfe=Object.defineProperty,Ife=Object.getOwnPropertyDescriptor,Qo=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ife(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Tfe(e,t,s),s};const dm=te("debugbutton");class ad{constructor(){d(this,"colorMultiplier"),d(this,"disabledColor"),d(this,"fadeDuration"),d(this,"highlightedColor"),d(this,"normalColor"),d(this,"pressedColor"),d(this,"selectedColor")}}Qo([w()],ad.prototype,"colorMultiplier",2),Qo([w(Si)],ad.prototype,"disabledColor",2),Qo([w()],ad.prototype,"fadeDuration",2),Qo([w(Si)],ad.prototype,"highlightedColor",2),Qo([w(Si)],ad.prototype,"normalColor",2),Qo([w(Si)],ad.prototype,"pressedColor",2),Qo([w(Si)],ad.prototype,"selectedColor",2);class Rfe{constructor(){d(this,"disabledTrigger"),d(this,"highlightedTrigger"),d(this,"normalTrigger"),d(this,"pressedTrigger"),d(this,"selectedTrigger")}}class Eh extends Be{constructor(){super(...arguments),d(this,"onClick"),d(this,"_isHovered",0),d(this,"colors"),d(this,"transition"),d(this,"animationTriggers"),d(this,"animator"),d(this,"_interactable",!0),d(this,"_requestedAnimatorTrigger"),d(this,"_isInit",!1),d(this,"_image")}onPointerEnter(e){var t,r;const s=e.event.pointerType==="mouse"&&e.button===0;s&&(this._isHovered+=1),dm&&console.warn("Button Enter",s,this._isHovered,(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((r=this._image)==null||r.setState("hovered")),s&&this.context.input.setCursorPointer())}onPointerExit(){var e,t;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),dm&&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&&((t=this._image)==null||t.setState("normal")),this.context.input.setCursorNormal()))}onPointerDown(e){var t,r;dm&&console.log("Button Down",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((r=this._image)==null||r.setState("pressed")))}onPointerUp(e){var t,r;dm&&console.warn("Button Up",(t=this.animationTriggers)==null?void 0:t.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&&((r=this._image)==null||r.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===q1.Mouse)&&(dm&&(console.warn("Button Click",this.onClick),rn("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),dm))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),At.DrawLabel(t,"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(),dm&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable),this.gameObject.getComponentInParent(xA)||this.gameObject.addComponent(FS)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.setCursorNormal()}*setAnimatorTriggerAtEndOfFrame(e){var t;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((t=this.animator)==null||t.SetTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=ie.getComponent(this.gameObject,s0),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var t,r,s,o,a;e.setInteractable(this.interactable);const l=this.getFinalColor(e.color,(t=this.colors)==null?void 0:t.normalColor),c={state:"normal",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);const h=this.getFinalColor(e.color,(r=this.colors)==null?void 0:r.highlightedColor),u={state:"hovered",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(u);const p=this.getFinalColor(e.color,(s=this.colors)==null?void 0:s.pressedColor),m={state:"pressed",attributes:{backgroundColor:p,backgroundOpacity:p.alpha}};e.setupState(m);const f=this.getFinalColor(e.color,(o=this.colors)==null?void 0:o.selectedColor),g={state:"selected",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(g);const v=this.getFinalColor(e.color,(a=this.colors)==null?void 0:a.disabledColor),y={state:"disabled",attributes:{backgroundColor:v,backgroundOpacity:v.alpha}};e.setupState(y)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}Qo([w(Un)],Eh.prototype,"onClick",2),Qo([w(ad)],Eh.prototype,"colors",2),Qo([w()],Eh.prototype,"transition",2),Qo([w(Rfe)],Eh.prototype,"animationTriggers",2),Qo([w(Wr)],Eh.prototype,"animator",2),Qo([w()],Eh.prototype,"interactable",1);var Pfe=Object.defineProperty,Bfe=Object.getOwnPropertyDescriptor,Jn=(n,e,t,r)=>{for(var s=r>1?void 0:r?Bfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Pfe(e,t,s),s};const QV=te("debuguilayout");class ld{constructor(){d(this,"left",0),d(this,"right",0),d(this,"top",0),d(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Jn([w()],ld.prototype,"left",2),Jn([w()],ld.prototype,"right",2),Jn([w()],ld.prototype,"top",2),Jn([w()],ld.prototype,"bottom",2);class Ho extends Be{constructor(){super(...arguments),d(this,"_rectTransform",null),d(this,"_needsUpdate",!1),d(this,"childAlignment",0),d(this,"reverseArrangement",!1),d(this,"spacing",0),d(this,"padding"),d(this,"minWidth",0),d(this,"minHeight",0),d(this,"flexibleHeight",0),d(this,"flexibleWidth",0),d(this,"preferredHeight",0),d(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&&(QV&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){QV&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ts);const e=this.gameObject.getComponentInParent(Jr);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Jr);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Jn([w()],Ho.prototype,"childAlignment",2),Jn([w()],Ho.prototype,"reverseArrangement",2),Jn([w()],Ho.prototype,"spacing",2),Jn([w(ld)],Ho.prototype,"padding",2),Jn([w()],Ho.prototype,"minWidth",2),Jn([w()],Ho.prototype,"minHeight",2),Jn([w()],Ho.prototype,"flexibleHeight",2),Jn([w()],Ho.prototype,"flexibleWidth",2),Jn([w()],Ho.prototype,"preferredHeight",2),Jn([w()],Ho.prototype,"preferredWidth",2);class cd extends Ho{constructor(){super(...arguments),d(this,"childControlHeight",!0),d(this,"childControlWidth",!0),d(this,"childForceExpandHeight",!1),d(this,"childForceExpandWidth",!1),d(this,"childScaleHeight",!1),d(this,"childScaleWidth",!1)}onCalculateLayout(e){var t;const r=this.primaryAxis,s=e.width;let o=s;const a=e.height;let l=a;o-=this.padding.horizontal,l-=this.padding.vertical,r==="x"?this.padding.horizontal:this.padding.vertical;const c=r==="x",h=c?"y":"x",u=c?this.childControlWidth:this.childControlHeight,p=c?this.childControlHeight:this.childControlWidth,m=c?this.childForceExpandWidth:this.childForceExpandHeight,f=c?this.childForceExpandHeight:this.childForceExpandWidth,g=c?l:o,v=c?s:a,y=.5*(c?this.childAlignment%3:Math.floor(this.childAlignment/3));let A=0;c?A+=this.padding.left:A+=this.padding.top;let _=0,b=0;for(let R=0;R<this.gameObject.children.length;R++){const D=this.gameObject.children[R],M=ie.getComponent(D,Ts);M!=null&&M.activeAndEnabled&&(b+=1,c?_+=M.width:_+=M.height)}let x=0;const E=this.spacing*(b-1);if(m||u){let R=0;c?R=o-=E:R=l-=E,b>0&&(x=R/b)}let I=0;I+=this.padding.left,I-=this.padding.right,y!==0&&(A=v-_,A*=y,A-=E*y,c?(A-=this.padding.right*y,A+=this.padding.left*(1-y),A<this.padding.left&&(A=this.padding.left)):(A-=this.padding.bottom*y,A+=this.padding.top*(1-y),A<this.padding.top&&(A=this.padding.top)));let T=1;for(let R=0;R<this.gameObject.children.length;R++){const D=this.gameObject.children[R],M=ie.getComponent(D,Ts);if(M!=null&&M.activeAndEnabled){(t=M.pivot)==null||t.set(.5,.5),M.anchorMin.set(0,1),M.anchorMax.set(0,1);const P=s*.5+I*.5;M.anchoredPosition.x!==P&&(M.anchoredPosition.x=P);const z=a*-.5;M.anchoredPosition.y!==z&&(M.anchoredPosition.y=z),f&&p&&M.sizeDelta[h]!==g&&(M.sizeDelta[h]=g),m&&u&&M.sizeDelta[r]!==x&&(M.sizeDelta[r]=x);const V=c?M.width:M.height,L=V*.5;if(A+=L,m){const O=x*T-x*.5;O>A&&(A=O-x*.5+V+this.padding.left,A-=L)}let H=A;r==="y"&&(H=-H),M.anchoredPosition[r]!==H&&(M.anchoredPosition[r]=H),A+=L,A+=this.spacing,T+=1}}}}Jn([w()],cd.prototype,"childControlHeight",2),Jn([w()],cd.prototype,"childControlWidth",2),Jn([w()],cd.prototype,"childForceExpandHeight",2),Jn([w()],cd.prototype,"childForceExpandWidth",2),Jn([w()],cd.prototype,"childScaleHeight",2),Jn([w()],cd.prototype,"childScaleWidth",2);class Qk extends cd{get primaryAxis(){return"y"}}class Hk extends cd{get primaryAxis(){return"x"}}class Wk extends Ho{onCalculateLayout(){}}var kfe=Object.defineProperty,Dfe=Object.getOwnPropertyDescriptor,lc=(n,e,t,r)=>{for(var s=r>1?void 0:r?Dfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&kfe(e,t,s),s},HV=(n=>(n[n.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",n[n.ScreenSpaceCamera=1]="ScreenSpaceCamera",n[n.WorldSpace=2]="WorldSpace",n[n.Undefined=-1]="Undefined",n))(HV||{});const Xk=te("debuguilayout"),WV=class extends _A{constructor(){super(...arguments),d(this,"_renderOnTop"),d(this,"_depthWrite",!1),d(this,"_doubleSided",!0),d(this,"_castShadows",!1),d(this,"_receiveShadows",!1),d(this,"_renderMode",-1),d(this,"_rootCanvas"),d(this,"_scaleFactor",1),d(this,"worldCamera"),d(this,"planeDistance",-1),d(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),d(this,"previousParent",null),d(this,"_lastMatrixWorld",null),d(this,"_rectTransforms",[]),d(this,"_layoutGroups",new Map),d(this,"_receivers",[]),d(this,"onBeforeRenderRoutine",()=>{var n,e,t,r;if(this.previousParent=this.gameObject.parent,((n=this.context.xr)!=null&&n.isVR||(e=this.context.xr)!=null&&e.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(t=this.shadowComponent)==null||t.updateMatrixWorld(!0),(r=this.shadowComponent)==null||r.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),Ta.ensureUpdateMeshUI(JN,this.context))}),d(this,"onAfterRenderRoutine",()=>{var n,e,t,r,s;if(((n=this.context.xr)!=null&&n.isVR||(e=this.context.xr)!=null&&e.isPassThrough)&&this.screenspace){(t=this.previousParent)==null||t.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const l=this.context.mainCamera;l?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const o=this.context.renderer.autoClear,a=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(r=this.shadowComponent)==null||r.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),Ta.ensureUpdateMeshUI(JN,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=o,this.context.renderer.autoClearColor=a,this.previousParent.add(this.gameObject)}(s=this._lastMatrixWorld)==null||s.copy(this.gameObject.matrixWorld)}),d(this,"_updateRenderSettingsRoutine"),d(this,"_activeRenderMode",-1),d(this,"_lastWidth",-1),d(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(n){n!==this._renderOnTop&&(this._renderOnTop=n,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(n){this._depthWrite!==n&&(this._depthWrite=n,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(n){this._doubleSided!==n&&(this._doubleSided=n,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(n){this._castShadows!==n&&(this._castShadows=n,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(n){this._receiveShadows!==n&&(this._receiveShadows=n,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(n){this._renderMode!==n&&(this._renderMode=n,this.onRenderSettingsChanged())}set rootCanvas(n){this._rootCanvas instanceof WV||(this._rootCanvas=n)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(n){this._scaleFactor=n}awake(){var n;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,Xk&&console.log("Canvas.Awake()",((n=this.previousParent)==null?void 0:n.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ve,this.onUpdateRenderMode(),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 n=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);n!==-1&&this.context.pre_render_callbacks.splice(n,1);const e=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);e!==-1&&this.context.post_render_callbacks.splice(e,1)}registerTransform(n){this._rectTransforms.push(n)}unregisterTransform(n){const e=this._rectTransforms.indexOf(n);e!==-1&&this._rectTransforms.splice(e,1)}registerLayoutGroup(n){const e=n.gameObject;this._layoutGroups.set(e,n)}unregisterLayoutGroup(n){const e=n.gameObject;this._layoutGroups.delete(e)}registerEventReceiver(n){this._receivers.push(n)}unregisterEventReceiver(n){const e=this._receivers.indexOf(n);e!==-1&&this._receivers.splice(e,1)}async onEnterXR(n){this.screenspace?(n.xr.isVR||n.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await NU(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(n){this.screenspace&&(n.xr.isVR||n.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var n;for(const e of this._receivers)(n=e.onBeforeCanvasRender)==null||n.call(e,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ve);const n=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);Xk&&n&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const e=!1;for(const t of this._rectTransforms){n&&t.markDirty();let r=this._layoutGroups.get(t.gameObject);t.isDirty&&!r&&(r=t.gameObject.getComponentInParent(Ho)),(t.isDirty||r!=null&&r.isDirty)&&(Xk&&!e&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),r?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Hi.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),NS(this.shadowComponent,this);for(const n of ie.getComponentsInChildren(this.gameObject,Va))NS(n.shadowComponent,this)}}onUpdateRenderMode(n=!1){if(!n&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let e=this.context.mainCameraComponent,t=10;switch(e&&e.nearClipPlane>0&&e.farClipPlane>0&&(t=it.lerp(e.nearClipPlane,e.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(e=this.worldCamera),this.planeDistance>0&&(t=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!e)return;const r=t+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-r,this.gameObject.quaternion.identity();const s=this.gameObject.getComponent(Ts);let o=!1;s.sizeDelta.x!==this.context.domWidth&&(o=!0),s.sizeDelta.y!==this.context.domHeight&&(o=!0);const a=e.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(r);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,o&&(s.sizeDelta.x=this.context.domWidth,s.sizeDelta.y=this.context.domHeight,s?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let Jr=WV;lc([w()],Jr.prototype,"renderOnTop",1),lc([w()],Jr.prototype,"depthWrite",1),lc([w()],Jr.prototype,"doubleSided",1),lc([w()],Jr.prototype,"castShadows",1),lc([w()],Jr.prototype,"receiveShadows",1),lc([w()],Jr.prototype,"renderMode",1),lc([w(Jr)],Jr.prototype,"rootCanvas",1),lc([w()],Jr.prototype,"scaleFactor",1),lc([w(Li)],Jr.prototype,"worldCamera",2),lc([w()],Jr.prototype,"planeDistance",2);var Ofe=Object.defineProperty,Lfe=Object.getOwnPropertyDescriptor,qk=(n,e,t,r)=>{for(var s=r>1?void 0:r?Lfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Ofe(e,t,s),s};class hd extends Be{constructor(){super(...arguments),d(this,"_alpha",1),d(this,"interactable",!0),d(this,"blocksRaycasts",!0),d(this,"_isDirty",!1),d(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(),Hi.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of ie.getComponentsInChildren(this.gameObject,Va,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}qk([w()],hd.prototype,"alpha",1),qk([w()],hd.prototype,"interactable",2),qk([w()],hd.prototype,"blocksRaycasts",2);var Ffe=Object.defineProperty,Ufe=Object.getOwnPropertyDescriptor,mn=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ufe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Ffe(e,t,s),s};const XV=te("debugusdzbehaviours");function XA(n){n&&(n.getComponentInParent(xA)||(st()&&console.warn("Create Raycaster on "+n.name+" because no raycaster was found in the hierarchy"),n.addNewComponent(No)))}class pm extends Be{constructor(){super(...arguments),d(this,"object"),d(this,"target"),d(this,"duration",1),d(this,"relativeMotion",!1),d(this,"coroutine",null),d(this,"targetPos",new C),d(this,"targetRot",new Ce),d(this,"targetScale",new C)}start(){XA(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=Bt(this.object).clone(),t=Bt(this.target).clone(),r=Mi(this.object).clone(),s=Mi(this.target).clone(),o=Vi(this.object).clone(),a=Vi(this.target).clone(),l=e.distanceTo(t),c=r.angleTo(s),h=o.distanceTo(a);if(l<.01&&c<.01&&h<.01){lr(this.object,t),ca(this.object,s),Uf(this.object,a),this.coroutine=null;return}let u=0,p=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),p=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(e,t,p),this.targetRot.slerpQuaternions(r,s,p),this.targetScale.lerpVectors(o,a,p),lr(this.object,this.targetPos),ca(this.object,this.targetRot),Uf(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),r=this.object.scale.clone(),s=this.target.position.clone(),o=this.target.quaternion.clone(),a=this.target.scale.clone();s.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(s),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(a);let l=0,c=0;for(;l<1;)l+=this.context.time.deltaTime/this.duration,l>1&&(l=1),c=l<.5?4*l*l*l:1-Math.pow(-2*l+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,c),this.object.quaternion.slerpQuaternions(t,this.targetRot,c),this.object.scale.lerpVectors(r,this.targetScale,c),yield;this.coroutine=null}beforeCreateDocument(e){var t;if(this.target&&this.object&&this.gameObject){const r=new Ar("Move to "+((t=this.target)==null?void 0:t.name),br.tapTrigger(this.gameObject),gi.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(r)}}}mn([w(ye)],pm.prototype,"object",2),mn([w(ye)],pm.prototype,"target",2),mn([w()],pm.prototype,"duration",2),mn([w()],pm.prototype,"relativeMotion",2);var oC;const cc=(oC=class extends Be{constructor(){super(...arguments),d(this,"materialToSwitch"),d(this,"variantMaterial"),d(this,"fadeDuration",0),d(this,"_objectsWithThisMaterial",null),d(this,"selfModel"),d(this,"targetModels")}start(){var n;this._objectsWithThisMaterial=this.objectsWithThisMaterial,XA(this.gameObject),st()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((n=this.materialToSwitch)==null?void 0:n.name)+'"')}onPointerEnter(n){this.context.input.setCursorPointer()}onPointerExit(n){this.context.input.setCursorNormal()}onPointerClick(n){if(n.use(),!!this.variantMaterial)for(let e=0;e<this.objectsWithThisMaterial.length;e++){const t=this.objectsWithThisMaterial[e];t.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(n=>{if(n instanceof me)if(Array.isArray(n.material)){for(const e of n.material)if(e===this.materialToSwitch){this.objectsWithThisMaterial.push(n);break}}else n.material===this.materialToSwitch?this.objectsWithThisMaterial.push(n):p6(n.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(n)}),this._objectsWithThisMaterial)}async beforeCreateDocument(n,e){this.targetModels=[],cc._materialTriggersPerId={},cc.variantSwitchIndex=0,this.materialToSwitch&&await fi.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await fi.assignTextureLOD(this.variantMaterial,0)}createBehaviours(n,e,t){this.objectsWithThisMaterial.find(r=>r.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(cc._materialTriggersPerId[this.materialToSwitch.uuid]||(cc._materialTriggersPerId[this.materialToSwitch.uuid]=[]),cc._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(n,e){if(!this.materialToSwitch)return;const t=cc._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const r={};for(const s of t){const o=s.createVariants();o&&o.length>0&&(r[s.selfModel.uuid]=o)}for(const s of t){const o=[];for(const a in r)a!==s.selfModel.uuid&&o.push(...r[a]);s.createAndAttachBehaviors(n,r[s.selfModel.uuid],o)}}delete cc._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(n,e,t){const r=[],s=[],o=Math.max(0,this.fadeDuration);s.push(gi.fadeAction([...this.targetModels,...t],o,!1)),r.push(gi.fadeAction(e,o,!1)),s.push(gi.fadeAction(e,o,!0)),n.addBehavior(new Ar("Select_"+this.selfModel.name,br.tapTrigger(this.selfModel),gi.parallel(...s))),n.addBehavior(new Ar("StartHidden_"+this.selfModel.name,br.sceneStartTrigger(),gi.parallel(...r)))}static getMaterialName(n){return ul(n.name||"Material")+"_"+n.id}createVariants(){if(!this.variantMaterial)return null;const n=[];for(const e of this.targetModels){const t=e.clone();t.name+="_Variant_"+cc.variantSwitchIndex+++"_"+cc.getMaterialName(this.variantMaterial),t.displayName=t.displayName+": Variant with material "+this.variantMaterial.name,t.material=this.variantMaterial,t.geometry=e.geometry,t.matrix=e.matrix,(!e.parent||!e.parent.isEmpty())&&Ws.createEmptyParent(e),e.parent&&e.parent.add(t),n.push(t)}return n}},d(oC,"_materialTriggersPerId",{}),d(oC,"variantSwitchIndex",0),oC);let o0=cc;mn([w(Ot)],o0.prototype,"materialToSwitch",2),mn([w(Ot)],o0.prototype,"variantMaterial",2),mn([w()],o0.prototype,"fadeDuration",2);var a0;const fn=(a0=class extends Be{constructor(){super(...arguments),d(this,"target"),d(this,"toggleOnClick",!1),d(this,"targetState",!0),d(this,"hideSelf",!0),d(this,"selfModel"),d(this,"selfModelClone"),d(this,"targetModel"),d(this,"toggleModel"),d(this,"stateBeforeCreatingDocument",!1),d(this,"targetStateBeforeCreatingDocument",!1)}start(){XA(this.gameObject)}onPointerClick(n){n.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(n,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e,this.selfModelClone=e.clone())}beforeCreateDocument(){this.target&&(this.gameObject[fn.wasVisible]===void 0&&(this.gameObject[fn.wasVisible]=this.gameObject.activeSelf),this.target[fn.wasVisible]===void 0&&(this.target[fn.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[fn.wasVisible],this.targetStateBeforeCreatingDocument=this.target[fn.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(n,e){if(!this.target)return;this.targetModel=e.document.findById(this.target.uuid);const t=this.selfModel;if(this.selfModel&&this.targetModel){let r=this.selfModel,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&e5.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[fn.toggleClone]){const l=this.selfModelClone.clone();l.matrix.identity(),l.name+="_toggle"+fn.clonedToggleIndex++,t.add(l),this.gameObject[fn.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[fn.toggleClone];if(!this.gameObject[fn.reverseToggleClone]){const l=this.selfModelClone.clone();l.matrix.identity(),l.name+="_toggleReverse"+fn.clonedToggleIndex++,t.add(l),this.gameObject[fn.reverseToggleClone]=l}this.toggleModel=this.gameObject[fn.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,t.geometry),r=a,t.geometry=null,t.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(gi.fadeAction(r,0,!1)),a.push(gi.fadeAction(this.toggleModel,0,!0)),a.push(gi.fadeAction(this.targetModel,0,s)),n.addBehavior(new Ar("Toggle_"+r.name+"_toggleTo"+(s?"On":"Off"),br.tapTrigger(r),gi.parallel(...a)));const l=[];l.push(gi.fadeAction(this.toggleModel,0,!1)),l.push(gi.fadeAction(r,0,!0)),l.push(gi.fadeAction(this.targetModel,0,!s)),n.addBehavior(new Ar("Toggle_"+r.name+"_toggleTo"+(s?"Off":"On"),br.tapTrigger(this.toggleModel),gi.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(gi.fadeAction(r,0,!1)),a.push(gi.fadeAction(this.targetModel,0,s)),n.addBehavior(new Ar("Toggle_"+r.name+"_toggleTo"+(s?"On":"Off"),br.tapTrigger(r),gi.parallel(...a)))}const o=new Array;this.targetStateBeforeCreatingDocument||o.push(this.targetModel),this.stateBeforeCreatingDocument||o.push(t),this.toggleModel&&o.push(this.toggleModel),n.addBehavior(new Ar("HideOnStart_"+this.gameObject.name,br.sceneStartTrigger(),gi.fadeAction(o,0,!1)))}}afterSerialize(n,e){this.gameObject[fn.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[fn.wasVisible],delete this.gameObject[fn.wasVisible]),this.target&&this.target[fn.wasVisible]!==void 0&&(this.target.visible=this.target[fn.wasVisible],delete this.target[fn.wasVisible]),delete this.gameObject[fn.toggleClone],delete this.gameObject[fn.reverseToggleClone]}},d(a0,"clonedToggleIndex",0),d(a0,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),d(a0,"toggleClone",Symbol("clone for toggling")),d(a0,"reverseToggleClone",Symbol("clone for reverse toggling")),a0);let mm=fn;mn([w(ye)],mm.prototype,"target",2),mn([w()],mm.prototype,"toggleOnClick",2),mn([w()],mm.prototype,"targetState",2),mn([w()],mm.prototype,"hideSelf",2);class Yk extends Be{constructor(){super(...arguments),d(this,"wasVisible",!1)}start(){ie.setActive(this.gameObject,!1)}createBehaviours(e,t,r){t.uuid===this.gameObject.uuid&&(this.wasVisible||e.addBehavior(new Ar("HideOnStart_"+this.gameObject.name,br.sceneStartTrigger(),gi.fadeAction(t,0,!1))))}beforeCreateDocument(){this.wasVisible=ie.isActiveSelf(this.gameObject)}}class l0 extends Be{constructor(){super(...arguments),d(this,"target"),d(this,"duration",.5),d(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(e,t,r){if(this.target&&t.uuid===this.gameObject.uuid){const s=new Ar("emphasize "+this.name,br.tapTrigger(this.gameObject),gi.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(s)}}afterCreateDocument(e,t){}}mn([w()],l0.prototype,"target",2),mn([w()],l0.prototype,"duration",2),mn([w()],l0.prototype,"motionType",2);class ud extends Be{constructor(){super(...arguments),d(this,"target"),d(this,"clip",""),d(this,"toggleOnClick",!1),d(this,"trigger","tap")}start(){XA(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addNewComponent(Mn);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){var t;e.use(),!(!((t=this.target)!=null&&t.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,t,r){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const s=this.clip?this.clip:this.target?this.target.clip:void 0;if(!s||typeof s!="string")return;const o=this.target?this.target.gameObject:this.gameObject;Pd.getName(s);const a=this.target?this.target.volume:1,l=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let c=!1;this.gameObject.traverse(m=>{m instanceof me&&m.visible&&(c=!0)}),c=!0;const h=e.addAudioClip(s);let u=gi.playAudioAction(o,h,"play",a,l);this.target&&this.target.loop&&(u=gi.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(c&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const m=new Ar("playAudio"+p,br.tapTrigger(t),u);e.addBehavior(m)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(c&&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 m=new Ar("playAudioOnStart"+p,br.sceneStartTrigger(),u);e.addBehavior(m)}}}}mn([w(Mn)],ud.prototype,"target",2),mn([w(URL)],ud.prototype,"clip",2),mn([w()],ud.prototype,"toggleOnClick",2);var aC;const hc=(aC=class extends Be{constructor(){super(...arguments),d(this,"animator"),d(this,"stateName"),d(this,"trigger","tap"),d(this,"animation"),d(this,"selfModel"),d(this,"stateAnimationModel"),d(this,"animationSequence",new Array),d(this,"animationLoopAfterSequence",new Array)}get target(){var n,e;return((n=this.animator)==null?void 0:n.gameObject)||((e=this.animation)==null?void 0:e.gameObject)}start(){XA(this.gameObject)}onPointerClick(n){var e;n.use(),this.target&&this.stateName&&((e=this.animator)==null||e.play(this.stateName,0,0,.1))}createBehaviours(n,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}afterSerialize(){if(hc.rootsWithExclusivePlayback.size>1){const n='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.';st()&&Di(n),console.warn(n,...hc.rootsWithExclusivePlayback)}hc.animationActions=[],hc.rootsWithExclusivePlayback=new Set}afterCreateDocument(n,e){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const t=e.document,r=e.extensions.find(a=>a instanceof BA);if(!r)return;const s=r.getClipCount(this.target)>1;s&&(st()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+r.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),hc.rootsWithExclusivePlayback.add(this.target));const o=this.name?this.name:"";t.traverse(a=>{var l,c;if(a.uuid===((l=this.target)==null?void 0:l.uuid)){const h=hc.getActionForSequences(a,this.animationSequence,this.animationLoopAfterSequence),u=new Ar(this.trigger+"_"+o+"_toPlayAnimation_"+this.stateName+"_on_"+((c=this.target)==null?void 0:c.name),this.trigger=="tap"?br.tapTrigger(this.selfModel):br.sceneStartTrigger(),h);s&&u.makeExclusive(!0),n.addBehavior(u)}})}static getActionForSequences(n,e,t){const r=(o,a)=>{let l=hc.animationActions.find(c=>c.affectedObjects==o&&c.start==a.start&&c.duration==a.duration&&c.animationSpeed==a.speed);return l||(l=gi.startAnimationAction(o,a.start,a.duration,a.speed),hc.animationActions.push(l)),l},s=gi.sequence();if(e&&e.length>0)for(const o of e)s.addAction(r(n,o));if(t&&t.length>0){const o=s.actions.length==0?s:gi.sequence();for(const a of t)o.addAction(r(n,a));o.makeLooping(),s!==o&&s.addAction(o)}return s}static getAndRegisterAnimationSequences(n,e,t){var r,s,o,a,l;if(!e)return;const c=e.getComponent(Wr),h=e.getComponent(Es);if(!c&&!h)return;if(c&&!t)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+c.name+" on "+e.name);let u=[],p=[];if(h){const A=n.registerAnimation(e,h.clip);return A&&(h.loop?p.push(A):u.push(A)),{animationSequence:u,animationLoopAfterSequence:p}}const m=c?.runtimeAnimatorController;let f=m?.findState(t),g=[],v=[];if(m&&f){const A=new Array;A.push(f);let _=!1;for(;A.length<100;){if(!f||f===null||!f.transitions||f.transitions.length===0){(r=f.motion)!=null&&r.isLooping&&(_=!0);break}const b=f.transitions.find(E=>E.conditions.length===0),x=b?m.getState(b.destinationState,0):null;if(x&&A.includes(x)){f=x,_=!0;break}else if(b){if(f=x,!f)break;A.push(f)}else{_=((s=f.motion)==null?void 0:s.isLooping)??!1;break}}if(_&&f){const b=A.indexOf(f);g=A.slice(0,b),v=A.slice(b),XV&&console.log("found loop from "+t,"states until loop",g,"states looping",v)}else g=A,v=[],XV&&console.log("found no loop from "+t,"states",g)}if(g.length===1&&(!((o=g[0].motion)!=null&&o.clip)||((l=(a=g[0].motion)==null?void 0:a.clip.tracks)==null?void 0:l.length)===0)){u=new Array;const A=n.registerAnimation(e,null);A&&u.push(A);return}if(g=g.filter(A=>{var _,b,x;return((_=A.motion)==null?void 0:_.clip)&&((x=(b=A.motion)==null?void 0:b.clip.tracks)==null?void 0:x.length)>0}),v=v.filter(A=>{var _,b,x;return((_=A.motion)==null?void 0:_.clip)&&((x=(b=A.motion)==null?void 0:b.clip.tracks)==null?void 0:x.length)>0}),g.length===0&&v.length===0){console.warn("No clips found for state "+t+" on "+c?.name+", can't export animation data");return}const y=(A,_)=>{if(!e)return;const b=n.registerAnimation(e,A.motion.clip??null);b?(b.speed=A.speed,_.push(b)):console.warn("Couldn't register animation for state "+A.name+" on "+c?.name)};if(g.length>0){u=new Array;for(const A of g)y(A,u)}if(v.length>0){p=new Array;for(const A of v)y(A,p)}return{animationSequence:u,animationLoopAfterSequence:p}}createAnimation(n,e,t){if(!this.target||!this.animator&&!this.animation)return;const r=hc.getAndRegisterAnimationSequences(n,this.target,this.stateName);r&&(this.animationSequence=r.animationSequence,this.animationLoopAfterSequence=r.animationLoopAfterSequence,this.stateAnimationModel=e)}},d(aC,"animationActions",[]),d(aC,"rootsWithExclusivePlayback",new Set),aC);let fm=hc;mn([w(Wr)],fm.prototype,"animator",2),mn([w()],fm.prototype,"stateName",2);class c0 extends Be{constructor(){super(...arguments),d(this,"target")}getType(){}getDuration(){}}mn([w(ye)],c0.prototype,"target",2);class qA extends Be{constructor(){super(...arguments),d(this,"target")}}mn([w(c0)],qA.prototype,"target",2);class YA extends c0{constructor(){super(...arguments),d(this,"type",1),d(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}mn([w()],YA.prototype,"type",2),mn([w()],YA.prototype,"duration",2);class Jk extends qA{}var Nfe=Object.defineProperty,zfe=Object.getOwnPropertyDescriptor,Mh=(n,e,t,r)=>{for(var s=r>1?void 0:r?zfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Nfe(e,t,s),s};const qV=te("debugcharactercontroller");class gm extends Be{constructor(){super(...arguments),d(this,"center",new C(0,0,0)),d(this,"radius",.5),d(this,"height",2),d(this,"_rigidbody",null),d(this,"_activeGroundCollisions"),d(this,"_contactVelocity",new C)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Oi),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(Oi)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Ch);t||(t=this.gameObject.addNewComponent(Ch)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const r=new C(0,0,1),s=new C(1,0,0),o=new C(0,1,0),a=this.gameObject.getWorldDirection(new C);a.y=0;const l=s.dot(a)<0?-1:1,c=r.angleTo(a)*l;this.gameObject.setRotationFromAxisAngle(o,c),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(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),qV&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),qV&&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 t of this._activeGroundCollisions){const r=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(t.collider);r&&(this._contactVelocity.x+=r.x,this._contactVelocity.y+=r.y,this._contactVelocity.z+=r.z)}return this._contactVelocity}}Mh([w(C)],gm.prototype,"center",2),Mh([w()],gm.prototype,"radius",2),Mh([w()],gm.prototype,"height",2);class Th extends Be{constructor(){super(...arguments),d(this,"controller"),d(this,"movementSpeed",2),d(this,"rotationSpeed",2),d(this,"jumpForce",1),d(this,"doubleJumpForce",2),d(this,"animator"),d(this,"lookForward",!0),d(this,"lookInput",new Z(0,0)),d(this,"moveInput",new Z(0,0)),d(this,"jumpInput",!1),d(this,"_currentSpeed",new C(0,0,0)),d(this,"_currentAngularSpeed",new C(0,0,0)),d(this,"_temp",new C(0,0,0)),d(this,"_jumpCount",0),d(this,"_currentRotation"),d(this,"_raycastOptions",new ml)}awake(){this._currentRotation=new Ce}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,t,r){var s,o,a,l,c,h,u,p,m,f,g;if((s=this.controller)!=null&&s.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((o=this.animator)==null||o.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(a=this.animator)==null||a.setBool("running",e.length()>.01),(c=this.animator)==null||c.setBool("jumping",((l=this.controller)==null?void 0:l.isGrounded)===!0&&r),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+=it.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const v=this.context.mainCameraComponent.forward;v.y=0,v.normalize(),this._currentRotation.setFromUnitVectors(new C(0,0,1),v),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&&r&&this.jumpForce>0){let v=(h=this.controller)==null?void 0:h.isGrounded;if(this.doubleJumpForce>0&&!((u=this.controller)!=null&&u.isGrounded)&&this._jumpCount===1&&(v=!0,(p=this.animator)==null||p.setBool("doubleJump",!0)),v){this._jumpCount+=1;const y=this.controller.rigidbody,A=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;y.applyImpulse(new C(0,1,0).multiplyScalar(A))}}if(this.controller){const v=(m=this.controller)==null?void 0:m.rigidbody.getVelocity().y;if(v<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new co),this._raycastOptions.ray.origin.copy(Bt(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const y=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const A=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(y),(A.length&&A[0].distance>2||v<-10)&&((f=this.animator)==null||f.setBool("falling",!0))}else(g=this.animator)==null||g.setBool("falling",!1)}}}Mh([w(gm)],Th.prototype,"controller",2),Mh([w()],Th.prototype,"movementSpeed",2),Mh([w()],Th.prototype,"rotationSpeed",2),Mh([w()],Th.prototype,"jumpForce",2),Mh([w()],Th.prototype,"doubleJumpForce",2),Mh([w(Wr)],Th.prototype,"animator",2);var jfe=Object.defineProperty,Gfe=Object.getOwnPropertyDescriptor,Vfe=(n,e,t,r)=>{for(var s=r>1?void 0:r?Gfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&jfe(e,t,s),s};class JA extends Xr{constructor(){super(...arguments),d(this,"intensity",new qe(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new J5;return e.offset=new Z(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}Vfe([w(qe)],JA.prototype,"intensity",2),Ra("ChromaticAberration",JA);var Qfe=Object.defineProperty,Hfe=Object.getOwnPropertyDescriptor,YV=(n,e,t,r)=>{for(var s=r>1?void 0:r?Hfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Qfe(e,t,s),s};const JV=te("debugpost");var lC=(n=>(n[n.None=0]="None",n[n.Neutral=1]="Neutral",n[n.ACES=2]="ACES",n[n.AgX=3]="AgX",n[n.KhronosNeutral=4]="KhronosNeutral",n))(lC||{});function Kk(n){switch(n){case 0:return Xm;case 1:return tv;case 2:return iv;case 3:return qm;case 4:return Ud;default:return Ud}}function Wfe(n){switch(n){case Xm:return 0;case iv:return 2;case qm:return 3;case Ud:return 1;case tv:return 1;default:return 0}}function KV(n){switch(n){case Xm:return _r.LINEAR;case iv:return _r.ACES_FILMIC;case qm:return _r.AGX;case Ud:return _r.NEUTRAL;case tv:return _r.REINHARD;default:return _r.LINEAR}}const ZV=class extends Xr{constructor(){super(...arguments),d(this,"mode",new qe(void 0)),d(this,"exposure",new qe(1))}get typeName(){return"ToneMapping"}setMode(n){const e=lC[n];return e===void 0?(console.error("Invalid ToneMapping mode",n),this):(this.mode.value=e,this)}get isToneMapping(){return!0}onEffectEnabled(){const n=EV(this);n&&super.onEffectEnabled(n)}onCreateEffect(){if(this.postprocessingContext)for(const t of this.postprocessingContext.components){if(t===this)break;if(t!=this&&t instanceof ZV){console.warn("Multiple tonemapping effects found in the same postprocessing stack: Please check your scene setup.",{activeEffect:t,ignoredEffect:this});return}}if(this.mode.isInitialized==!1){const t=Wfe(this.context.renderer.toneMapping);this.mode.initialize(t)}const n=Kk(this.mode.value),e=new U1({mode:KV(n)});return this.mode.onValueChanged=t=>{const r=Kk(t);e.mode=KV(r),JV&&console.log("ToneMapping mode changed to",lC[t],r,e.mode)},JV&&console.log("Use ToneMapping",lC[this.mode.value],n,e.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),this.exposure.onValueChanged=t=>{this.context.renderer.toneMappingExposure=t},e}onBeforeRender(){this.mode.overrideState&&(this.context.renderer.toneMapping=Kk(this.mode.value)),this.exposure.overrideState&&(this.context.renderer.toneMappingExposure=this.exposure.value)}};let dd=ZV;YV([w(qe)],dd.prototype,"mode",2),YV([w(qe)],dd.prototype,"exposure",2),Ra("Tonemapping",dd);var Xfe=Object.defineProperty,qfe=Object.getOwnPropertyDescriptor,cC=(n,e,t,r)=>{for(var s=r>1?void 0:r?qfe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Xfe(e,t,s),s};class pd extends Xr{constructor(){super(...arguments),d(this,"postExposure",new qe(0)),d(this,"contrast",new qe(0)),d(this,"hueShift",new qe(0)),d(this,"saturation",new qe(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(e=Math.pow(2,e),e),this.contrast.valueProcessor=e=>{let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>Math.PI*e/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>e<0?e/100:e/(100*Math.PI),this.saturation.defaultValue=0}onCreateEffect(){var e,t;const r=[];this.context.renderer.toneMapping!==Ls&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=Ls);let s=(e=this.postprocessingContext)==null?void 0:e.components.find(l=>l instanceof dd);s||(s=new dd,(t=this.postprocessingContext)==null||t.components.push(s)),this.postExposure.onValueChanged=l=>{this.postExposure.overrideState&&(s.exposure.value=l)};const o=new Y5;this.contrast.onValueChanged=l=>o.contrast=l;const a=new e6;return r.push(o),r.push(a),this.hueShift.onValueChanged=l=>a.hue=l,this.saturation.onValueChanged=l=>a.saturation=l,r}}cC([w(qe)],pd.prototype,"postExposure",2),cC([w(qe)],pd.prototype,"contrast",2),cC([w(qe)],pd.prototype,"hueShift",2),cC([w(qe)],pd.prototype,"saturation",2),Ra("ColorAdjustments",pd);const Yfe=(Math.sqrt(5)-1)/4,Kr=(5-Math.sqrt(5))/20,hC=n=>Math.floor(n)|0,uC=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);function Jfe(n=Math.random){const e=Kfe(n),t=new Float64Array(e).map(a=>uC[a%32*4]),r=new Float64Array(e).map(a=>uC[a%32*4+1]),s=new Float64Array(e).map(a=>uC[a%32*4+2]),o=new Float64Array(e).map(a=>uC[a%32*4+3]);return function(a,l,c,h){let u,p,m,f,g;const v=(a+l+c+h)*Yfe,y=hC(a+v),A=hC(l+v),_=hC(c+v),b=hC(h+v),x=(y+A+_+b)*Kr,E=y-x,I=A-x,T=_-x,R=b-x,D=a-E,M=l-I,P=c-T,z=h-R;let V=0,L=0,H=0,O=0;D>M?V++:L++,D>P?V++:H++,D>z?V++:O++,M>P?L++:H++,M>z?L++:O++,P>z?H++:O++;const F=V>=3?1:0,G=L>=3?1:0,J=H>=3?1:0,K=O>=3?1:0,oe=V>=2?1:0,we=L>=2?1:0,De=H>=2?1:0,se=O>=2?1:0,be=V>=1?1:0,Ie=L>=1?1:0,Je=H>=1?1:0,$e=O>=1?1:0,Oe=D-F+Kr,lt=M-G+Kr,fe=P-J+Kr,X=z-K+Kr,ze=D-oe+2*Kr,Te=M-we+2*Kr,Me=P-De+2*Kr,Qe=z-se+2*Kr,Ae=D-be+3*Kr,et=M-Ie+3*Kr,ct=P-Je+3*Kr,Tt=z-$e+3*Kr,Q=D-1+4*Kr,k=M-1+4*Kr,he=P-1+4*Kr,Ee=z-1+4*Kr,Le=y&255,Pe=A&255,vt=_&255,ht=b&255;let je=.6-D*D-M*M-P*P-z*z;if(je<0)u=0;else{const Fe=Le+e[Pe+e[vt+e[ht]]];je*=je,u=je*je*(t[Fe]*D+r[Fe]*M+s[Fe]*P+o[Fe]*z)}let Ve=.6-Oe*Oe-lt*lt-fe*fe-X*X;if(Ve<0)p=0;else{const Fe=Le+F+e[Pe+G+e[vt+J+e[ht+K]]];Ve*=Ve,p=Ve*Ve*(t[Fe]*Oe+r[Fe]*lt+s[Fe]*fe+o[Fe]*X)}let St=.6-ze*ze-Te*Te-Me*Me-Qe*Qe;if(St<0)m=0;else{const Fe=Le+oe+e[Pe+we+e[vt+De+e[ht+se]]];St*=St,m=St*St*(t[Fe]*ze+r[Fe]*Te+s[Fe]*Me+o[Fe]*Qe)}let Ue=.6-Ae*Ae-et*et-ct*ct-Tt*Tt;if(Ue<0)f=0;else{const Fe=Le+be+e[Pe+Ie+e[vt+Je+e[ht+$e]]];Ue*=Ue,f=Ue*Ue*(t[Fe]*Ae+r[Fe]*et+s[Fe]*ct+o[Fe]*Tt)}let qt=.6-Q*Q-k*k-he*he-Ee*Ee;if(qt<0)g=0;else{const Fe=Le+1+e[Pe+1+e[vt+1+e[ht+1]]];qt*=qt,g=qt*qt*(t[Fe]*Q+r[Fe]*k+s[Fe]*he+o[Fe]*Ee)}return 27*(u+p+m+f+g)}}function Kfe(n){const e=new Uint8Array(512);for(let t=0;t<512/2;t++)e[t]=t;for(let t=0;t<512/2-1;t++){const r=t+~~(n()*(256-t)),s=e[t];e[t]=e[r],e[r]=s}for(let t=256;t<512;t++)e[t]=e[t-256];return e}const Zk=te("debugstencil");function Zfe(n,e){return(n&1<<e.layer)!=0}const $fe=Symbol("stencils"),h0=class{constructor(n,e){d(this,"parser"),d(this,"source"),this.parser=n,this.source=e}get name(){return"NEEDLE_render_objects"}static applyStencil(n){if(!n)return;const e=n.sourceId;if(Zk&&console.log(e,h0.stencils),!e)return;const t=h0.stencils[e];if(t)for(let r=t.length-1;r>=0;r--){const s=t[r];if(Zfe(s.layer,n)){Zk&&console.log(s),setTimeout(()=>{js()&&CS(n.gameObject)&&(Di("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",n))},500);for(let o=0;o<n.sharedMaterials.length;o++){let a=n.sharedMaterials[o];a&&(a=a.clone(),a[$fe]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=s.value,a.stencilFunc=s.compareFunc,a.stencilZPass=s.passOp,a.stencilFail=s.failOp,a.stencilZFail=s.zFailOp,n.sharedMaterials[o]=a)}n.gameObject.renderOrder=s.event*1e3+s.index*50;break}}}afterRoot(n){const e=this.parser.json.extensions;if(e){const t=e[tge];if(t){Zk&&console.log(t);const r=t.stencil;if(r&&Array.isArray(r))for(const s of r){const o={...s};o.compareFunc=ege(o.compareFunc),o.passOp=eD(o.passOp),o.failOp=eD(o.failOp),o.zFailOp=eD(o.zFailOp),h0.stencils[this.source]||(h0.stencils[this.source]=[]),h0.stencils[this.source].push(o)}}}return null}};let $k=h0;d($k,"stencils",{});function eD(n){switch(n){case 0:return Kh;case 1:return jL;case 2:return GL;case 3:return VL;case 4:return QL;case 6:return HL;case 7:return WL;case 5:return XL}return 0}function ege(n){switch(n){case 1:return YM;case 2:return qL;case 3:return YL;case 4:return JL;case 5:return KL;case 6:return ZL;case 7:return $L;case 8:return B_}return YM}const tge="NEEDLE_render_objects";var ige=Object.defineProperty,nge=Object.getOwnPropertyDescriptor,$V=(n,e,t,r)=>{for(var s=r>1?void 0:r?nge(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ige(e,t,s),s};const KA=te("debugreflectionprobe"),eQ=te("noreflectionprobe"),rge=Symbol("reflectionProbeKey"),sge=Symbol("original material");var dC;const Ih=(dC=class extends Be{constructor(){var n;super(),d(this,"_texture"),d(this,"center"),d(this,"size"),d(this,"_boxHelper"),Ih._probes.has(this.context)||Ih._probes.set(this.context,[]),(n=Ih._probes.get(this.context))==null||n.push(this)}static get(n,e,t,r){if(!n||n.isObject3D!==!0||eQ)return null;const s=Ih._probes.get(e);if(s){for(const o of s)if(o.__didAwake||o.__internalAwake(),o.enabled){if(r){if(o.gameObject===r)return o}else if(o.isInBox(n,void 0))return KA&&console.log("Found reflection probe",n.name,o.name),o}}return KA&&console.debug("Did not find reflection probe",n.name,t,n),null}set texture(n){if(n&&!(n instanceof zt)){console.error("ReflectionProbe.texture must be a Texture",n);return}this._texture=n,n&&(n.mapping=so,n.colorSpace=ft,n.needsUpdate=!0)}get texture(){return this._texture}isInBox(n,e){var t;return(t=this._boxHelper)==null?void 0:t.isInBox(n,e)}awake(){this._boxHelper=this.gameObject.addNewComponent(ac),this._boxHelper.updateBox(!0),KA&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=so,this.texture.colorSpace=ft,this.texture.needsUpdate=!0)}onDestroy(){const n=Ih._probes.get(this.context);if(n){const e=n.indexOf(this);e>=0&&n.splice(e,1)}}onSet(n){var e;if(eQ||!this.enabled||((e=n.sharedMaterials)==null?void 0:e.length)<=0||!this.texture)return;let t=Ih._rendererMaterialsCache.get(n);t||(t=[],Ih._rendererMaterialsCache.set(n,t));for(let r=0;r<n.sharedMaterials.length;r++){const s=n.sharedMaterials[r];if(!s||s.envMap===void 0||s instanceof $t)continue;let o=t[r];const a=s===o?.copy,l=!o||o.material.uuid!==s.uuid||o.copy.version!==s.version;if(!a&&l){if(KA){let u="";o?o.material!==s?u="reference changed; cached instance?: "+a:o.copy.version!==s.version&&(u="version changed"):u="not cached",console.warn("Cloning material",s.name,s.version,"Reason:",u,`
5739
5739
  `,s.uuid,`
5740
5740
  `,o?.copy.uuid,`
5741
- `,n.name)}const h=s.clone();h.version=s.version,o?(o.copy=h,o.material=s):(o={material:s,copy:h},t.push(o)),h[rge]=this,h[sge]=s,KA&&console.log("Set reflection",n.name,n.guid)}o&&o.copy&&(o.copy.onBeforeCompile=s.onBeforeCompile);const c=o?.copy;c.envMap=this.texture,n.sharedMaterials[r]=c}}onUnset(n){const e=Ih._rendererMaterialsCache.get(n);if(e)for(let t=0;t<e.length;t++){const r=e[t];n.sharedMaterials[t]=r.material}}},d(dC,"_probes",new Map),d(dC,"_rendererMaterialsCache",new Map),dC);let u0=Ih;$8([w(C)],u0.prototype,"center",2),$8([w(C)],u0.prototype,"size",2);const tD=te("debugexr");class oge{constructor(e){d(this,"parser"),this.parser=e,tD&&console.log(e)}get name(){return"EXT_texture_exr"}loadTexture(e){const t=this.name,r=this.parser,s=r.json.textures[e];if(tD&&console.log("EXT_texture_exr.loadTexture",e,s),!s.extensions||!s.extensions[t])return null;const o=s.extensions[t],a=new oA(r.options.manager);return tD&&console.log("EXT_texture_exr.loadTexture",o),r.loadTextureImage(e,o.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",n=>{});const Rh=xr,pC="$___Export_Components",age="NEEDLE_components";var tQ;class lge{constructor(){d(this,tQ)}}tQ=wp;class cge{constructor(e,t,r){d(this,"node"),d(this,"nodeIndex"),d(this,"nodeDef"),this.node=e,this.nodeIndex=t,this.nodeDef=r}}class hge{constructor(){d(this,"parser"),d(this,"nodeToObjectMap",{}),d(this,"exportContext"),d(this,"objectToNodeMap",{}),d(this,"context"),d(this,"writer")}get name(){return age}registerExport(e){e.register(t=>{if("serializeUserData"in t){const r=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(s,o)=>{try{this.serializeUserData(s,o),r(s,o)}finally{this.afterSerializeUserData(s,o)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){var r;const s=(r=e.userData)==null?void 0:r.components;!s||s.length<=0||(delete e.userData.components,e[pC]=s)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Rh&&console.log("DONE",JSON.stringify(t)),e[pC]===void 0)return;const r=e[pC];delete e[pC],r!==null&&(e.userData.components=r)}writeNode(e,t){const r=this.writer.json.nodes.length;Rh&&console.log(e.name,r,e.uuid);const s=new cge(e,r,t);this.exportContext[r]=s,this.objectToNodeMap[e.uuid]=r}afterParse(e){var t;Rh&&console.log("AFTER",e);for(const r in this.exportContext){const s=this.exportContext[r],o=s.node,a=s.nodeDef,l=s.nodeIndex,c=(t=o.userData)==null?void 0:t.components;if(!c||c.length<=0)continue;const h=new lge;a.extensions=a.extensions||{},a.extensions[this.name]=h,this.context.object=o,this.context.nodeId=l,this.context.objectToNode=this.objectToNodeMap;const u=[];for(const p of c){this.context.target=p;const m=Ka().writeBuiltinComponentData(p,this.context);m!==null&&u.push(m)}u.length>0&&(h[wp]=u,Rh&&console.log("DID WRITE",o,"nodeIndex",l,u))}}beforeRoot(){return Rh&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){const t=e.parser,r=t?.extensions;if(!r)return;const s=r[this.name];Rh&&console.log("After root",e,this.parser,r);const o=[];if(s===!0){const a=t.json.nodes;if(a){for(let l=0;l<a.length;l++){const c=await t.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 p=u[this.name];if(!p)continue;Rh&&console.log("NODE",c);const m=this.nodeToObjectMap[h];if(!m){console.error("Could not find object for node index: "+h,c,t);continue}IS(m),o.push(this.createComponents(m,p))}}}await Promise.all(o);for(const a of t.associations.keys()){const l=t.associations.get(a);if(l?.materials!=null){const c="/materials/"+l.materials;Whe(a,c)}}}async createComponents(e,t){if(!t)return;const r=t[wp];if(r){const s=new Array;Rh&&console.log(e.name,r);for(const o in r){const a=r[o];Rh&&console.log("Serialized data",JSON.parse(JSON.stringify(a))),a&&this.parser&&s.push(nB(this.parser,a).catch(l=>console.error(`Error while resolving references (see console for details)
5741
+ `,n.name)}const h=s.clone();h.version=s.version,o?(o.copy=h,o.material=s):(o={material:s,copy:h},t.push(o)),h[rge]=this,h[sge]=s,KA&&console.log("Set reflection",n.name,n.guid)}o&&o.copy&&(o.copy.onBeforeCompile=s.onBeforeCompile);const c=o?.copy;c.envMap=this.texture,n.sharedMaterials[r]=c}}onUnset(n){const e=Ih._rendererMaterialsCache.get(n);if(e)for(let t=0;t<e.length;t++){const r=e[t];n.sharedMaterials[t]=r.material}}},d(dC,"_probes",new Map),d(dC,"_rendererMaterialsCache",new Map),dC);let u0=Ih;$V([w(C)],u0.prototype,"center",2),$V([w(C)],u0.prototype,"size",2);const tD=te("debugexr");class oge{constructor(e){d(this,"parser"),this.parser=e,tD&&console.log(e)}get name(){return"EXT_texture_exr"}loadTexture(e){const t=this.name,r=this.parser,s=r.json.textures[e];if(tD&&console.log("EXT_texture_exr.loadTexture",e,s),!s.extensions||!s.extensions[t])return null;const o=s.extensions[t],a=new oA(r.options.manager);return tD&&console.log("EXT_texture_exr.loadTexture",o),r.loadTextureImage(e,o.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",n=>{});const Rh=xr,pC="$___Export_Components",age="NEEDLE_components";var tQ;class lge{constructor(){d(this,tQ)}}tQ=wp;class cge{constructor(e,t,r){d(this,"node"),d(this,"nodeIndex"),d(this,"nodeDef"),this.node=e,this.nodeIndex=t,this.nodeDef=r}}class hge{constructor(){d(this,"parser"),d(this,"nodeToObjectMap",{}),d(this,"exportContext"),d(this,"objectToNodeMap",{}),d(this,"context"),d(this,"writer")}get name(){return age}registerExport(e){e.register(t=>{if("serializeUserData"in t){const r=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(s,o)=>{try{this.serializeUserData(s,o),r(s,o)}finally{this.afterSerializeUserData(s,o)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){var r;const s=(r=e.userData)==null?void 0:r.components;!s||s.length<=0||(delete e.userData.components,e[pC]=s)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Rh&&console.log("DONE",JSON.stringify(t)),e[pC]===void 0)return;const r=e[pC];delete e[pC],r!==null&&(e.userData.components=r)}writeNode(e,t){const r=this.writer.json.nodes.length;Rh&&console.log(e.name,r,e.uuid);const s=new cge(e,r,t);this.exportContext[r]=s,this.objectToNodeMap[e.uuid]=r}afterParse(e){var t;Rh&&console.log("AFTER",e);for(const r in this.exportContext){const s=this.exportContext[r],o=s.node,a=s.nodeDef,l=s.nodeIndex,c=(t=o.userData)==null?void 0:t.components;if(!c||c.length<=0)continue;const h=new lge;a.extensions=a.extensions||{},a.extensions[this.name]=h,this.context.object=o,this.context.nodeId=l,this.context.objectToNode=this.objectToNodeMap;const u=[];for(const p of c){this.context.target=p;const m=Ka().writeBuiltinComponentData(p,this.context);m!==null&&u.push(m)}u.length>0&&(h[wp]=u,Rh&&console.log("DID WRITE",o,"nodeIndex",l,u))}}beforeRoot(){return Rh&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){const t=e.parser,r=t?.extensions;if(!r)return;const s=r[this.name];Rh&&console.log("After root",e,this.parser,r);const o=[];if(s===!0){const a=t.json.nodes;if(a){for(let l=0;l<a.length;l++){const c=await t.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 p=u[this.name];if(!p)continue;Rh&&console.log("NODE",c);const m=this.nodeToObjectMap[h];if(!m){console.error("Could not find object for node index: "+h,c,t);continue}IS(m),o.push(this.createComponents(m,p))}}}await Promise.all(o);for(const a of t.associations.keys()){const l=t.associations.get(a);if(l?.materials!=null){const c="/materials/"+l.materials;Whe(a,c)}}}async createComponents(e,t){if(!t)return;const r=t[wp];if(r){const s=new Array;Rh&&console.log(e.name,r);for(const o in r){const a=r[o];Rh&&console.log("Serialized data",JSON.parse(JSON.stringify(a))),a&&this.parser&&s.push(nB(this.parser,a).catch(l=>console.error(`Error while resolving references (see console for details)
5742
5742
  `,l,e,a))),e.userData=e.userData||{},e.userData[wp]=e.userData[wp]||[],e.userData[wp].push(a)}await Promise.all(s).catch(o=>{console.error("Error while loading components",o)})}}}const iQ="NEEDLE_gameobject_data";class uge{constructor(e){d(this,"parser"),this.parser=e}get name(){return iQ}afterRoot(e){var t;const r=[];for(let s=0;s<((t=this.parser.json.nodes)==null?void 0:t.length);s++){const o=this.parser.json.nodes[s];if(o&&o.extensions){const a=o.extensions[iQ];if(a){const l=this.findAndApplyExtensionData(s,a);r.push(l)}}}return Promise.all(r).then(()=>null)}async findAndApplyExtensionData(e,t){const r=await this.parser.getDependency("node",e);r&&this.applyExtensionData(r,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.userData.hideFlags=t.hideFlags??0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const nQ="NEEDLE_lighting_settings",d0=te("debugenvlight");class dge{constructor(e,t,r){d(this,"parser"),d(this,"sourceId"),d(this,"context"),this.parser=e,this.sourceId=t,this.context=r}get name(){return nQ}afterRoot(e){const t=this.parser.json.extensions;if(t){const r=t[nQ];if(r){d0&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',r);let s;if(e.scene.children.length===1){const o=e.scene.children[0];s=ie.addNewComponent(o,mC,{},!1)}else{const o=new ye;o.name="LightSettings "+this.sourceId,e.scene.add(o),s=ie.addNewComponent(o,mC,{},!1)}s.sourceId=this.sourceId,s.ambientIntensity=r.ambientIntensity,s.ambientLight=new xe().fromArray(r.ambientLight),Array.isArray(r.ambientTrilight)&&(s.ambientTrilight=r.ambientTrilight.map(o=>new xe().fromArray(o))),s.ambientMode=r.ambientMode,s.environmentReflectionSource=r.environmentReflectionSource}}return null}}di.registerCallback(Ci.ContextCreated,n=>{const e=n.context,t=ie.findObjectOfType(mC,e);t!=null&&t.sourceId&&(t.enabled=!0)});class mC extends Be{constructor(){super(...arguments),d(this,"ambientMode",Ng.Skybox),d(this,"ambientLight"),d(this,"ambientTrilight"),d(this,"ambientIntensity",1),d(this,"environmentReflectionSource",gS.Skybox),d(this,"_hasReflection",!1),d(this,"_ambientLightObj"),d(this,"_hemisphereLightObj")}awake(){var e;if(this.sourceId){const r=this.environmentReflectionSource===gS.Skybox?Hu.Skybox:Hu.Reflection,s=this.context.lightmaps.tryGet(this.sourceId,r,0);this._hasReflection=s!=null,s&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,s)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),d0&&window.addEventListener("keydown",r=>{if(!this.destroyed)switch(r.key){case"l":this.enabled=!this.enabled;break}});const t=(e=this.gameObject.userData)==null?void 0:e.components;if(t){const r=t.indexOf(this);t.splice(r,1),t.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*it.lerp(0,1.33,t)}onEnable(){if(d0&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ng.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new Ox(this.ambientLight,this.ambientIntensity*e),d0&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ng.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],r=this.calculateIntensityFactor(t);this._hemisphereLightObj=new uI(t,e,this.ambientIntensity*r),this.gameObject.add(this._hemisphereLightObj),d0&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,r)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){d0&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}var rQ=(n=>(n[n.INT=5124]="INT",n[n.FLOAT=5126]="FLOAT",n[n.FLOAT_VEC2=35664]="FLOAT_VEC2",n[n.FLOAT_VEC3=35665]="FLOAT_VEC3",n[n.FLOAT_VEC4=35666]="FLOAT_VEC4",n[n.INT_VEC2=35667]="INT_VEC2",n[n.INT_VEC3=35668]="INT_VEC3",n[n.INT_VEC4=35669]="INT_VEC4",n[n.BOOL=35670]="BOOL",n[n.BOOL_VEC2=35671]="BOOL_VEC2",n[n.BOOL_VEC3=35672]="BOOL_VEC3",n[n.BOOL_VEC4=35673]="BOOL_VEC4",n[n.FLOAT_MAT2=35674]="FLOAT_MAT2",n[n.FLOAT_MAT3=35675]="FLOAT_MAT3",n[n.FLOAT_MAT4=35676]="FLOAT_MAT4",n[n.SAMPLER_2D=35678]="SAMPLER_2D",n[n.SAMPLER_3D=35680]="SAMPLER_3D",n[n.SAMPLER_CUBE=35681]="SAMPLER_CUBE",n[n.UNKNOWN=0]="UNKNOWN",n))(rQ||{});const md=te("debugcustomshader"),p0="NEEDLE_techniques_webgl";class pge{constructor(){d(this,"objectToWorldMatrix",new ve),d(this,"worldToObjectMatrix",new ve),d(this,"objectToWorld",new Array),d(this,"worldToObject",new Array)}updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),fS(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),fS(this.worldToObjectMatrix,this.worldToObject)}}const gn=class extends Px{constructor(n,...e){super(...e),d(this,"identifier"),d(this,"onBeforeRenderSceneCallback",this.onBeforeRenderScene.bind(this)),d(this,"_sphericalHarmonicsName","unity_SpecCube0"),d(this,"_objToWorldName","hlslcc_mtx4x4unity_ObjectToWorld"),d(this,"_worldToObjectName","hlslcc_mtx4x4unity_WorldToObject"),d(this,"_viewProjectionName","hlslcc_mtx4x4unity_MatrixVP"),d(this,"_viewMatrixName","hlslcc_mtx4x4unity_MatrixV"),d(this,"_rendererData",new pge),this.identifier=n,md&&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)&&kt.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}clone(){const n=super.clone();return sQ(n),n}dispose(){super.dispose();const n=kt.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);n>=0&&kt.Current.pre_render_callbacks.splice(n,1)}get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&kt.Current.setRequireColor(!0),this.depthTextureUniform&&kt.Current.setRequireDepth(!0)}onBeforeRender(n,e,t,r,s,o){r.attributes.tangent||r.computeTangents(),this.onUpdateUniforms(t,s)}onUpdateUniforms(n,e){const t=kt.Current;if(n&&(gn.viewProjection&&this.uniforms[this._viewProjectionName]&&(gn.viewProjection.copy(n.projectionMatrix).multiply(n.matrixWorldInverse),fS(gn.viewProjection,gn._viewProjectionValues)),gn.viewMatrix&&this.uniforms[this._viewMatrixName]&&(gn.viewMatrix.copy(n.matrixWorldInverse),fS(gn.viewMatrix,gn._viewMatrixValues)),this.uniforms[gn._worldSpaceCameraPosName]&&gn._worldSpaceCameraPos.setFromMatrixPosition(n.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=t.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=t.sceneLighting.timeVec4.x/20,a.y=t.sceneLighting.timeVec4.x,a.z=t.sceneLighting.timeVec4.x*2,a.w=t.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(t.sceneLighting.timeVec4.x/8),a.y=Math.sin(t.sceneLighting.timeVec4.x/4),a.z=Math.sin(t.sceneLighting.timeVec4.x/2),a.w=Math.sin(t.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(t.sceneLighting.timeVec4.x/8),a.y=Math.cos(t.sceneLighting.timeVec4.x/4),a.z=Math.cos(t.sceneLighting.timeVec4.x/2),a.w=Math.cos(t.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=t.time.deltaTime,a.y=1/t.time.deltaTime,a.z=t.time.smoothedDeltaTime,a.w=1/t.time.smoothedDeltaTime}const r=t.mainLight;if(r){const a=Bt(r.gameObject,gn._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},gn._mainLightColor.set(r.color.r,r.color.g,r.color.b,0),this.uniforms._MainLightColor={value:gn._mainLightColor};const l=r.intensity;gn._lightData.z=l,this.uniforms.unity_LightData={value:gn._lightData}}if(n&&(gn.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=gn._viewProjectionValues),gn.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=gn._viewMatrixValues),this.uniforms[gn._worldSpaceCameraPosName]&&(this.uniforms[gn._worldSpaceCameraPosName]={value:gn._worldSpaceCameraPos}),t.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=t.mainCameraComponent.nearClipPlane,a.z=t.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=t.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=t.domWidth,a.y=t.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=t.domWidth,a.y=t.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const s=this.depthTextureUniform;s&&(s.value=t.depthTexture);const o=this.opaqueTextureUniform;if(o&&(o.value=t.opaqueColorTexture),e){const a=this._rendererData;a.updateFrom(e),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}};let Al=gn;d(Al,"viewProjection",new ve),d(Al,"_viewProjectionValues",[]),d(Al,"viewMatrix",new ve),d(Al,"_viewMatrixValues",[]),d(Al,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),d(Al,"_worldSpaceCameraPos",new C),d(Al,"_mainLightColor",new Ye),d(Al,"_mainLightPosition",new C),d(Al,"_lightData",new Ye);class mge{constructor(e,t){d(this,"parser"),d(this,"identifier"),this.parser=e,this.identifier=t}get name(){return p0}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return md&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[p0])return md&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;const r=t.extensions[p0].technique;if(r<0)return null;const s=this.parser.json.extensions[p0];if(!s)return null;md&&console.log(s);const o=s.techniques[r];return o?new Promise(async(a,l)=>{var c,h,u;const p=await kde(s,o.program),m=p?.fragmentShader,f=p?.vertexShader;if(!m||!f)return l();md&&console.log("loadMaterial",t,p);const g={},v=o.uniforms;(f.includes("_Time")||m.includes("_Time"))&&(g._Time={value:new Ye(0,0,0,0)}),(f.includes("_SinTime")||m.includes("_SinTime"))&&(g._SinTime={value:new Ye(0,0,0,0)}),(f.includes("_CosTime")||m.includes("_CosTime"))&&(g._CosTime={value:new Ye(0,0,0,0)}),(f.includes("unity_DeltaTime")||m.includes("unity_DeltaTime"))&&(g.unity_DeltaTime={value:new Ye(0,0,0,0)});for(const _ in v){const b=_;switch(b){case"_TimeParameters":const x=new Ye;g[b]={value:x};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":g[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":g[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":g[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":g[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":g[b]={value:null};break}}let y=!1;if(t.extensions&&t.extensions[p0]){const _=t.extensions[p0];if(_.technique===r){md&&console.log(t.name,"Material Properties",_);for(const b in _.values){const x=_.values[b];if(typeof x=="string"){if(x.startsWith("/textures/")){const E=x.substring(10),I=Number.parseInt(E);if(I>=0){const T=await this.parser.getDependency("texture",I);T instanceof zt&&(T.colorSpace=Ri,T.needsUpdate=!0),g[b]={value:T};continue}}switch(b){case"alphaMode":x==="BLEND"&&(y=!0);continue}}if(Array.isArray(x)&&x.length===4){g[b]={value:new Ye(x[0],x[1],x[2],x[3])};continue}g[b]={value:x}}}}const A=new Al(this.identifier,{name:t.name??"",uniforms:g,vertexShader:f,fragmentShader:m,lights:!1});switch(A.glslVersion=k_,A.vertexShader=A.vertexShader.replace("#version 300 es",""),A.fragmentShader=A.fragmentShader.replace("#version 300 es",""),(c=g._Cull)==null?void 0:c.value){case 0:A.side=yi;break;case 1:A.side=dn;break;case 2:A.side=nr;break;default:A.side=nr;break}switch((h=g._ZTest)==null?void 0:h.value){case 3:A.depthTest=!0,A.depthFunc=Wm;break;case 6:A.depthTest=!0,A.depthFunc=$0;break;case 2:A.depthTest=!0,A.depthFunc=Z0;break;case 4:A.depthTest=!0,A.depthFunc=Fd;break;case 5:A.depthTest=!0,A.depthFunc=y_;break;case 7:A.depthTest=!0,A.depthFunc=v_;break;case 8:A.depthTest=!1,A.depthFunc=g_;break}A.transparent=y,y&&(A.depthWrite=!1),Pde(g),A.onUpdateUniforms();for(const _ in v){const b=_,x=v[_].type;if(((u=g[b])==null?void 0:u.value)===void 0)switch(x){case rQ.SAMPLER_2D:g[b]={value:Ide},console.warn("Missing/unassigned texture, fallback to white: "+b);break;default:b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,v[_]);break}}md&&console.log(A.uuid,g),sQ(A),a(A)}):null}}function sQ(n){if(n.uniforms){md&&console.log("Uniforms:",n.uniforms);for(const t in n.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break}}function e(t,r){Object.getOwnPropertyDescriptor(n,t)||Object.defineProperty(n,t,{get:()=>n.uniforms[r].value,set:s=>{n.uniforms[r].value=s,n.needsUpdate=!0}})}}const fge=te("debugextensions");let fC;const gge=Promise.resolve().then(()=>exe).then(async n=>(fC=n.GLTFAnimationPointerExtension,fC)).catch(n=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",n)}),vm=new Array;function vge(n){vm.includes(n)||vm.push(n)}function yge(n){const e=vm.indexOf(n);e>=0&&vm.splice(e,1)}function iD(n){const e=new hge;return n.register(t=>(e.parser=t,e)),e}class Age{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}async function nD(n,e,t){const r=t.indexOf("?");r>=0&&(t=t.substring(0,r)),n.register(s=>new uge(s)),n.register(s=>new qhe(s)),n.register(s=>new Cde(s,e.lightmaps,t)),n.register(s=>new dge(s,t,e)),n.register(s=>new mge(s,t)),n.register(s=>new $k(s,t)),n.register(s=>new fi(s,t)),n.register(s=>new oge(s)),B5()&&n.register(s=>new FP(s)),await gge.catch(s=>{}),n.register(s=>{if(fC){const o=new fC(s);return o.setAnimationPointerResolver.bind(o)(new Age),o}else return(fge||st())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const s of vm)s.onImport&&s.onImport(n,t,e)}function rD(n,e){for(const t of vm)t.onExport&&t.onExport(n,e)}function sD(n,e,t){for(const r of vm)r.onLoaded&&r.onLoaded(n,e,t)}const bl=te("debuginstancing"),oQ=class{constructor(){d(this,"objs",[])}setup(n,e,t,r,s,o=0){n.applySettings(e);const a=this.tryCreateOrAddInstance(e,t,s);if(a)fi.assignTextureLOD(a.renderer.material,0),r===null&&(r=[]),r.push(a);else if(o<=0&&e.type!=="Mesh"){const l=o+1;for(const c of e.children)r=this.setup(n,c,t,r,s,l)}return o===0&&s.useMatrixWorldAutoUpdate&&r&&r.length>=0&&this.autoUpdateInstanceMatrix(e),r}tryCreateOrAddInstance(n,e,t){if(n.type==="Mesh"){const r=t.foundMeshes;if(t.foundMeshes+=1,!t.rend.enableInstancing)return null;if(t.rend.enableInstancing!==!0){if(r>=t.rend.enableInstancing.length)return bl&&console.error("Something is wrong with instance setup",n,t.rend.enableInstancing,r),null;if(!t.rend.enableInstancing[r])return null}const s=n,o=s.material;for(const h of this.objs)if(!!h.canAdd(s.geometry,o))return h.addInstance(s);const a=16;let l=n.name;l!=null&&l.length||(l=RI());const c=new aQ(l,s.geometry,o,a,e);return this.objs.push(c),c.addInstance(s)}return null}autoUpdateInstanceMatrix(n){const e=n.matrixWorld.multiplyMatrices.bind(n.matrixWorld),t=n.matrixWorld.clone(),r=(s,o)=>{const a=e(s,o);return(n[zy]||t.equals(a)===!1)&&(t.copy(a),n[zy]=!0),a};n.matrixWorld.multiplyMatrices=r}};let ZA=oQ;d(ZA,"instance",new oQ);const gC=class{constructor(n,e){d(this,"object"),d(this,"renderer"),d(this,"__instanceIndex",-1),d(this,"__reservedVertexRange",0),d(this,"__reservedIndexRange",0),d(this,"meshInformation"),this.__instanceIndex=-1,this.object=n,this.renderer=e,n[U5]=e,this.meshInformation=m0(n.geometry),gC.all.push(this)}get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return this.meshInformation.vertexCount}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return this.meshInformation.indexCount}get reservedIndexCount(){return this.__reservedIndexRange}updateInstanceMatrix(n=!1,e=!0){this.__instanceIndex<0||(e&&this.object.updateWorldMatrix(!0,n),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(n){this.__instanceIndex<0||this.renderer.updateInstance(n,this.__instanceIndex)}setGeometry(n){return this.__instanceIndex<0?!1:this.vertexCount>this.__reservedVertexRange?(console.error(`Cannot update geometry, reserved range is too small: ${this.__reservedVertexRange} < ${this.vertexCount} vertices for ${this.name}`),!1):this.indexCount>this.__reservedIndexRange?(console.error(`Cannot update geometry, reserved range is too small: ${this.__reservedIndexRange} < ${this.indexCount} indices for ${this.name}`),!1):this.renderer.updateGeometry(n,this.__instanceIndex)}add(){this.__instanceIndex>=0||(this.renderer.add(this),ie.markAsInstancedRendered(this.object,!0))}remove(n){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,n),ie.markAsInstancedRendered(this.object,!1),n)){const e=gC.all.indexOf(this);e>=0&&gC.all.splice(e,1)}}};let $A=gC;d($A,"all",[]);class aQ{constructor(e,t,r,s,o){d(this,"allowResize",!0),d(this,"name",""),d(this,"geometry"),d(this,"material"),d(this,"context"),d(this,"inst"),d(this,"handles",[]),d(this,"maxInstanceCount"),d(this,"_currentInstanceCount",0),d(this,"_currentVertexCount",0),d(this,"_currentIndexCount",0),d(this,"_maxVertexCount"),d(this,"_maxIndexCount"),d(this,"_needUpdateBounds",!1),d(this,"_debugMaterial",null),d(this,"onBeforeRender",()=>{this.inst.layers.enableAll(),this._needUpdateBounds&&this.inst[jy]===!0&&(bl&&console.log("Update instancing bounds",this.name,this.inst.matrixWorldNeedsUpdate),this.updateBounds())}),d(this,"onAfterRender",()=>{this.inst.layers.disableAll()}),d(this,"_availableBuckets",new Array),d(this,"_usedBuckets",new Array),this.name=e,this.geometry=t,this.material=r,this.context=o,this.maxInstanceCount=Math.max(2,s),bl&&(this._debugMaterial=lQ());const a=this.tryEstimateVertexCountSize(this.maxInstanceCount,[t],s);this._maxVertexCount=a.vertexCount,this._maxIndexCount=a.indexCount,this.inst=new vx(this.maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this.inst[jy]=!0,this.inst.visible=!0,this.context.scene.add(this.inst),r instanceof Px&&(r.defines.USE_INSTANCING=!0,r.needsUpdate=!0),o.pre_render_callbacks.push(this.onBeforeRender),o.post_render_callbacks.push(this.onAfterRender),bl&&console.log(`Instanced renderer created with ${this.maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}get mesh(){return this.inst}get visible(){return this.inst.visible}set visible(e){this.inst.visible=e}get castShadow(){return this.inst.castShadow}set castShadow(e){this.inst.castShadow=e}set receiveShadow(e){this.inst.receiveShadow=e}updateBounds(e=!0,t=!0){this._needUpdateBounds=!1,e&&this.inst.computeBoundingBox(),t&&this.inst.computeBoundingSphere()}get count(){return this._currentInstanceCount}canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material?!1:!!(!this.mustGrow(e)||this.allowResize)}dispose(){bl&&console.warn("Dispose instanced renderer",this.name),this.context.scene.remove(this.inst),this.inst.dispose(),this.inst=null,this.handles=[]}addInstance(e){const t=new $A(e,this);e.castShadow===!0&&this.inst.castShadow===!1&&(this.inst.castShadow=!0),e.receiveShadow===!0&&this.inst.receiveShadow===!1&&(this.inst.receiveShadow=!0);try{this.add(t)}catch(r){return console.error(`Failed adding mesh to instancing
5743
5743
  `,r),st()&&IR("Failed instancing mesh. See the browser console for details."),null}return t}add(e){const t=e.object.geometry;if(!this.validateGeometry(t)){bl&&console.error("Cannot add instance, invalid geometry",this.name,t);return}if(this.mustGrow(t))if(this.allowResize)this.grow(t);else{console.error("Cannot add instance, max count reached",this.name,this.count,this.maxInstanceCount);return}e.object.updateWorldMatrix(!0,!0),this.addGeometry(e),this.handles[e.__instanceIndex]=e,this._currentInstanceCount+=1,this.markNeedsUpdate(),this._currentInstanceCount>0&&(this.inst.visible=!0)}remove(e,t){e&&(e.__instanceIndex<0||this.handles[e.__instanceIndex]!=e||this._currentInstanceCount<=0||(this.removeGeometry(e,t),this.handles[e.__instanceIndex]=null,e.__instanceIndex=-1,this._currentInstanceCount>0&&(this._currentInstanceCount-=1),this._currentInstanceCount<=0&&(this.inst.visible=!1),this.markNeedsUpdate()))}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.markNeedsUpdate()}updateGeometry(e,t){return this.validateGeometry(e)?(this.mustGrow()&&this.grow(e),bl&&console.debug("UPDATE MESH",t,e.name,m0(e),e.attributes.position.count,e.index?e.index.count:0),this.inst.setGeometryAt(t,e),this.markNeedsUpdate(),!0):!1}validateGeometry(e){return this.geometry,!0}markNeedsUpdate(){this._needUpdateBounds=!0}mustGrow(e){if(this.count>=this.maxInstanceCount)return!0;if(!e)return!1;const t=m0(e),r=t.vertexCount,s=t.indexCount;return this._currentVertexCount+r>this._maxVertexCount||this._currentIndexCount+s>this._maxIndexCount}grow(e){const t=this.maxInstanceCount*2,r=this.tryEstimateVertexCountSize(t,[e]),s=Math.max(this._maxVertexCount,r.vertexCount),o=Math.max(this._maxIndexCount,r.indexCount,this._maxVertexCount*2);if(bl){const l=m0(e);console.warn(`Growing batched mesh for "${this.name}/${e.name}" ${l.vertexCount} vertices, ${l.indexCount} indices
5744
5744
  Max count ${this.maxInstanceCount} \u2192 ${t}
@@ -5837,7 +5837,7 @@ Texture:`,r),this.setLightmapDebugMaterial()):f0&&console.log("Use debuglightmap
5837
5837
 
5838
5838
  gl_FragColor = sum;
5839
5839
 
5840
- }`};var Tge=Object.defineProperty,Ige=Object.getOwnPropertyDescriptor,g0=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ige(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Tge(e,t,s),s};const xC=te("debugcontactshadows");f8(n=>{const e=n.domElement.getAttribute("contactshadows");e!=null&&e!="0"&&e!="false"&&dc.auto(n)});var cD;const pQ=(cD=class extends Be{constructor(){super(...arguments),d(this,"autoFit",!1),d(this,"darkness",.5),d(this,"opacity",.5),d(this,"blur",4),d(this,"occludeBelowGround",!1),d(this,"backfaceShadows",!0),d(this,"shadowsRoot",new ye),d(this,"shadowCamera"),d(this,"shadowGroup",new Fr),d(this,"renderTarget"),d(this,"renderTargetBlur"),d(this,"plane"),d(this,"occluderMesh"),d(this,"blurPlane"),d(this,"depthMaterial"),d(this,"horizontalBlurMaterial"),d(this,"verticalBlurMaterial"),d(this,"textureSize",512)}static auto(n){if(n||(n=kt.Current),!n)throw new Error("No context provided and no current context set.");let e=this._instances.get(n);if(!e||e.destroyed){const t=new ye;e=gl(t,pQ,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(n,e)}return n.scene.add(e.gameObject),e.fitShadows(),e}fitShadows(){xC&&console.log("Fitting shadows to scene"),AR(this.gameObject,!1);const n=Ul(this.context.scene.children,[this.gameObject]),e=Math.max(1,this.blur/32),t=n.max.x-n.min.x,r=n.max.z-n.min.z;n.expandByVector(new C(e*t,0,e*r)),xC&&At.DrawWireBox3(n,16776960,60),this.gameObject.parent&&n.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const s=n.min,o=Math.max(1e-5,(n.max.y-s.y)*.002);n.max.y+=o,this.shadowsRoot.position.set((s.x+n.max.x)/2,s.y-o,(s.z+n.max.z)/2),this.shadowsRoot.scale.set(n.max.x-s.x,n.max.y-s.y,n.max.z-s.z),this.shadowsRoot.matrixWorldNeedsUpdate=!0}awake(){AR(this.gameObject,!1)}start(){xC&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new Wt(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new Wt(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const n=new tr(1,1).rotateX(Math.PI/2);this.gameObject instanceof me&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),sd(this.gameObject,!1));const e=new $t({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:nr});this.plane=new me(n,e),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new me(this.plane.geometry,new $t({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:dn})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new me(n),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane),this.shadowCamera=new Bl(-1/2,1/2,1/2,-1/2,0,1),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new bv,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=lM,this.depthMaterial.blendEquation=p_,this.depthMaterial.onBeforeCompile=t=>{this.depthMaterial&&(t.uniforms.darkness=this.depthMaterial.userData.darkness,t.fragmentShader=`
5840
+ }`};var Tge=Object.defineProperty,Ige=Object.getOwnPropertyDescriptor,g0=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ige(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Tge(e,t,s),s};const xC=te("debugcontactshadows");fV(n=>{const e=n.domElement.getAttribute("contactshadows");e!=null&&e!="0"&&e!="false"&&dc.auto(n)});var cD;const pQ=(cD=class extends Be{constructor(){super(...arguments),d(this,"autoFit",!1),d(this,"darkness",.5),d(this,"opacity",.5),d(this,"blur",4),d(this,"occludeBelowGround",!1),d(this,"backfaceShadows",!0),d(this,"shadowsRoot",new ye),d(this,"shadowCamera"),d(this,"shadowGroup",new Fr),d(this,"renderTarget"),d(this,"renderTargetBlur"),d(this,"plane"),d(this,"occluderMesh"),d(this,"blurPlane"),d(this,"depthMaterial"),d(this,"horizontalBlurMaterial"),d(this,"verticalBlurMaterial"),d(this,"textureSize",512)}static auto(n){if(n||(n=kt.Current),!n)throw new Error("No context provided and no current context set.");let e=this._instances.get(n);if(!e||e.destroyed){const t=new ye;e=gl(t,pQ,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(n,e)}return n.scene.add(e.gameObject),e.fitShadows(),e}fitShadows(){xC&&console.log("Fitting shadows to scene"),AR(this.gameObject,!1);const n=Ul(this.context.scene.children,[this.gameObject]),e=Math.max(1,this.blur/32),t=n.max.x-n.min.x,r=n.max.z-n.min.z;n.expandByVector(new C(e*t,0,e*r)),xC&&At.DrawWireBox3(n,16776960,60),this.gameObject.parent&&n.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const s=n.min,o=Math.max(1e-5,(n.max.y-s.y)*.002);n.max.y+=o,this.shadowsRoot.position.set((s.x+n.max.x)/2,s.y-o,(s.z+n.max.z)/2),this.shadowsRoot.scale.set(n.max.x-s.x,n.max.y-s.y,n.max.z-s.z),this.shadowsRoot.matrixWorldNeedsUpdate=!0}awake(){AR(this.gameObject,!1)}start(){xC&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new Wt(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new Wt(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const n=new tr(1,1).rotateX(Math.PI/2);this.gameObject instanceof me&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),sd(this.gameObject,!1));const e=new $t({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:nr});this.plane=new me(n,e),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new me(this.plane.geometry,new $t({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:dn})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new me(n),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane),this.shadowCamera=new Bl(-1/2,1/2,1/2,-1/2,0,1),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new bv,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=lM,this.depthMaterial.blendEquation=p_,this.depthMaterial.onBeforeCompile=t=>{this.depthMaterial&&(t.uniforms.darkness=this.depthMaterial.userData.darkness,t.fragmentShader=`
5841
5841
  uniform float darkness;
5842
5842
  ${t.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) );")}
5843
5843
  `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Rt(Ege),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Rt(Mge),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit&&this.fitShadows()}onDestroy(){var n,e,t,r,s,o,a,l;(n=this.renderTarget)==null||n.dispose(),(e=this.renderTargetBlur)==null||e.dispose(),(t=this.depthMaterial)==null||t.dispose(),(r=this.horizontalBlurMaterial)==null||r.dispose(),(s=this.verticalBlurMaterial)==null||s.dispose(),(o=this.blurPlane)==null||o.geometry.dispose(),(a=this.plane)==null||a.geometry.dispose(),(l=this.occluderMesh)==null||l.geometry.dispose()}onBeforeRender(n){if(!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){xC&&console.error("ContactShadows: not initialized yet");return}const e=this.context.scene,t=this.context.renderer,r=t.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const s=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof me&&sd(this.gameObject,!1);const o=e.background;e.background=null,e.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=yi:this.depthMaterial.side=nr;const a=t.getClearAlpha();t.setClearAlpha(0);const l=t.xr.enabled;t.xr.enabled=!1;const c=t.renderLists.get(e,0),h=c.transparent;c.transparent=[],t.setRenderTarget(this.renderTarget),t.clear(),t.render(e,this.shadowCamera),c.transparent=h,e.overrideMaterial=null;const u=Math.max(this.blur,.05);this.blurShadow(u*2),this.blurShadow(u*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=s,t.setRenderTarget(r),t.setClearAlpha(a),e.background=o,t.xr.enabled=l}blurShadow(n){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const e=this.shadowsRoot.worldScale,t=(e.x+e.z)/2,r=e.z/t,s=e.x/t;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=n*1/this.textureSize*r;const o=this.context.renderer,a=o.getRenderTarget();o.setRenderTarget(this.renderTargetBlur),o.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=n*1/this.textureSize*s,o.setRenderTarget(this.renderTarget),o.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,o.setRenderTarget(a)}},d(cD,"_instances",new Map),cD);let dc=pQ;g0([w()],dc.prototype,"autoFit",2),g0([w()],dc.prototype,"darkness",2),g0([w()],dc.prototype,"opacity",2),g0([w()],dc.prototype,"blur",2),g0([w()],dc.prototype,"occludeBelowGround",2),g0([w()],dc.prototype,"backfaceShadows",2);const mQ=class{constructor(){d(this,"_quicklookButton"),d(this,"_arButton"),d(this,"_vrButton"),d(this,"_sendToQuestButton")}static create(){return new mQ}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 yh.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const n=document.createElement("button");this._quicklookButton=n,n.dataset.needle="quicklook-button",n.innerText="Open in Quicklook",n.prepend(Ao("view_in_ar"));let e=!1,t=null;return n.addEventListener("click",()=>{t=PS(Rn),t||(e=!0,t=new Rn),e&&(t.objectToExport=kt.Current.scene),t?(n.classList.add("this-mode-is-requested"),t.exportAndOpen().then(()=>{n.classList.remove("this-mode-is-requested")}).catch(r=>{n.classList.remove("this-mode-is-requested"),console.error(r)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(n),n}createARButton(n){var e;if(this._arButton)return this._arButton;const t="immersive-ar",r=document.createElement("button");return this._arButton=r,r.classList.add("webxr-button"),r.dataset.needle="webxr-ar-button",r.innerText="Enter AR",r.prepend(Ao("view_in_ar")),r.title="Click to start an AR session",r.addEventListener("click",()=>wt.start(t,n)),this.updateSessionSupported(r,t),this.listenToXRSessionState(r,t),this.hideElementDuringXRSession(r),this.isSecureConnection||(r.disabled=!0,r.title="WebXR requires a secure connection (HTTPS)"),gp()||(e=navigator.xr)==null||e.addEventListener("devicechange",()=>this.updateSessionSupported(r,t)),r}createVRButton(n){var e;if(this._vrButton)return this._vrButton;const t="immersive-vr",r=document.createElement("button");return this._vrButton=r,r.classList.add("webxr-button"),r.dataset.needle="webxr-vr-button",r.innerText="Enter VR",r.prepend(Ao("panorama_photosphere")),r.title="Click to start a VR session",r.addEventListener("click",()=>wt.start(t,n)),this.updateSessionSupported(r,t),this.listenToXRSessionState(r,t),this.hideElementDuringXRSession(r),this.isSecureConnection||(r.disabled=!0,r.title="WebXR requires a secure connection (HTTPS)"),gp()||(e=navigator.xr)==null||e.addEventListener("devicechange",()=>this.updateSessionSupported(r,t)),r}createSendToQuestButton(){var n;if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(Ao("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const r=encodeURIComponent(window.location.href),s=e+r;window.open(s)==null&&rn("This page doesn't allow popups. Please paste "+s+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),gp()||(n=navigator.xr)==null||n.addEventListener("devicechange",()=>{var r;(r=navigator.xr)!=null&&r.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return yh.getOrCreate().createQRCode()}updateSessionSupported(n,e){if(!("xr"in navigator)){n.style.display="none";return}wt.isSessionSupported(e).then(t=>{n.style.display=t?"":"none",st()&&!t&&console.log('[WebXR] "'+e+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+e)})}hideElementDuringXRSession(n){X1(e=>{n["previous-display"]=n.style.display,n.style.display="none"}),mB(e=>{n["previous-display"]!=null&&(n.style.display=n["previous-display"])})}listenToXRSessionState(n,e){e&&(wt.onSessionRequestStart(t=>{t.mode===e?n.classList.add("this-mode-is-requested"):(n["was-disabled"]=n.disabled,n.disabled=!0,n.classList.add("other-mode-is-requested"))}),wt.onSessionRequestEnd(t=>{n.classList.remove("this-mode-is-requested"),n.classList.remove("other-mode-is-requested"),n.disabled=n["was-disabled"]}))}};let Am=mQ;d(Am,"_instance");var Rge=Object.defineProperty,Pge=Object.getOwnPropertyDescriptor,Is=(n,e,t,r)=>{for(var s=r>1?void 0:r?Pge(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Rge(e,t,s),s};const wC=te("debugspriterenderer"),Bge=te("wireframe"),hD=class{static getOrCreateGeometry(n){if(n.__cached_geometry)return n.__cached_geometry;if(n.guid&&hD.cache[n.guid])return wC&&console.log("Take cached geometry for sprite",n.guid),hD.cache[n.guid];const e=new yt;n.__cached_geometry=e;const t=new Float32Array(n.triangles.length*3),r=new Float32Array(n.triangles.length*2);for(let s=0;s<n.triangles.length;s+=1){const o=n.triangles[s];t[s*3]=-n.vertices[o].x,t[s*3+1]=n.vertices[o].y,t[s*3+2]=0;const a=n.uv[o];r[s*2]=a.x,r[s*2+1]=1-a.y}return e.setAttribute("position",new nt(t,3)),e.setAttribute("uv",new nt(r,2)),n.guid&&(this.cache[n.guid]=e),wC&&console.log("Built sprite geometry",n,e),e}};let ab=hD;d(ab,"cache",{});class kge{constructor(){d(this,"x"),d(this,"y")}}class kh{constructor(){d(this,"guid"),d(this,"texture"),d(this,"triangles"),d(this,"uv"),d(this,"vertices"),d(this,"__cached_geometry"),d(this,"_mesh"),d(this,"_material")}get mesh(){return this._mesh||(this._mesh=new me(ab.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&(this.texture.colorSpace=ft,this.texture.minFilter==Nt&&this.texture.magFilter==Nt&&(this.texture.anisotropy=1),this.texture.needsUpdate=!0),this._material=new $t({map:this.texture,color:16777215,side:yi,transparent:!0})),this._material}getGeometry(){return ab.getOrCreateGeometry(this)}}Is([w()],kh.prototype,"guid",2),Is([w(zt)],kh.prototype,"texture",2),Is([Eg()],kh.prototype,"triangles",2),Is([Eg()],kh.prototype,"uv",2),Is([Eg()],kh.prototype,"vertices",2);const uD=Symbol("spriteOwner");class lb{constructor(){d(this,"sprites")}}Is([w(kh)],lb.prototype,"sprites",2);class v0{constructor(){d(this,"spriteSheet"),d(this,"index",0)}update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const r=this.spriteSheet.sprites[t],s=r?.texture;if(s&&(s.colorSpace=ft,s.minFilter==Nt&&s.magFilter==Nt&&(s.anisotropy=1),s.needsUpdate=!0,!r.__hasLoadedProgressive)){r.__hasLoadedProgressive=!0;const o=s;fi.assignTextureLOD(s,0).then(a=>{a instanceof zt&&(r.texture=a,e?.map===o&&(e.map=a,e.needsUpdate=!0))})}}}Is([w(lb)],v0.prototype,"spriteSheet",2),Is([w()],v0.prototype,"index",2);class ka extends Be{constructor(){super(...arguments),d(this,"drawMode",0),d(this,"size",{x:1,y:1}),d(this,"color"),d(this,"sharedMaterial"),d(this,"transparent",!0),d(this,"cutoutThreshold",0),d(this,"castShadows",!1),d(this,"_spriteSheet"),d(this,"_currentSprite")}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.floor(e);this.spriteIndex=t;return}else 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,t;return((t=(e=this._spriteSheet)==null?void 0:e.spriteSheet)==null?void 0:t.sprites.length)??0}awake(){this._currentSprite=void 0,wC&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){var e,t,r;if(!this.__didAwake||!((t=(e=this.sprite)==null?void 0:e.spriteSheet)!=null&&t.sprites))return;const s=this.sprite.spriteSheet.sprites[this.spriteIndex];if(!s){wC&&console.warn("Sprite not found",this.spriteIndex,this.sprite.spriteSheet.sprites);return}if(this._currentSprite)this._currentSprite.geometry=ab.getOrCreateGeometry(s),this._currentSprite.material.map=s.texture;else{const o=new $t({color:16777215,side:yi});if(!o)return;if(Bge&&(o.wireframe=!0),this.color&&(o.color||(o.color=new xe),o.color.copy(this.color),o.opacity=this.color.alpha),o.transparent=!0,s.texture&&!o.wireframe){let a=s.texture;a[uD]!==void 0&&a[uD]!==this&&this.spriteFrames>1&&(a=s.texture=a.clone()),a[uD]=this,o.map=a}this.sharedMaterial=o,this._currentSprite=new me(ab.getOrCreateGeometry(s),o),fi.assignTextureLOD(o,0)}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,(r=this._spriteSheet)==null||r.update(this.sharedMaterial)}}Is([w()],ka.prototype,"drawMode",2),Is([w(kge)],ka.prototype,"size",2),Is([w(Si)],ka.prototype,"color",2),Is([w(Ot)],ka.prototype,"sharedMaterial",2),Is([w()],ka.prototype,"transparent",2),Is([w()],ka.prototype,"cutoutThreshold",2),Is([w()],ka.prototype,"castShadows",2),Is([w(v0)],ka.prototype,"sprite",1);var Dge=Object.defineProperty,Oge=Object.getOwnPropertyDescriptor,y0=(n,e,t,r)=>{for(var s=r>1?void 0:r?Oge(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Dge(e,t,s),s};const fQ=te("debugwebxr"),Lge=new ve().makeRotationY(Math.PI);class io extends Be{constructor(){super(...arguments),d(this,"_arScale",1),d(this,"invertForward",!1),d(this,"customReticle"),d(this,"useXRAnchor",!1),d(this,"arTouchTransform",!1),d(this,"autoPlace",!1),d(this,"_isPlacing",!0),d(this,"_startOffset",new ve),d(this,"_createdPlacementObject",null),d(this,"_reparentedComponents",[]),d(this,"_placementScene",new Ur),d(this,"_reticle",[]),d(this,"_hits",[]),d(this,"_placementStartTime",-1),d(this,"_rigPlacementMatrix"),d(this,"_anchor",null),d(this,"userInput"),d(this,"onPlaceScene",e=>{var t;if(this._isPlacing==!1||e!=null&&e.used)return;let r=this._reticle[0];if(!r){console.warn("No reticle to place...");return}if(!r.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((t=wt.active)!=null&&t.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let s=this._hits[0];if(e&&e.origin instanceof vB){const o=this._reticle[e.origin.index];o&&(r=o,s=this._hits[e.origin.index])}e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),r.position.copy(r.lastPos),r.quaternion.copy(r.lastQuat),this.onApplyPose(r),this.useXRAnchor&&this.onCreateAnchor(wt.active,s)}),d(this,"upVec",new C(0,1,0)),d(this,"lookPoint",new C),d(this,"worldUpVec",new C(0,1,0))}static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const r=this._eventListeners[t].indexOf(e);r>=0&&this._eventListeners[t].splice(r,1)}}get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.onScaleChanged())}onEnable(){var e;(e=this.customReticle)==null||e.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){fQ&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new ye;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let r=this.context.scene.children.length-1;r>=0;r--){const s=this.context.scene.children[r];this._placementScene.add(s)}this.context.scene.add(t),this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),ie.addComponent(t,this);for(const r of this._reticle)Ca(r);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ql.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ql.Early}),this.onRevertSceneChanges(),this._anchor=null,this._rigPlacementMatrix=void 0}onUpdateXR(e){var t,r,s,o;if(e.xr.isTrackingImages){for(const a of this._reticle)a.visible=!1;return}if(this._isPlacing){const a=(t=e.xr.rig)==null?void 0:t.gameObject;a&&a.parent!==this.context.scene&&this.context.scene.add(a);let l=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0)for(const c of e.xr.controllers){const h=c.getHitTest();h&&(l=!0,this.updateReticleAndHits(e.xr,c.index,h,e.xr.rigScale))}if(!l){const c=e.xr.getHitTest();c&&this.updateReticleAndHits(e.xr,0,c,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const a=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(a&&this.context.time.frame%20===0){const l=e.xr.convertSpace(a.transform),c=this._reticle[0];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion),this.onApplyPose(c))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new SC(this.context)),(r=this.userInput)==null||r.enable()):(s=this.userInput)==null||s.disable(),this.arTouchTransform&&(o=this.userInput)!=null&&o.hasChanged){if(e.xr.rig){const a=e.xr.rig.gameObject;this.userInput.applyMatrixTo(a.matrix,!0),a.matrix.decompose(a.position,a.quaternion,a.scale),this.userInput.factor=a.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,r,s){this._hits[t]=r.hit;let o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=Gg(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new me(new n_(.07,.09,32).rotateX(-Math.PI/2),new $t({side:yi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:16777215})),o.name="AR Placement Reticle";if(fQ){const a=new Po(1);a.position.y+=.01,o.add(a)}this._reticle[t]=o,o.matrixAutoUpdate=!1,o.visible=!1}o.lastPos=o.lastPos||r.position.clone(),o.lastQuat=o.lastQuat||r.quaternion.clone(),o.position.copy(o.lastPos.lerp(r.position,this.context.time.deltaTime/.1)),o.lastPos.copy(o.position),o.quaternion.copy(o.lastQuat.slerp(r.quaternion,this.context.time.deltaTime/.05)),o.lastQuat.copy(o.quaternion),o.scale.set(s,s,s),this.customReticle&&this.applyViewBasedTransform(o),o.updateMatrix(),o.visible=!0,o.parent!==this.context.scene&&this.context.scene.add(o),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace&&(o.visible=!1,this.onPlaceScene(null))}onScaleChanged(){}onRevertSceneChanges(){var e;for(const t of this._reticle)t&&(t.visible=!1,t?.removeFromParent());this._reticle.length=0;for(let t=this._placementScene.children.length-1;t>=0;t--){const r=this._placementScene.children[t];this.context.scene.add(r)}(e=this._createdPlacementObject)==null||e.removeFromParent();for(const t of this._reparentedComponents)ie.addComponent(t.originalObject,t.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),st()&&Di("Hit does not support creating an anchor");return}else{const r=await t.createAnchor(e.viewerPose.transform);e.running&&r&&(this._anchor=r)}}applyViewBasedTransform(e){const t=this.context.mainCamera,r=e,s=t.worldPosition,o=r.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const a=t.worldPosition;a&&e.position.clone().sub(a).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const l=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,c=30;l>c&&l<180-c||l<-c&&l>-180+c?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(s.y=o.y,e.lookAt(s))}onApplyPose(e){var t,r,s,o;const a=(r=(t=wt.active)==null?void 0:t.rig)==null?void 0:r.gameObject;if(!a){console.warn("No rig object to place");return}(s=wt.active)!=null&&s.rigScale;const l=a.parent||this.context.scene;this._rigPlacementMatrix?(o=this._rigPlacementMatrix)==null||o.decompose(a.position,a.quaternion,a.scale):this._rigPlacementMatrix=a.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(a),e.removeFromParent(),a.scale.set(this.arScale,this.arScale,this.arScale),a.position.multiplyScalar(this.arScale),a.updateMatrix(),this.invertForward&&a.matrix.premultiply(Lge),a.matrix.premultiply(this._startOffset),a.matrix.decompose(a.position,a.quaternion,a.scale),l.add(a)}}d(io,"_eventListeners",{}),y0([w()],io.prototype,"arScale",1),y0([w()],io.prototype,"invertForward",2),y0([w(ti)],io.prototype,"customReticle",2),y0([w()],io.prototype,"useXRAnchor",2),y0([w()],io.prototype,"arTouchTransform",2),y0([w()],io.prototype,"autoPlace",2);const dD=class{constructor(n){d(this,"oneFingerDrag",!0),d(this,"twoFingerRotate",!0),d(this,"twoFingerScale",!0),d(this,"factor",1),d(this,"context"),d(this,"offset"),d(this,"plane"),d(this,"_scale",1),d(this,"_hasChanged",!1),d(this,"_enabled",!1),d(this,"currentlyUsedPointerIds",new Set),d(this,"currentlyUnusedPointerIds",new Set),d(this,"onPointerDownEarly",e=>{this.isActive&&e.stopPropagation()}),d(this,"onPointerDownLate",e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)}),d(this,"onPointerUpEarly",e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)}),d(this,"prev",new Map),d(this,"_didMultitouch",!1),d(this,"touchStart",e=>{for(let t=0;t<e.changedTouches.length;t++){const r=e.changedTouches[t],s=jU()&&r.clientY<window.innerHeight*.1;this.prev.has(r.identifier)||this.prev.set(r.identifier,{ignore:s,x:0,z:0,screenx:0,screeny:0});const o=this.prev.get(r.identifier);if(o){const a=this.getPositionOnPlane(r.clientX,r.clientY);o.x=a.x,o.z=a.z,o.screenx=r.clientX,o.screeny=r.clientY}}}),d(this,"touchEnd",e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const r=e.changedTouches[t];this.prev.delete(r.identifier)}}),d(this,"touchMove",e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],r=this.prev.get(t.identifier);if(!r||r.ignore)return;const s=this.getPositionOnPlane(t.clientX,t.clientY),o=s.x-r.x,a=s.z-r.z;if(o===0&&a===0)return;this.oneFingerDrag&&this.addMovement(o,a),r.x=s.x,r.z=s.z,r.screenx=t.clientX,r.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],r=e.touches[1],s=this.prev.get(t.identifier),o=this.prev.get(r.identifier);if(!s||!o)return;if(this.twoFingerRotate){const a=Math.atan2(t.clientY-r.clientY,t.clientX-r.clientX),l=Math.atan2(s.screeny-o.screeny,s.screenx-o.screenx),c=a-l;Math.abs(c)>.001&&this.addRotation(c)}if(this.twoFingerScale){const a=t.clientX-r.clientX,l=t.clientY-r.clientY,c=Math.sqrt(a*a+l*l),h=s.screenx-o.screenx,u=s.screeny-o.screeny,p=Math.sqrt(h*h+u*u),m=c-p;Math.abs(m)>2&&this.addScale(m)}s.screenx=t.clientX,s.screeny=t.clientY,o.screenx=r.clientX,o.screeny=r.clientY}}}),d(this,"_raycaster",new pp),d(this,"_intersection",new C),d(this,"_screenPos",new C),d(this,"_tempMatrix",new ve),this.context=n,this.offset=new ve,this.plane=new ms,this.plane.setFromNormalAndCoplanarPoint(dD.up,dD.zero)}reset(){this._scale=1,this.offset.identity()}get hasChanged(){return this._hasChanged}applyMatrixTo(n,e){this._hasChanged=!1,e?(this.offset.invert(),n.premultiply(this.offset)):n.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:ql.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ql.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ql.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:ql.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ql.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ql.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(n,e){const t=this.context.mainCamera;return this._screenPos.x=n/window.innerWidth*2-1,this._screenPos.y=-(e/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(t),this._raycaster.set(t.position,this._screenPos.sub(t.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(n,e){n/=this._scale,e/=this._scale,n*=this.factor,e*=this.factor,this.offset.elements[12]+=n,this.offset.elements[14]+=e,(n!==0||e!==0)&&(this._hasChanged=!0)}addScale(n){n/=window.innerWidth,n*=-1,this._scale*=1+n,this._tempMatrix.makeScale(1-n,1-n,1-n),this.offset.premultiply(this._tempMatrix),n!==0&&(this._hasChanged=!0)}addRotation(n){n*=-1,this._tempMatrix.makeRotationY(n),this.offset.premultiply(this._tempMatrix),n!==0&&(this._hasChanged=!0)}};let SC=dD;d(SC,"up",new C(0,1,0)),d(SC,"zero",new C(0,0,0)),d(SC,"one",new C(1,1,1));var Fge=Object.defineProperty,Uge=Object.getOwnPropertyDescriptor,A0=(n,e,t,r)=>{for(var s=r>1?void 0:r?Uge(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Fge(e,t,s),s};class pc extends Be{constructor(){super(...arguments),d(this,"position","bottom"),d(this,"showNeedleLogo",!0),d(this,"showSpatialMenu"),d(this,"createFullscreenButton"),d(this,"createMuteButton"),d(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&&(aa()||this.context.menu.showQRCodeButton(!0))}}A0([w()],pc.prototype,"position",2),A0([w()],pc.prototype,"showNeedleLogo",2),A0([w()],pc.prototype,"showSpatialMenu",2),A0([w()],pc.prototype,"createFullscreenButton",2),A0([w()],pc.prototype,"createMuteButton",2),A0([w()],pc.prototype,"createQRCodeButton",2);const In={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function gQ(n){const e=await fetch(n);if(e.ok)return e.json();throw new Error(e.statusText)}async function Nge(n){if(!n)throw new Error("No basePath supplied");return await gQ(`${n}/profilesList.json`)}async function zge(n,e,t=null,r=!0){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const s=await Nge(e);let o;if(n.profiles.some(c=>{const h=s[c];return h&&(o={profileId:c,profilePath:`${e}/${h.path}`,deprecated:!!h.deprecated}),!!o}),!o){if(!t)throw new Error("No matching profile name found");const c=s[t];if(!c)throw new Error(`No matching profile name found and default profile "${t}" missing.`);o={profileId:t,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}}const a=await gQ(o.profilePath);let l;if(r){let c;if(n.handedness==="any"?c=a.layouts[Object.keys(a.layouts)[0]]:c=a.layouts[n.handedness],!c)throw new Error(`No matching handedness, ${n.handedness}, in profile ${o.profileId}`);c.assetPath&&(l=o.profilePath.replace("profile.json",c.assetPath))}return{profile:a,assetPath:l}}const jge={xAxis:0,yAxis:0,button:0,state:In.ComponentState.DEFAULT};function Gge(n=0,e=0){let t=n,r=e;if(Math.sqrt(n*n+e*e)>1){const s=Math.atan2(e,n);t=Math.cos(s),r=Math.sin(s)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:r*.5+.5}}class Vge{constructor(e){this.componentProperty=e.componentProperty,this.states=e.states,this.valueNodeName=e.valueNodeName,this.valueNodeProperty=e.valueNodeProperty,this.valueNodeProperty===In.VisualResponseProperty.TRANSFORM&&(this.minNodeName=e.minNodeName,this.maxNodeName=e.maxNodeName),this.value=0,this.updateFromComponent(jge)}updateFromComponent({xAxis:e,yAxis:t,button:r,state:s}){const{normalizedXAxis:o,normalizedYAxis:a}=Gge(e,t);switch(this.componentProperty){case In.ComponentProperty.X_AXIS:this.value=this.states.includes(s)?o:.5;break;case In.ComponentProperty.Y_AXIS:this.value=this.states.includes(s)?a:.5;break;case In.ComponentProperty.BUTTON:this.value=this.states.includes(s)?r:0;break;case In.ComponentProperty.STATE:this.valueNodeProperty===In.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(s):this.value=this.states.includes(s)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class Qge{constructor(e,t){if(!e||!t||!t.visualResponses||!t.gamepadIndices||Object.keys(t.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=e,this.type=t.type,this.rootNodeName=t.rootNodeName,this.touchPointNodeName=t.touchPointNodeName,this.visualResponses={},Object.keys(t.visualResponses).forEach(r=>{const s=new Vge(t.visualResponses[r]);this.visualResponses[r]=s}),this.gamepadIndices=Object.assign({},t.gamepadIndices),this.values={state:In.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(e){if(this.values.state=In.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&e.buttons.length>this.gamepadIndices.button){const t=e.buttons[this.gamepadIndices.button];this.values.button=t.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,t.pressed||this.values.button===1?this.values.state=In.ComponentState.PRESSED:(t.touched||this.values.button>In.ButtonTouchThreshold)&&(this.values.state=In.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&e.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=e.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===In.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>In.AxisTouchThreshold&&(this.values.state=In.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&e.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=e.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===In.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>In.AxisTouchThreshold&&(this.values.state=In.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(t=>{t.updateFromComponent(this.values)})}}class Hge{constructor(e,t,r){if(!e)throw new Error("No xrInputSource supplied");if(!t)throw new Error("No profile supplied");this.xrInputSource=e,this.assetUrl=r,this.id=t.profileId,this.layoutDescription=t.layouts[e.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(s=>{const o=this.layoutDescription.components[s];this.components[s]=new Qge(s,o)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const e=[];return Object.values(this.components).forEach(t=>{e.push(t.data)}),e}updateFromGamepad(){Object.values(this.components).forEach(e=>{e.updateFromGamepad(this.xrInputSource.gamepad)})}}const Wge="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",Xge="generic-trigger";let qge=class extends ye{constructor(){super(),this.motionController=null,this.envMap=null}setEnvironmentMap(n){return this.envMap==n?this:(this.envMap=n,this.traverse(e=>{e.isMesh&&(e.material.envMap=this.envMap,e.material.needsUpdate=!0)}),this)}updateMatrixWorld(n){super.updateMatrixWorld(n),this.motionController&&(this.motionController.updateFromGamepad(),Object.values(this.motionController.components).forEach(e=>{Object.values(e.visualResponses).forEach(t=>{const{valueNode:r,minNode:s,maxNode:o,value:a,valueNodeProperty:l}=t;r&&(l===In.VisualResponseProperty.VISIBILITY?r.visible=a:l===In.VisualResponseProperty.TRANSFORM&&(r.quaternion.slerpQuaternions(s.quaternion,o.quaternion,a),r.position.lerpVectors(s.position,o.position,a)))})}))}};function Yge(n,e){Object.values(n.components).forEach(t=>{const{type:r,touchPointNodeName:s,visualResponses:o}=t;if(r===In.ComponentType.TOUCHPAD)if(t.touchPointNode=e.getObjectByName(s),t.touchPointNode){const a=new ja(.001),l=new $t({color:255}),c=new me(a,l);t.touchPointNode.add(c)}else console.warn(`Could not find touch dot, ${t.touchPointNodeName}, in touchpad component ${t.id}`);Object.values(o).forEach(a=>{const{valueNodeName:l,minNodeName:c,maxNodeName:h,valueNodeProperty:u}=a;if(u===In.VisualResponseProperty.TRANSFORM){if(a.minNode=e.getObjectByName(c),a.maxNode=e.getObjectByName(h),!a.minNode){console.warn(`Could not find ${c} in the model`);return}if(!a.maxNode){console.warn(`Could not find ${h} in the model`);return}}a.valueNode=e.getObjectByName(l),a.valueNode||console.warn(`Could not find ${l} in the model`)})})}function vQ(n,e){Yge(n.motionController,e),n.envMap&&e.traverse(t=>{t.isMesh&&(t.material.envMap=n.envMap,t.material.needsUpdate=!0)}),n.layers.mask!=0&&e.traverse(t=>{t.layers.mask=n.layers.mask}),n.add(e)}class Jge{constructor(e=null,t=null){this.gltfLoader=e,this.path=Wge,this._assetCache={},this.onLoad=t,this.gltfLoader||(this.gltfLoader=new Ru)}setPath(e){return this.path=e,this}createControllerModel(e){const t=new qge;let r=null;return e.addEventListener("connected",s=>{const o=s.data;o.targetRayMode!=="tracked-pointer"||!o.gamepad||zge(o,this.path,Xge).then(({profile:a,assetPath:l})=>{t.motionController=new Hge(o,a,l);const c=this._assetCache[t.motionController.assetUrl];if(c)r=c.scene.clone(),vQ(t,r),this.onLoad&&this.onLoad(r);else{if(!this.gltfLoader)throw new Error("GLTFLoader not set.");this.gltfLoader.setPath(""),this.gltfLoader.load(t.motionController.assetUrl,h=>{this._assetCache[t.motionController.assetUrl]=h,r=h.scene.clone(),vQ(t,r),this.onLoad&&this.onLoad(r)},null,()=>{throw new Error(`Asset ${t.motionController.assetUrl} missing or malformed.`)})}}).catch(a=>{console.warn(a)})}),e.addEventListener("disconnected",()=>{t.motionController=null,t.remove(r),r=null}),t}}const Kge="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class Zge{constructor(e,t,r,s,o=null,a=null){this.controller=t,this.handModel=e,this.bones=[],o===null&&(o=new Ru,o.setPath(r||Kge)),o.load(`${s}.glb`,l=>{const c=l.scene.children[0];this.handModel.add(c),c.layers.mask=this.handModel.layers.mask;const h=c.getObjectByProperty("type","SkinnedMesh");h.frustumCulled=!1,h.castShadow=!0,h.receiveShadow=!0,["wrist","thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip","index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip","middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip","ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip","pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"].forEach(u=>{const p=c.getObjectByName(u);p!==void 0?p.jointName=u:console.warn(`Couldn't find ${u} in ${s} hand mesh`),this.bones.push(p)}),a&&a(c)})}updateMesh(){const e=this.controller.joints;for(let t=0;t<this.bones.length;t++){const r=this.bones[t];if(r){const s=e[r.jointName];if(s.visible){const o=s.position;r.position.copy(o),r.quaternion.copy(s.quaternion)}}}}}var $ge=Object.defineProperty,e0e=Object.getOwnPropertyDescriptor,CC=(n,e,t,r)=>{for(var s=r>1?void 0:r?e0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&$ge(e,t,s),s};const mc=te("debugwebxr"),yd=new Array;class fc extends Be{constructor(){super(...arguments),d(this,"createControllerModel",!0),d(this,"createHandModel",!0),d(this,"customLeftHand"),d(this,"customRightHand"),d(this,"_models",new Array)}supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}async onXRControllerAdded(e){var t,r,s;if(!(e.xr.isVR||e.xr.isPassThrough))return;const{controller:o}=e;if(mc&&console.warn("Add Controller Model for",o.side,o.index),this.createControllerModel||this.createHandModel){if(o.hand){if(this.createHandModel){const a=await this.loadHandModel(o);if(!a||!o.connected||!o.isHand){(t=a?.handObject)==null||t.removeFromParent(),(s=(r=a?.handmesh)==null?void 0:r.controller)==null||s.removeFromParent();return}this._models.push({controller:o,model:a.handObject,handmesh:a.handmesh}),this._models.sort((l,c)=>l.controller.index-c.controller.index),this.scene.add(a.handObject),o.model=a.handObject}}else if(this.createControllerModel){const a=await o.getModelUrl();if(a){const l=await this.loadModel(o,a);if(!l||!o.connected||o.isHand)return;this._models.push({controller:o,model:l}),this._models.sort((c,h)=>c.controller.index-h.controller.index),this.scene.add(l),l.traverse(c=>{c.layers.set(2)}),o.model=l}else o.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+o.side)}}}onXRControllerRemoved(e){var t;const r=this._models.findIndex(o=>o.controller===e.controller),s=this._models[r];s&&(this._models.splice(r,1),s.handmesh&&((t=s.handmesh.handModel)==null||t.removeFromParent(),s.handmesh=void 0),s.model&&(s.model.removeFromParent(),s.model=void 0))}onBeforeRender(){if(wt.active&&(mc&&(yd[0]=Date.now()),this.updateRendering(wt.active),mc)){const e=Date.now()-yd[0];if(yd.push(e),yd.length>=30){yd[0]=0;const t=yd.reduce((r,s)=>r+s,0)/yd.length;yd.length=0,console.log("[XRControllerModel] "+t.toFixed(2)+" ms")}}}onLeaveXR(e){var t;for(const r of this._models)r&&((t=r.model)==null||t.removeFromParent(),r.controller.model===r.model&&(r.controller.model=null));this._models.length=0}updateRendering(e){var t,r,s,o,a;for(let l=0;l<this._models.length;l++){const c=this._models[l];if(!c)continue;const h=c.controller;if(!h.connected){mc&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",h.side,h.hand);continue}if(c.model&&!c.handmesh)c.model.position.copy(h.gripPosition),c.model.quaternion.copy(h.gripQuaternion),c.model.visible=h.isTracking,(t=e.rig)==null||t.gameObject.add(c.model);else if(h.inputSource.hand&&c.handmesh){const u=e.referenceSpace,p=this.context.renderer.xr.getHand(h.index);if(u&&e.frame.getJointPose){for(const m of h.inputSource.hand.values()){const f=p.joints[m.jointName];if(f){const g=h.getHandJointPose(m);if(g){const{position:v,quaternion:y}=e.convertSpace(g.transform);f.position.copy(v),f.quaternion.copy(y),f.matrixWorldAutoUpdate=!1}f.visible=g!=null}}c.model&&(c.model.visible=h.isTracking,c.model.visible&&c.model.parent!==((r=e.rig)==null?void 0:r.gameObject)&&((s=e.rig)==null||s.gameObject.add(c.model)),c.model.position.set(0,0,0)),(o=c.model)!=null&&o.visible&&((a=c.handmesh)==null||a.updateMesh())}}}}async loadModel(e,t){var r;if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const s=await ti.getOrCreate("",t).instantiate();return ik(s),(r=wt.active)!=null&&r.isPassThrough&&s.traverseVisible(o=>{this.makeOccluder(o)}),s}async loadHandModel(e){const t=this.context,r=t.renderer.xr.getHand(e.index);r||(mc?At.DrawLabel(e.rayWorldPosition,"No hand found for index "+e.index,.05,5):console.warn("No hand found for index "+e.index));const s=new Ru;u1(s,t),await nD(s,t,this.sourceId??""),s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const o=e.side==="left"?"left.":"right.",a=e.side==="left"?this.customLeftHand:this.customRightHand;if(a)if(!a.uri.includes(o))console.warn("XRControllerModel: custom hand model must be named "+o),Di("Custom Hand: unexpected name, please see the console for details");else{const h=a.uri.substring(0,a.uri.indexOf(o));s.setPath(h),mc&&console.log("XRControllerModel: loading custom hand model from "+h)}const l=new ye;ik(l);const c=new Zge(l,r,s.path,e.inputSource.handedness,s,h=>{h.traverse(u=>{var p;u.layers.set(2),(p=wt.active)!=null&&p.isPassThrough&&this.makeOccluder(u),u instanceof me&&fi.assignMeshLOD(u,0)}),e.connected||(mc&&At.DrawLabel(e.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),h.removeFromParent())});if(mc&&l.add(new Po(.5)),e.inputSource.hand){mc&&console.log(e.inputSource.hand);for(const h of e.inputSource.hand.values())if(r.joints[h.jointName]===void 0){const u=new Fr;u.matrixAutoUpdate=!1,u.visible=!0,r.joints[h.jointName]=u,r.add(u)}}else mc&&At.DrawLabel(e.rayWorldPosition,"No inputSource.hand found for index "+e.index,.05,5);return{handObject:l,handmesh:c}}makeOccluder(e){if(e instanceof me){let t=e.material;t instanceof Ot&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.renderOrder=-100)}}}d(fc,"factory",new Jge),CC([w()],fc.prototype,"createControllerModel",2),CC([w()],fc.prototype,"createHandModel",2),CC([w(ti)],fc.prototype,"customLeftHand",2),CC([w(ti)],fc.prototype,"customRightHand",2);const yQ=new xi,EC=new C;class AQ extends Lx{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry";const e=[-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],t=[-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],r=[0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5];this.setIndex(r),this.setAttribute("position",new tt(e,3)),this.setAttribute("uv",new tt(t,2))}applyMatrix4(e){const t=this.attributes.instanceStart,r=this.attributes.instanceEnd;return t!==void 0&&(t.applyMatrix4(e),r.applyMatrix4(e),t.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));const r=new jx(t,6,1);return this.setAttribute("instanceStart",new Io(r,3,0)),this.setAttribute("instanceEnd",new Io(r,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));const r=new jx(t,6,1);return this.setAttribute("instanceColorStart",new Io(r,3,0)),this.setAttribute("instanceColorEnd",new Io(r,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new sI(e.geometry)),this}fromLineSegments(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new xi);const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;e!==void 0&&t!==void 0&&(this.boundingBox.setFromBufferAttribute(e),yQ.setFromBufferAttribute(t),this.boundingBox.union(yQ))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new wn),this.boundingBox===null&&this.computeBoundingBox();const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;if(e!==void 0&&t!==void 0){const r=this.boundingSphere.center;this.boundingBox.getCenter(r);let s=0;for(let o=0,a=e.count;o<a;o++)EC.fromBufferAttribute(e,o),s=Math.max(s,r.distanceToSquared(EC)),EC.fromBufferAttribute(t,o),s=Math.max(s,r.distanceToSquared(EC));this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&console.error("THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.",this)}}toJSON(){}applyMatrix(e){return console.warn("THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4()."),this.applyMatrix4(e)}}Ge.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new Z(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},Lr.line={uniforms:gf.merge([Ge.common,Ge.fog,Ge.line]),vertexShader:`
@@ -6210,7 +6210,7 @@ Texture:`,r),this.setLightmapDebugMaterial()):f0&&console.log("Use debuglightmap
6210
6210
  #include <premultiplied_alpha_fragment>
6211
6211
 
6212
6212
  }
6213
- `};class pD extends Rt{constructor(e){super({type:"LineMaterial",uniforms:gf.clone(Lr.line.uniforms),vertexShader:Lr.line.vertexShader,fragmentShader:Lr.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1))}}const bQ=new C,_Q=new C,es=new Ye,ts=new Ye,gc=new Ye,mD=new C,fD=new ve,is=new Vx,xQ=new C,MC=new xi,TC=new wn,vc=new Ye;let yc,bm;function wQ(n,e,t){return vc.set(0,0,-e,1).applyMatrix4(n.projectionMatrix),vc.multiplyScalar(1/vc.w),vc.x=bm/t.width,vc.y=bm/t.height,vc.applyMatrix4(n.projectionMatrixInverse),vc.multiplyScalar(1/vc.w),Math.abs(Math.max(vc.x,vc.y))}function t0e(n,e){const t=n.matrixWorld,r=n.geometry,s=r.attributes.instanceStart,o=r.attributes.instanceEnd,a=Math.min(r.instanceCount,s.count);for(let l=0,c=a;l<c;l++){is.start.fromBufferAttribute(s,l),is.end.fromBufferAttribute(o,l),is.applyMatrix4(t);const h=new C,u=new C;yc.distanceSqToSegment(is.start,is.end,u,h),u.distanceTo(h)<bm*.5&&e.push({point:u,pointOnLine:h,distance:yc.origin.distanceTo(u),object:n,face:null,faceIndex:l,uv:null,uv1:null})}}function i0e(n,e,t){const r=e.projectionMatrix,s=n.material.resolution,o=n.matrixWorld,a=n.geometry,l=a.attributes.instanceStart,c=a.attributes.instanceEnd,h=Math.min(a.instanceCount,l.count),u=-e.near;yc.at(1,gc),gc.w=1,gc.applyMatrix4(e.matrixWorldInverse),gc.applyMatrix4(r),gc.multiplyScalar(1/gc.w),gc.x*=s.x/2,gc.y*=s.y/2,gc.z=0,mD.copy(gc),fD.multiplyMatrices(e.matrixWorldInverse,o);for(let p=0,m=h;p<m;p++){if(es.fromBufferAttribute(l,p),ts.fromBufferAttribute(c,p),es.w=1,ts.w=1,es.applyMatrix4(fD),ts.applyMatrix4(fD),es.z>u&&ts.z>u)continue;if(es.z>u){const A=es.z-ts.z,_=(es.z-u)/A;es.lerp(ts,_)}else if(ts.z>u){const A=ts.z-es.z,_=(ts.z-u)/A;ts.lerp(es,_)}es.applyMatrix4(r),ts.applyMatrix4(r),es.multiplyScalar(1/es.w),ts.multiplyScalar(1/ts.w),es.x*=s.x/2,es.y*=s.y/2,ts.x*=s.x/2,ts.y*=s.y/2,is.start.copy(es),is.start.z=0,is.end.copy(ts),is.end.z=0;const f=is.closestPointToPointParameter(mD,!0);is.at(f,xQ);const g=ui.lerp(es.z,ts.z,f),v=g>=-1&&g<=1,y=mD.distanceTo(xQ)<bm*.5;if(v&&y){is.start.fromBufferAttribute(l,p),is.end.fromBufferAttribute(c,p),is.start.applyMatrix4(o),is.end.applyMatrix4(o);const A=new C,_=new C;yc.distanceSqToSegment(is.start,is.end,_,A),t.push({point:_,pointOnLine:A,distance:yc.origin.distanceTo(_),object:n,face:null,faceIndex:p,uv:null,uv1:null})}}}class n0e extends me{constructor(e=new AQ,t=new pD({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,r=e.attributes.instanceEnd,s=new Float32Array(2*t.count);for(let a=0,l=0,c=t.count;a<c;a++,l+=2)bQ.fromBufferAttribute(t,a),_Q.fromBufferAttribute(r,a),s[l]=l===0?0:s[l-1],s[l+1]=s[l]+bQ.distanceTo(_Q);const o=new jx(s,2,1);return e.setAttribute("instanceDistanceStart",new Io(o,1,0)),e.setAttribute("instanceDistanceEnd",new Io(o,1,1)),this}raycast(e,t){const r=this.material.worldUnits,s=e.camera;s===null&&!r&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const o=e.params.Line2!==void 0&&e.params.Line2.threshold||0;yc=e.ray;const a=this.matrixWorld,l=this.geometry,c=this.material;bm=c.linewidth+o,l.boundingSphere===null&&l.computeBoundingSphere(),TC.copy(l.boundingSphere).applyMatrix4(a);let h;if(r)h=bm*.5;else{const p=Math.max(s.near,TC.distanceToPoint(yc.origin));h=wQ(s,p,c.resolution)}if(TC.radius+=h,yc.intersectsSphere(TC)===!1)return;l.boundingBox===null&&l.computeBoundingBox(),MC.copy(l.boundingBox).applyMatrix4(a);let u;if(r)u=bm*.5;else{const p=Math.max(s.near,MC.distanceToPoint(yc.origin));u=wQ(s,p,c.resolution)}MC.expandByScalar(u),yc.intersectsBox(MC)!==!1&&(r?t0e(this,t):i0e(this,s,t))}}class SQ extends AQ{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(e){const t=e.length-3,r=new Float32Array(2*t);for(let s=0;s<t;s+=3)r[2*s]=e[s],r[2*s+1]=e[s+1],r[2*s+2]=e[s+2],r[2*s+3]=e[s+3],r[2*s+4]=e[s+4],r[2*s+5]=e[s+5];return super.setPositions(r),this}setColors(e){const t=e.length-3,r=new Float32Array(2*t);for(let s=0;s<t;s+=3)r[2*s]=e[s],r[2*s+1]=e[s+1],r[2*s+2]=e[s+2],r[2*s+3]=e[s+3],r[2*s+4]=e[s+4],r[2*s+5]=e[s+5];return super.setColors(r),this}fromLine(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}}class r0e extends n0e{constructor(e=new SQ,t=new pD({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type="Line2"}}class IC extends Be{}var s0e=Object.defineProperty,o0e=Object.getOwnPropertyDescriptor,_m=(n,e,t,r)=>{for(var s=r>1?void 0:r?o0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&s0e(e,t,s),s};const CQ=te("debugwebxr");class Da extends Be{constructor(){super(...arguments),d(this,"movementSpeed",1.5),d(this,"rotationStep",30),d(this,"useTeleport",!0),d(this,"useTeleportTarget",!1),d(this,"useTeleportFade",!1),d(this,"showRays",!0),d(this,"showHits",!1),d(this,"isXRMovementHandler",!0),d(this,"xrSessionMode","immersive-vr"),d(this,"_didApplyRotation",!1),d(this,"_didTeleport",!1),d(this,"_plane",null),d(this,"_lines",[]),d(this,"_hitDiscs",[]),d(this,"_hitDistances",[]),d(this,"hitPointRaycastFilter",e=>e.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(e){const t=e.xr.rig;if(!(t!=null&&t.gameObject)||e.xr.isPassThrough)return;const r=e.xr.leftController,s=e.xr.rightController;r&&this.onHandleMovement(r,t.gameObject),s&&(this.onHandleRotation(s,t.gameObject),this.useTeleport&&this.onHandleTeleport(s,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.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,t){const r=e.getStick("xr-standard-thumbstick"),s=new C(r.x,0,r.y);s.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=Vi(t);s.multiplyScalar(o.x),s.applyQuaternion(e.xr.poseOrientation),s.y=0,s.applyQuaternion(t.worldQuaternion),t.position.add(s),t.updateMatrixWorld()}onHandleRotation(e,t){const r=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(r)<.3&&(this._didApplyRotation=!1);else if(Math.abs(r)>.5){this._didApplyRotation=!0;const s=r>0?1:-1;t.rotateY(s*it.toRadians(this.rotationStep))}}onHandleTeleport(e,t){var r;const s=e.getStick("xr-standard-thumbstick");if(this._didTeleport)s.y<.2&&(this._didTeleport=!1);else if(s.y>.8){this._didTeleport=!0;const o=this.context.physics.raycastFromRay(e.ray)[0];let a=o?.point;if(!a){this._plane||(this._plane=new ms(new C(0,1,0),0));const l=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new C(0,1,0),l);const c=e.ray;a=l.clone(),this._plane.intersectLine(new Vx(c.origin,pi(c.direction).multiplyScalar(1e4).add(c.origin)),a),a.distanceTo(l)>t.scale.x*10&&(a=null)}if(a){if(this.useTeleportTarget&&!ie.getComponentInParent(o.object,IC))return;CQ&&At.DrawSphere(a,.025,16711680,5);const l=a.clone();this.useTeleportFade?(r=e.xr.fadeTransition())==null||r.then(()=>{t.worldPosition=l}):t.worldPosition=l}}}renderRays(e){for(let t=0;t<this._lines.length;t++){const r=this._lines[t];r&&(r.visible=!1)}for(let t=0;t<e.controllers.length;t++){const r=e.controllers[t];let s=this._lines[t];if(!r.connected||!r.isTracking||!r.ray||r.targetRayMode==="transient-pointer"||!r.hasSelectEvent){s&&(s.visible=!1);continue}s||(s=this.createRayLineObject(),s.scale.z=.5,this._lines[t]=s),r.updateRayWorldPosition(),r.updateRayWorldQuaternion();const o=r.rayWorldPosition,a=r.rayWorldQuaternion;s.position.copy(o),s.quaternion.copy(a);const l=e.rigScale,c=this._hitDistances[t]??l;s.scale.set(l,l,c),s.visible=!0,s.layers.disableAll(),s.layers.enable(2),s.parent!==this.context.scene&&this.context.scene.add(s)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const r=t.controller;if(!r||!r.connected||!r.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const r=e.controllers[t];if(!r.connected||!r.isTracking||!r.ray||!r.hasSelectEvent)continue;const s=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+r.index)%s!==0){const l=this._hitDiscs[t];l&&l.hit&&(l.visible=!0,this.hitPointerSetPosition(r,l,l.hit.distance));continue}const o=this.context.physics.raycastFromRay(r.ray,{testObject:this.hitPointRaycastFilter})[0];this._hitDistances[t]=o?.distance;let a=this._hitDiscs[t];if(a&&(a.controller=r,a.hit=o),o){const l=e.rigScale??1;CQ&&(At.DrawWireSphere(o.point,.025*l,16711680),At.DrawLabel(pi(0,.2,0).add(o.point),o.object.name,.02,0)),a||(a=this.createHitPointObject(),this._hitDiscs[t]=a),a.visible=!0;const c=.01*(l+o.distance);if(a.scale.set(c,c,c),a.layers.disableAll(),a.layers.enable(2),a.hit=o,o.normal){this.hitPointerSetPosition(r,a,o.distance);const h=o.normal.applyQuaternion(Mi(o.object));a.quaternion.setFromUnitVectors(a0e,h)}else this.hitPointerSetPosition(r,a,o.distance);a.parent!==this.context.scene&&this.context.scene.add(a)}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}hitPointerSetPosition(e,t,r){t.position.copy(e.rayWorldPosition),t.position.add(pi(0,0,r-.01).applyQuaternion(e.rayWorldQuaternion))}createHitPointObject(){var e=new ye;const t=new me(new ja(.3,6,6),new $t({color:15658734,opacity:.7,transparent:!0,depthTest:!1,side:yi}));return t.layers.disableAll(),t.layers.enable(2),e.add(t),e}createRayLineObject(){const e=new r0e;e.layers.disableAll(),e.layers.enable(2);const t=new SQ;e.geometry=t;const r=new Float32Array(9);r.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(r);const s=new Float32Array(9);s.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(s);const o=new pD({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,blending:Ld,dashed:!1,alphaToCoverage:!0});return e.material=o,e}}_m([w()],Da.prototype,"movementSpeed",2),_m([w()],Da.prototype,"rotationStep",2),_m([w()],Da.prototype,"useTeleport",2),_m([w()],Da.prototype,"useTeleportTarget",2),_m([w()],Da.prototype,"useTeleportFade",2),_m([w()],Da.prototype,"showRays",2),_m([w()],Da.prototype,"showHits",2);const a0e=new C(0,1,0);var l0e=Object.defineProperty,c0e=Object.getOwnPropertyDescriptor,xo=(n,e,t,r)=>{for(var s=r>1?void 0:r?c0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&l0e(e,t,s),s};const cb=te("debugwebxr"),h0e=te("debugusdz");class Ir extends Be{constructor(){super(...arguments),d(this,"createVRButton",!0),d(this,"createARButton",!0),d(this,"createSendToQuestButton",!0),d(this,"createQRCode",!0),d(this,"useDefaultControls",!0),d(this,"showControllerModels",!0),d(this,"showHandModels",!0),d(this,"usePlacementReticle",!0),d(this,"usePlacementAdjustment",!0),d(this,"arSceneScale",1),d(this,"useXRAnchor",!1),d(this,"useQuicklookExport",!1),d(this,"useDepthSensing",!1),d(this,"defaultAvatar"),d(this,"_playerSync"),d(this,"_createdComponentsInSession",[]),d(this,"_usdzExporter"),d(this,"_previousXRState",0),d(this,"onAvatarSpawned",e=>{cb&&console.log("WebXR.onAvatarSpawned",e),ie.getComponentInChildren(e,od)??(i=ie.addComponent(e,od))}),d(this,"_buttonFactory"),d(this,"_buttons",[])}awake(){wt.getXRSync(this.context)}onEnable(){var e,t;window.location.protocol!=="https:"&&Di('<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&&(ie.findObjectOfType(Rn)||(cb&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=ie.addComponent(this.gameObject,Rn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar||(cb&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ti("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Kg),this._playerSync.autoSync=!1),this._playerSync&&(this._playerSync.asset=this.defaultAvatar,(e=this._playerSync.onPlayerSpawned)==null||e.removeEventListener(this.onAvatarSpawned),(t=this._playerSync.onPlayerSpawned)==null||t.addEventListener(this.onAvatarSpawned))}onDisable(){var e;(e=this._usdzExporter)==null||e.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await wt.isVRSupported()&&this.createVRButton?wt.offerSession("immersive-vr","default",this.context):this.createARButton&&await wt.isARSupported()&&this.createARButton?wt.offerSession("immersive-ar","default",this.context):!1}get session(){return wt.active??null}get sessionMode(){return wt.activeMode??null}async enterVR(e){return wt.start("immersive-vr",e,this.context)}async enterAR(e){return wt.start("immersive-ar",e,this.context)}exitXR(){wt.stop()}onBeforeXR(e,t){e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){cb&&console.log("WebXR onEnterXR"),this._previousXRState=eo.Global.Mask;const t=e.xr.isVR;if(eo.Global.Set(t?rc.VR:rc.AR),this.usePlacementReticle&&e.xr.isAR){let s=ie.findObjectOfType(io);if(s)cb&&console.log("WebXR: WebARSessionRoot already exists, not creating a new one");else{const o=new ye;for(const a of this.context.scene.children)o.add(a);this.context.scene.add(o),s=ie.addComponent(o,io),this._createdComponentsInSession.push(s),s.arScale=this.arSceneScale,s.arTouchTransform=this.usePlacementAdjustment,s.useXRAnchor=this.useXRAnchor}}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0);let r=ie.findObjectOfType(wA);r||(r=this.gameObject.addNewComponent(wA)),this.createLocalAvatar(e.xr)}onLeaveXR(e){var t;eo.Global.Set(this._previousXRState),(t=this._playerSync)==null||t.destroyInstance();for(const r of this._createdComponentsInSession)r.destroy();this._createdComponentsInSession.length=0,this.handleOfferSession()}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Da);return!t&&e&&(t=this.gameObject.addComponent(Da),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(fc);return!t&&e&&(t=this.gameObject.addComponent(fc),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Am.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((vp()&&Lf()||h0e)&&this.useQuicklookExport){const e=ie.findObjectOfType(Rn);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e,50)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e,50)}}if(this.createSendToQuestButton&&!ew()&&wt.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode&&!aa()){const e=PS(pc);e&&e.createQRCodeButton===!1?st()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component"):wt.isXRSupported().then(t=>{if(fp()||!t){const r=yh.getOrCreate().createQRCode();this.addButton(r,50)}})}}addButton(e,t){this._buttons.push(e),e.setAttribute("priority",t.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}}xo([w()],Ir.prototype,"createVRButton",2),xo([w()],Ir.prototype,"createARButton",2),xo([w()],Ir.prototype,"createSendToQuestButton",2),xo([w()],Ir.prototype,"createQRCode",2),xo([w()],Ir.prototype,"useDefaultControls",2),xo([w()],Ir.prototype,"showControllerModels",2),xo([w()],Ir.prototype,"showHandModels",2),xo([w()],Ir.prototype,"usePlacementReticle",2),xo([w()],Ir.prototype,"usePlacementAdjustment",2),xo([w()],Ir.prototype,"arSceneScale",2),xo([w()],Ir.prototype,"useXRAnchor",2),xo([w()],Ir.prototype,"useQuicklookExport",2),xo([w()],Ir.prototype,"useDepthSensing",2),xo([w(ti)],Ir.prototype,"defaultAvatar",2);class RC{get extensionName(){return"Physics"}onExportObject(e,t,r){const s=ie.getComponents(e,Oi).filter(c=>c.enabled),o=ie.getComponents(e,Vo).filter(c=>c.enabled&&!c.isTrigger);let a=s.length>0?s[0]:null;const l=o.length>0?o[0]:null;l&&!a&&(a=new Oi,a.isKinematic=!0),a&&t.addEventListener("serialize",(c,h)=>{var u,p,m;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("}"),o.length>0){const f=o[0];c.beginBlock('def RealityKitStruct "material"',"{",!0);const g=f.sharedMaterial;g&&g.dynamicFriction!==void 0&&c.appendLine(`double dynamicFriction = ${(u=f.sharedMaterial)==null?void 0:u.dynamicFriction}`),g&&g.bounciness!==void 0&&c.appendLine(`double restitution = ${(p=f.sharedMaterial)==null?void 0:p.bounciness}`),g&&g.staticFriction!==void 0&&c.appendLine(`double staticFriction = ${(m=f.sharedMaterial)==null?void 0:m.staticFriction}`),c.closeBlock("}")}c.closeBlock("}")}}),l&&(t.addEventListener("serialize",(c,h)=>{var u;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 p=l.isTrigger?"Trigger":"Default";if(c.appendLine(`token type = "${p}"`),c.beginBlock('def RealityKitStruct "Shape"',"{",!0),l instanceof i0){const m=l;c.appendLine('token shapeType = "Sphere"'),c.appendLine(`float radius = ${m.radius}`)}else if(l instanceof n0){const m=l;c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${m.size.x}, ${m.size.y}, ${m.size.z})`)}else if(l instanceof Ch){const m=l;c.appendLine('token shapeType = "Capsule"'),c.appendLine(`float radius = ${m.radius}`),c.appendLine(`float height = ${m.height}`)}else if(l instanceof cm&&(u=l.sharedMesh)!=null&&u.geometry){const m=l.sharedMesh.geometry;m.boundingBox||m.computeBoundingBox();const f=l.sharedMesh.geometry.boundingBox;f&&(c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${f.max.x-f.min.x}, ${f.max.y-f.min.y}, ${f.max.z-f.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("}")}),o.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",l))}}var u0e=Object.defineProperty,d0e=Object.getOwnPropertyDescriptor,Dh=(n,e,t,r)=>{for(var s=r>1?void 0:r?d0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&u0e(e,t,s),s};const xm=te("debugtext");var ur=(n=>(n[n.UpperLeft=0]="UpperLeft",n[n.UpperCenter=1]="UpperCenter",n[n.UpperRight=2]="UpperRight",n[n.MiddleLeft=3]="MiddleLeft",n[n.MiddleCenter=4]="MiddleCenter",n[n.MiddleRight=5]="MiddleRight",n[n.LowerLeft=6]="LowerLeft",n[n.LowerCenter=7]="LowerCenter",n[n.LowerRight=8]="LowerRight",n))(ur||{}),EQ=(n=>(n[n.Normal=0]="Normal",n[n.Bold=1]="Bold",n[n.Italic=2]="Italic",n[n.BoldAndItalic=3]="BoldAndItalic",n))(EQ||{});class Rs extends um{constructor(){super(...arguments),d(this,"alignment",0),d(this,"verticalOverflow",0),d(this,"horizontalOverflow",0),d(this,"lineSpacing",1),d(this,"supportRichText",!1),d(this,"font"),d(this,"fontStyle",0),d(this,"sRGBTextColor",new xe(1,0,1)),d(this,"_text",""),d(this,"_fontSize",12),d(this,"_textMeshUi",null),d(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.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 t;this._fontSize=e,(t=this.uiObject)==null||t.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 e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0,this.markDirty())}onCreate(e){xm&&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,xm&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),xm&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}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,t){var r,s,o;if(xm&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let a=this.getNextTag(e);if(a){if(a.startIndex>0){for(let h=this.uiObject.children.length-1;h>=0;h--){const u=this.uiObject.children[h];u.isUI&&(this.uiObject.remove(u),u.clear())}const c=new mw({textContent:e.substring(0,a.startIndex),color:"inherit"});this.uiObject.add(c)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const l=[];for(;a;){const c=this.getNextTag(e,a.endIndex),h={fontFamily:(r=this.uiObject)==null?void 0:r.get("fontFamily"),color:"inherit",textContent:""};if(c){h.textContent=this.getText(e,a,c),this.handleTag(a,h,l);const u=new mw(h);(s=this.uiObject)==null||s.add(u)}else{h.textContent=e.substring(a.endIndex),this.handleTag(a,h,l);const u=new mw(h);(o=this.uiObject)==null||o.add(u)}a=c}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,r={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let s=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;s=!0;const a=this._textMeshUi[o];a.textContent&&(NS(a,r),e[o]=!0)}if(!s)break;yield}}handleTag(e,t,r){if(!e.isEndTag){if(e.type.includes("color")){const s=new gD(e,{color:t.color});if(r.push(s),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new xe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const s=new gD(e,{fontWeight:700});r.push(s)}else if(e.type=="i"){this.setFont(t,2);const s=new gD(e,{fontStyle:"italic"});r.push(s)}}}getText(e,t,r){return e.substring(t.endIndex,r.startIndex)}getNextTag(e,t=0){const r=e.indexOf("<",t),s=e.indexOf(">",r);if(r>=0&&s>=0){const o=e.substring(r+1,s);return{type:o,startIndex:r,endIndex:s+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const r=this.font,s=this.getFamilyNameWithCorrectSuffix(r,t);xm&&console.log("Selected font family:"+s);let o=mR.getFontFamily(s);switch(o||(o=mR.addFontFamily(s)),e.fontFamily=o,t){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 a=o.getVariant(e.fontWeight,e.fontStyle);if(!a){let l=s;l!=null&&l.endsWith("-msdf.json")||(l+="-msdf.json");let c=s;c!=null&&c.endsWith(".png")||(c+=".png"),a=o.addVariant(e.fontWeight,e.fontStyle,l,c),a?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var r;const s=e.lastIndexOf("-");if(s<0)return e;const o=(r=e.substring(s+1))==null?void 0:r.toLowerCase();if(p0e.includes(o))return xm&&console.warn("Unsupported font style: "+o),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,s);switch(xm&&console.log("Select font: ",e,EQ[t],l,c,h),t){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}}}Dh([w()],Rs.prototype,"alignment",2),Dh([w()],Rs.prototype,"verticalOverflow",2),Dh([w()],Rs.prototype,"horizontalOverflow",2),Dh([w()],Rs.prototype,"lineSpacing",2),Dh([w()],Rs.prototype,"supportRichText",2),Dh([w(URL)],Rs.prototype,"font",2),Dh([w()],Rs.prototype,"fontStyle",2),Dh([w()],Rs.prototype,"text",1),Dh([w()],Rs.prototype,"fontSize",1);class gD{constructor(e,t){d(this,"tag"),d(this,"previousValues"),this.tag=e,this.previousValues=t}}const p0e=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Ad{constructor(e){d(this,"id"),d(this,"content",""),d(this,"font",[]),d(this,"pointSize",144),d(this,"width"),d(this,"height"),d(this,"depth"),d(this,"wrapMode"),d(this,"horizontalAlignment"),d(this,"verticalAlignment"),d(this,"material"),this.id=e}static getId(){return this.global_id++}setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}writeTo(e,t){var r;t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(r=this.font)==null||r.push("sans-serif"));const s=this.font.map(o=>`"${o}"`).join(", ");t.appendLine(`string[] font = [ ${s} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${CP(this.material)}>`),t.closeBlock()}}d(Ad,"global_id",0);class PC{static singleLine(e,t,r){const s=new Ad("text_"+Ad.getId());return s.content=e,t&&(s.pointSize=t),r&&(s.depth=r),s}static multiLine(e,t,r,s,o,a){const l=new Ad("text_"+Ad.getId());return l.content=e,l.width=t,l.height=r,l.horizontalAlignment=s,l.verticalAlignment=o,a!==void 0&&(l.wrapMode=a),l}}const m0e=new ve().makeRotationY(Math.PI),f0e=new ve().makeScale(-1,1,-1);class hb{get extensionName(){return"text"}exportText(e,t,r){const s=ie.getComponent(e,Rs);if(!s)return;const o=ie.getComponent(e,Ts);let a=100,l=100;o&&(a=o.width,l=o.height),t.matrix=m0e.clone(),o&&t.matrix.premultiply(f0e);const c=s.color.clone();t.material=new vs({color:c,emissive:c}),t.addEventListener("serialize",(h,u)=>{let p=s.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=PC.multiLine(p,a,l,"center","bottom","flowing");this.setTextAlignment(m,s.alignment),this.setOverflow(m,s),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(s.fontSize),m.depth=.001,m.writeTo(void 0,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case ur.LowerLeft:case ur.MiddleLeft:case ur.UpperLeft:e.horizontalAlignment="left";break;case ur.LowerCenter:case ur.MiddleCenter:case ur.UpperCenter:e.horizontalAlignment="center";break;case ur.LowerRight:case ur.MiddleRight:case ur.UpperRight:e.horizontalAlignment="right";break}switch(t){case ur.LowerLeft:case ur.LowerCenter:case ur.LowerRight:e.verticalAlignment="bottom";break;case ur.MiddleLeft:case ur.MiddleCenter:case ur.MiddleRight:e.verticalAlignment="middle";break;case ur.UpperLeft:case ur.UpperCenter:case ur.UpperRight:e.verticalAlignment="top";break}}}class BC{get extensionName(){return"tmui"}onExportObject(e,t,r){const s=ie.getComponent(e,Jr);if(s&&s.enabled&&s.renderMode===H8.WorldSpace){const o=new hb,a=ie.getComponent(e,Ts),l=ie.getComponent(e,hd),c=new Array;if(a){if(!ie.isActiveSelf(e)){const p=ie.isActiveSelf(e);ie.setActive(e,!0),a.onEnable(),a.updateTransform(),c.push(()=>{a.onDisable(),ie.setActive(e,p)})}e.traverse(p=>{if(!ie.isActiveInHierarchy(p)){const m=ie.isActiveSelf(p);ie.setActive(p,!0);const f=ie.getComponent(p,Va);f&&(f.onEnable(),c.push(()=>{f.onDisable()}));const g=ie.getComponent(p,Ts);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),c.push(()=>{g.onDisable()}));const v=ie.getComponent(p,Rs);v&&(v.onEnable(),c.push(()=>{v.onDisable()})),c.push(()=>{ie.setActive(p,m)})}}),a.width,a.height;const h=Ws.createEmpty(),u=a.shadowComponent;if(t.add(h),u){const p=u.matrix;h.matrix.copy(p);const m=new Map,f=new Map;m.set(u,h),f.set(u,l?l.alpha:1),u.traverse(g=>{if(g===u)return;const v=Ws.createEmpty();v.matrix.copy(g.matrix);const y=g.parent,A=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let _=f.get(y)||1;const b=ie.getComponent(g,hd);if(b&&(_*=b.alpha),g instanceof me&&A){const E=g[Ma];E?o.exportText(E.gameObject,v,r):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof me&&!A){const E=g.geometry.clone();E.scale(1,1,-1),this.flipWindingOrder(E),v.geometry=E;const I=new xe,T=g.material.opacity;I.copy(g.material.color),v.material=new $t({color:I,opacity:T*_,map:g.material.map,transparent:!0})}m.set(g,v),f.set(g,_);const x=m.get(y);if(!x){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}x.add(v)})}}for(const h of c)h()}}flipWindingOrder(e){const t=e.index.array;for(let r=0,s=t.length/3;r<s;r++){const o=t[r*3];t[r*3]=t[r*3+2],t[r*3+2]=o}e.index.needsUpdate=!0}}const ub=te("debugusdz");function g0e(n,e){var t;const r=[],s=ie.getComponentsInChildren(n,Wr),o=ie.getComponentsInChildren(n,Es),a=new Array,l=new Array;if(e.injectImplicitBehaviours)for(const c of s){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;const h=c.runtimeAnimatorController.activeState;if(!h||!h.motion||!h.motion.clip||((t=h.motion.clip.tracks)==null?void 0:t.length)<1||a.includes(c))continue;const u=new fm;u.animator=c,u.stateName=h.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new ye;ie.addComponent(p,u),l.push(p),a.push(c),n.add(p)}else for(const c of s){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;ub&&console.log(c);const h=[];for(const u of c.runtimeAnimatorController.enumerateActions()){ub&&console.log(u);const p=u.getClip();h.includes(p)||h.push(p)}r.push({root:c.gameObject,clips:h})}if(e.injectImplicitBehaviours)for(const c of o){if(!c||!c.clip||!c.enabled||!c.playAutomatically||a.includes(c))continue;const h=new fm;h.animation=c,h.stateName=c.clip.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const u=new ye;ie.addComponent(u,h),l.push(u),a.push(c),n.add(u)}else for(const c of o){ub&&console.log(c);const h=[];for(const u of c.animations)h.includes(u)||h.push(u);r.push({root:c.gameObject,clips:h})}ub&&r?.length>0&&console.log("USDZ Animation Clips without behaviours",r);for(const c of r)for(const h of c.clips)e.registerAnimation(c.root,h);return l}function v0e(n,e){const t=ie.getComponentsInChildren(n,Mn),r=ie.getComponentsInChildren(n,ud),s=new Array,o=new Array;ub&&console.log({audioSources:t,playAudioOnClicks:r});for(const a of r){if(!a.target)continue;const l=t.indexOf(a.target);l>-1&&t.splice(l,1)}for(const a of t){if(!a||!a.clip||a.volume<=0||s.includes(a))continue;const l=new ud;l.target=a,l.name="PlayAudioOnClick_implicitAtStart_",l.trigger="start";const c=new ye;ie.addComponent(c,l),console.log("implicit PlayAudioOnStart",c,l),o.push(c),s.push(a),n.add(c)}return o}function y0e(n){return new Ar("DisableAtStart",br.sceneStartTrigger(),gi.fadeAction(n,0,!1))}function MQ(n){const e=n.domElement.shadowRoot.querySelector("link[rel='ar']");if(e)return e;const t=document.createElement("div");t.classList.add("menu"),t.classList.add("quicklook-menu"),t.style.display="none",t.style.visibility="hidden";const r=document.createElement("button");r.id="open-in-ar",r.innerText="Open in QuickLook",t.appendChild(r);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",t.appendChild(s);const o=document.createElement("img");return o.id="button",s.appendChild(o),n.domElement.shadowRoot.appendChild(t),s}var A0e=Object.defineProperty,b0e=Object.getOwnPropertyDescriptor,Ps=(n,e,t,r)=>{for(var s=r>1?void 0:r?b0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&A0e(e,t,s),s};const Oa=te("debugusdz");class bd{constructor(){d(this,"callToAction"),d(this,"checkoutTitle"),d(this,"checkoutSubtitle"),d(this,"callToActionURL")}}Ps([w()],bd.prototype,"callToAction",2),Ps([w()],bd.prototype,"checkoutTitle",2),Ps([w()],bd.prototype,"checkoutSubtitle",2),Ps([w()],bd.prototype,"callToActionURL",2);var kC;const vD=(kC=class extends Be{constructor(){super(...arguments),d(this,"objectToExport"),d(this,"autoExportAnimations",!0),d(this,"autoExportAudioSources",!0),d(this,"exportFileName"),d(this,"customUsdzFile"),d(this,"customBranding"),d(this,"anchoringType","plane"),d(this,"maxTextureSize",2048),d(this,"planeAnchoringAlignment","horizontal"),d(this,"interactive",!0),d(this,"allowCreateQuicklookButton",!0),d(this,"quickLookCompatible",!0),d(this,"extensions",[]),d(this,"link"),d(this,"button"),d(this,"onClickedOpenInARElement",n=>{n.preventDefault(),this.exportAndOpen()}),d(this,"_currentExportTasks",new Map),d(this,"_previousTimeScale",1),d(this,"lastCallback"),d(this,"_rootSessionRootWasAppliedTo",null),d(this,"_rootPositionBeforeExport",new C),d(this,"_rootRotationBeforeExport",new Ce),d(this,"_rootScaleBeforeExport",new C)}start(){var n,e,t;Oa&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",r=>{switch(r.key){case"t":this.exportAsync();break}}),aa()&&setTimeout(()=>{this.exportAsync()},2e3)),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(n=this.objectToExport)==null?void 0:n.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new tC),this.extensions.push(new Pd),this.extensions.push(new RC),this.extensions.push(new hb),this.extensions.push(new BC))}onEnable(){var n;const e=vp(),t=Lf();(Oa||e&&t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=MQ(this.context),this.link.addEventListener("message",this.lastCallback)),Oa&&rn("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement)}onDisable(){var n,e,t;(n=this.button)==null||n.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),Oa&&rn("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement)}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+="-"+Kj(),uu()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=MQ(this.context)),this.customUsdzFile)return Oa&&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 t=await this.export(this.objectToExport);return t?(Oa&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(n){if(!n)return console.warn("No object to export"),null;const e=this._currentExportTasks.get(n);if(e)return e;const t=this.internalExport(n);return t instanceof Promise?(this._currentExportTasks.set(n,t),t.then(r=>(this._currentExportTasks.delete(n),r)).catch(r=>(this._currentExportTasks.delete(n),console.error("Error during USDZ export \u2013 please report a bug!",r),null))):t}async internalExport(n){ni.start("export-usdz",{onProgress:y=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:y}}))}}),ni.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ni.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ni.start("export-usdz-textures","export-usdz");const e=ie.getComponentsInChildren(n,ka);for(const y of e)y&&y.enabled&&y.start&&y.start();const t=ie.getComponentsInChildren(n,Tn),r=new Array;let s=0;for(const y of t){for(const A of y.sharedMeshes)if(A){const _=fi.assignMeshLOD(A,0);_ instanceof Promise&&r.push(new Promise((b,x)=>{_.then(()=>{s++,ni.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:r.length}),b()}).catch(E=>x(E))}))}for(const A of y.sharedMaterials)if(A){const _=fi.assignTextureLOD(A,0);_ instanceof Promise&&r.push(new Promise((b,x)=>{_.then(()=>{s++,ni.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:r.length}),b()}).catch(E=>x(E))}))}}Oa&&rn("Progressive Loading: "+r.length),await Promise.all(r),Oa&&rn("Progressive Loading: done"),ni.end("export-usdz-textures");const o=eo.Global.Mask;eo.Global.Set(rc.AR);const a=new i5,l=new BA(this.quickLookCompatible),c=[l,...this.extensions],h={self:this,exporter:a,extensions:c,object:n};ni.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:h})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,ni.report("export-usdz","auto export animations and audio sources");const u=new Array;this.autoExportAnimations&&u.push(...g0e(n,l)),this.extensions.find(y=>y.extensionName==="Audio")&&this.autoExportAudioSources&&u.push(...v0e(n)),a.debug=Oa,a.keepObject=y=>{const A=ie.getComponent(y,Tn);return!(A&&!A.enabled)};const p=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(y=>{y.visible||p.push(y)});const m=this.extensions.find(y=>y.extensionName==="Behaviour");this.interactive&&m&&p.length>0&&m.addBehavior(y0e(p));let f=!0;this.quickLookCompatible&&!this.interactive&&(f=!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"),ni.report("export-usdz","Invoking exporter.parse");const g=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:c,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:f}),v=new Blob([g],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ni.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:h}));for(const y of u)ie.destroy(y);return eo.Global.Set(o),ni.end("export-usdz"),v}openInQuickLook(n,e){const t=n instanceof Blob?URL.createObjectURL(n):n,r=this.buildQuicklookOverlay();Oa&&console.log("QuickLook Overlay",r);const s=r.callToAction?encodeURIComponent(r.callToAction):"",o=r.checkoutTitle?encodeURIComponent(r.checkoutTitle):"",a=r.checkoutSubtitle?encodeURIComponent(r.checkoutSubtitle):"";this.link.href=t+`#callToAction=${s}&checkoutTitle=${o}&checkoutSubtitle=${a}&callToActionURL=${r.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(n,e){vD.save(n,e)}static save(n,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof n=="string"?t.href=n:t.href=URL.createObjectURL(n),t.download=e,t.click(),t.remove()}quicklookCallback(n){if(n?.data=="_apple_ar_quicklook_button_tapped"){Oa&&Di("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const r=t.get("callToActionURL");Oa&&rn("Quicklook url: "+r),r&&(uu()?globalThis.open(r,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",r))}}}}buildQuicklookOverlay(){var n,e,t,r,s,o;const a={};return this.customBranding&&Object.assign(a,this.customBranding),uu()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),a.callToAction="Close",a.checkoutTitle="\u{1F335} Made with Needle",a.checkoutSubtitle="_"),(((n=a.callToAction)==null?void 0:n.length)||((e=a.checkoutTitle)==null?void 0:e.length)||((t=a.checkoutSubtitle)==null?void 0:t.length))&&((r=a.callToAction)!=null&&r.length||(a.callToAction="\0"),(s=a.checkoutTitle)!=null&&s.length||(a.checkoutTitle="\0"),(o=a.checkoutSubtitle)!=null&&o.length||(a.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:a})),a}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};let n=ie.getComponentInParent(this.objectToExport,io);n||(n=ie.getComponentInChildren(this.objectToExport,io));let e=1,t=!1;const r=this.objectToExport;if(n)e=n.arScale,t=n.invertForward;else{const s=ie.findObjectOfType(Ir);s&&(e=s.arSceneScale)}return{scale:1/e,_invertForward:t,target:r,sessionRoot:n?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:n,_invertForward:e,target:t,sessionRoot:r}=this.getARScaleAndTarget(),s=r?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=t,this._rootPositionBeforeExport.copy(t.position),this._rootRotationBeforeExport.copy(t.quaternion),this._rootScaleBeforeExport.copy(t.scale),t.scale.multiplyScalar(n),e&&t.quaternion.multiply(vD.invertForwardQuaternion),t.updateMatrix(),t.updateMatrixWorld(!0),r&&s&&t.matrix.premultiply(s)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const n=this._rootSessionRootWasAppliedTo;n.position.copy(this._rootPositionBeforeExport),n.quaternion.copy(this._rootRotationBeforeExport),n.scale.copy(this._rootScaleBeforeExport),n.updateMatrix(),n.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const n=Am.getOrCreate().createQuicklookButton();return n.parentNode||this.context.menu.appendChild(n),n}},d(kC,"invertForwardMatrix",new ve().makeRotationY(Math.PI)),d(kC,"invertForwardQuaternion",new Ce().setFromEuler(new ii(0,Math.PI,0))),kC);let Rn=vD;Ps([w(ye)],Rn.prototype,"objectToExport",2),Ps([w()],Rn.prototype,"autoExportAnimations",2),Ps([w()],Rn.prototype,"autoExportAudioSources",2),Ps([w()],Rn.prototype,"exportFileName",2),Ps([w(URL)],Rn.prototype,"customUsdzFile",2),Ps([w(bd)],Rn.prototype,"customBranding",2),Ps([w()],Rn.prototype,"anchoringType",2),Ps([w()],Rn.prototype,"maxTextureSize",2),Ps([w()],Rn.prototype,"planeAnchoringAlignment",2),Ps([w()],Rn.prototype,"interactive",2),Ps([w()],Rn.prototype,"allowCreateQuicklookButton",2),Ps([w()],Rn.prototype,"quickLookCompatible",2);class db extends Be{constructor(){super(...arguments),d(this,"isUsed",!0),d(this,"usedBy",null)}}class yD extends Be{}const TQ=te("debugdeletable");class DC extends ac{}class AD extends Be{constructor(){super(...arguments),d(this,"deleteBoxes",[])}awake(){this.deleteBoxes=ie.findObjectsOfType(DC,this.context)}update(){for(const e of this.deleteBoxes){const t=this.gameObject;if(e.isInBox(t)===!0){const r=ie.getComponentInParent(this.gameObject,db);r?TQ&&console.warn("Can not delete object with usage marker",this.guid,r):(TQ&&console.log("DESTROY",this.gameObject),hA(this.gameObject,this.context.connection))}}}}var _0e=Object.defineProperty,x0e=Object.getOwnPropertyDescriptor,wm=(n,e,t,r)=>{for(var s=r>1?void 0:r?x0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&_0e(e,t,s),s};const w0e=te("debugpost");class xl extends Xr{constructor(){super(...arguments),d(this,"mode"),d(this,"focusDistance",new qe(1)),d(this,"focalLength",new qe(.2)),d(this,"aperture",new qe(20)),d(this,"gaussianMaxRadius",new qe),d(this,"resolutionScale",new qe(1*1/window.devicePixelRatio)),d(this,"bokehScale",new qe)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const r=t/300,s=2;return it.lerp(s,.01,r)};const e=20;this.aperture.valueProcessor=t=>{const r=1-t/32;return it.lerp(1,e,r)}}onCreateEffect(){if(this.mode===0){w0e&&console.warn("DepthOfField: Mode is set to Off");return}const e=new $5(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}wm([w()],xl.prototype,"mode",2),wm([w(qe)],xl.prototype,"focusDistance",2),wm([w(qe)],xl.prototype,"focalLength",2),wm([w(qe)],xl.prototype,"aperture",2),wm([w(qe)],xl.prototype,"gaussianMaxRadius",2),wm([w(qe)],xl.prototype,"resolutionScale",2),wm([w(qe)],xl.prototype,"bokehScale",2),Ra("DepthOfField",xl);var S0e=Object.defineProperty,C0e=Object.getOwnPropertyDescriptor,E0e=(n,e,t,r)=>{for(var s=r>1?void 0:r?C0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&S0e(e,t,s),s};class OC extends Be{constructor(){super(...arguments),d(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||ie.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:aa()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}E0e([w()],OC.prototype,"visibleOn",2);class bD{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}var M0e=Object.defineProperty,T0e=Object.getOwnPropertyDescriptor,Sm=(n,e,t,r)=>{for(var s=r>1?void 0:r?T0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&M0e(e,t,s),s};const Ac=te("debugdrag");var IQ=(n=>(n[n.XZPlane=0]="XZPlane",n[n.Attached=1]="Attached",n[n.HitNormal=2]="HitNormal",n[n.DynamicViewAngle=3]="DynamicViewAngle",n[n.SnapToSurfaces=4]="SnapToSurfaces",n[n.None=5]="None",n))(IQ||{}),LC;const bc=(LC=class extends Be{constructor(){super(...arguments),d(this,"dragMode",3),d(this,"snapGridResolution",0),d(this,"keepRotation",!0),d(this,"xrDragMode",1),d(this,"xrKeepRotation",!1),d(this,"xrDistanceDragFactor",1),d(this,"showGizmo",!1),d(this,"targetObject",null),d(this,"orbit",null),d(this,"_dragHelper",null),d(this,"_draggingRigidbodies",[]),d(this,"_potentialDragStartEvt",null),d(this,"_dragHandlers",new Map),d(this,"_totalMovement",new C),d(this,"_marker",null),d(this,"_isDragging",!1),d(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}setTargetObject(n){this.targetObject=n;for(const e of this._dragHandlers.values())e.setTargetObject(n)}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new C,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.orbit=ie.findObjectOfType(bi,this.context),this.gameObject.getComponentInParent(No)||this.gameObject.addComponent(No)}allowEdit(n=null){return this.context.connection.allowEditing}onPointerEnter(n){if(!this.allowEdit(this.gameObject)||n.mode!=="screen"||(n.event.mode==="tracked-pointer"||n.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const e=ie.getComponentInParent(n.object,bc);!e||e!==this||(bc.lastHovered=n.object,this.context.domElement.style.cursor="pointer")}onPointerExit(n){this.allowEdit(this.gameObject)&&n.mode==="screen"&&bc.lastHovered===n.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(n){if(!(!this.allowEdit(this.gameObject)||n.used||(n.mode==="tracked-pointer"||n.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(bc.lastHovered=n.object,n.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=n),bc._active+=1;const e=new R0e(this,this.targetObject||this.gameObject);if(this._dragHandlers.set(n.event.space,e),this.orbit&&(this.orbit.enabled=!1),e.onDragStart(n),this._dragHandlers.size===2){const t=this._dragHandlers.values(),r=t.next().value,s=t.next().value,o=new I0e(this,this.targetObject||this.gameObject,r,s);this._dragHandlers.set(this.gameObject,o),o.onDragStart(n)}n.use()}}onPointerMove(n){(this._isDragging||this._potentialDragStartEvt!==null)&&n.use()}onPointerUp(n){if(Ac&&At.DrawLabel(n.point??this.gameObject.worldPosition,"POINTERUP:"+n.pointerId+", "+n.button,.03,3),!this.allowEdit(this.gameObject)||n.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(n.event.space),t=this._dragHandlers.get(this.gameObject);t&&(t.handlerA===e||t.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),t.onDragEnd(n)),e&&(bc._active>0&&(bc._active-=1),e.onDragEnd&&e.onDragEnd(n),this._dragHandlers.delete(n.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(n),n.use()),bc._active===0&&this.orbit&&(this.orbit.enabled=!0)}update(){for(const n of this._dragHandlers.values())n.collectMovementInfo&&n.collectMovementInfo(),n.getTotalMovement&&this._totalMovement.add(n.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const n=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(n)}for(const n of this._dragHandlers.values())n.onDragUpdate&&n.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(n){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new PQ(this.context.mainCamera);else return;if(!n||!n.object)return;const e=ie.getComponentInParent(n.object,bc);if(!e||e!==this&&e._isDragging)return;const t=this.targetObject||this.gameObject;if(!t)return;this._isDragging=!0,this._dragHelper.setSelected(t,this.context),this.orbit&&(this.orbit.enabled=!1);const r=ie.getComponentInChildren(t,Ku);Ac&&console.log("DRAG START",r,t),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=ie.addComponent(t,db),this._draggingRigidbodies.length=0;const s=ie.getComponentsInChildren(t,Oi);s&&this._draggingRigidbodies.push(...s)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const n=this.targetObject||this.gameObject;Qa.markDirty(n)}onLastDragEnd(n){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const t of this._draggingRigidbodies)t.setVelocity(t.smoothedVelocity);this._draggingRigidbodies.length=0;const e=this._dragHelper.selected;if(Ac&&console.log("DRAG END",e,e?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),n!=null&&n.object){const t=ie.getComponentInChildren(n.object,Ku);t&&(t.fastMode=!1)}this._marker&&this._marker.destroy()}},d(LC,"_active",0),d(LC,"lastHovered"),LC);let La=bc;Sm([w()],La.prototype,"dragMode",2),Sm([w()],La.prototype,"snapGridResolution",2),Sm([w()],La.prototype,"keepRotation",2),Sm([w()],La.prototype,"xrDragMode",2),Sm([w()],La.prototype,"xrKeepRotation",2),Sm([w()],La.prototype,"xrDistanceDragFactor",2),Sm([w()],La.prototype,"showGizmo",2);class I0e{constructor(e,t,r,s){d(this,"handlerA"),d(this,"handlerB"),d(this,"context"),d(this,"settings"),d(this,"gameObject"),d(this,"_handlerAAttachmentPoint",new C),d(this,"_handlerBAttachmentPoint",new C),d(this,"_followObject"),d(this,"_manipulatorObject"),d(this,"_deviceMode"),d(this,"_followObjectStartWorldQuaternion",new Ce),d(this,"_manipulatorPosOffset",new C),d(this,"_manipulatorRotOffset",new Ce),d(this,"_manipulatorScaleOffset",new C),d(this,"_tempVec1",new C),d(this,"_tempVec2",new C),d(this,"_tempVec3",new C),d(this,"tempLookMatrix",new ve),d(this,"_initialScale",new C),d(this,"_initialDistance",0);var o,a;this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=r,this.handlerB=s,this._followObject=new ye,this._manipulatorObject=new ye,this.context.scene.add(this._manipulatorObject);const l=(a=(o=wt.active)==null?void 0:o.rig)==null?void 0:a.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),l&&(l.worldToLocal(this._tempVec1),l.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(Ac&&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 \u2013 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(t.scale),Ac){this._followObject.add(new Po(2)),this._manipulatorObject.add(new Po(5));const c=h=>`${h.x.toFixed(2)}, ${h.y.toFixed(2)}, ${h.z.toFixed(2)}`;At.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),At.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
6213
+ `};class pD extends Rt{constructor(e){super({type:"LineMaterial",uniforms:gf.clone(Lr.line.uniforms),vertexShader:Lr.line.vertexShader,fragmentShader:Lr.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1))}}const bQ=new C,_Q=new C,es=new Ye,ts=new Ye,gc=new Ye,mD=new C,fD=new ve,is=new Vx,xQ=new C,MC=new xi,TC=new wn,vc=new Ye;let yc,bm;function wQ(n,e,t){return vc.set(0,0,-e,1).applyMatrix4(n.projectionMatrix),vc.multiplyScalar(1/vc.w),vc.x=bm/t.width,vc.y=bm/t.height,vc.applyMatrix4(n.projectionMatrixInverse),vc.multiplyScalar(1/vc.w),Math.abs(Math.max(vc.x,vc.y))}function t0e(n,e){const t=n.matrixWorld,r=n.geometry,s=r.attributes.instanceStart,o=r.attributes.instanceEnd,a=Math.min(r.instanceCount,s.count);for(let l=0,c=a;l<c;l++){is.start.fromBufferAttribute(s,l),is.end.fromBufferAttribute(o,l),is.applyMatrix4(t);const h=new C,u=new C;yc.distanceSqToSegment(is.start,is.end,u,h),u.distanceTo(h)<bm*.5&&e.push({point:u,pointOnLine:h,distance:yc.origin.distanceTo(u),object:n,face:null,faceIndex:l,uv:null,uv1:null})}}function i0e(n,e,t){const r=e.projectionMatrix,s=n.material.resolution,o=n.matrixWorld,a=n.geometry,l=a.attributes.instanceStart,c=a.attributes.instanceEnd,h=Math.min(a.instanceCount,l.count),u=-e.near;yc.at(1,gc),gc.w=1,gc.applyMatrix4(e.matrixWorldInverse),gc.applyMatrix4(r),gc.multiplyScalar(1/gc.w),gc.x*=s.x/2,gc.y*=s.y/2,gc.z=0,mD.copy(gc),fD.multiplyMatrices(e.matrixWorldInverse,o);for(let p=0,m=h;p<m;p++){if(es.fromBufferAttribute(l,p),ts.fromBufferAttribute(c,p),es.w=1,ts.w=1,es.applyMatrix4(fD),ts.applyMatrix4(fD),es.z>u&&ts.z>u)continue;if(es.z>u){const A=es.z-ts.z,_=(es.z-u)/A;es.lerp(ts,_)}else if(ts.z>u){const A=ts.z-es.z,_=(ts.z-u)/A;ts.lerp(es,_)}es.applyMatrix4(r),ts.applyMatrix4(r),es.multiplyScalar(1/es.w),ts.multiplyScalar(1/ts.w),es.x*=s.x/2,es.y*=s.y/2,ts.x*=s.x/2,ts.y*=s.y/2,is.start.copy(es),is.start.z=0,is.end.copy(ts),is.end.z=0;const f=is.closestPointToPointParameter(mD,!0);is.at(f,xQ);const g=ui.lerp(es.z,ts.z,f),v=g>=-1&&g<=1,y=mD.distanceTo(xQ)<bm*.5;if(v&&y){is.start.fromBufferAttribute(l,p),is.end.fromBufferAttribute(c,p),is.start.applyMatrix4(o),is.end.applyMatrix4(o);const A=new C,_=new C;yc.distanceSqToSegment(is.start,is.end,_,A),t.push({point:_,pointOnLine:A,distance:yc.origin.distanceTo(_),object:n,face:null,faceIndex:p,uv:null,uv1:null})}}}class n0e extends me{constructor(e=new AQ,t=new pD({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,r=e.attributes.instanceEnd,s=new Float32Array(2*t.count);for(let a=0,l=0,c=t.count;a<c;a++,l+=2)bQ.fromBufferAttribute(t,a),_Q.fromBufferAttribute(r,a),s[l]=l===0?0:s[l-1],s[l+1]=s[l]+bQ.distanceTo(_Q);const o=new jx(s,2,1);return e.setAttribute("instanceDistanceStart",new Io(o,1,0)),e.setAttribute("instanceDistanceEnd",new Io(o,1,1)),this}raycast(e,t){const r=this.material.worldUnits,s=e.camera;s===null&&!r&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const o=e.params.Line2!==void 0&&e.params.Line2.threshold||0;yc=e.ray;const a=this.matrixWorld,l=this.geometry,c=this.material;bm=c.linewidth+o,l.boundingSphere===null&&l.computeBoundingSphere(),TC.copy(l.boundingSphere).applyMatrix4(a);let h;if(r)h=bm*.5;else{const p=Math.max(s.near,TC.distanceToPoint(yc.origin));h=wQ(s,p,c.resolution)}if(TC.radius+=h,yc.intersectsSphere(TC)===!1)return;l.boundingBox===null&&l.computeBoundingBox(),MC.copy(l.boundingBox).applyMatrix4(a);let u;if(r)u=bm*.5;else{const p=Math.max(s.near,MC.distanceToPoint(yc.origin));u=wQ(s,p,c.resolution)}MC.expandByScalar(u),yc.intersectsBox(MC)!==!1&&(r?t0e(this,t):i0e(this,s,t))}}class SQ extends AQ{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(e){const t=e.length-3,r=new Float32Array(2*t);for(let s=0;s<t;s+=3)r[2*s]=e[s],r[2*s+1]=e[s+1],r[2*s+2]=e[s+2],r[2*s+3]=e[s+3],r[2*s+4]=e[s+4],r[2*s+5]=e[s+5];return super.setPositions(r),this}setColors(e){const t=e.length-3,r=new Float32Array(2*t);for(let s=0;s<t;s+=3)r[2*s]=e[s],r[2*s+1]=e[s+1],r[2*s+2]=e[s+2],r[2*s+3]=e[s+3],r[2*s+4]=e[s+4],r[2*s+5]=e[s+5];return super.setColors(r),this}fromLine(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}}class r0e extends n0e{constructor(e=new SQ,t=new pD({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type="Line2"}}class IC extends Be{}var s0e=Object.defineProperty,o0e=Object.getOwnPropertyDescriptor,_m=(n,e,t,r)=>{for(var s=r>1?void 0:r?o0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&s0e(e,t,s),s};const CQ=te("debugwebxr");class Da extends Be{constructor(){super(...arguments),d(this,"movementSpeed",1.5),d(this,"rotationStep",30),d(this,"useTeleport",!0),d(this,"useTeleportTarget",!1),d(this,"useTeleportFade",!1),d(this,"showRays",!0),d(this,"showHits",!1),d(this,"isXRMovementHandler",!0),d(this,"xrSessionMode","immersive-vr"),d(this,"_didApplyRotation",!1),d(this,"_didTeleport",!1),d(this,"_plane",null),d(this,"_lines",[]),d(this,"_hitDiscs",[]),d(this,"_hitDistances",[]),d(this,"hitPointRaycastFilter",e=>e.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(e){const t=e.xr.rig;if(!(t!=null&&t.gameObject)||e.xr.isPassThrough)return;const r=e.xr.leftController,s=e.xr.rightController;r&&this.onHandleMovement(r,t.gameObject),s&&(this.onHandleRotation(s,t.gameObject),this.useTeleport&&this.onHandleTeleport(s,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.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,t){const r=e.getStick("xr-standard-thumbstick"),s=new C(r.x,0,r.y);s.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=Vi(t);s.multiplyScalar(o.x),s.applyQuaternion(e.xr.poseOrientation),s.y=0,s.applyQuaternion(t.worldQuaternion),t.position.add(s),t.updateMatrixWorld()}onHandleRotation(e,t){const r=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(r)<.3&&(this._didApplyRotation=!1);else if(Math.abs(r)>.5){this._didApplyRotation=!0;const s=r>0?1:-1;t.rotateY(s*it.toRadians(this.rotationStep))}}onHandleTeleport(e,t){var r;const s=e.getStick("xr-standard-thumbstick");if(this._didTeleport)s.y<.2&&(this._didTeleport=!1);else if(s.y>.8){this._didTeleport=!0;const o=this.context.physics.raycastFromRay(e.ray)[0];let a=o?.point;if(!a){this._plane||(this._plane=new ms(new C(0,1,0),0));const l=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new C(0,1,0),l);const c=e.ray;a=l.clone(),this._plane.intersectLine(new Vx(c.origin,pi(c.direction).multiplyScalar(1e4).add(c.origin)),a),a.distanceTo(l)>t.scale.x*10&&(a=null)}if(a){if(this.useTeleportTarget&&!ie.getComponentInParent(o.object,IC))return;CQ&&At.DrawSphere(a,.025,16711680,5);const l=a.clone();this.useTeleportFade?(r=e.xr.fadeTransition())==null||r.then(()=>{t.worldPosition=l}):t.worldPosition=l}}}renderRays(e){for(let t=0;t<this._lines.length;t++){const r=this._lines[t];r&&(r.visible=!1)}for(let t=0;t<e.controllers.length;t++){const r=e.controllers[t];let s=this._lines[t];if(!r.connected||!r.isTracking||!r.ray||r.targetRayMode==="transient-pointer"||!r.hasSelectEvent){s&&(s.visible=!1);continue}s||(s=this.createRayLineObject(),s.scale.z=.5,this._lines[t]=s),r.updateRayWorldPosition(),r.updateRayWorldQuaternion();const o=r.rayWorldPosition,a=r.rayWorldQuaternion;s.position.copy(o),s.quaternion.copy(a);const l=e.rigScale,c=this._hitDistances[t]??l;s.scale.set(l,l,c),s.visible=!0,s.layers.disableAll(),s.layers.enable(2),s.parent!==this.context.scene&&this.context.scene.add(s)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const r=t.controller;if(!r||!r.connected||!r.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const r=e.controllers[t];if(!r.connected||!r.isTracking||!r.ray||!r.hasSelectEvent)continue;const s=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+r.index)%s!==0){const l=this._hitDiscs[t];l&&l.hit&&(l.visible=!0,this.hitPointerSetPosition(r,l,l.hit.distance));continue}const o=this.context.physics.raycastFromRay(r.ray,{testObject:this.hitPointRaycastFilter})[0];this._hitDistances[t]=o?.distance;let a=this._hitDiscs[t];if(a&&(a.controller=r,a.hit=o),o){const l=e.rigScale??1;CQ&&(At.DrawWireSphere(o.point,.025*l,16711680),At.DrawLabel(pi(0,.2,0).add(o.point),o.object.name,.02,0)),a||(a=this.createHitPointObject(),this._hitDiscs[t]=a),a.visible=!0;const c=.01*(l+o.distance);if(a.scale.set(c,c,c),a.layers.disableAll(),a.layers.enable(2),a.hit=o,o.normal){this.hitPointerSetPosition(r,a,o.distance);const h=o.normal.applyQuaternion(Mi(o.object));a.quaternion.setFromUnitVectors(a0e,h)}else this.hitPointerSetPosition(r,a,o.distance);a.parent!==this.context.scene&&this.context.scene.add(a)}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}hitPointerSetPosition(e,t,r){t.position.copy(e.rayWorldPosition),t.position.add(pi(0,0,r-.01).applyQuaternion(e.rayWorldQuaternion))}createHitPointObject(){var e=new ye;const t=new me(new ja(.3,6,6),new $t({color:15658734,opacity:.7,transparent:!0,depthTest:!1,side:yi}));return t.layers.disableAll(),t.layers.enable(2),e.add(t),e}createRayLineObject(){const e=new r0e;e.layers.disableAll(),e.layers.enable(2);const t=new SQ;e.geometry=t;const r=new Float32Array(9);r.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(r);const s=new Float32Array(9);s.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(s);const o=new pD({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,blending:Ld,dashed:!1,alphaToCoverage:!0});return e.material=o,e}}_m([w()],Da.prototype,"movementSpeed",2),_m([w()],Da.prototype,"rotationStep",2),_m([w()],Da.prototype,"useTeleport",2),_m([w()],Da.prototype,"useTeleportTarget",2),_m([w()],Da.prototype,"useTeleportFade",2),_m([w()],Da.prototype,"showRays",2),_m([w()],Da.prototype,"showHits",2);const a0e=new C(0,1,0);var l0e=Object.defineProperty,c0e=Object.getOwnPropertyDescriptor,xo=(n,e,t,r)=>{for(var s=r>1?void 0:r?c0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&l0e(e,t,s),s};const cb=te("debugwebxr"),h0e=te("debugusdz");class Ir extends Be{constructor(){super(...arguments),d(this,"createVRButton",!0),d(this,"createARButton",!0),d(this,"createSendToQuestButton",!0),d(this,"createQRCode",!0),d(this,"useDefaultControls",!0),d(this,"showControllerModels",!0),d(this,"showHandModels",!0),d(this,"usePlacementReticle",!0),d(this,"usePlacementAdjustment",!0),d(this,"arSceneScale",1),d(this,"useXRAnchor",!1),d(this,"useQuicklookExport",!1),d(this,"useDepthSensing",!1),d(this,"defaultAvatar"),d(this,"_playerSync"),d(this,"_createdComponentsInSession",[]),d(this,"_usdzExporter"),d(this,"_previousXRState",0),d(this,"onAvatarSpawned",e=>{cb&&console.log("WebXR.onAvatarSpawned",e),ie.getComponentInChildren(e,od)??(i=ie.addComponent(e,od))}),d(this,"_buttonFactory"),d(this,"_buttons",[])}awake(){wt.getXRSync(this.context)}onEnable(){var e,t;window.location.protocol!=="https:"&&Di('<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&&(ie.findObjectOfType(Rn)||(cb&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=ie.addComponent(this.gameObject,Rn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar||(cb&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ti("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Kg),this._playerSync.autoSync=!1),this._playerSync&&(this._playerSync.asset=this.defaultAvatar,(e=this._playerSync.onPlayerSpawned)==null||e.removeEventListener(this.onAvatarSpawned),(t=this._playerSync.onPlayerSpawned)==null||t.addEventListener(this.onAvatarSpawned))}onDisable(){var e;(e=this._usdzExporter)==null||e.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await wt.isVRSupported()&&this.createVRButton?wt.offerSession("immersive-vr","default",this.context):this.createARButton&&await wt.isARSupported()&&this.createARButton?wt.offerSession("immersive-ar","default",this.context):!1}get session(){return wt.active??null}get sessionMode(){return wt.activeMode??null}async enterVR(e){return wt.start("immersive-vr",e,this.context)}async enterAR(e){return wt.start("immersive-ar",e,this.context)}exitXR(){wt.stop()}onBeforeXR(e,t){e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){cb&&console.log("WebXR onEnterXR"),this._previousXRState=eo.Global.Mask;const t=e.xr.isVR;if(eo.Global.Set(t?rc.VR:rc.AR),this.usePlacementReticle&&e.xr.isAR){let s=ie.findObjectOfType(io);if(s)cb&&console.log("WebXR: WebARSessionRoot already exists, not creating a new one");else{const o=new ye;for(const a of this.context.scene.children)o.add(a);this.context.scene.add(o),s=ie.addComponent(o,io),this._createdComponentsInSession.push(s),s.arScale=this.arSceneScale,s.arTouchTransform=this.usePlacementAdjustment,s.useXRAnchor=this.useXRAnchor}}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0);let r=ie.findObjectOfType(wA);r||(r=this.gameObject.addNewComponent(wA)),this.createLocalAvatar(e.xr)}onLeaveXR(e){var t;eo.Global.Set(this._previousXRState),(t=this._playerSync)==null||t.destroyInstance();for(const r of this._createdComponentsInSession)r.destroy();this._createdComponentsInSession.length=0,this.handleOfferSession()}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Da);return!t&&e&&(t=this.gameObject.addComponent(Da),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(fc);return!t&&e&&(t=this.gameObject.addComponent(fc),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Am.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((vp()&&Lf()||h0e)&&this.useQuicklookExport){const e=ie.findObjectOfType(Rn);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e,50)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e,50)}}if(this.createSendToQuestButton&&!ew()&&wt.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode&&!aa()){const e=PS(pc);e&&e.createQRCodeButton===!1?st()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component"):wt.isXRSupported().then(t=>{if(fp()||!t){const r=yh.getOrCreate().createQRCode();this.addButton(r,50)}})}}addButton(e,t){this._buttons.push(e),e.setAttribute("priority",t.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}}xo([w()],Ir.prototype,"createVRButton",2),xo([w()],Ir.prototype,"createARButton",2),xo([w()],Ir.prototype,"createSendToQuestButton",2),xo([w()],Ir.prototype,"createQRCode",2),xo([w()],Ir.prototype,"useDefaultControls",2),xo([w()],Ir.prototype,"showControllerModels",2),xo([w()],Ir.prototype,"showHandModels",2),xo([w()],Ir.prototype,"usePlacementReticle",2),xo([w()],Ir.prototype,"usePlacementAdjustment",2),xo([w()],Ir.prototype,"arSceneScale",2),xo([w()],Ir.prototype,"useXRAnchor",2),xo([w()],Ir.prototype,"useQuicklookExport",2),xo([w()],Ir.prototype,"useDepthSensing",2),xo([w(ti)],Ir.prototype,"defaultAvatar",2);class RC{get extensionName(){return"Physics"}onExportObject(e,t,r){const s=ie.getComponents(e,Oi).filter(c=>c.enabled),o=ie.getComponents(e,Vo).filter(c=>c.enabled&&!c.isTrigger);let a=s.length>0?s[0]:null;const l=o.length>0?o[0]:null;l&&!a&&(a=new Oi,a.isKinematic=!0),a&&t.addEventListener("serialize",(c,h)=>{var u,p,m;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("}"),o.length>0){const f=o[0];c.beginBlock('def RealityKitStruct "material"',"{",!0);const g=f.sharedMaterial;g&&g.dynamicFriction!==void 0&&c.appendLine(`double dynamicFriction = ${(u=f.sharedMaterial)==null?void 0:u.dynamicFriction}`),g&&g.bounciness!==void 0&&c.appendLine(`double restitution = ${(p=f.sharedMaterial)==null?void 0:p.bounciness}`),g&&g.staticFriction!==void 0&&c.appendLine(`double staticFriction = ${(m=f.sharedMaterial)==null?void 0:m.staticFriction}`),c.closeBlock("}")}c.closeBlock("}")}}),l&&(t.addEventListener("serialize",(c,h)=>{var u;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 p=l.isTrigger?"Trigger":"Default";if(c.appendLine(`token type = "${p}"`),c.beginBlock('def RealityKitStruct "Shape"',"{",!0),l instanceof i0){const m=l;c.appendLine('token shapeType = "Sphere"'),c.appendLine(`float radius = ${m.radius}`)}else if(l instanceof n0){const m=l;c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${m.size.x}, ${m.size.y}, ${m.size.z})`)}else if(l instanceof Ch){const m=l;c.appendLine('token shapeType = "Capsule"'),c.appendLine(`float radius = ${m.radius}`),c.appendLine(`float height = ${m.height}`)}else if(l instanceof cm&&(u=l.sharedMesh)!=null&&u.geometry){const m=l.sharedMesh.geometry;m.boundingBox||m.computeBoundingBox();const f=l.sharedMesh.geometry.boundingBox;f&&(c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${f.max.x-f.min.x}, ${f.max.y-f.min.y}, ${f.max.z-f.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("}")}),o.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",l))}}var u0e=Object.defineProperty,d0e=Object.getOwnPropertyDescriptor,Dh=(n,e,t,r)=>{for(var s=r>1?void 0:r?d0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&u0e(e,t,s),s};const xm=te("debugtext");var ur=(n=>(n[n.UpperLeft=0]="UpperLeft",n[n.UpperCenter=1]="UpperCenter",n[n.UpperRight=2]="UpperRight",n[n.MiddleLeft=3]="MiddleLeft",n[n.MiddleCenter=4]="MiddleCenter",n[n.MiddleRight=5]="MiddleRight",n[n.LowerLeft=6]="LowerLeft",n[n.LowerCenter=7]="LowerCenter",n[n.LowerRight=8]="LowerRight",n))(ur||{}),EQ=(n=>(n[n.Normal=0]="Normal",n[n.Bold=1]="Bold",n[n.Italic=2]="Italic",n[n.BoldAndItalic=3]="BoldAndItalic",n))(EQ||{});class Rs extends um{constructor(){super(...arguments),d(this,"alignment",0),d(this,"verticalOverflow",0),d(this,"horizontalOverflow",0),d(this,"lineSpacing",1),d(this,"supportRichText",!1),d(this,"font"),d(this,"fontStyle",0),d(this,"sRGBTextColor",new xe(1,0,1)),d(this,"_text",""),d(this,"_fontSize",12),d(this,"_textMeshUi",null),d(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.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 t;this._fontSize=e,(t=this.uiObject)==null||t.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 e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0,this.markDirty())}onCreate(e){xm&&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,xm&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),xm&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}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,t){var r,s,o;if(xm&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let a=this.getNextTag(e);if(a){if(a.startIndex>0){for(let h=this.uiObject.children.length-1;h>=0;h--){const u=this.uiObject.children[h];u.isUI&&(this.uiObject.remove(u),u.clear())}const c=new mw({textContent:e.substring(0,a.startIndex),color:"inherit"});this.uiObject.add(c)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const l=[];for(;a;){const c=this.getNextTag(e,a.endIndex),h={fontFamily:(r=this.uiObject)==null?void 0:r.get("fontFamily"),color:"inherit",textContent:""};if(c){h.textContent=this.getText(e,a,c),this.handleTag(a,h,l);const u=new mw(h);(s=this.uiObject)==null||s.add(u)}else{h.textContent=e.substring(a.endIndex),this.handleTag(a,h,l);const u=new mw(h);(o=this.uiObject)==null||o.add(u)}a=c}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,r={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let s=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;s=!0;const a=this._textMeshUi[o];a.textContent&&(NS(a,r),e[o]=!0)}if(!s)break;yield}}handleTag(e,t,r){if(!e.isEndTag){if(e.type.includes("color")){const s=new gD(e,{color:t.color});if(r.push(s),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new xe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const s=new gD(e,{fontWeight:700});r.push(s)}else if(e.type=="i"){this.setFont(t,2);const s=new gD(e,{fontStyle:"italic"});r.push(s)}}}getText(e,t,r){return e.substring(t.endIndex,r.startIndex)}getNextTag(e,t=0){const r=e.indexOf("<",t),s=e.indexOf(">",r);if(r>=0&&s>=0){const o=e.substring(r+1,s);return{type:o,startIndex:r,endIndex:s+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const r=this.font,s=this.getFamilyNameWithCorrectSuffix(r,t);xm&&console.log("Selected font family:"+s);let o=mR.getFontFamily(s);switch(o||(o=mR.addFontFamily(s)),e.fontFamily=o,t){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 a=o.getVariant(e.fontWeight,e.fontStyle);if(!a){let l=s;l!=null&&l.endsWith("-msdf.json")||(l+="-msdf.json");let c=s;c!=null&&c.endsWith(".png")||(c+=".png"),a=o.addVariant(e.fontWeight,e.fontStyle,l,c),a?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var r;const s=e.lastIndexOf("-");if(s<0)return e;const o=(r=e.substring(s+1))==null?void 0:r.toLowerCase();if(p0e.includes(o))return xm&&console.warn("Unsupported font style: "+o),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,s);switch(xm&&console.log("Select font: ",e,EQ[t],l,c,h),t){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}}}Dh([w()],Rs.prototype,"alignment",2),Dh([w()],Rs.prototype,"verticalOverflow",2),Dh([w()],Rs.prototype,"horizontalOverflow",2),Dh([w()],Rs.prototype,"lineSpacing",2),Dh([w()],Rs.prototype,"supportRichText",2),Dh([w(URL)],Rs.prototype,"font",2),Dh([w()],Rs.prototype,"fontStyle",2),Dh([w()],Rs.prototype,"text",1),Dh([w()],Rs.prototype,"fontSize",1);class gD{constructor(e,t){d(this,"tag"),d(this,"previousValues"),this.tag=e,this.previousValues=t}}const p0e=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Ad{constructor(e){d(this,"id"),d(this,"content",""),d(this,"font",[]),d(this,"pointSize",144),d(this,"width"),d(this,"height"),d(this,"depth"),d(this,"wrapMode"),d(this,"horizontalAlignment"),d(this,"verticalAlignment"),d(this,"material"),this.id=e}static getId(){return this.global_id++}setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}writeTo(e,t){var r;t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(r=this.font)==null||r.push("sans-serif"));const s=this.font.map(o=>`"${o}"`).join(", ");t.appendLine(`string[] font = [ ${s} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${CP(this.material)}>`),t.closeBlock()}}d(Ad,"global_id",0);class PC{static singleLine(e,t,r){const s=new Ad("text_"+Ad.getId());return s.content=e,t&&(s.pointSize=t),r&&(s.depth=r),s}static multiLine(e,t,r,s,o,a){const l=new Ad("text_"+Ad.getId());return l.content=e,l.width=t,l.height=r,l.horizontalAlignment=s,l.verticalAlignment=o,a!==void 0&&(l.wrapMode=a),l}}const m0e=new ve().makeRotationY(Math.PI),f0e=new ve().makeScale(-1,1,-1);class hb{get extensionName(){return"text"}exportText(e,t,r){const s=ie.getComponent(e,Rs);if(!s)return;const o=ie.getComponent(e,Ts);let a=100,l=100;o&&(a=o.width,l=o.height),t.matrix=m0e.clone(),o&&t.matrix.premultiply(f0e);const c=s.color.clone();t.material=new vs({color:c,emissive:c}),t.addEventListener("serialize",(h,u)=>{let p=s.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=PC.multiLine(p,a,l,"center","bottom","flowing");this.setTextAlignment(m,s.alignment),this.setOverflow(m,s),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(s.fontSize),m.depth=.001,m.writeTo(void 0,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case ur.LowerLeft:case ur.MiddleLeft:case ur.UpperLeft:e.horizontalAlignment="left";break;case ur.LowerCenter:case ur.MiddleCenter:case ur.UpperCenter:e.horizontalAlignment="center";break;case ur.LowerRight:case ur.MiddleRight:case ur.UpperRight:e.horizontalAlignment="right";break}switch(t){case ur.LowerLeft:case ur.LowerCenter:case ur.LowerRight:e.verticalAlignment="bottom";break;case ur.MiddleLeft:case ur.MiddleCenter:case ur.MiddleRight:e.verticalAlignment="middle";break;case ur.UpperLeft:case ur.UpperCenter:case ur.UpperRight:e.verticalAlignment="top";break}}}class BC{get extensionName(){return"tmui"}onExportObject(e,t,r){const s=ie.getComponent(e,Jr);if(s&&s.enabled&&s.renderMode===HV.WorldSpace){const o=new hb,a=ie.getComponent(e,Ts),l=ie.getComponent(e,hd),c=new Array;if(a){if(!ie.isActiveSelf(e)){const p=ie.isActiveSelf(e);ie.setActive(e,!0),a.onEnable(),a.updateTransform(),c.push(()=>{a.onDisable(),ie.setActive(e,p)})}e.traverse(p=>{if(!ie.isActiveInHierarchy(p)){const m=ie.isActiveSelf(p);ie.setActive(p,!0);const f=ie.getComponent(p,Va);f&&(f.onEnable(),c.push(()=>{f.onDisable()}));const g=ie.getComponent(p,Ts);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),c.push(()=>{g.onDisable()}));const v=ie.getComponent(p,Rs);v&&(v.onEnable(),c.push(()=>{v.onDisable()})),c.push(()=>{ie.setActive(p,m)})}}),a.width,a.height;const h=Ws.createEmpty(),u=a.shadowComponent;if(t.add(h),u){const p=u.matrix;h.matrix.copy(p);const m=new Map,f=new Map;m.set(u,h),f.set(u,l?l.alpha:1),u.traverse(g=>{if(g===u)return;const v=Ws.createEmpty();v.matrix.copy(g.matrix);const y=g.parent,A=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let _=f.get(y)||1;const b=ie.getComponent(g,hd);if(b&&(_*=b.alpha),g instanceof me&&A){const E=g[Ma];E?o.exportText(E.gameObject,v,r):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof me&&!A){const E=g.geometry.clone();E.scale(1,1,-1),this.flipWindingOrder(E),v.geometry=E;const I=new xe,T=g.material.opacity;I.copy(g.material.color),v.material=new $t({color:I,opacity:T*_,map:g.material.map,transparent:!0})}m.set(g,v),f.set(g,_);const x=m.get(y);if(!x){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}x.add(v)})}}for(const h of c)h()}}flipWindingOrder(e){const t=e.index.array;for(let r=0,s=t.length/3;r<s;r++){const o=t[r*3];t[r*3]=t[r*3+2],t[r*3+2]=o}e.index.needsUpdate=!0}}const ub=te("debugusdz");function g0e(n,e){var t;const r=[],s=ie.getComponentsInChildren(n,Wr),o=ie.getComponentsInChildren(n,Es),a=new Array,l=new Array;if(e.injectImplicitBehaviours)for(const c of s){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;const h=c.runtimeAnimatorController.activeState;if(!h||!h.motion||!h.motion.clip||((t=h.motion.clip.tracks)==null?void 0:t.length)<1||a.includes(c))continue;const u=new fm;u.animator=c,u.stateName=h.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new ye;ie.addComponent(p,u),l.push(p),a.push(c),n.add(p)}else for(const c of s){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;ub&&console.log(c);const h=[];for(const u of c.runtimeAnimatorController.enumerateActions()){ub&&console.log(u);const p=u.getClip();h.includes(p)||h.push(p)}r.push({root:c.gameObject,clips:h})}if(e.injectImplicitBehaviours)for(const c of o){if(!c||!c.clip||!c.enabled||!c.playAutomatically||a.includes(c))continue;const h=new fm;h.animation=c,h.stateName=c.clip.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const u=new ye;ie.addComponent(u,h),l.push(u),a.push(c),n.add(u)}else for(const c of o){ub&&console.log(c);const h=[];for(const u of c.animations)h.includes(u)||h.push(u);r.push({root:c.gameObject,clips:h})}ub&&r?.length>0&&console.log("USDZ Animation Clips without behaviours",r);for(const c of r)for(const h of c.clips)e.registerAnimation(c.root,h);return l}function v0e(n,e){const t=ie.getComponentsInChildren(n,Mn),r=ie.getComponentsInChildren(n,ud),s=new Array,o=new Array;ub&&console.log({audioSources:t,playAudioOnClicks:r});for(const a of r){if(!a.target)continue;const l=t.indexOf(a.target);l>-1&&t.splice(l,1)}for(const a of t){if(!a||!a.clip||a.volume<=0||s.includes(a))continue;const l=new ud;l.target=a,l.name="PlayAudioOnClick_implicitAtStart_",l.trigger="start";const c=new ye;ie.addComponent(c,l),console.log("implicit PlayAudioOnStart",c,l),o.push(c),s.push(a),n.add(c)}return o}function y0e(n){return new Ar("DisableAtStart",br.sceneStartTrigger(),gi.fadeAction(n,0,!1))}function MQ(n){const e=n.domElement.shadowRoot.querySelector("link[rel='ar']");if(e)return e;const t=document.createElement("div");t.classList.add("menu"),t.classList.add("quicklook-menu"),t.style.display="none",t.style.visibility="hidden";const r=document.createElement("button");r.id="open-in-ar",r.innerText="Open in QuickLook",t.appendChild(r);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",t.appendChild(s);const o=document.createElement("img");return o.id="button",s.appendChild(o),n.domElement.shadowRoot.appendChild(t),s}var A0e=Object.defineProperty,b0e=Object.getOwnPropertyDescriptor,Ps=(n,e,t,r)=>{for(var s=r>1?void 0:r?b0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&A0e(e,t,s),s};const Oa=te("debugusdz");class bd{constructor(){d(this,"callToAction"),d(this,"checkoutTitle"),d(this,"checkoutSubtitle"),d(this,"callToActionURL")}}Ps([w()],bd.prototype,"callToAction",2),Ps([w()],bd.prototype,"checkoutTitle",2),Ps([w()],bd.prototype,"checkoutSubtitle",2),Ps([w()],bd.prototype,"callToActionURL",2);var kC;const vD=(kC=class extends Be{constructor(){super(...arguments),d(this,"objectToExport"),d(this,"autoExportAnimations",!0),d(this,"autoExportAudioSources",!0),d(this,"exportFileName"),d(this,"customUsdzFile"),d(this,"customBranding"),d(this,"anchoringType","plane"),d(this,"maxTextureSize",2048),d(this,"planeAnchoringAlignment","horizontal"),d(this,"interactive",!0),d(this,"allowCreateQuicklookButton",!0),d(this,"quickLookCompatible",!0),d(this,"extensions",[]),d(this,"link"),d(this,"button"),d(this,"onClickedOpenInARElement",n=>{n.preventDefault(),this.exportAndOpen()}),d(this,"_currentExportTasks",new Map),d(this,"_previousTimeScale",1),d(this,"lastCallback"),d(this,"_rootSessionRootWasAppliedTo",null),d(this,"_rootPositionBeforeExport",new C),d(this,"_rootRotationBeforeExport",new Ce),d(this,"_rootScaleBeforeExport",new C)}start(){var n,e,t;Oa&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",r=>{switch(r.key){case"t":this.exportAsync();break}}),aa()&&setTimeout(()=>{this.exportAsync()},2e3)),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(n=this.objectToExport)==null?void 0:n.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new tC),this.extensions.push(new Pd),this.extensions.push(new RC),this.extensions.push(new hb),this.extensions.push(new BC))}onEnable(){var n;const e=vp(),t=Lf();(Oa||e&&t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=MQ(this.context),this.link.addEventListener("message",this.lastCallback)),Oa&&rn("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement)}onDisable(){var n,e,t;(n=this.button)==null||n.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),Oa&&rn("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement)}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+="-"+Kj(),uu()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=MQ(this.context)),this.customUsdzFile)return Oa&&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 t=await this.export(this.objectToExport);return t?(Oa&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(n){if(!n)return console.warn("No object to export"),null;const e=this._currentExportTasks.get(n);if(e)return e;const t=this.internalExport(n);return t instanceof Promise?(this._currentExportTasks.set(n,t),t.then(r=>(this._currentExportTasks.delete(n),r)).catch(r=>(this._currentExportTasks.delete(n),console.error("Error during USDZ export \u2013 please report a bug!",r),null))):t}async internalExport(n){ni.start("export-usdz",{onProgress:y=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:y}}))}}),ni.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ni.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ni.start("export-usdz-textures","export-usdz");const e=ie.getComponentsInChildren(n,ka);for(const y of e)y&&y.enabled&&y.start&&y.start();const t=ie.getComponentsInChildren(n,Tn),r=new Array;let s=0;for(const y of t){for(const A of y.sharedMeshes)if(A){const _=fi.assignMeshLOD(A,0);_ instanceof Promise&&r.push(new Promise((b,x)=>{_.then(()=>{s++,ni.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:r.length}),b()}).catch(E=>x(E))}))}for(const A of y.sharedMaterials)if(A){const _=fi.assignTextureLOD(A,0);_ instanceof Promise&&r.push(new Promise((b,x)=>{_.then(()=>{s++,ni.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:r.length}),b()}).catch(E=>x(E))}))}}Oa&&rn("Progressive Loading: "+r.length),await Promise.all(r),Oa&&rn("Progressive Loading: done"),ni.end("export-usdz-textures");const o=eo.Global.Mask;eo.Global.Set(rc.AR);const a=new i5,l=new BA(this.quickLookCompatible),c=[l,...this.extensions],h={self:this,exporter:a,extensions:c,object:n};ni.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:h})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,ni.report("export-usdz","auto export animations and audio sources");const u=new Array;this.autoExportAnimations&&u.push(...g0e(n,l)),this.extensions.find(y=>y.extensionName==="Audio")&&this.autoExportAudioSources&&u.push(...v0e(n)),a.debug=Oa,a.keepObject=y=>{const A=ie.getComponent(y,Tn);return!(A&&!A.enabled)};const p=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(y=>{y.visible||p.push(y)});const m=this.extensions.find(y=>y.extensionName==="Behaviour");this.interactive&&m&&p.length>0&&m.addBehavior(y0e(p));let f=!0;this.quickLookCompatible&&!this.interactive&&(f=!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"),ni.report("export-usdz","Invoking exporter.parse");const g=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:c,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:f}),v=new Blob([g],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ni.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:h}));for(const y of u)ie.destroy(y);return eo.Global.Set(o),ni.end("export-usdz"),v}openInQuickLook(n,e){const t=n instanceof Blob?URL.createObjectURL(n):n,r=this.buildQuicklookOverlay();Oa&&console.log("QuickLook Overlay",r);const s=r.callToAction?encodeURIComponent(r.callToAction):"",o=r.checkoutTitle?encodeURIComponent(r.checkoutTitle):"",a=r.checkoutSubtitle?encodeURIComponent(r.checkoutSubtitle):"";this.link.href=t+`#callToAction=${s}&checkoutTitle=${o}&checkoutSubtitle=${a}&callToActionURL=${r.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(n,e){vD.save(n,e)}static save(n,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof n=="string"?t.href=n:t.href=URL.createObjectURL(n),t.download=e,t.click(),t.remove()}quicklookCallback(n){if(n?.data=="_apple_ar_quicklook_button_tapped"){Oa&&Di("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const r=t.get("callToActionURL");Oa&&rn("Quicklook url: "+r),r&&(uu()?globalThis.open(r,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",r))}}}}buildQuicklookOverlay(){var n,e,t,r,s,o;const a={};return this.customBranding&&Object.assign(a,this.customBranding),uu()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),a.callToAction="Close",a.checkoutTitle="\u{1F335} Made with Needle",a.checkoutSubtitle="_"),(((n=a.callToAction)==null?void 0:n.length)||((e=a.checkoutTitle)==null?void 0:e.length)||((t=a.checkoutSubtitle)==null?void 0:t.length))&&((r=a.callToAction)!=null&&r.length||(a.callToAction="\0"),(s=a.checkoutTitle)!=null&&s.length||(a.checkoutTitle="\0"),(o=a.checkoutSubtitle)!=null&&o.length||(a.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:a})),a}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};let n=ie.getComponentInParent(this.objectToExport,io);n||(n=ie.getComponentInChildren(this.objectToExport,io));let e=1,t=!1;const r=this.objectToExport;if(n)e=n.arScale,t=n.invertForward;else{const s=ie.findObjectOfType(Ir);s&&(e=s.arSceneScale)}return{scale:1/e,_invertForward:t,target:r,sessionRoot:n?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:n,_invertForward:e,target:t,sessionRoot:r}=this.getARScaleAndTarget(),s=r?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=t,this._rootPositionBeforeExport.copy(t.position),this._rootRotationBeforeExport.copy(t.quaternion),this._rootScaleBeforeExport.copy(t.scale),t.scale.multiplyScalar(n),e&&t.quaternion.multiply(vD.invertForwardQuaternion),t.updateMatrix(),t.updateMatrixWorld(!0),r&&s&&t.matrix.premultiply(s)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const n=this._rootSessionRootWasAppliedTo;n.position.copy(this._rootPositionBeforeExport),n.quaternion.copy(this._rootRotationBeforeExport),n.scale.copy(this._rootScaleBeforeExport),n.updateMatrix(),n.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const n=Am.getOrCreate().createQuicklookButton();return n.parentNode||this.context.menu.appendChild(n),n}},d(kC,"invertForwardMatrix",new ve().makeRotationY(Math.PI)),d(kC,"invertForwardQuaternion",new Ce().setFromEuler(new ii(0,Math.PI,0))),kC);let Rn=vD;Ps([w(ye)],Rn.prototype,"objectToExport",2),Ps([w()],Rn.prototype,"autoExportAnimations",2),Ps([w()],Rn.prototype,"autoExportAudioSources",2),Ps([w()],Rn.prototype,"exportFileName",2),Ps([w(URL)],Rn.prototype,"customUsdzFile",2),Ps([w(bd)],Rn.prototype,"customBranding",2),Ps([w()],Rn.prototype,"anchoringType",2),Ps([w()],Rn.prototype,"maxTextureSize",2),Ps([w()],Rn.prototype,"planeAnchoringAlignment",2),Ps([w()],Rn.prototype,"interactive",2),Ps([w()],Rn.prototype,"allowCreateQuicklookButton",2),Ps([w()],Rn.prototype,"quickLookCompatible",2);class db extends Be{constructor(){super(...arguments),d(this,"isUsed",!0),d(this,"usedBy",null)}}class yD extends Be{}const TQ=te("debugdeletable");class DC extends ac{}class AD extends Be{constructor(){super(...arguments),d(this,"deleteBoxes",[])}awake(){this.deleteBoxes=ie.findObjectsOfType(DC,this.context)}update(){for(const e of this.deleteBoxes){const t=this.gameObject;if(e.isInBox(t)===!0){const r=ie.getComponentInParent(this.gameObject,db);r?TQ&&console.warn("Can not delete object with usage marker",this.guid,r):(TQ&&console.log("DESTROY",this.gameObject),hA(this.gameObject,this.context.connection))}}}}var _0e=Object.defineProperty,x0e=Object.getOwnPropertyDescriptor,wm=(n,e,t,r)=>{for(var s=r>1?void 0:r?x0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&_0e(e,t,s),s};const w0e=te("debugpost");class xl extends Xr{constructor(){super(...arguments),d(this,"mode"),d(this,"focusDistance",new qe(1)),d(this,"focalLength",new qe(.2)),d(this,"aperture",new qe(20)),d(this,"gaussianMaxRadius",new qe),d(this,"resolutionScale",new qe(1*1/window.devicePixelRatio)),d(this,"bokehScale",new qe)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const r=t/300,s=2;return it.lerp(s,.01,r)};const e=20;this.aperture.valueProcessor=t=>{const r=1-t/32;return it.lerp(1,e,r)}}onCreateEffect(){if(this.mode===0){w0e&&console.warn("DepthOfField: Mode is set to Off");return}const e=new $5(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}wm([w()],xl.prototype,"mode",2),wm([w(qe)],xl.prototype,"focusDistance",2),wm([w(qe)],xl.prototype,"focalLength",2),wm([w(qe)],xl.prototype,"aperture",2),wm([w(qe)],xl.prototype,"gaussianMaxRadius",2),wm([w(qe)],xl.prototype,"resolutionScale",2),wm([w(qe)],xl.prototype,"bokehScale",2),Ra("DepthOfField",xl);var S0e=Object.defineProperty,C0e=Object.getOwnPropertyDescriptor,E0e=(n,e,t,r)=>{for(var s=r>1?void 0:r?C0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&S0e(e,t,s),s};class OC extends Be{constructor(){super(...arguments),d(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||ie.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:aa()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}E0e([w()],OC.prototype,"visibleOn",2);class bD{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}var M0e=Object.defineProperty,T0e=Object.getOwnPropertyDescriptor,Sm=(n,e,t,r)=>{for(var s=r>1?void 0:r?T0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&M0e(e,t,s),s};const Ac=te("debugdrag");var IQ=(n=>(n[n.XZPlane=0]="XZPlane",n[n.Attached=1]="Attached",n[n.HitNormal=2]="HitNormal",n[n.DynamicViewAngle=3]="DynamicViewAngle",n[n.SnapToSurfaces=4]="SnapToSurfaces",n[n.None=5]="None",n))(IQ||{}),LC;const bc=(LC=class extends Be{constructor(){super(...arguments),d(this,"dragMode",3),d(this,"snapGridResolution",0),d(this,"keepRotation",!0),d(this,"xrDragMode",1),d(this,"xrKeepRotation",!1),d(this,"xrDistanceDragFactor",1),d(this,"showGizmo",!1),d(this,"targetObject",null),d(this,"orbit",null),d(this,"_dragHelper",null),d(this,"_draggingRigidbodies",[]),d(this,"_potentialDragStartEvt",null),d(this,"_dragHandlers",new Map),d(this,"_totalMovement",new C),d(this,"_marker",null),d(this,"_isDragging",!1),d(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}setTargetObject(n){this.targetObject=n;for(const e of this._dragHandlers.values())e.setTargetObject(n)}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new C,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.orbit=ie.findObjectOfType(bi,this.context),this.gameObject.getComponentInParent(No)||this.gameObject.addComponent(No)}allowEdit(n=null){return this.context.connection.allowEditing}onPointerEnter(n){if(!this.allowEdit(this.gameObject)||n.mode!=="screen"||(n.event.mode==="tracked-pointer"||n.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const e=ie.getComponentInParent(n.object,bc);!e||e!==this||(bc.lastHovered=n.object,this.context.domElement.style.cursor="pointer")}onPointerExit(n){this.allowEdit(this.gameObject)&&n.mode==="screen"&&bc.lastHovered===n.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(n){if(!(!this.allowEdit(this.gameObject)||n.used||(n.mode==="tracked-pointer"||n.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(bc.lastHovered=n.object,n.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=n),bc._active+=1;const e=new R0e(this,this.targetObject||this.gameObject);if(this._dragHandlers.set(n.event.space,e),this.orbit&&(this.orbit.enabled=!1),e.onDragStart(n),this._dragHandlers.size===2){const t=this._dragHandlers.values(),r=t.next().value,s=t.next().value,o=new I0e(this,this.targetObject||this.gameObject,r,s);this._dragHandlers.set(this.gameObject,o),o.onDragStart(n)}n.use()}}onPointerMove(n){(this._isDragging||this._potentialDragStartEvt!==null)&&n.use()}onPointerUp(n){if(Ac&&At.DrawLabel(n.point??this.gameObject.worldPosition,"POINTERUP:"+n.pointerId+", "+n.button,.03,3),!this.allowEdit(this.gameObject)||n.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(n.event.space),t=this._dragHandlers.get(this.gameObject);t&&(t.handlerA===e||t.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),t.onDragEnd(n)),e&&(bc._active>0&&(bc._active-=1),e.onDragEnd&&e.onDragEnd(n),this._dragHandlers.delete(n.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(n),n.use()),bc._active===0&&this.orbit&&(this.orbit.enabled=!0)}update(){for(const n of this._dragHandlers.values())n.collectMovementInfo&&n.collectMovementInfo(),n.getTotalMovement&&this._totalMovement.add(n.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const n=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(n)}for(const n of this._dragHandlers.values())n.onDragUpdate&&n.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(n){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new PQ(this.context.mainCamera);else return;if(!n||!n.object)return;const e=ie.getComponentInParent(n.object,bc);if(!e||e!==this&&e._isDragging)return;const t=this.targetObject||this.gameObject;if(!t)return;this._isDragging=!0,this._dragHelper.setSelected(t,this.context),this.orbit&&(this.orbit.enabled=!1);const r=ie.getComponentInChildren(t,Ku);Ac&&console.log("DRAG START",r,t),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=ie.addComponent(t,db),this._draggingRigidbodies.length=0;const s=ie.getComponentsInChildren(t,Oi);s&&this._draggingRigidbodies.push(...s)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const n=this.targetObject||this.gameObject;Qa.markDirty(n)}onLastDragEnd(n){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const t of this._draggingRigidbodies)t.setVelocity(t.smoothedVelocity);this._draggingRigidbodies.length=0;const e=this._dragHelper.selected;if(Ac&&console.log("DRAG END",e,e?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),n!=null&&n.object){const t=ie.getComponentInChildren(n.object,Ku);t&&(t.fastMode=!1)}this._marker&&this._marker.destroy()}},d(LC,"_active",0),d(LC,"lastHovered"),LC);let La=bc;Sm([w()],La.prototype,"dragMode",2),Sm([w()],La.prototype,"snapGridResolution",2),Sm([w()],La.prototype,"keepRotation",2),Sm([w()],La.prototype,"xrDragMode",2),Sm([w()],La.prototype,"xrKeepRotation",2),Sm([w()],La.prototype,"xrDistanceDragFactor",2),Sm([w()],La.prototype,"showGizmo",2);class I0e{constructor(e,t,r,s){d(this,"handlerA"),d(this,"handlerB"),d(this,"context"),d(this,"settings"),d(this,"gameObject"),d(this,"_handlerAAttachmentPoint",new C),d(this,"_handlerBAttachmentPoint",new C),d(this,"_followObject"),d(this,"_manipulatorObject"),d(this,"_deviceMode"),d(this,"_followObjectStartWorldQuaternion",new Ce),d(this,"_manipulatorPosOffset",new C),d(this,"_manipulatorRotOffset",new Ce),d(this,"_manipulatorScaleOffset",new C),d(this,"_tempVec1",new C),d(this,"_tempVec2",new C),d(this,"_tempVec3",new C),d(this,"tempLookMatrix",new ve),d(this,"_initialScale",new C),d(this,"_initialDistance",0);var o,a;this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=r,this.handlerB=s,this._followObject=new ye,this._manipulatorObject=new ye,this.context.scene.add(this._manipulatorObject);const l=(a=(o=wt.active)==null?void 0:o.rig)==null?void 0:a.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),l&&(l.worldToLocal(this._tempVec1),l.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(Ac&&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 \u2013 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(t.scale),Ac){this._followObject.add(new Po(2)),this._manipulatorObject.add(new Po(5));const c=h=>`${h.x.toFixed(2)}, ${h.y.toFixed(2)}, ${h.z.toFixed(2)}`;At.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),At.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
6214
6214
  `+c(this._tempVec1)+`
6215
6215
  `+c(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(e){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),Ac&&(At.DrawLabel(this._tempVec3.clone().add(new C(0,.2,0)),"A:B "+t.toFixed(2),.03),At.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const e=30,t=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const r=this.gameObject,s=this._followObject;s.updateMatrix(),s.updateMatrixWorld(!0);const o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const u=this._followObject.worldPosition,p=this.settings.snapGridResolution;u.x=Math.round(u.x/p)*p,u.y=Math.round(u.y/p)*p,u.z=Math.round(u.z/p)*p,this._followObject.worldPosition=u,this._followObject.updateMatrix()}o&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const a=it.clamp01(this.context.time.deltaTime*e*t),l=r.worldPosition;l.lerp(s.worldPosition,a),r.worldPosition=l;const c=r.worldQuaternion;c.slerp(s.worldQuaternion,a),r.worldQuaternion=c;const h=r.worldScale;h.lerp(s.worldScale,a),r.worldScale=h}setTargetObject(e){this.gameObject=e}}class R0e{constructor(e,t){d(this,"context"),d(this,"gameObject"),d(this,"settings"),d(this,"_lastRig"),d(this,"_followObject"),d(this,"_totalMovement",new C),d(this,"_totalMovementAlongRayDirection",0),d(this,"_grabStartDistance",0),d(this,"_deviceMode"),d(this,"_followObjectStartPosition",new C),d(this,"_followObjectStartQuaternion",new Ce),d(this,"_followObjectStartWorldQuaternion",new Ce),d(this,"_lastDragPosRigSpace"),d(this,"_tempVec",new C),d(this,"_tempMat",new ve),d(this,"_hitPointInLocalSpace",new C),d(this,"_hitNormalInLocalSpace",new C),d(this,"_bottomCenter",new C),d(this,"_backCenter",new C),d(this,"_backBottomCenter",new C),d(this,"_bounds",new xi),d(this,"_dragPlane",new ms(new C(0,1,0))),d(this,"_draggedOverObject",null),d(this,"_draggedOverObjectLastSetUp",null),d(this,"_draggedOverObjectLastNormal",new C),d(this,"_draggedOverObjectDuration",0),this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new ye}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(e){this.gameObject=e}recenter(){var e,t;if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}const r=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),r.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const s=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(s),this._grabStartDistance=s.distanceTo(r.worldPosition);const o=(t=(e=wt.active)==null?void 0:e.rig)==null?void 0:t.gameObject,a=o?.worldScale.x||1;this._grabStartDistance/=a,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,Ac&&(At.DrawLine(s,r.worldPosition,65280,.5,!1),At.DrawLabel(r.worldPosition.add(new C(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const f=e.event.space,g=f.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const v=f.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),v.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(v)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const t=this._followObject.parent.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,s=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(s),r){case 0:const f=new C(0,1,0);this.gameObject.parent&&f.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(f,s);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,s);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,s);break;case 3:const v=new C(0,1,0),y=t,A=v.angleTo(y),_=.5;A>Math.PI/2+_||A<Math.PI/2-_?this._dragPlane.setFromNormalAndCoplanarPoint(new C(0,1,0),s):this._dragPlane.setFromNormalAndCoplanarPoint(t,s);break}const o=this.gameObject.parent,a=this.gameObject.position.clone(),l=this.gameObject.quaternion.clone(),c=this.gameObject.scale.clone(),h=this.gameObject.matrixWorld.clone();o&&o.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const u=Ul([this.gameObject]);u.expandByPoint(this.gameObject.worldPosition);const p=new C;u.getCenter(p);const m=new C;u.getSize(m),this._bottomCenter.copy(p.clone().add(new C(0,-m.y/2,0))),this._backCenter.copy(p.clone().add(new C(0,0,m.z/2))),this._backBottomCenter.copy(p.clone().add(new C(0,-m.y/2,m.z/2))),this._bounds.copy(u),o&&o.add(this.gameObject),this.gameObject.position.copy(a),this.gameObject.quaternion.copy(l),this.gameObject.scale.copy(c),this.gameObject.matrixWorld.copy(h),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var e,t;if(!this._followObject.parent)return;const r=this._followObject.parent;this._followObject.updateMatrix();const s=r.worldPosition,o=(t=(e=wt.active)==null?void 0:e.rig)==null?void 0:t.gameObject;o&&o.worldToLocal(s),(this._lastDragPosRigSpace===void 0||o!=this._lastRig)&&(this._lastDragPosRigSpace=s.clone(),this._lastRig=o),this._tempVec.copy(s).sub(this._lastDragPosRigSpace);const a=r.worldForward;if(o&&(this._tempMat.copy(o.matrixWorld).invert(),a.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=a.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(s),Ac){let l=s;o&&(l=l.clone(),l.transformDirection(o.matrixWorld)),At.DrawRay(l,a,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject,r=this._followObject.parent;this._followObject.updateMatrix();const s=r.worldPosition,o=r.worldForward,a=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",l=a?this.settings.xrKeepRotation:this.settings.keepRotation,c=a?this.settings.xrDragMode:this.settings.dragMode;if(c===5)return;const h=10;l&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let u=1,p=2;if(a&&this._grabStartDistance>.5){const y=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);u=Math.max(0,y),u=u*u*u}else this._grabStartDistance<=.5&&(p=3);this._followObject.position.copy(this._followObjectStartPosition),l||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(u),this._followObject.updateMatrix();const m=new co(s,o);if(c==4){const y=new ml;y.testObject=_=>_!==this.followObject&&_!==r&&_!==t;const A=this.context.physics.raycastFromRay(m,y);if(A.length>0){const _=A[0];if(this._draggedOverObject===_.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=_.object,this._draggedOverObjectDuration=0),_.face){const b=this._draggedOverObjectDuration>=.15,x=.001,E=this._totalMovement.length()>=x;if((b||E)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(_.face.normal)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(_.face.normal);const I=pi(),T=pi();this._bounds.getCenter(I),this._bounds.getSize(T),I.sub(T.multiplyScalar(.5).multiply(_.face.normal)),this._hitPointInLocalSpace.copy(I),this._hitNormalInLocalSpace.copy(_.face.normal),this._bounds.getCenter(I),this._bounds.getSize(T),I.add(T.multiplyScalar(.5).multiply(_.face.normal));const R=pi(this._hitPointInLocalSpace).add(I);this._followObject.localToWorld(R);const D=_.point;this._dragPlane.setFromNormalAndCoplanarPoint(_.face.normal,D)}else if(!(b||E))return}}}if(c!==1&&m.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const y=this._hitPointInLocalSpace.clone();this._followObject.localToWorld(y),Ac&&At.DrawLine(y,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(y),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const y=this._followObject.worldPosition,A=this.settings.snapGridResolution;y.x=Math.round(y.x/A)*A,y.y=Math.round(y.y/A)*A,y.z=Math.round(y.z/A)*A,this._followObject.worldPosition=y,this._followObject.updateMatrix()}l&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const f=it.clamp01(this.context.time.deltaTime*h*p),g=t.worldPosition;g.lerp(this._followObject.worldPosition,f),t.worldPosition=g;const v=t.worldQuaternion;if(v.slerp(this._followObject.worldQuaternion,f),t.worldQuaternion=v,Ac){const y=this._hitPointInLocalSpace.clone();t.localToWorld(y),At.DrawSphere(y,.02,16711680);const A=this._hitNormalInLocalSpace.clone();A.applyQuaternion(v),At.DrawRay(y,A,16711680),At.DrawLabel(g.add(new C(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
6216
6216
 
@@ -6849,7 +6849,7 @@ void main() {
6849
6849
  vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
6850
6850
 
6851
6851
  #include <fog_vertex>
6852
- }`);new C(0,0,1);var Eye=function(n){T0(t,n);var e=I0(t);function t(r){var s;return Et(this,t),s=e.call(this,r),$(si(s),"positionBuffer",void 0),$(si(s),"previousBuffer",void 0),$(si(s),"nextBuffer",void 0),$(si(s),"uvBuffer",void 0),$(si(s),"sideBuffer",void 0),$(si(s),"widthBuffer",void 0),$(si(s),"colorBuffer",void 0),$(si(s),"indexBuffer",void 0),$(si(s),"vector_",new C),$(si(s),"vector2_",new C),$(si(s),"vector3_",new C),$(si(s),"quaternion_",new Ce),s.maxParticles=1e4,s.setupBuffers(),s.rebuildMaterial(),s}return Mt(t,[{key:"setupBuffers",value:function(){this.geometry&&this.geometry.dispose(),this.geometry=new yt,this.indexBuffer=new nt(new Uint32Array(this.maxParticles*6),1),this.indexBuffer.setUsage(hs),this.geometry.setIndex(this.indexBuffer),this.positionBuffer=new nt(new Float32Array(this.maxParticles*6),3),this.positionBuffer.setUsage(hs),this.geometry.setAttribute("position",this.positionBuffer),this.previousBuffer=new nt(new Float32Array(this.maxParticles*6),3),this.previousBuffer.setUsage(hs),this.geometry.setAttribute("previous",this.previousBuffer),this.nextBuffer=new nt(new Float32Array(this.maxParticles*6),3),this.nextBuffer.setUsage(hs),this.geometry.setAttribute("next",this.nextBuffer),this.widthBuffer=new nt(new Float32Array(this.maxParticles*2),1),this.widthBuffer.setUsage(hs),this.geometry.setAttribute("width",this.widthBuffer),this.sideBuffer=new nt(new Float32Array(this.maxParticles*2),1),this.sideBuffer.setUsage(hs),this.geometry.setAttribute("side",this.sideBuffer),this.uvBuffer=new nt(new Float32Array(this.maxParticles*4),2),this.uvBuffer.setUsage(hs),this.geometry.setAttribute("uv",this.uvBuffer),this.colorBuffer=new nt(new Float32Array(this.maxParticles*8),4),this.colorBuffer.setUsage(hs),this.geometry.setAttribute("color",this.colorBuffer)}},{key:"expandBuffers",value:function(r){for(;r>=this.maxParticles;)this.maxParticles*=2;this.setupBuffers()}},{key:"rebuildMaterial",value:function(){this.layers.mask=this.settings.layers.mask;var r={lineWidth:{value:1},map:{value:null},useMap:{value:0},alphaMap:{value:null},useAlphaMap:{value:0},resolution:{value:new Z(1,1)},sizeAttenuation:{value:1},visibility:{value:1},alphaTest:{value:0},repeat:{value:new Z(1,1)}},s={};if(s.USE_UV="",s.USE_COLOR_ALPHA="",this.settings.material.map&&(s.USE_MAP="",s.MAP_UV=$D(this.settings.material.map.channel),r.map=new Se(this.settings.material.map),r.mapTransform=new Se(new Dt().copy(this.settings.material.map.matrix))),this.settings.renderMode===ot.Trail)this.material=new Rt({uniforms:r,defines:s,vertexShader:Cye,fragmentShader:Sye,transparent:this.settings.material.transparent,depthWrite:!this.settings.material.transparent,side:this.settings.material.side,blending:this.settings.material.blending||Ld});else throw new Error("render mode unavailable")}},{key:"update",value:function(){var r=this,s=0,o=0,a=0;this.systems.forEach(function(l){for(var c=0;c<l.particleNum;c++)a+=l.particles[c].previous.length*2}),a>this.maxParticles&&this.expandBuffers(a),this.systems.forEach(function(l){var c=r.quaternion_,h=r.vector2_,u=r.vector3_;l.emitter.matrixWorld.decompose(h,c,u);for(var p=l.particles,m=l.particleNum,f=r.settings.uTileCount,g=r.settings.vTileCount,v=1/f,y=1/g,A=0;A<m;A++){var _=p[A],b=_.uvTile%g,x=Math.floor(_.uvTile/g),E=_.previous.values(),I=E.next(),T=I.value,R=T;I.done||(I=E.next());var D=void 0;I.value!==void 0?D=I.value:D=R;for(var M=0;M<_.previous.length;M++,s+=2){if(r.positionBuffer.setXYZ(s,R.position.x,R.position.y,R.position.z),r.positionBuffer.setXYZ(s+1,R.position.x,R.position.y,R.position.z),l.worldSpace?(r.positionBuffer.setXYZ(s,R.position.x,R.position.y,R.position.z),r.positionBuffer.setXYZ(s+1,R.position.x,R.position.y,R.position.z)):(_.parentMatrix?r.vector_.copy(R.position).applyMatrix4(_.parentMatrix):r.vector_.copy(R.position).applyMatrix4(l.emitter.matrixWorld),r.positionBuffer.setXYZ(s,r.vector_.x,r.vector_.y,r.vector_.z),r.positionBuffer.setXYZ(s+1,r.vector_.x,r.vector_.y,r.vector_.z)),l.worldSpace?(r.previousBuffer.setXYZ(s,T.position.x,T.position.y,T.position.z),r.previousBuffer.setXYZ(s+1,T.position.x,T.position.y,T.position.z)):(_.parentMatrix?r.vector_.copy(T.position).applyMatrix4(_.parentMatrix):r.vector_.copy(T.position).applyMatrix4(l.emitter.matrixWorld),r.previousBuffer.setXYZ(s,r.vector_.x,r.vector_.y,r.vector_.z),r.previousBuffer.setXYZ(s+1,r.vector_.x,r.vector_.y,r.vector_.z)),l.worldSpace?(r.nextBuffer.setXYZ(s,D.position.x,D.position.y,D.position.z),r.nextBuffer.setXYZ(s+1,D.position.x,D.position.y,D.position.z)):(_.parentMatrix?r.vector_.copy(D.position).applyMatrix4(_.parentMatrix):r.vector_.copy(D.position).applyMatrix4(l.emitter.matrixWorld),r.nextBuffer.setXYZ(s,r.vector_.x,r.vector_.y,r.vector_.z),r.nextBuffer.setXYZ(s+1,r.vector_.x,r.vector_.y,r.vector_.z)),r.sideBuffer.setX(s,-1),r.sideBuffer.setX(s+1,1),l.worldSpace)r.widthBuffer.setX(s,R.size),r.widthBuffer.setX(s+1,R.size);else if(_.parentMatrix)r.widthBuffer.setX(s,R.size),r.widthBuffer.setX(s+1,R.size);else{var P=(Math.abs(u.x)+Math.abs(u.y)+Math.abs(u.z))/3;r.widthBuffer.setX(s,R.size*P),r.widthBuffer.setX(s+1,R.size*P)}r.uvBuffer.setXY(s,(M/_.previous.length+b)*v,(g-x-1)*y),r.uvBuffer.setXY(s+1,(M/_.previous.length+b)*v,(g-x)*y),r.colorBuffer.setXYZW(s,R.color.x,R.color.y,R.color.z,R.color.w),r.colorBuffer.setXYZW(s+1,R.color.x,R.color.y,R.color.z,R.color.w),M+1<_.previous.length&&(r.indexBuffer.setX(o*3,s),r.indexBuffer.setX(o*3+1,s+1),r.indexBuffer.setX(o*3+2,s+2),o++,r.indexBuffer.setX(o*3,s+2),r.indexBuffer.setX(o*3+1,s+1),r.indexBuffer.setX(o*3+2,s+3),o++),T=R,R=D,I.done||(I=E.next(),I.value!==void 0&&(D=I.value))}}}),this.positionBuffer.updateRange.count=s*3,this.positionBuffer.needsUpdate=!0,this.previousBuffer.updateRange.count=s*3,this.previousBuffer.needsUpdate=!0,this.nextBuffer.updateRange.count=s*3,this.nextBuffer.needsUpdate=!0,this.sideBuffer.updateRange.count=s,this.sideBuffer.needsUpdate=!0,this.widthBuffer.updateRange.count=s,this.widthBuffer.needsUpdate=!0,this.uvBuffer.updateRange.count=s*2,this.uvBuffer.needsUpdate=!0,this.colorBuffer.updateRange.count=s*4,this.colorBuffer.needsUpdate=!0,this.indexBuffer.updateRange.count=o*3,this.indexBuffer.needsUpdate=!0,this.geometry.setDrawRange(0,o*3)}},{key:"dispose",value:function(){this.geometry.dispose()}}]),t}(TH),Mye=function(n){T0(t,n);var e=I0(t);function t(){var r;return Et(this,t),r=e.call(this),$(si(r),"batches",[]),$(si(r),"systemToBatchIndex",new Map),$(si(r),"type","BatchedRenderer"),r}return Mt(t,[{key:"addSystem",value:function(r){r._renderer=this;for(var s=r.getRendererSettings(),o=0;o<this.batches.length;o++)if(t.equals(this.batches[o].settings,s)){this.batches[o].addSystem(r),this.systemToBatchIndex.set(r,o);return}var a;switch(s.renderMode){case ot.Trail:a=new Eye(s);break;case ot.Mesh:case ot.BillBoard:case ot.VerticalBillBoard:case ot.HorizontalBillBoard:case ot.StretchedBillBoard:a=new wye(s);break}a.addSystem(r),this.batches.push(a),this.systemToBatchIndex.set(r,this.batches.length-1),this.add(a)}},{key:"deleteSystem",value:function(r){var s=this.systemToBatchIndex.get(r);s!=null&&(this.batches[s].removeSystem(r),this.systemToBatchIndex.delete(r))}},{key:"updateSystem",value:function(r){this.deleteSystem(r),this.addSystem(r)}},{key:"update",value:function(r){this.systemToBatchIndex.forEach(function(o,a){a.update(r)});for(var s=0;s<this.batches.length;s++)this.batches[s].update()}}],[{key:"equals",value:function(r,s){return r.material.side===s.material.side&&r.material.blending===s.material.blending&&r.material.transparent===s.material.transparent&&r.material.type===s.material.type&&r.material.alphaTest===s.material.alphaTest&&r.material.map===s.material.map&&r.renderMode===s.renderMode&&r.uTileCount===s.uTileCount&&r.vTileCount===s.vTileCount&&r.instancingGeometry===s.instancingGeometry&&r.renderOrder===s.renderOrder&&r.layers.mask===s.layers.mask}}]),t}(ye),Tye=Mye,RH=function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new C;Et(this,n),$(this,"locations",[]),this.scaleX=e,this.scaleY=t,this.position=r}return Mt(n,[{key:"transform",value:function(e,t){e.x=this.locations[t%this.locations.length].x*this.scaleX+this.position.x,e.y=this.locations[t%this.locations.length].y*this.scaleY+this.position.y,e.z=this.position.z}},{key:"clone",value:function(){var e=new n(this.scaleX,this.scaleY,this.position.clone());return e.locations=this.locations.map(function(t){return t.clone()}),e}},{key:"toJSON",value:function(){return{scaleX:this.scaleX,scaleY:this.scaleY,position:this.position,locations:this.locations.map(function(e){return{x:e.x,y:e.y}})}}},{key:"fromImage",value:function(e,t){var r=document.createElement("canvas");r.width=e.width,r.height=e.height;var s=r.getContext("2d");if(s){s.drawImage(e,0,0);var o=s.getImageData(0,0,r.width,r.height,{colorSpace:"srgb"});r.remove(),this.locations.length=0;for(var a=0;a<o.height;a++)for(var l=0;l<o.width;l++)o.data[(a*o.width+l)*4+3]>t&&this.locations.push(new Z(l,o.height-a))}}}],[{key:"fromJSON",value:function(e){var t=new n(e.scaleX,e.scaleY,new C(e.position[0],e.position[1],e.position[2]));return t.locations=e.locations.map(function(r){return new Z(r.x,r.y)}),t}}]),n}();function Iye(n){switch(n.type){case"TextureSequencer":return RH.fromJSON(n);default:return new RH}}var Rye=function(){function n(e){Et(this,n),$(this,"type","ApplySequences"),$(this,"sequencers",[]),$(this,"time",0),$(this,"index",0),$(this,"pCount",0),$(this,"delay",void 0),$(this,"tempV",new C),this.delay=e}return Mt(n,[{key:"initialize",value:function(e){e.id=this.pCount,e.dst=new C,e.begin=new C,e.inMotion=!1,this.pCount++}},{key:"reset",value:function(){this.time=0,this.index=0,this.pCount=0}},{key:"update",value:function(e,t){var r=this.sequencers[this.index],s=e.id*this.delay;this.time>=r[0].a+s&&this.time<=r[0].b+s?(e.inMotion||(e.inMotion=!0,e.begin.copy(e.position),r[1].transform(e.dst,e.id)),e.position.lerpVectors(e.begin,e.dst,n.BEZIER.genValue((this.time-r[0].a-s)/(r[0].b-r[0].a)))):this.time>r[0].b+s&&(e.inMotion=!1)}},{key:"frameUpdate",value:function(e){for(;this.index+1<this.sequencers.length&&this.time>=this.sequencers[this.index+1][0].a;)this.index++;this.time+=e}},{key:"appendSequencer",value:function(e,t){this.sequencers.push([e,t])}},{key:"toJSON",value:function(){return{type:this.type,delay:this.delay,sequencers:this.sequencers.map(function(e){var t=R0(e,2),r=t[0],s=t[1];return{range:r.toJSON(),sequencer:s.toJSON()}})}}},{key:"clone",value:function(){var e=new n(this.delay);return e.sequencers=this.sequencers.map(function(t){return[t[0].clone(),t[1].clone()]}),e}}],[{key:"fromJSON",value:function(e){var t=new n(e.delay);return e.sequencers.forEach(function(r){t.sequencers.push([Wi(r.range),Iye(r.sequencer)])}),t}}]),n}();$(Rye,"BEZIER",new HD(0,0,1,1));var ue=function(n){return n[n.Number=0]="Number",n[n.Vec2=1]="Vec2",n[n.Vec3=2]="Vec3",n[n.Vec4=3]="Vec4",n[n.Boolean=4]="Boolean",n[n.AnyType=5]="AnyType",n}({}),PH=Mt(function n(e,t,r,s){Et(this,n),$(this,"input",void 0),$(this,"inputIndex",void 0),$(this,"output",void 0),$(this,"outputIndex",void 0),this.input=e,this.inputIndex=t,this.input.outputs[t].push(this),this.output=r,this.outputIndex=s,this.output.inputs[s]=this}),Pye=function(){function n(){Et(this,n),$(this,"visited",new Set),$(this,"graph_",void 0),$(this,"context_",void 0),n.Instance=this}return Mt(n,[{key:"traverse",value:function(e){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");this.visited.add(e.id);for(var t=[],r=0;r<e.inputs.length;r++)if(e.inputs[r]instanceof PH){var s=e.inputs[r].input;this.visited.has(s.id)||this.traverse(s),t.push(s.outputValues[e.inputs[r].inputIndex])}else t.push(e.inputs[r].getValue(this.context_));e.func(this.context_,t,e.outputValues),this.graph_.nodesInOrder.push(e)}},{key:"executeCompiledGraph",value:function(){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");for(var e=this.graph_.nodesInOrder,t=0;t<e.length;t++){for(var r=[],s=e[t],o=0;o<s.inputs.length;o++)if(s.inputs[o]instanceof PH)r.push(s.inputs[o].input.outputValues[s.inputs[o].inputIndex]);else if(s.inputs[o]!==void 0)r.push(s.inputs[o].getValue(this.context_));else throw new Error("miss input for node ".concat(s.id));s.func(this.context_,r,s.outputValues)}}},{key:"run",value:function(e,t){if(this.graph_=e,this.context_=t,e.compiled)this.executeCompiledGraph();else{e.nodesInOrder.length=0,this.visited.clear();for(var r=0;r<e.outputNodes.length;r++){var s=e.outputNodes[r];this.traverse(s)}e.compiled=!0}}}]),n}();$(Pye,"Instance",void 0);var mi=function(){function n(e){Et(this,n),$(this,"name",void 0),$(this,"nodeTypeSignatures",[]),this.name=e}return Mt(n,[{key:"addSignature",value:function(e,t,r){this.nodeTypeSignatures.push({inputTypes:e,outputTypes:t,func:r})}}]),n}(),ZC=new mi("add");ZC.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=t[0]+t[1]}),ZC.addSignature([ue.Vec2,ue.Vec2],[ue.Vec2],function(n,e,t,r){r[0].addVectors(t[0],t[1])}),ZC.addSignature([ue.Vec3,ue.Vec3],[ue.Vec3],function(n,e,t,r){r[0].addVectors(t[0],t[1])}),ZC.addSignature([ue.Vec4,ue.Vec4],[ue.Vec4],function(n,e,t,r){r[0].addVectors(t[0],t[1])});var $C=new mi("sub");$C.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=t[0]-t[1]}),$C.addSignature([ue.Vec2,ue.Vec2],[ue.Vec2],function(n,e,t,r){r[0].subVectors(t[0],t[1])}),$C.addSignature([ue.Vec3,ue.Vec3],[ue.Vec3],function(n,e,t,r){r[0].subVectors(t[0],t[1])}),$C.addSignature([ue.Vec4,ue.Vec4],[ue.Vec4],function(n,e,t,r){r[0].subVectors(t[0],t[1])});var eE=new mi("mul");eE.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=t[0]*t[1]}),eE.addSignature([ue.Vec2,ue.Number],[ue.Vec2],function(n,e,t,r){r[0].copy(t[0]).multiplyScalar(t[1])}),eE.addSignature([ue.Vec3,ue.Number],[ue.Vec3],function(n,e,t,r){r[0].copy(t[0]).multiplyScalar(t[1])}),eE.addSignature([ue.Vec4,ue.Number],[ue.Vec4],function(n,e,t,r){r[0].copy(t[0]).multiplyScalar(t[1])});var tE=new mi("div");tE.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=t[0]/t[1]}),tE.addSignature([ue.Vec2,ue.Number],[ue.Vec2],function(n,e,t,r){r[0].copy(t[0]).divideScalar(t[1])}),tE.addSignature([ue.Vec3,ue.Number],[ue.Vec3],function(n,e,t,r){r[0].copy(t[0]).divideScalar(t[1])}),tE.addSignature([ue.Vec4,ue.Number],[ue.Vec4],function(n,e,t,r){r[0].copy(t[0]).divideScalar(t[1])});var Bye=new mi("sin");Bye.addSignature([ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.sin(t[0])});var kye=new mi("cos");kye.addSignature([ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.cos(t[0])});var Dye=new mi("tan");Dye.addSignature([ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.tan(t[0])});var Oye=new mi("abs");Oye.addSignature([ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.abs(t[0])});var Lye=new mi("min");Lye.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.min(t[0],t[1])});var Fye=new mi("max");Fye.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.max(t[0],t[1])});var eO=new mi("dot");eO.addSignature([ue.Vec2,ue.Vec2],[ue.Number],function(n,e,t,r){r[0]=t[0].dot(t[1])}),eO.addSignature([ue.Vec3,ue.Vec3],[ue.Number],function(n,e,t,r){r[0]=t[0].dot(t[1])}),eO.addSignature([ue.Vec4,ue.Vec4],[ue.Number],function(n,e,t,r){r[0]=t[0].dot(t[1])});var Uye=new mi("cross");Uye.addSignature([ue.Vec3,ue.Vec3],[ue.Vec3],function(n,e,t,r){r[0].crossVectors(t[0],t[1])});var tO=new mi("length");tO.addSignature([ue.Vec2],[ue.Number],function(n,e,t,r){r[0]=t[0].length()}),tO.addSignature([ue.Vec3],[ue.Number],function(n,e,t,r){r[0]=t[0].length()}),tO.addSignature([ue.Vec4],[ue.Number],function(n,e,t,r){r[0]=t[0].length()});var iO=new mi("lengthSq");iO.addSignature([ue.Vec2],[ue.Number],function(n,e,t,r){r[0]=t[0].lengthSq()}),iO.addSignature([ue.Vec3],[ue.Number],function(n,e,t,r){r[0]=t[0].lengthSq()}),iO.addSignature([ue.Vec4],[ue.Number],function(n,e,t,r){r[0]=t[0].lengthSq()});var nO=new mi("normalize");nO.addSignature([ue.Vec2],[ue.Vec2],function(n,e,t,r){r[0].copy(t[0]).normalize()}),nO.addSignature([ue.Vec3],[ue.Vec3],function(n,e,t,r){r[0].copy(t[0]).normalize()}),nO.addSignature([ue.Vec4],[ue.Vec4],function(n,e,t,r){r[0].copy(t[0]).normalize()});var BH=new mi("distance");BH.addSignature([ue.Vec2,ue.Vec2],[ue.Number],function(n,e,t,r){r[0]=t[0].distanceTo(t[1])}),BH.addSignature([ue.Vec3,ue.Vec3],[ue.Number],function(n,e,t,r){r[0]=t[0].distanceTo(t[1])});var Nye=new mi("and");Nye.addSignature([ue.Boolean,ue.Boolean],[ue.Boolean],function(n,e,t,r){r[0]=t[0]&&t[1]});var zye=new mi("or");zye.addSignature([ue.Boolean,ue.Boolean],[ue.Boolean],function(n,e,t,r){r[0]=t[0]||t[1]});var jye=new mi("not");jye.addSignature([ue.Boolean],[ue.Boolean],function(n,e,t,r){r[0]=!t[0]});var iE=new mi("equal");iE.addSignature([ue.Number,ue.Number],[ue.Boolean],function(n,e,t,r){r[0]=t[0]===t[1]}),iE.addSignature([ue.Vec2,ue.Vec2],[ue.Boolean],function(n,e,t,r){r[0]=t[0].equals(t[1])}),iE.addSignature([ue.Vec3,ue.Vec3],[ue.Boolean],function(n,e,t,r){r[0]=t[0].equals(t[1])}),iE.addSignature([ue.Vec4,ue.Vec4],[ue.Boolean],function(n,e,t,r){r[0]=t[0].equals(t[1])});var Gye=new mi("lessThan");Gye.addSignature([ue.Number,ue.Number],[ue.Boolean],function(n,e,t,r){r[0]=t[0]<t[1]});var Vye=new mi("greaterThan");Vye.addSignature([ue.Number,ue.Number],[ue.Boolean],function(n,e,t,r){r[0]=t[0]>t[1]});var Qye=new mi("lessThanOrEqual");Qye.addSignature([ue.Number,ue.Number],[ue.Boolean],function(n,e,t,r){r[0]=t[0]<=t[1]});var Hye=new mi("greaterThanOrEqual");Hye.addSignature([ue.Number,ue.Number],[ue.Boolean],function(n,e,t,r){r[0]=t[0]>=t[1]});var Wye=new mi("if");Wye.addSignature([ue.Boolean,ue.AnyType,ue.AnyType],[ue.AnyType],function(n,e,t,r){r[0]=t[0]?t[1]:t[2]});var Xye=new mi("number");Xye.addSignature([],[ue.Number],function(n,e,t,r){r[0]=e.value});var qye=new mi("vec2");qye.addSignature([],[ue.Vec2],function(n,e,t,r){r[0]=e.value});var Yye=new mi("vec3");Yye.addSignature([],[ue.Vec3],function(n,e,t,r){r[0]=e.value});var Jye=new mi("vec4");Jye.addSignature([],[ue.Vec4],function(n,e,t,r){r[0]=e.value});var Kye=new mi("bool");Kye.addSignature([],[ue.Boolean],function(n,e,t,r){r[0]=e.value});var Zye=new mi("particlePosition");Zye.addSignature([],[ue.Vec3],function(n,e,t,r){r[0]=n.particle[e.property]});var $ye=new mi("particleVelocity");$ye.addSignature([],[ue.Vec3],function(n,e,t,r){r[0]=n.particle[e.property]});var eAe=new mi("particleRotation");eAe.addSignature([],[ue.Number],function(n,e,t,r){r[0]=n.particle[e.property]});var tAe=new mi("particleAge");tAe.addSignature([],[ue.Number],function(n,e,t,r){r[0]=n.particle[e.property]});var Mb=new mi("output");Mb.addSignature([ue.Number],[ue.Number],function(n,e,t,r){r[0]=t[0]}),Mb.addSignature([ue.Vec2],[ue.Vec2],function(n,e,t,r){r[0]=t[0]}),Mb.addSignature([ue.Vec3],[ue.Vec3],function(n,e,t,r){r[0]=t[0]}),Mb.addSignature([ue.Vec4],[ue.Vec4],function(n,e,t,r){r[0]=t[0]}),Mb.addSignature([ue.Boolean],[ue.Boolean],function(n,e,t,r){r[0]=t[0]}),console.log("%c Particle system powered by three.quarks. https://quarks.art/","font-size: 16px; font-weight: bold;");var iAe=Object.defineProperty,nAe=Object.getOwnPropertyDescriptor,An=(n,e,t,r)=>{for(var s=r>1?void 0:r?nAe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&iAe(e,t,s),s};const Tb=te("debugparticles"),rAe=te("noprogressive"),sAe=te("debugprogressive");var rO=(n=>(n[n.Birth=0]="Birth",n[n.Collision=1]="Collision",n[n.Death=2]="Death",n[n.Trigger=3]="Trigger",n[n.Manual=4]="Manual",n))(rO||{});class Fa extends Be{constructor(){super(...arguments),d(this,"renderMode"),d(this,"particleMaterial"),d(this,"trailMaterial"),d(this,"particleMesh"),d(this,"maxParticleSize"),d(this,"minParticleSize"),d(this,"velocityScale"),d(this,"cameraVelocityScale"),d(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&st()){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 e;return((e=this.particleMaterial)==null?void 0:e.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;return t&&e&&t.side===nr&&(t=t.clone(),t.side=dn,e?this.trailMaterial=t:this.particleMaterial=t),t&&!rAe&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,sAe&&console.log("Load material LOD",t.name),fi.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof me&&(t=this.particleMesh.geometry),t===null)){t=new tr(1,1);const r=t.attributes.uv;for(let s=0;s<r.count;s++)r.setX(s,1-r.getX(s))}return new me(t,this.getMaterial())}}An([w()],Fa.prototype,"renderMode",2),An([w(Ot)],Fa.prototype,"particleMaterial",2),An([w(Ot)],Fa.prototype,"trailMaterial",2),An([w()],Fa.prototype,"maxParticleSize",2),An([w()],Fa.prototype,"minParticleSize",2),An([w()],Fa.prototype,"velocityScale",2),An([w()],Fa.prototype,"cameraVelocityScale",2),An([w()],Fa.prototype,"lengthScale",2);class nE{constructor(e,t=1){d(this,"_curve"),d(this,"_factor"),d(this,"type","function"),this._curve=e,this._factor=t}genValue(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 sO{constructor(e){d(this,"type","value"),d(this,"system"),this.system=e}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class oAe extends sO{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class aAe extends sO{constructor(){super(...arguments),d(this,"_lastPosition",new C),d(this,"_lastDistance",0)}update(){const e=Bt(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 o=this._lastDistance/this.system.deltaTime*s;Number.isFinite(o)||(o=0),e+=o}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const r=this.system.maxParticles-this.system.currentParticles;return it.clamp(e,0,r/this.system.deltaTime)}}class lAe extends sO{genValue(){return this.system.isPlaying,0}}class Sd{constructor(e){d(this,"system"),d(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}get context(){return this.system.context}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class cAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleTextureSheet")}update(e,t){const r=this.system.textureSheetAnimation;if(r.enabled){const s=e.age/e.life,o=r.evaluate(s);o!==void 0&&(e.uvTile=o)}}}const kH=Symbol("particleRotation");class hAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleRotation")}initialize(e){e[kH]=Math.random()}update(e,t){if(e.rotation===void 0)return;const r=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(r,e[kH])*t:this.system.renderer.renderMode===Bh.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const s=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(r,s)*t}}}const DH=Symbol("sizeLerpFactor"),uAe=new C;class dAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleSize"),d(this,"_minSize",0),d(this,"_maxSize",1)}initialize(e){e[DH]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const r=e.age/e.life;let s=1;this.system.sizeOverLifetime.enabled&&(s*=this.system.sizeOverLifetime.evaluate(r,void 0,e[DH]).x);let o=1;if(this.system.renderer.renderMode!==Bh.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale),e.size=e.startSize*s*o,this.system.localspace){const a=NH(this.system,uAe);e.size*=a.x}}}const P0=Symbol("particleLife"),oO=Symbol("trailLifetime"),OH=Symbol("trailStartLength"),aO=Symbol("trailWidthRandom");class pAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleTrail")}initialize(e){e instanceof xb&&(e[P0]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[oO]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[oO]),e[OH]=e.length,e[aO]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof xb){const r=e,s=e.age/e[P0],o=e.previous.values(),a=e.previous.length;for(let l=0;l<a;l++){const c=o.next().value,h=1-l/(a-1);let u=e.size;u<=0&&!this.system.trails.sizeAffectsWidth&&(u=20*this.system.trails.widthOverTrail.evaluate(.5,r[aO])),c.size=this.system.trails.getWidth(u,s,h,r[aO]),c.color.copy(e.color),this.system.trails.getColor(c.color,s,h)}if(e.age>e[P0]){e.velocity.set(0,0,0);const l=(e.age-e[P0])/e[oO];r.length=it.lerp(e[OH],0,l)}}}}const rE=Symbol("startVelocity"),LH=Symbol("gravityModifier"),lO=Symbol("gravitySpeed"),sE=Symbol("velocity lerp factor"),cO=new C;class mAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleVelocity"),d(this,"_gravityDirection",new C)}initialize(e){var t,r;const s=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random()),e.velocity.copy(this.system.shape.getDirection(e,e.position)).multiplyScalar(e.startSpeed),(t=this.system.inheritVelocity)!=null&&t.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[rE]?e[rE].copy(e.velocity):e[rE]=e.velocity.clone();const o=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[LH]=o*s,e[lO]=o*s*.5,e[sE]=Math.random(),(r=this.system.velocityOverLifetime)==null||r.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===nb.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var r;const s=e[rE],o=e[LH];if(o!==0){const m=o*e[lO];cO.copy(this._gravityDirection).multiplyScalar(m),e[lO]+=t*.05,s.add(cO)}e.velocity.copy(s);const a=e.age/e.life;(r=this.system.inheritVelocity)!=null&&r.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,a,e[sE]);const l=this.system.noise;l.enabled&&l.apply(0,e.position,e.velocity,t,e.age,e.life);const c=this.system.sizeBySpeed;c!=null&&c.enabled&&(e.size=c.evaluate(e.velocity,a,e[sE],e.size));const h=this.system.colorBySpeed;h!=null&&h.enabled&&h.evaluate(e.velocity,e[sE],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,t,e.age,e.life);const p=this.system.limitVelocityOverLifetime;p.enabled&&p.apply(e.position,s,e.velocity,e.size,a,t,1),this.system.worldspace&&e.velocity.multiply(this.system.worldScale)}}const FH=Symbol("colorLerpFactor"),UH=new Si(1,1,1,1),Pm=new Si(1,1,1,1);class fAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Pm.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(UH.copy(t.color),Pm.multiply(UH)),Pm.convertLinearToSRGB(),e.startColor.set(Pm.r,Pm.g,Pm.b,Pm.alpha),e.color.copy(e.startColor),e[FH]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const r=e.age/e.life,s=this.system.colorOverLifetime.color.evaluate(r,e[FH]);e.color.set(s.r,s.g,s.b,s.alpha).multiply(e.startColor)}else e.color.copy(e.startColor)}}class gAe{constructor(e){d(this,"system"),d(this,"emission"),d(this,"autoDestroy"),d(this,"startLength"),d(this,"emissionBursts"),d(this,"onlyUsedByOther"),d(this,"behaviors",[]),d(this,"rendererEmitterSettings",{startLength:new Bs(220),followLocalOrigin:!1}),d(this,"flatWhiteTexture"),d(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=e,this.emission=new aAe(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 nE(this.system.main.startLifetime)}get startSpeed(){return new nE(this.system.main.startSpeed)}get startRotation(){return new nE(this.system.main.startRotation)}get startSize(){return new nE(this.system.main.startSize)}get startColor(){return new KC(new Ye(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new lAe(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return ot.Trail;switch(this.system.renderer.renderMode){case Bh.Billboard:return ot.BillBoard;case Bh.Stretch:return ot.StretchedBillBoard;case Bh.HorizontalBillboard:return ot.HorizontalBillBoard;case Bh.VerticalBillboard:return ot.VerticalBillBoard;case Bh.Mesh:return ot.Mesh}return ot.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===Bh.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const r=t.clone();r.premultiplyAlpha=!1,r.colorSpace=Ri,this.clonedTexture.original=t,this.clonedTexture.clone=r}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=WB(new Si(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new oAe(this.system)}get uTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesX:void 0}get vTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesY:void 0}get renderOrder(){return 1}get blending(){var e;return((e=this.system.renderer.particleMaterial)==null?void 0:e.blending)??Qh}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===nb.World}}class vAe{constructor(){d(this,"burstIndex",0),d(this,"burstWaveIndex",0),d(this,"time",0),d(this,"waitEmiting",0)}}const oE=class extends Be{constructor(){super(...arguments),d(this,"_state"),d(this,"colorOverLifetime"),d(this,"main"),d(this,"emission"),d(this,"sizeOverLifetime"),d(this,"shape"),d(this,"noise"),d(this,"trails"),d(this,"velocityOverLifetime"),d(this,"limitVelocityOverLifetime"),d(this,"inheritVelocity"),d(this,"colorBySpeed"),d(this,"textureSheetAnimation"),d(this,"rotationOverLifetime"),d(this,"rotationBySpeed"),d(this,"sizeBySpeed"),d(this,"_cameraScale",1),d(this,"__worldQuaternion",new Ce),d(this,"_worldQuaternionInverted",new Ce),d(this,"_worldScale",new C),d(this,"_worldPositionFrame",-1),d(this,"_worldPos",new C),d(this,"_renderer"),d(this,"_batchSystem"),d(this,"_particleSystem"),d(this,"_interface"),d(this,"_container"),d(this,"_time",0),d(this,"_isPlaying",!0),d(this,"_isUsedAsSubsystem",!1),d(this,"_didPreWarm",!1),d(this,"_bursts"),d(this,"_subEmitterSystems"),d(this,"_lastBatchesCount",-1),d(this,"lastMaterialVersion",-1)}play(n=!1){var e;n&&ie.foreachComponent(this.gameObject,t=>{t instanceof oE&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(e=this.emission)==null||e.reset()}pause(n=!0){n&&ie.foreachComponent(this.gameObject,e=>{e instanceof oE&&e!==this&&e.pause(!1)},!0),this._isPlaying=!1}stop(n=!0,e=!1){n&&ie.foreachComponent(this.gameObject,t=>{t instanceof oE&&t!==this&&t.stop(!1,e)},!0),this._isPlaying=!1,this._time=0,e&&this.reset()}reset(){var n;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(n=this.emission)==null||n.reset())}emit(n){if(this._particleSystem){this.onUpdate(),n=Math.min(n,this.maxParticles-this.currentParticles),this._state||(this._state=new vAe),this._state.waitEmiting=n,this._state.time=0;const e=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=e}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(n){this.main.playOnAwake=n}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var n;return((n=this._particleSystem)==null?void 0:n.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===nb.World}get localspace(){return this.main.simulationSpace===nb.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,Bt(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(n){return this._particleSystem?(n instanceof Sd&&(n.system=this),st()&&console.log("add behaviour",n),this._particleSystem.addBehavior(n),!0):!1}removeBehaviour(n){if(!this._particleSystem)return!1;const e=this._particleSystem.behaviors,t=e.indexOf(n);return t!==-1&&e.splice(t,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(n){for(let e=0;e<n.length;e++){const t=n[e];if(!(t instanceof rb)){const r=new rb;Rg(r,t),n[e]=r}}this._bursts=n}set subEmitterSystems(n){for(let e=0;e<n.length;e++){const t=n[e];if(!(t instanceof Ib)){const r=new Ib;Rg(r,t),n[e]=r}}Tb&&n.length>0&&console.log("SubEmitters: ",n,this),this._subEmitterSystems=n}onAfterDeserialize(n){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const e of this._subEmitterSystems)e._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(Fa),!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 ye,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new Tye,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new gAe(this),this._particleSystem=new vye(this._interface),this._particleSystem.addBehavior(new dAe(this)),this._particleSystem.addBehavior(new fAe(this)),this._particleSystem.addBehavior(new cAe(this)),this._particleSystem.addBehavior(new hAe(this)),this._particleSystem.addBehavior(new mAe(this)),this._particleSystem.addBehavior(new pAe(this)),this._batchSystem.addSystem(this._particleSystem);const n=this._particleSystem.emitter;this.context.scene.add(n),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Tb&&(console.log(this),this.gameObject.add(new Po(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof me&&this._interface.renderMode==ot.Mesh&&fi.assignMeshLOD(this.renderer.particleMesh,0).then(n=>{n&&this.particleSystem&&this._interface.renderMode==ot.Mesh&&(this.particleSystem.instancingGeometry=n)})}onDestroy(){var n,e,t,r;(n=this._container)==null||n.removeFromParent(),(e=this._batchSystem)==null||e.removeFromParent(),(t=this._particleSystem)==null||t.emitter.removeFromParent(),(r=this._particleSystem)==null||r.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 n;this.main&&(this._didPreWarm===!1&&((n=this.main)==null?void 0:n.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var n;if(!((n=this.emission)!=null&&n.enabled)||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,r=this.main.startLifetime.getMax(),s=1e3,o=Math.min(Math.max(t,r)/Math.max(.01,this.main.simulationSpeed),s),a=Math.ceil(o/e),l=Date.now();Tb&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${o} sec). Duration: ${t}, Lifetime: ${r}`);for(let c=0;c<a&&!(this.currentParticles>=this.maxParticles);c++){const h=Date.now()-l;if(h>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${h}`);break}this.onUpdate(),this.onSimulate(e)}}onSimulate(n){if(this._batchSystem){let e=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,e=!0),e&&this.updateLayers(),this._batchSystem.update(n)}this._time+=n,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let n=0;n<this._batchSystem.batches.length;n++){const e=this._batchSystem.batches[n];e.layers.disableAll();const t=this.layer;e.layers.mask=1<<t}}onUpdate(){var n,e;const t=this.renderer.getMaterial(this.trails.enabled);if(t&&t.version!=this.lastMaterialVersion&&this._particleSystem&&(this.lastMaterialVersion=t.version,this._particleSystem.texture=this._interface.texture),this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const r=this.context.mainCamera;if(r){const a=Vi(r);this._cameraScale=a.x}const s=!this.worldspace,o=this.gameObject;if(Mi(o,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Vi(this.gameObject,this._worldScale),s&&this._container&&(n=this.gameObject)!=null&&n.parent){const a=NH(this,cO);this._container.matrix.makeScale(a.x,a.y,a.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.update(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(e=this.inheritVelocity)==null||e.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var n;if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():st()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=(n=e.particleSystem)==null?void 0:n._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const r=new aE(this,this._particleSystem,e.particleSystem,t);r.emitterType=e.type,r.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(r)}else Tb&&console.warn("Could not add SubParticleSystem",e,this)}}};let $n=oE;An([w(sb)],$n.prototype,"colorOverLifetime",2),An([w(Zr)],$n.prototype,"main",2),An([w(uc)],$n.prototype,"emission",2),An([w(gd)],$n.prototype,"sizeOverLifetime",2),An([w(vn)],$n.prototype,"shape",2),An([w(Ii)],$n.prototype,"noise",2),An([w(cn)],$n.prototype,"trails",2),An([w(yn)],$n.prototype,"velocityOverLifetime",2),An([w(Kn)],$n.prototype,"limitVelocityOverLifetime",2),An([w(vd)],$n.prototype,"inheritVelocity",2),An([w(ym)],$n.prototype,"colorBySpeed",2),An([w($r)],$n.prototype,"textureSheetAnimation",2),An([w(Ba)],$n.prototype,"rotationOverLifetime",2),An([w(Wo)],$n.prototype,"rotationBySpeed",2),An([w(to)],$n.prototype,"sizeBySpeed",2);class Ib{constructor(){d(this,"particleSystem"),d(this,"emitProbability",1),d(this,"properties"),d(this,"type")}_deserialize(e,t){const r=this.particleSystem;if(r instanceof $n)return;let s="";r&&typeof r.guid=="string"&&(s=r.guid,this.particleSystem=ie.findByGuid(s,t)),Tb&&!(this.particleSystem instanceof $n)&&console.warn("Could not find particle system for sub emitter",s,t,this)}}function NH(n,e){if(e.set(1,1,1),n.gameObject.parent&&n.localspace)switch(n.main.scalingMode){case lD.Local:e=Vi(n.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!n.unsupported_scaling_mode){n.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+lD[n.main.scalingMode]+" is not supported";st()&&Di(t),console.warn(t,n.name,n)}e=Vi(n.gameObject,e);break}return e}new C(1,1,1),new C(0,0,1);class aE{constructor(e,t,r,s){d(this,"type","NeedleParticleSubEmitter"),d(this,"emitterType"),d(this,"emitterProbability"),d(this,"q_",new Ce),d(this,"v_",new C),d(this,"v2_",new C),d(this,"_emitterMatrix",new ve),d(this,"_circularBuffer"),this.system=e,this.particleSystem=t,this.subSystem=r,this.subParticleSystem=s,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new oa(()=>new ve,o)}clone(){throw new Error("Method not implemented.")}initialize(e){e.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===rO.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===rO.Death){let s=e.life;if(e[P0]!==void 0&&(s=e[P0]),!(e.age+t*1.2>=s))return;const o=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=o}const r=new ve;r.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||r.multiplyMatrices(this._emitterMatrix,r),this.subParticleSystem.emit(t,e.emissionState,r)}}var yAe=Object.defineProperty,AAe=Object.getOwnPropertyDescriptor,bAe=(n,e,t,r)=>{for(var s=r>1?void 0:r?AAe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&yAe(e,t,s),s};class Rb extends Xr{constructor(){super(...arguments),d(this,"granularity",new qe(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new t6;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}bAe([w(qe)],Rb.prototype,"granularity",2),Ra("PixelationEffect",Rb);class J0 extends Be{constructor(){super(...arguments),d(this,"_didAssignPlayerColor",!1),d(this,"tryAssignColor",()=>{const e=ie.getComponentInParent(this.gameObject,Pa);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=ie.getComponentInParent(this.gameObject,Yr);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(Vt.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(Vt.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield pV(.2),!this.tryAssignColor()););}assignUserColor(e){const t=J0.hashCode(e),r=J0.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const s=this.gameObject;this.assignColor(r,e,s)}else if(this.gameObject.children)for(const s of this.gameObject.children){const o=s;o.material&&o.material.color&&this.assignColor(r,e,o)}}assignColor(e,t,r){let s=r.material;s&&(s._playerMaterial!==t&&(s=s.clone(),s._playerMaterial=t,r.material=s),s.color=e)}static hashCode(e){var t=0,r,s;if(e.length===0)return t;for(r=0;r<e.length;r++)s=e.charCodeAt(r),t=(t<<5)-t+s,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,r=(e&65280)>>8,s=e&255;return new xe(t/255,r/255,s/255)}}const Pb=new yt;Pb.setAttribute("position",new nt(new Float32Array([-1,-1,3,-1,-1,3]),2)),Pb.setAttribute("uv",new nt(new Float32Array([0,0,2,0,0,2]),2)),Pb.boundingSphere=new wn,Pb.computeBoundingSphere=function(){};const _Ae=new Bl;class Bm{constructor(e){this._mesh=new me(Pb,e),this._mesh.frustumCulled=!1}render(e){e.render(this._mesh,_Ae)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}dispose(){this._mesh.material.dispose(),this._mesh.geometry.dispose()}}const xAe={uniforms:{sceneDiffuse:{value:null},sceneDepth:{value:null},sceneNormal:{value:null},projMat:{value:new ve},viewMat:{value:new ve},projViewMat:{value:new ve},projectionMatrixInv:{value:new ve},viewMatrixInv:{value:new ve},cameraPos:{value:new C},resolution:{value:new Z},time:{value:0},samples:{value:[]},bluenoise:{value:null},distanceFalloff:{value:1},radius:{value:5},near:{value:.1},far:{value:1e3},logDepth:{value:!1},ortho:{value:!1},screenSpaceRadius:{value:!1},frame:{value:0}},depthWrite:!1,depthTest:!1,vertexShader:`
6852
+ }`);new C(0,0,1);var Eye=function(n){T0(t,n);var e=I0(t);function t(r){var s;return Et(this,t),s=e.call(this,r),$(si(s),"positionBuffer",void 0),$(si(s),"previousBuffer",void 0),$(si(s),"nextBuffer",void 0),$(si(s),"uvBuffer",void 0),$(si(s),"sideBuffer",void 0),$(si(s),"widthBuffer",void 0),$(si(s),"colorBuffer",void 0),$(si(s),"indexBuffer",void 0),$(si(s),"vector_",new C),$(si(s),"vector2_",new C),$(si(s),"vector3_",new C),$(si(s),"quaternion_",new Ce),s.maxParticles=1e4,s.setupBuffers(),s.rebuildMaterial(),s}return Mt(t,[{key:"setupBuffers",value:function(){this.geometry&&this.geometry.dispose(),this.geometry=new yt,this.indexBuffer=new nt(new Uint32Array(this.maxParticles*6),1),this.indexBuffer.setUsage(hs),this.geometry.setIndex(this.indexBuffer),this.positionBuffer=new nt(new Float32Array(this.maxParticles*6),3),this.positionBuffer.setUsage(hs),this.geometry.setAttribute("position",this.positionBuffer),this.previousBuffer=new nt(new Float32Array(this.maxParticles*6),3),this.previousBuffer.setUsage(hs),this.geometry.setAttribute("previous",this.previousBuffer),this.nextBuffer=new nt(new Float32Array(this.maxParticles*6),3),this.nextBuffer.setUsage(hs),this.geometry.setAttribute("next",this.nextBuffer),this.widthBuffer=new nt(new Float32Array(this.maxParticles*2),1),this.widthBuffer.setUsage(hs),this.geometry.setAttribute("width",this.widthBuffer),this.sideBuffer=new nt(new Float32Array(this.maxParticles*2),1),this.sideBuffer.setUsage(hs),this.geometry.setAttribute("side",this.sideBuffer),this.uvBuffer=new nt(new Float32Array(this.maxParticles*4),2),this.uvBuffer.setUsage(hs),this.geometry.setAttribute("uv",this.uvBuffer),this.colorBuffer=new nt(new Float32Array(this.maxParticles*8),4),this.colorBuffer.setUsage(hs),this.geometry.setAttribute("color",this.colorBuffer)}},{key:"expandBuffers",value:function(r){for(;r>=this.maxParticles;)this.maxParticles*=2;this.setupBuffers()}},{key:"rebuildMaterial",value:function(){this.layers.mask=this.settings.layers.mask;var r={lineWidth:{value:1},map:{value:null},useMap:{value:0},alphaMap:{value:null},useAlphaMap:{value:0},resolution:{value:new Z(1,1)},sizeAttenuation:{value:1},visibility:{value:1},alphaTest:{value:0},repeat:{value:new Z(1,1)}},s={};if(s.USE_UV="",s.USE_COLOR_ALPHA="",this.settings.material.map&&(s.USE_MAP="",s.MAP_UV=$D(this.settings.material.map.channel),r.map=new Se(this.settings.material.map),r.mapTransform=new Se(new Dt().copy(this.settings.material.map.matrix))),this.settings.renderMode===ot.Trail)this.material=new Rt({uniforms:r,defines:s,vertexShader:Cye,fragmentShader:Sye,transparent:this.settings.material.transparent,depthWrite:!this.settings.material.transparent,side:this.settings.material.side,blending:this.settings.material.blending||Ld});else throw new Error("render mode unavailable")}},{key:"update",value:function(){var r=this,s=0,o=0,a=0;this.systems.forEach(function(l){for(var c=0;c<l.particleNum;c++)a+=l.particles[c].previous.length*2}),a>this.maxParticles&&this.expandBuffers(a),this.systems.forEach(function(l){var c=r.quaternion_,h=r.vector2_,u=r.vector3_;l.emitter.matrixWorld.decompose(h,c,u);for(var p=l.particles,m=l.particleNum,f=r.settings.uTileCount,g=r.settings.vTileCount,v=1/f,y=1/g,A=0;A<m;A++){var _=p[A],b=_.uvTile%g,x=Math.floor(_.uvTile/g),E=_.previous.values(),I=E.next(),T=I.value,R=T;I.done||(I=E.next());var D=void 0;I.value!==void 0?D=I.value:D=R;for(var M=0;M<_.previous.length;M++,s+=2){if(r.positionBuffer.setXYZ(s,R.position.x,R.position.y,R.position.z),r.positionBuffer.setXYZ(s+1,R.position.x,R.position.y,R.position.z),l.worldSpace?(r.positionBuffer.setXYZ(s,R.position.x,R.position.y,R.position.z),r.positionBuffer.setXYZ(s+1,R.position.x,R.position.y,R.position.z)):(_.parentMatrix?r.vector_.copy(R.position).applyMatrix4(_.parentMatrix):r.vector_.copy(R.position).applyMatrix4(l.emitter.matrixWorld),r.positionBuffer.setXYZ(s,r.vector_.x,r.vector_.y,r.vector_.z),r.positionBuffer.setXYZ(s+1,r.vector_.x,r.vector_.y,r.vector_.z)),l.worldSpace?(r.previousBuffer.setXYZ(s,T.position.x,T.position.y,T.position.z),r.previousBuffer.setXYZ(s+1,T.position.x,T.position.y,T.position.z)):(_.parentMatrix?r.vector_.copy(T.position).applyMatrix4(_.parentMatrix):r.vector_.copy(T.position).applyMatrix4(l.emitter.matrixWorld),r.previousBuffer.setXYZ(s,r.vector_.x,r.vector_.y,r.vector_.z),r.previousBuffer.setXYZ(s+1,r.vector_.x,r.vector_.y,r.vector_.z)),l.worldSpace?(r.nextBuffer.setXYZ(s,D.position.x,D.position.y,D.position.z),r.nextBuffer.setXYZ(s+1,D.position.x,D.position.y,D.position.z)):(_.parentMatrix?r.vector_.copy(D.position).applyMatrix4(_.parentMatrix):r.vector_.copy(D.position).applyMatrix4(l.emitter.matrixWorld),r.nextBuffer.setXYZ(s,r.vector_.x,r.vector_.y,r.vector_.z),r.nextBuffer.setXYZ(s+1,r.vector_.x,r.vector_.y,r.vector_.z)),r.sideBuffer.setX(s,-1),r.sideBuffer.setX(s+1,1),l.worldSpace)r.widthBuffer.setX(s,R.size),r.widthBuffer.setX(s+1,R.size);else if(_.parentMatrix)r.widthBuffer.setX(s,R.size),r.widthBuffer.setX(s+1,R.size);else{var P=(Math.abs(u.x)+Math.abs(u.y)+Math.abs(u.z))/3;r.widthBuffer.setX(s,R.size*P),r.widthBuffer.setX(s+1,R.size*P)}r.uvBuffer.setXY(s,(M/_.previous.length+b)*v,(g-x-1)*y),r.uvBuffer.setXY(s+1,(M/_.previous.length+b)*v,(g-x)*y),r.colorBuffer.setXYZW(s,R.color.x,R.color.y,R.color.z,R.color.w),r.colorBuffer.setXYZW(s+1,R.color.x,R.color.y,R.color.z,R.color.w),M+1<_.previous.length&&(r.indexBuffer.setX(o*3,s),r.indexBuffer.setX(o*3+1,s+1),r.indexBuffer.setX(o*3+2,s+2),o++,r.indexBuffer.setX(o*3,s+2),r.indexBuffer.setX(o*3+1,s+1),r.indexBuffer.setX(o*3+2,s+3),o++),T=R,R=D,I.done||(I=E.next(),I.value!==void 0&&(D=I.value))}}}),this.positionBuffer.updateRange.count=s*3,this.positionBuffer.needsUpdate=!0,this.previousBuffer.updateRange.count=s*3,this.previousBuffer.needsUpdate=!0,this.nextBuffer.updateRange.count=s*3,this.nextBuffer.needsUpdate=!0,this.sideBuffer.updateRange.count=s,this.sideBuffer.needsUpdate=!0,this.widthBuffer.updateRange.count=s,this.widthBuffer.needsUpdate=!0,this.uvBuffer.updateRange.count=s*2,this.uvBuffer.needsUpdate=!0,this.colorBuffer.updateRange.count=s*4,this.colorBuffer.needsUpdate=!0,this.indexBuffer.updateRange.count=o*3,this.indexBuffer.needsUpdate=!0,this.geometry.setDrawRange(0,o*3)}},{key:"dispose",value:function(){this.geometry.dispose()}}]),t}(TH),Mye=function(n){T0(t,n);var e=I0(t);function t(){var r;return Et(this,t),r=e.call(this),$(si(r),"batches",[]),$(si(r),"systemToBatchIndex",new Map),$(si(r),"type","BatchedRenderer"),r}return Mt(t,[{key:"addSystem",value:function(r){r._renderer=this;for(var s=r.getRendererSettings(),o=0;o<this.batches.length;o++)if(t.equals(this.batches[o].settings,s)){this.batches[o].addSystem(r),this.systemToBatchIndex.set(r,o);return}var a;switch(s.renderMode){case ot.Trail:a=new Eye(s);break;case ot.Mesh:case ot.BillBoard:case ot.VerticalBillBoard:case ot.HorizontalBillBoard:case ot.StretchedBillBoard:a=new wye(s);break}a.addSystem(r),this.batches.push(a),this.systemToBatchIndex.set(r,this.batches.length-1),this.add(a)}},{key:"deleteSystem",value:function(r){var s=this.systemToBatchIndex.get(r);s!=null&&(this.batches[s].removeSystem(r),this.systemToBatchIndex.delete(r))}},{key:"updateSystem",value:function(r){this.deleteSystem(r),this.addSystem(r)}},{key:"update",value:function(r){this.systemToBatchIndex.forEach(function(o,a){a.update(r)});for(var s=0;s<this.batches.length;s++)this.batches[s].update()}}],[{key:"equals",value:function(r,s){return r.material.side===s.material.side&&r.material.blending===s.material.blending&&r.material.transparent===s.material.transparent&&r.material.type===s.material.type&&r.material.alphaTest===s.material.alphaTest&&r.material.map===s.material.map&&r.renderMode===s.renderMode&&r.uTileCount===s.uTileCount&&r.vTileCount===s.vTileCount&&r.instancingGeometry===s.instancingGeometry&&r.renderOrder===s.renderOrder&&r.layers.mask===s.layers.mask}}]),t}(ye),Tye=Mye,RH=function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new C;Et(this,n),$(this,"locations",[]),this.scaleX=e,this.scaleY=t,this.position=r}return Mt(n,[{key:"transform",value:function(e,t){e.x=this.locations[t%this.locations.length].x*this.scaleX+this.position.x,e.y=this.locations[t%this.locations.length].y*this.scaleY+this.position.y,e.z=this.position.z}},{key:"clone",value:function(){var e=new n(this.scaleX,this.scaleY,this.position.clone());return e.locations=this.locations.map(function(t){return t.clone()}),e}},{key:"toJSON",value:function(){return{scaleX:this.scaleX,scaleY:this.scaleY,position:this.position,locations:this.locations.map(function(e){return{x:e.x,y:e.y}})}}},{key:"fromImage",value:function(e,t){var r=document.createElement("canvas");r.width=e.width,r.height=e.height;var s=r.getContext("2d");if(s){s.drawImage(e,0,0);var o=s.getImageData(0,0,r.width,r.height,{colorSpace:"srgb"});r.remove(),this.locations.length=0;for(var a=0;a<o.height;a++)for(var l=0;l<o.width;l++)o.data[(a*o.width+l)*4+3]>t&&this.locations.push(new Z(l,o.height-a))}}}],[{key:"fromJSON",value:function(e){var t=new n(e.scaleX,e.scaleY,new C(e.position[0],e.position[1],e.position[2]));return t.locations=e.locations.map(function(r){return new Z(r.x,r.y)}),t}}]),n}();function Iye(n){switch(n.type){case"TextureSequencer":return RH.fromJSON(n);default:return new RH}}var Rye=function(){function n(e){Et(this,n),$(this,"type","ApplySequences"),$(this,"sequencers",[]),$(this,"time",0),$(this,"index",0),$(this,"pCount",0),$(this,"delay",void 0),$(this,"tempV",new C),this.delay=e}return Mt(n,[{key:"initialize",value:function(e){e.id=this.pCount,e.dst=new C,e.begin=new C,e.inMotion=!1,this.pCount++}},{key:"reset",value:function(){this.time=0,this.index=0,this.pCount=0}},{key:"update",value:function(e,t){var r=this.sequencers[this.index],s=e.id*this.delay;this.time>=r[0].a+s&&this.time<=r[0].b+s?(e.inMotion||(e.inMotion=!0,e.begin.copy(e.position),r[1].transform(e.dst,e.id)),e.position.lerpVectors(e.begin,e.dst,n.BEZIER.genValue((this.time-r[0].a-s)/(r[0].b-r[0].a)))):this.time>r[0].b+s&&(e.inMotion=!1)}},{key:"frameUpdate",value:function(e){for(;this.index+1<this.sequencers.length&&this.time>=this.sequencers[this.index+1][0].a;)this.index++;this.time+=e}},{key:"appendSequencer",value:function(e,t){this.sequencers.push([e,t])}},{key:"toJSON",value:function(){return{type:this.type,delay:this.delay,sequencers:this.sequencers.map(function(e){var t=R0(e,2),r=t[0],s=t[1];return{range:r.toJSON(),sequencer:s.toJSON()}})}}},{key:"clone",value:function(){var e=new n(this.delay);return e.sequencers=this.sequencers.map(function(t){return[t[0].clone(),t[1].clone()]}),e}}],[{key:"fromJSON",value:function(e){var t=new n(e.delay);return e.sequencers.forEach(function(r){t.sequencers.push([Wi(r.range),Iye(r.sequencer)])}),t}}]),n}();$(Rye,"BEZIER",new HD(0,0,1,1));var ue=function(n){return n[n.Number=0]="Number",n[n.Vec2=1]="Vec2",n[n.Vec3=2]="Vec3",n[n.Vec4=3]="Vec4",n[n.Boolean=4]="Boolean",n[n.AnyType=5]="AnyType",n}({}),PH=Mt(function n(e,t,r,s){Et(this,n),$(this,"input",void 0),$(this,"inputIndex",void 0),$(this,"output",void 0),$(this,"outputIndex",void 0),this.input=e,this.inputIndex=t,this.input.outputs[t].push(this),this.output=r,this.outputIndex=s,this.output.inputs[s]=this}),Pye=function(){function n(){Et(this,n),$(this,"visited",new Set),$(this,"graph_",void 0),$(this,"context_",void 0),n.Instance=this}return Mt(n,[{key:"traverse",value:function(e){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");this.visited.add(e.id);for(var t=[],r=0;r<e.inputs.length;r++)if(e.inputs[r]instanceof PH){var s=e.inputs[r].input;this.visited.has(s.id)||this.traverse(s),t.push(s.outputValues[e.inputs[r].inputIndex])}else t.push(e.inputs[r].getValue(this.context_));e.func(this.context_,t,e.outputValues),this.graph_.nodesInOrder.push(e)}},{key:"executeCompiledGraph",value:function(){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");for(var e=this.graph_.nodesInOrder,t=0;t<e.length;t++){for(var r=[],s=e[t],o=0;o<s.inputs.length;o++)if(s.inputs[o]instanceof PH)r.push(s.inputs[o].input.outputValues[s.inputs[o].inputIndex]);else if(s.inputs[o]!==void 0)r.push(s.inputs[o].getValue(this.context_));else throw new Error("miss input for node ".concat(s.id));s.func(this.context_,r,s.outputValues)}}},{key:"run",value:function(e,t){if(this.graph_=e,this.context_=t,e.compiled)this.executeCompiledGraph();else{e.nodesInOrder.length=0,this.visited.clear();for(var r=0;r<e.outputNodes.length;r++){var s=e.outputNodes[r];this.traverse(s)}e.compiled=!0}}}]),n}();$(Pye,"Instance",void 0);var mi=function(){function n(e){Et(this,n),$(this,"name",void 0),$(this,"nodeTypeSignatures",[]),this.name=e}return Mt(n,[{key:"addSignature",value:function(e,t,r){this.nodeTypeSignatures.push({inputTypes:e,outputTypes:t,func:r})}}]),n}(),ZC=new mi("add");ZC.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=t[0]+t[1]}),ZC.addSignature([ue.Vec2,ue.Vec2],[ue.Vec2],function(n,e,t,r){r[0].addVectors(t[0],t[1])}),ZC.addSignature([ue.Vec3,ue.Vec3],[ue.Vec3],function(n,e,t,r){r[0].addVectors(t[0],t[1])}),ZC.addSignature([ue.Vec4,ue.Vec4],[ue.Vec4],function(n,e,t,r){r[0].addVectors(t[0],t[1])});var $C=new mi("sub");$C.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=t[0]-t[1]}),$C.addSignature([ue.Vec2,ue.Vec2],[ue.Vec2],function(n,e,t,r){r[0].subVectors(t[0],t[1])}),$C.addSignature([ue.Vec3,ue.Vec3],[ue.Vec3],function(n,e,t,r){r[0].subVectors(t[0],t[1])}),$C.addSignature([ue.Vec4,ue.Vec4],[ue.Vec4],function(n,e,t,r){r[0].subVectors(t[0],t[1])});var eE=new mi("mul");eE.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=t[0]*t[1]}),eE.addSignature([ue.Vec2,ue.Number],[ue.Vec2],function(n,e,t,r){r[0].copy(t[0]).multiplyScalar(t[1])}),eE.addSignature([ue.Vec3,ue.Number],[ue.Vec3],function(n,e,t,r){r[0].copy(t[0]).multiplyScalar(t[1])}),eE.addSignature([ue.Vec4,ue.Number],[ue.Vec4],function(n,e,t,r){r[0].copy(t[0]).multiplyScalar(t[1])});var tE=new mi("div");tE.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=t[0]/t[1]}),tE.addSignature([ue.Vec2,ue.Number],[ue.Vec2],function(n,e,t,r){r[0].copy(t[0]).divideScalar(t[1])}),tE.addSignature([ue.Vec3,ue.Number],[ue.Vec3],function(n,e,t,r){r[0].copy(t[0]).divideScalar(t[1])}),tE.addSignature([ue.Vec4,ue.Number],[ue.Vec4],function(n,e,t,r){r[0].copy(t[0]).divideScalar(t[1])});var Bye=new mi("sin");Bye.addSignature([ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.sin(t[0])});var kye=new mi("cos");kye.addSignature([ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.cos(t[0])});var Dye=new mi("tan");Dye.addSignature([ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.tan(t[0])});var Oye=new mi("abs");Oye.addSignature([ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.abs(t[0])});var Lye=new mi("min");Lye.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.min(t[0],t[1])});var Fye=new mi("max");Fye.addSignature([ue.Number,ue.Number],[ue.Number],function(n,e,t,r){r[0]=Math.max(t[0],t[1])});var eO=new mi("dot");eO.addSignature([ue.Vec2,ue.Vec2],[ue.Number],function(n,e,t,r){r[0]=t[0].dot(t[1])}),eO.addSignature([ue.Vec3,ue.Vec3],[ue.Number],function(n,e,t,r){r[0]=t[0].dot(t[1])}),eO.addSignature([ue.Vec4,ue.Vec4],[ue.Number],function(n,e,t,r){r[0]=t[0].dot(t[1])});var Uye=new mi("cross");Uye.addSignature([ue.Vec3,ue.Vec3],[ue.Vec3],function(n,e,t,r){r[0].crossVectors(t[0],t[1])});var tO=new mi("length");tO.addSignature([ue.Vec2],[ue.Number],function(n,e,t,r){r[0]=t[0].length()}),tO.addSignature([ue.Vec3],[ue.Number],function(n,e,t,r){r[0]=t[0].length()}),tO.addSignature([ue.Vec4],[ue.Number],function(n,e,t,r){r[0]=t[0].length()});var iO=new mi("lengthSq");iO.addSignature([ue.Vec2],[ue.Number],function(n,e,t,r){r[0]=t[0].lengthSq()}),iO.addSignature([ue.Vec3],[ue.Number],function(n,e,t,r){r[0]=t[0].lengthSq()}),iO.addSignature([ue.Vec4],[ue.Number],function(n,e,t,r){r[0]=t[0].lengthSq()});var nO=new mi("normalize");nO.addSignature([ue.Vec2],[ue.Vec2],function(n,e,t,r){r[0].copy(t[0]).normalize()}),nO.addSignature([ue.Vec3],[ue.Vec3],function(n,e,t,r){r[0].copy(t[0]).normalize()}),nO.addSignature([ue.Vec4],[ue.Vec4],function(n,e,t,r){r[0].copy(t[0]).normalize()});var BH=new mi("distance");BH.addSignature([ue.Vec2,ue.Vec2],[ue.Number],function(n,e,t,r){r[0]=t[0].distanceTo(t[1])}),BH.addSignature([ue.Vec3,ue.Vec3],[ue.Number],function(n,e,t,r){r[0]=t[0].distanceTo(t[1])});var Nye=new mi("and");Nye.addSignature([ue.Boolean,ue.Boolean],[ue.Boolean],function(n,e,t,r){r[0]=t[0]&&t[1]});var zye=new mi("or");zye.addSignature([ue.Boolean,ue.Boolean],[ue.Boolean],function(n,e,t,r){r[0]=t[0]||t[1]});var jye=new mi("not");jye.addSignature([ue.Boolean],[ue.Boolean],function(n,e,t,r){r[0]=!t[0]});var iE=new mi("equal");iE.addSignature([ue.Number,ue.Number],[ue.Boolean],function(n,e,t,r){r[0]=t[0]===t[1]}),iE.addSignature([ue.Vec2,ue.Vec2],[ue.Boolean],function(n,e,t,r){r[0]=t[0].equals(t[1])}),iE.addSignature([ue.Vec3,ue.Vec3],[ue.Boolean],function(n,e,t,r){r[0]=t[0].equals(t[1])}),iE.addSignature([ue.Vec4,ue.Vec4],[ue.Boolean],function(n,e,t,r){r[0]=t[0].equals(t[1])});var Gye=new mi("lessThan");Gye.addSignature([ue.Number,ue.Number],[ue.Boolean],function(n,e,t,r){r[0]=t[0]<t[1]});var Vye=new mi("greaterThan");Vye.addSignature([ue.Number,ue.Number],[ue.Boolean],function(n,e,t,r){r[0]=t[0]>t[1]});var Qye=new mi("lessThanOrEqual");Qye.addSignature([ue.Number,ue.Number],[ue.Boolean],function(n,e,t,r){r[0]=t[0]<=t[1]});var Hye=new mi("greaterThanOrEqual");Hye.addSignature([ue.Number,ue.Number],[ue.Boolean],function(n,e,t,r){r[0]=t[0]>=t[1]});var Wye=new mi("if");Wye.addSignature([ue.Boolean,ue.AnyType,ue.AnyType],[ue.AnyType],function(n,e,t,r){r[0]=t[0]?t[1]:t[2]});var Xye=new mi("number");Xye.addSignature([],[ue.Number],function(n,e,t,r){r[0]=e.value});var qye=new mi("vec2");qye.addSignature([],[ue.Vec2],function(n,e,t,r){r[0]=e.value});var Yye=new mi("vec3");Yye.addSignature([],[ue.Vec3],function(n,e,t,r){r[0]=e.value});var Jye=new mi("vec4");Jye.addSignature([],[ue.Vec4],function(n,e,t,r){r[0]=e.value});var Kye=new mi("bool");Kye.addSignature([],[ue.Boolean],function(n,e,t,r){r[0]=e.value});var Zye=new mi("particlePosition");Zye.addSignature([],[ue.Vec3],function(n,e,t,r){r[0]=n.particle[e.property]});var $ye=new mi("particleVelocity");$ye.addSignature([],[ue.Vec3],function(n,e,t,r){r[0]=n.particle[e.property]});var eAe=new mi("particleRotation");eAe.addSignature([],[ue.Number],function(n,e,t,r){r[0]=n.particle[e.property]});var tAe=new mi("particleAge");tAe.addSignature([],[ue.Number],function(n,e,t,r){r[0]=n.particle[e.property]});var Mb=new mi("output");Mb.addSignature([ue.Number],[ue.Number],function(n,e,t,r){r[0]=t[0]}),Mb.addSignature([ue.Vec2],[ue.Vec2],function(n,e,t,r){r[0]=t[0]}),Mb.addSignature([ue.Vec3],[ue.Vec3],function(n,e,t,r){r[0]=t[0]}),Mb.addSignature([ue.Vec4],[ue.Vec4],function(n,e,t,r){r[0]=t[0]}),Mb.addSignature([ue.Boolean],[ue.Boolean],function(n,e,t,r){r[0]=t[0]}),console.log("%c Particle system powered by three.quarks. https://quarks.art/","font-size: 16px; font-weight: bold;");var iAe=Object.defineProperty,nAe=Object.getOwnPropertyDescriptor,An=(n,e,t,r)=>{for(var s=r>1?void 0:r?nAe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&iAe(e,t,s),s};const Tb=te("debugparticles"),rAe=te("noprogressive"),sAe=te("debugprogressive");var rO=(n=>(n[n.Birth=0]="Birth",n[n.Collision=1]="Collision",n[n.Death=2]="Death",n[n.Trigger=3]="Trigger",n[n.Manual=4]="Manual",n))(rO||{});class Fa extends Be{constructor(){super(...arguments),d(this,"renderMode"),d(this,"particleMaterial"),d(this,"trailMaterial"),d(this,"particleMesh"),d(this,"maxParticleSize"),d(this,"minParticleSize"),d(this,"velocityScale"),d(this,"cameraVelocityScale"),d(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&st()){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 e;return((e=this.particleMaterial)==null?void 0:e.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;return t&&e&&t.side===nr&&(t=t.clone(),t.side=dn,e?this.trailMaterial=t:this.particleMaterial=t),t&&!rAe&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,sAe&&console.log("Load material LOD",t.name),fi.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof me&&(t=this.particleMesh.geometry),t===null)){t=new tr(1,1);const r=t.attributes.uv;for(let s=0;s<r.count;s++)r.setX(s,1-r.getX(s))}return new me(t,this.getMaterial())}}An([w()],Fa.prototype,"renderMode",2),An([w(Ot)],Fa.prototype,"particleMaterial",2),An([w(Ot)],Fa.prototype,"trailMaterial",2),An([w()],Fa.prototype,"maxParticleSize",2),An([w()],Fa.prototype,"minParticleSize",2),An([w()],Fa.prototype,"velocityScale",2),An([w()],Fa.prototype,"cameraVelocityScale",2),An([w()],Fa.prototype,"lengthScale",2);class nE{constructor(e,t=1){d(this,"_curve"),d(this,"_factor"),d(this,"type","function"),this._curve=e,this._factor=t}genValue(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 sO{constructor(e){d(this,"type","value"),d(this,"system"),this.system=e}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class oAe extends sO{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class aAe extends sO{constructor(){super(...arguments),d(this,"_lastPosition",new C),d(this,"_lastDistance",0)}update(){const e=Bt(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 o=this._lastDistance/this.system.deltaTime*s;Number.isFinite(o)||(o=0),e+=o}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const r=this.system.maxParticles-this.system.currentParticles;return it.clamp(e,0,r/this.system.deltaTime)}}class lAe extends sO{genValue(){return this.system.isPlaying,0}}class Sd{constructor(e){d(this,"system"),d(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}get context(){return this.system.context}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class cAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleTextureSheet")}update(e,t){const r=this.system.textureSheetAnimation;if(r.enabled){const s=e.age/e.life,o=r.evaluate(s);o!==void 0&&(e.uvTile=o)}}}const kH=Symbol("particleRotation");class hAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleRotation")}initialize(e){e[kH]=Math.random()}update(e,t){if(e.rotation===void 0)return;const r=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(r,e[kH])*t:this.system.renderer.renderMode===Bh.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const s=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(r,s)*t}}}const DH=Symbol("sizeLerpFactor"),uAe=new C;class dAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleSize"),d(this,"_minSize",0),d(this,"_maxSize",1)}initialize(e){e[DH]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const r=e.age/e.life;let s=1;this.system.sizeOverLifetime.enabled&&(s*=this.system.sizeOverLifetime.evaluate(r,void 0,e[DH]).x);let o=1;if(this.system.renderer.renderMode!==Bh.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale),e.size=e.startSize*s*o,this.system.localspace){const a=NH(this.system,uAe);e.size*=a.x}}}const P0=Symbol("particleLife"),oO=Symbol("trailLifetime"),OH=Symbol("trailStartLength"),aO=Symbol("trailWidthRandom");class pAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleTrail")}initialize(e){e instanceof xb&&(e[P0]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[oO]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[oO]),e[OH]=e.length,e[aO]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof xb){const r=e,s=e.age/e[P0],o=e.previous.values(),a=e.previous.length;for(let l=0;l<a;l++){const c=o.next().value,h=1-l/(a-1);let u=e.size;u<=0&&!this.system.trails.sizeAffectsWidth&&(u=20*this.system.trails.widthOverTrail.evaluate(.5,r[aO])),c.size=this.system.trails.getWidth(u,s,h,r[aO]),c.color.copy(e.color),this.system.trails.getColor(c.color,s,h)}if(e.age>e[P0]){e.velocity.set(0,0,0);const l=(e.age-e[P0])/e[oO];r.length=it.lerp(e[OH],0,l)}}}}const rE=Symbol("startVelocity"),LH=Symbol("gravityModifier"),lO=Symbol("gravitySpeed"),sE=Symbol("velocity lerp factor"),cO=new C;class mAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleVelocity"),d(this,"_gravityDirection",new C)}initialize(e){var t,r;const s=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random()),e.velocity.copy(this.system.shape.getDirection(e,e.position)).multiplyScalar(e.startSpeed),(t=this.system.inheritVelocity)!=null&&t.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[rE]?e[rE].copy(e.velocity):e[rE]=e.velocity.clone();const o=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[LH]=o*s,e[lO]=o*s*.5,e[sE]=Math.random(),(r=this.system.velocityOverLifetime)==null||r.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===nb.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var r;const s=e[rE],o=e[LH];if(o!==0){const m=o*e[lO];cO.copy(this._gravityDirection).multiplyScalar(m),e[lO]+=t*.05,s.add(cO)}e.velocity.copy(s);const a=e.age/e.life;(r=this.system.inheritVelocity)!=null&&r.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,a,e[sE]);const l=this.system.noise;l.enabled&&l.apply(0,e.position,e.velocity,t,e.age,e.life);const c=this.system.sizeBySpeed;c!=null&&c.enabled&&(e.size=c.evaluate(e.velocity,a,e[sE],e.size));const h=this.system.colorBySpeed;h!=null&&h.enabled&&h.evaluate(e.velocity,e[sE],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,t,e.age,e.life);const p=this.system.limitVelocityOverLifetime;p.enabled&&p.apply(e.position,s,e.velocity,e.size,a,t,1),this.system.worldspace&&e.velocity.multiply(this.system.worldScale)}}const FH=Symbol("colorLerpFactor"),UH=new Si(1,1,1,1),Pm=new Si(1,1,1,1);class fAe extends Sd{constructor(){super(...arguments),d(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Pm.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(UH.copy(t.color),Pm.multiply(UH)),Pm.convertLinearToSRGB(),e.startColor.set(Pm.r,Pm.g,Pm.b,Pm.alpha),e.color.copy(e.startColor),e[FH]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const r=e.age/e.life,s=this.system.colorOverLifetime.color.evaluate(r,e[FH]);e.color.set(s.r,s.g,s.b,s.alpha).multiply(e.startColor)}else e.color.copy(e.startColor)}}class gAe{constructor(e){d(this,"system"),d(this,"emission"),d(this,"autoDestroy"),d(this,"startLength"),d(this,"emissionBursts"),d(this,"onlyUsedByOther"),d(this,"behaviors",[]),d(this,"rendererEmitterSettings",{startLength:new Bs(220),followLocalOrigin:!1}),d(this,"flatWhiteTexture"),d(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=e,this.emission=new aAe(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 nE(this.system.main.startLifetime)}get startSpeed(){return new nE(this.system.main.startSpeed)}get startRotation(){return new nE(this.system.main.startRotation)}get startSize(){return new nE(this.system.main.startSize)}get startColor(){return new KC(new Ye(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new lAe(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return ot.Trail;switch(this.system.renderer.renderMode){case Bh.Billboard:return ot.BillBoard;case Bh.Stretch:return ot.StretchedBillBoard;case Bh.HorizontalBillboard:return ot.HorizontalBillBoard;case Bh.VerticalBillboard:return ot.VerticalBillBoard;case Bh.Mesh:return ot.Mesh}return ot.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===Bh.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const r=t.clone();r.premultiplyAlpha=!1,r.colorSpace=Ri,this.clonedTexture.original=t,this.clonedTexture.clone=r}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=WB(new Si(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new oAe(this.system)}get uTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesX:void 0}get vTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesY:void 0}get renderOrder(){return 1}get blending(){var e;return((e=this.system.renderer.particleMaterial)==null?void 0:e.blending)??Qh}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===nb.World}}class vAe{constructor(){d(this,"burstIndex",0),d(this,"burstWaveIndex",0),d(this,"time",0),d(this,"waitEmiting",0)}}const oE=class extends Be{constructor(){super(...arguments),d(this,"_state"),d(this,"colorOverLifetime"),d(this,"main"),d(this,"emission"),d(this,"sizeOverLifetime"),d(this,"shape"),d(this,"noise"),d(this,"trails"),d(this,"velocityOverLifetime"),d(this,"limitVelocityOverLifetime"),d(this,"inheritVelocity"),d(this,"colorBySpeed"),d(this,"textureSheetAnimation"),d(this,"rotationOverLifetime"),d(this,"rotationBySpeed"),d(this,"sizeBySpeed"),d(this,"_cameraScale",1),d(this,"__worldQuaternion",new Ce),d(this,"_worldQuaternionInverted",new Ce),d(this,"_worldScale",new C),d(this,"_worldPositionFrame",-1),d(this,"_worldPos",new C),d(this,"_renderer"),d(this,"_batchSystem"),d(this,"_particleSystem"),d(this,"_interface"),d(this,"_container"),d(this,"_time",0),d(this,"_isPlaying",!0),d(this,"_isUsedAsSubsystem",!1),d(this,"_didPreWarm",!1),d(this,"_bursts"),d(this,"_subEmitterSystems"),d(this,"_lastBatchesCount",-1),d(this,"lastMaterialVersion",-1)}play(n=!1){var e;n&&ie.foreachComponent(this.gameObject,t=>{t instanceof oE&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(e=this.emission)==null||e.reset()}pause(n=!0){n&&ie.foreachComponent(this.gameObject,e=>{e instanceof oE&&e!==this&&e.pause(!1)},!0),this._isPlaying=!1}stop(n=!0,e=!1){n&&ie.foreachComponent(this.gameObject,t=>{t instanceof oE&&t!==this&&t.stop(!1,e)},!0),this._isPlaying=!1,this._time=0,e&&this.reset()}reset(){var n;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(n=this.emission)==null||n.reset())}emit(n){if(this._particleSystem){this.onUpdate(),n=Math.min(n,this.maxParticles-this.currentParticles),this._state||(this._state=new vAe),this._state.waitEmiting=n,this._state.time=0;const e=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=e}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(n){this.main.playOnAwake=n}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var n;return((n=this._particleSystem)==null?void 0:n.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===nb.World}get localspace(){return this.main.simulationSpace===nb.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,Bt(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(n){return this._particleSystem?(n instanceof Sd&&(n.system=this),st()&&console.log("add behaviour",n),this._particleSystem.addBehavior(n),!0):!1}removeBehaviour(n){if(!this._particleSystem)return!1;const e=this._particleSystem.behaviors,t=e.indexOf(n);return t!==-1&&e.splice(t,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(n){for(let e=0;e<n.length;e++){const t=n[e];if(!(t instanceof rb)){const r=new rb;Rg(r,t),n[e]=r}}this._bursts=n}set subEmitterSystems(n){for(let e=0;e<n.length;e++){const t=n[e];if(!(t instanceof Ib)){const r=new Ib;Rg(r,t),n[e]=r}}Tb&&n.length>0&&console.log("SubEmitters: ",n,this),this._subEmitterSystems=n}onAfterDeserialize(n){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const e of this._subEmitterSystems)e._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(Fa),!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 ye,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new Tye,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new gAe(this),this._particleSystem=new vye(this._interface),this._particleSystem.addBehavior(new dAe(this)),this._particleSystem.addBehavior(new fAe(this)),this._particleSystem.addBehavior(new cAe(this)),this._particleSystem.addBehavior(new hAe(this)),this._particleSystem.addBehavior(new mAe(this)),this._particleSystem.addBehavior(new pAe(this)),this._batchSystem.addSystem(this._particleSystem);const n=this._particleSystem.emitter;this.context.scene.add(n),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Tb&&(console.log(this),this.gameObject.add(new Po(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof me&&this._interface.renderMode==ot.Mesh&&fi.assignMeshLOD(this.renderer.particleMesh,0).then(n=>{n&&this.particleSystem&&this._interface.renderMode==ot.Mesh&&(this.particleSystem.instancingGeometry=n)})}onDestroy(){var n,e,t,r;(n=this._container)==null||n.removeFromParent(),(e=this._batchSystem)==null||e.removeFromParent(),(t=this._particleSystem)==null||t.emitter.removeFromParent(),(r=this._particleSystem)==null||r.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 n;this.main&&(this._didPreWarm===!1&&((n=this.main)==null?void 0:n.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var n;if(!((n=this.emission)!=null&&n.enabled)||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,r=this.main.startLifetime.getMax(),s=1e3,o=Math.min(Math.max(t,r)/Math.max(.01,this.main.simulationSpeed),s),a=Math.ceil(o/e),l=Date.now();Tb&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${o} sec). Duration: ${t}, Lifetime: ${r}`);for(let c=0;c<a&&!(this.currentParticles>=this.maxParticles);c++){const h=Date.now()-l;if(h>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${h}`);break}this.onUpdate(),this.onSimulate(e)}}onSimulate(n){if(this._batchSystem){let e=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,e=!0),e&&this.updateLayers(),this._batchSystem.update(n)}this._time+=n,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let n=0;n<this._batchSystem.batches.length;n++){const e=this._batchSystem.batches[n];e.layers.disableAll();const t=this.layer;e.layers.mask=1<<t}}onUpdate(){var n,e;const t=this.renderer.getMaterial(this.trails.enabled);if(t&&t.version!=this.lastMaterialVersion&&this._particleSystem&&(this.lastMaterialVersion=t.version,this._particleSystem.texture=this._interface.texture),this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const r=this.context.mainCamera;if(r){const a=Vi(r);this._cameraScale=a.x}const s=!this.worldspace,o=this.gameObject;if(Mi(o,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Vi(this.gameObject,this._worldScale),s&&this._container&&(n=this.gameObject)!=null&&n.parent){const a=NH(this,cO);this._container.matrix.makeScale(a.x,a.y,a.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.update(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(e=this.inheritVelocity)==null||e.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var n;if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():st()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=(n=e.particleSystem)==null?void 0:n._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const r=new aE(this,this._particleSystem,e.particleSystem,t);r.emitterType=e.type,r.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(r)}else Tb&&console.warn("Could not add SubParticleSystem",e,this)}}};let $n=oE;An([w(sb)],$n.prototype,"colorOverLifetime",2),An([w(Zr)],$n.prototype,"main",2),An([w(uc)],$n.prototype,"emission",2),An([w(gd)],$n.prototype,"sizeOverLifetime",2),An([w(vn)],$n.prototype,"shape",2),An([w(Ii)],$n.prototype,"noise",2),An([w(cn)],$n.prototype,"trails",2),An([w(yn)],$n.prototype,"velocityOverLifetime",2),An([w(Kn)],$n.prototype,"limitVelocityOverLifetime",2),An([w(vd)],$n.prototype,"inheritVelocity",2),An([w(ym)],$n.prototype,"colorBySpeed",2),An([w($r)],$n.prototype,"textureSheetAnimation",2),An([w(Ba)],$n.prototype,"rotationOverLifetime",2),An([w(Wo)],$n.prototype,"rotationBySpeed",2),An([w(to)],$n.prototype,"sizeBySpeed",2);class Ib{constructor(){d(this,"particleSystem"),d(this,"emitProbability",1),d(this,"properties"),d(this,"type")}_deserialize(e,t){const r=this.particleSystem;if(r instanceof $n)return;let s="";r&&typeof r.guid=="string"&&(s=r.guid,this.particleSystem=ie.findByGuid(s,t)),Tb&&!(this.particleSystem instanceof $n)&&console.warn("Could not find particle system for sub emitter",s,t,this)}}function NH(n,e){if(e.set(1,1,1),n.gameObject.parent&&n.localspace)switch(n.main.scalingMode){case lD.Local:e=Vi(n.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!n.unsupported_scaling_mode){n.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+lD[n.main.scalingMode]+" is not supported";st()&&Di(t),console.warn(t,n.name,n)}e=Vi(n.gameObject,e);break}return e}new C(1,1,1),new C(0,0,1);class aE{constructor(e,t,r,s){d(this,"type","NeedleParticleSubEmitter"),d(this,"emitterType"),d(this,"emitterProbability"),d(this,"q_",new Ce),d(this,"v_",new C),d(this,"v2_",new C),d(this,"_emitterMatrix",new ve),d(this,"_circularBuffer"),this.system=e,this.particleSystem=t,this.subSystem=r,this.subParticleSystem=s,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new oa(()=>new ve,o)}clone(){throw new Error("Method not implemented.")}initialize(e){e.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===rO.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===rO.Death){let s=e.life;if(e[P0]!==void 0&&(s=e[P0]),!(e.age+t*1.2>=s))return;const o=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=o}const r=new ve;r.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||r.multiplyMatrices(this._emitterMatrix,r),this.subParticleSystem.emit(t,e.emissionState,r)}}var yAe=Object.defineProperty,AAe=Object.getOwnPropertyDescriptor,bAe=(n,e,t,r)=>{for(var s=r>1?void 0:r?AAe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&yAe(e,t,s),s};class Rb extends Xr{constructor(){super(...arguments),d(this,"granularity",new qe(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new t6;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}bAe([w(qe)],Rb.prototype,"granularity",2),Ra("PixelationEffect",Rb);class J0 extends Be{constructor(){super(...arguments),d(this,"_didAssignPlayerColor",!1),d(this,"tryAssignColor",()=>{const e=ie.getComponentInParent(this.gameObject,Pa);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=ie.getComponentInParent(this.gameObject,Yr);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(Vt.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(Vt.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield p8(.2),!this.tryAssignColor()););}assignUserColor(e){const t=J0.hashCode(e),r=J0.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const s=this.gameObject;this.assignColor(r,e,s)}else if(this.gameObject.children)for(const s of this.gameObject.children){const o=s;o.material&&o.material.color&&this.assignColor(r,e,o)}}assignColor(e,t,r){let s=r.material;s&&(s._playerMaterial!==t&&(s=s.clone(),s._playerMaterial=t,r.material=s),s.color=e)}static hashCode(e){var t=0,r,s;if(e.length===0)return t;for(r=0;r<e.length;r++)s=e.charCodeAt(r),t=(t<<5)-t+s,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,r=(e&65280)>>8,s=e&255;return new xe(t/255,r/255,s/255)}}const Pb=new yt;Pb.setAttribute("position",new nt(new Float32Array([-1,-1,3,-1,-1,3]),2)),Pb.setAttribute("uv",new nt(new Float32Array([0,0,2,0,0,2]),2)),Pb.boundingSphere=new wn,Pb.computeBoundingSphere=function(){};const _Ae=new Bl;class Bm{constructor(e){this._mesh=new me(Pb,e),this._mesh.frustumCulled=!1}render(e){e.render(this._mesh,_Ae)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}dispose(){this._mesh.material.dispose(),this._mesh.geometry.dispose()}}const xAe={uniforms:{sceneDiffuse:{value:null},sceneDepth:{value:null},sceneNormal:{value:null},projMat:{value:new ve},viewMat:{value:new ve},projViewMat:{value:new ve},projectionMatrixInv:{value:new ve},viewMatrixInv:{value:new ve},cameraPos:{value:new C},resolution:{value:new Z},time:{value:0},samples:{value:[]},bluenoise:{value:null},distanceFalloff:{value:1},radius:{value:5},near:{value:.1},far:{value:1e3},logDepth:{value:!1},ortho:{value:!1},screenSpaceRadius:{value:!1},frame:{value:0}},depthWrite:!1,depthTest:!1,vertexShader:`
6853
6853
  varying vec2 vUv;
6854
6854
  void main() {
6855
6855
  vUv = uv;
@@ -7651,7 +7651,7 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
7651
7651
  // be blended onto the scene.
7652
7652
  gl_FragColor = vec4(direct, max);
7653
7653
  return;
7654
- `)}}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new Rx;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e)}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new $t;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}$H([w()],Lb.prototype,"mode",2),$H([w(Si)],Lb.prototype,"shadowColor",2);var tbe=Object.defineProperty,ibe=Object.getOwnPropertyDescriptor,hE=(n,e,t,r)=>{for(var s=r>1?void 0:r?ibe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&tbe(e,t,s),s},fO;const e9=(fO=class extends Be{constructor(){super(...arguments),d(this,"target",null),d(this,"followFactor",.1),d(this,"rotateFactor",.1),d(this,"positionAxes",Wg.All),d(this,"flipForward",!1),d(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(n){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=Bt(this.target),t=this._firstUpdate||n?1:it.clamp01(this.context.time.deltaTime*this.followFactor),r=this.worldPosition;this.positionAxes&Wg.X&&(r.x=it.lerp(r.x,e.x,t)),this.positionAxes&Wg.Y&&(r.y=it.lerp(r.y,e.y,t)),this.positionAxes&Wg.Z&&(r.z=it.lerp(r.z,e.z,t)),this.worldPosition=r}if(this.rotateFactor>0){const e=Mi(this.target);this.flipForward&&e.premultiply(e9._invertForward);const t=this._firstUpdate||n?1:it.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},d(fO,"_invertForward",new Ce().setFromAxisAngle(new C(0,1,0),Math.PI)),fO);let Md=e9;hE([w(ye)],Md.prototype,"target",2),hE([w()],Md.prototype,"followFactor",2),hE([w()],Md.prototype,"rotateFactor",2),hE([w()],Md.prototype,"positionAxes",2);class nbe extends me{constructor(e){const t=new rbe(e),r=new tr(t.image.width*.001,t.image.height*.001),s=new $t({map:t,toneMapped:!1,transparent:!0});super(r,s);function o(a){s.map.dispatchDOMEvent(a)}this.addEventListener("mousedown",o),this.addEventListener("mousemove",o),this.addEventListener("mouseup",o),this.addEventListener("click",o),this.dispose=function(){r.dispose(),s.dispose(),s.map.dispose(),gO.delete(e),this.removeEventListener("mousedown",o),this.removeEventListener("mousemove",o),this.removeEventListener("mouseup",o),this.removeEventListener("click",o)}}}class rbe extends HT{constructor(e){super(t9(e)),this.dom=e,this.anisotropy=16,this.colorSpace=ft,this.minFilter=Pt,this.magFilter=Pt;const t=new MutationObserver(()=>{this.scheduleUpdate||(this.scheduleUpdate=setTimeout(()=>this.update(),16))}),r={attributes:!0,childList:!0,subtree:!0,characterData:!0};t.observe(e,r),this.observer=t}dispatchDOMEvent(e){e.data&&sbe(this.dom,e.type,e.data.x,e.data.y)}update(){this.image=t9(this.dom),this.needsUpdate=!0,this.scheduleUpdate=null}dispose(){this.observer&&this.observer.disconnect(),this.scheduleUpdate=clearTimeout(this.scheduleUpdate),super.dispose()}}const gO=new WeakMap;function t9(n){const e=document.createRange(),t=new xe;function r(m){const f=[];let g=!1;function v(){if(g&&(g=!1,m.restore()),f.length===0)return;let y=-1/0,A=-1/0,_=1/0,b=1/0;for(let x=0;x<f.length;x++){const E=f[x];y=Math.max(y,E.x),A=Math.max(A,E.y),_=Math.min(_,E.x+E.width),b=Math.min(b,E.y+E.height)}m.save(),m.beginPath(),m.rect(y,A,_-y,b-A),m.clip(),g=!0}return{add:function(y){f.push(y),v()},remove:function(){f.pop(),v()}}}function s(m,f,g,v){v!==""&&(m.textTransform==="uppercase"&&(v=v.toUpperCase()),u.font=m.fontWeight+" "+m.fontSize+" "+m.fontFamily,u.textBaseline="top",u.fillStyle=m.color,u.fillText(v,f,g+parseFloat(m.fontSize)*.1))}function o(m,f,g,v,y){g<2*y&&(y=g/2),v<2*y&&(y=v/2),u.beginPath(),u.moveTo(m+y,f),u.arcTo(m+g,f,m+g,f+v,y),u.arcTo(m+g,f+v,m,f+v,y),u.arcTo(m,f+v,m,f,y),u.arcTo(m,f,m+g,f,y),u.closePath()}function a(m,f,g,v,y,A){const _=m[f+"Width"],b=m[f+"Style"],x=m[f+"Color"];_!=="0px"&&b!=="none"&&x!=="transparent"&&x!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=x,u.lineWidth=parseFloat(_),u.beginPath(),u.moveTo(g,v),u.lineTo(g+y,v+A),u.stroke())}function l(m,f){let g=0,v=0,y=0,A=0;if(m.nodeType===Node.TEXT_NODE){e.selectNode(m);const b=e.getBoundingClientRect();g=b.left-c.left-.5,v=b.top-c.top-.5,y=b.width,A=b.height,s(f,g,v,m.nodeValue.trim())}else{if(m.nodeType===Node.COMMENT_NODE)return;if(m instanceof HTMLCanvasElement){if(m.style.display==="none")return;const b=m.getBoundingClientRect();g=b.left-c.left-.5,v=b.top-c.top-.5,u.save();const x=window.devicePixelRatio;u.scale(1/x,1/x),u.drawImage(m,g,v),u.restore()}else if(m instanceof HTMLImageElement){if(m.style.display==="none")return;const b=m.getBoundingClientRect();g=b.left-c.left-.5,v=b.top-c.top-.5,y=b.width,A=b.height,u.drawImage(m,g,v,y,A)}else{if(m.style.display==="none")return;const b=m.getBoundingClientRect();g=b.left-c.left-.5,v=b.top-c.top-.5,y=b.width,A=b.height,f=window.getComputedStyle(m),o(g,v,y,A,parseFloat(f.borderRadius));const x=f.backgroundColor;x!=="transparent"&&x!=="rgba(0, 0, 0, 0)"&&(u.fillStyle=x,u.fill());const E=["borderTop","borderLeft","borderBottom","borderRight"];let I=!0,T=null;for(const R of E){if(T!==null&&(I=f[R+"Width"]===f[T+"Width"]&&f[R+"Color"]===f[T+"Color"]&&f[R+"Style"]===f[T+"Style"]),I===!1)break;T=R}if(I===!0){const R=parseFloat(f.borderTopWidth);f.borderTopWidth!=="0px"&&f.borderTopStyle!=="none"&&f.borderTopColor!=="transparent"&&f.borderTopColor!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=f.borderTopColor,u.lineWidth=R,u.stroke())}else a(f,"borderTop",g,v,y,0),a(f,"borderLeft",g,v,0,A),a(f,"borderBottom",g,v+A,y,0),a(f,"borderRight",g+y,v,0,A);if(m instanceof HTMLInputElement){let R=f.accentColor;(R===void 0||R==="auto")&&(R=f.color),t.set(R);const D=Math.sqrt(.299*t.r**2+.587*t.g**2+.114*t.b**2)<.5?"white":"#111111";if(m.type==="radio"&&(o(g,v,y,A,A),u.fillStyle="white",u.strokeStyle=R,u.lineWidth=1,u.fill(),u.stroke(),m.checked&&(o(g+2,v+2,y-4,A-4,A),u.fillStyle=R,u.strokeStyle=D,u.lineWidth=2,u.fill(),u.stroke())),m.type==="checkbox"&&(o(g,v,y,A,2),u.fillStyle=m.checked?R:"white",u.strokeStyle=m.checked?D:R,u.lineWidth=1,u.stroke(),u.fill(),m.checked)){const M=u.textAlign;u.textAlign="center";const P={color:D,fontFamily:f.fontFamily,fontSize:A+"px",fontWeight:"bold"};s(P,g+y/2,v,"\u2714"),u.textAlign=M}if(m.type==="range"){const[M,P,z]=["min","max","value"].map(L=>parseFloat(m[L])),V=(z-M)/(P-M)*(y-A);o(g,v+A/4,y,A/2,A/4),u.fillStyle=D,u.strokeStyle=R,u.lineWidth=1,u.fill(),u.stroke(),o(g,v+A/4,V+A/2,A/2,A/4),u.fillStyle=R,u.fill(),o(g+V,v,A,A,A/2),u.fillStyle=R,u.fill()}(m.type==="color"||m.type==="text"||m.type==="number")&&(p.add({x:g,y:v,width:y,height:A}),s(f,g+parseInt(f.paddingLeft),v+parseInt(f.paddingTop),m.value),p.remove())}}}const _=f.overflow==="auto"||f.overflow==="hidden";_&&p.add({x:g,y:v,width:y,height:A});for(let b=0;b<m.childNodes.length;b++)l(m.childNodes[b],f);_&&p.remove()}const c=n.getBoundingClientRect();let h=gO.get(n);h===void 0&&(h=document.createElement("canvas"),h.width=c.width,h.height=c.height,gO.set(n,h));const u=h.getContext("2d"),p=new r(u);return u.clearRect(0,0,h.width,h.height),l(n),h}function sbe(n,e,t,r){const s={clientX:t*n.offsetWidth+n.offsetLeft,clientY:r*n.offsetHeight+n.offsetTop,view:n.ownerDocument.defaultView};window.dispatchEvent(new MouseEvent(e,s));const o=n.getBoundingClientRect();t=t*o.width+o.left,r=r*o.height+o.top;function a(l){if(l.nodeType!==Node.TEXT_NODE&&l.nodeType!==Node.COMMENT_NODE){const c=l.getBoundingClientRect();if(t>c.left&&t<c.right&&r>c.top&&r<c.bottom&&(l.dispatchEvent(new MouseEvent(e,s)),l instanceof HTMLInputElement&&l.type==="range"&&(e==="mousedown"||e==="click"))){const[h,u]=["min","max"].map(f=>parseFloat(l[f])),p=c.width,m=(t-c.x)/p;l.value=h+(u-h)*m,l.dispatchEvent(new InputEvent("input",{bubbles:!0}))}for(let h=0;h<l.childNodes.length;h++)a(l.childNodes[h])}}a(n)}const uE=new Z,B0={type:"",data:uE},i9=new pp;class obe extends Fr{listenToPointerEvents(e,t){const r=this,s=new pp,o=e.domElement;function a(l){l.stopPropagation();const c=e.domElement.getBoundingClientRect();uE.x=(l.clientX-c.left)/c.width*2-1,uE.y=-(l.clientY-c.top)/c.height*2+1,s.setFromCamera(uE,t);const h=s.intersectObjects(r.children,!1);if(h.length>0){const u=h[0],p=u.object,m=u.uv;B0.type=l.type,B0.data.set(m.x,1-m.y),p.dispatchEvent(B0)}}o.addEventListener("pointerdown",a),o.addEventListener("pointerup",a),o.addEventListener("pointermove",a),o.addEventListener("mousedown",a),o.addEventListener("mouseup",a),o.addEventListener("mousemove",a),o.addEventListener("click",a)}listenToXRControllerEvents(e){const t=this,r={move:"mousemove",select:"click",selectstart:"mousedown",selectend:"mouseup"};function s(o){const a=o.target;i9.setFromXRController(a);const l=i9.intersectObjects(t.children,!1);if(l.length>0){const c=l[0],h=c.object,u=c.uv;B0.type=r[o.type],B0.data.set(u.x,1-u.y),h.dispatchEvent(B0)}}e.addEventListener("move",s),e.addEventListener("select",s),e.addEventListener("selectstart",s),e.addEventListener("selectend",s)}}var abe=Object.defineProperty,lbe=Object.getOwnPropertyDescriptor,n9=(n,e,t,r)=>{for(var s=r>1?void 0:r?lbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&abe(e,t,s),s};class Fb extends Be{constructor(){super(...arguments),d(this,"id",null),d(this,"keepAspect",!1),d(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 t=new obe;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const r=new nbe(e);t.add(r),r.visible=!1;const s=r.material;s.transparent=!0,setTimeout(()=>{r.visible=!0;const o=Wv(this.gameObject).clone();Xv(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const a=new xi;a.setFromObject(t),this.setWorldRotation(o.x,o.y,o.z);const l=a.max.x-a.min.x,c=a.max.y-a.min.y;if(this.keepAspect){const u=l/c;l>c?r.scale.set(1/l,1/c/u,1):r.scale.set(1/l*u,1/c,1)}else r.scale.set(1/l,1/c,1);const h=this.gameObject.scale;r.scale.multiply(h)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}n9([w()],Fb.prototype,"id",2),n9([w()],Fb.prototype,"keepAspect",2);var cbe=Object.defineProperty,hbe=Object.getOwnPropertyDescriptor,Ub=(n,e,t,r)=>{for(var s=r>1?void 0:r?hbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&cbe(e,t,s),s};const Nb=te("debugspatialtrigger"),r9=new ds,s9=new ds;function ube(n,e){return r9.mask=n,s9.mask=e,r9.test(s9)}class Sc extends Be{constructor(){super(...arguments),d(this,"triggerMask",0),d(this,"onEnter"),d(this,"onStay"),d(this,"onExit"),d(this,"currentIntersected",[]),d(this,"lastIntersected",[])}start(){Nb&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of zb.triggers)ube(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),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 t;Nb&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke(this,e)}onExitTrigger(e){var t;Nb&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke(this,e)}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke(this,e)}}Ub([w()],Sc.prototype,"triggerMask",2),Ub([w(Un)],Sc.prototype,"onEnter",2),Ub([w(Un)],Sc.prototype,"onStay",2),Ub([w(Un)],Sc.prototype,"onExit",2);var vO;const dE=(vO=class extends Be{constructor(){super(...arguments),d(this,"triggerMask"),d(this,"boxHelper")}start(){Nb&&console.log(this.name,this.triggerMask,this)}onEnable(){var n;dE.triggers.push(this),this.boxHelper||(this.boxHelper=ie.addNewComponent(this.gameObject,ac),(n=this.boxHelper)==null||n.showHelper(null,Nb))}onDisable(){dE.triggers.splice(dE.triggers.indexOf(this),1)}test(n){return this.boxHelper?this.boxHelper.isInBox(n)??!1:!1}raiseOnEnterEvent(n){ie.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof Sc&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(n){ie.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof Sc&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(n){ie.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof Sc&&e.onExitTrigger(this)},!1)}},d(vO,"triggers",[]),vO);let zb=dE;Ub([w()],zb.prototype,"triggerMask",2);var dbe=Object.defineProperty,pbe=Object.getOwnPropertyDescriptor,mbe=(n,e,t,r)=>{for(var s=r>1?void 0:r?pbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&dbe(e,t,s),s};const Ko=te("debugspectator");class pE extends Be{constructor(){super(...arguments),d(this,"cam",null),d(this,"useKeys",!0),d(this,"_mode",0),d(this,"orbit",null),d(this,"_handler"),d(this,"eventSub_WebXRRequestStartEvent",null),d(this,"eventSub_WebXRStartEvent",null),d(this,"eventSub_WebXREndEvent",null),d(this,"_debug"),d(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 t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.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 t;if(this._handler){const r=(t=this._handler.currentTarget)==null?void 0:t.userId,s=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&s?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),ie.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,r)):this._handler.currentTarget!==e&&(this._handler.set(e),ie.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,r))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new vbe(this.context,this),this._networking=new bbe(this.context,this),this._networking.awake(),ie.setActive(this.gameObject,!1),this.cam=ie.getComponent(this.gameObject,Li),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new fbe(this.context,this.cam,this)),this.orbit=ie.getComponent(this.context.mainCamera,bi)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),r=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!r}onBeforeXR(e){this.isSupportedPlatform()&&ie.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Ko&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,r;this.context.removeCamera(this.cam),ie.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(r=this._handler)==null||r.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,Wu.Headset),this.target=this.context.players.getPlayerView(this.localId)),Ko&&console.log("Follow self",this.target)}onAfterRender(){var e,t,r;if(!this.cam)return;const s=this.context.renderer,o=s.xr.enabled;if(!s.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const a=s.getRenderTarget();let l=null;const c=s.state;if(!a){if(!s.state.bindFramebuffer||!c.bindXRFramebuffer)return;l=s._framebuffer,c.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const h=this.context.mainCameraComponent;if(h){const m=h.backgroundColor;m&&s.setClearColor(m,m.alpha),this.cam.backgroundColor=m,this.cam.clearFlags=h.clearFlags,this.cam.nearClipPlane=h.nearClipPlane,this.cam.farClipPlane=h.farClipPlane}else s.setClearColor(new xe(1,1,1));s.setRenderTarget(null),s.xr.enabled=!1;const u=(r=this.cam)==null?void 0:r.cam;this.context.updateAspect(u);const p=s.xr.isPresenting;s.xr.isPresenting=!1,s.setSize(this.context.domWidth,this.context.domHeight),s.render(this.context.scene,u),s.xr.isPresenting=p,s.xr.enabled=o,a?s.setRenderTarget(a):c.bindXRFramebuffer&&c.bindXRFramebuffer(l),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of Yr.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let r=rc.All;this.isSpectatingSelf&&(r=e&&t.avatar.isLocalAvatar?rc.FirstPerson:rc.ThirdPerson);const s=t.avatar.flags;if(!s)continue;for(const o of s)o.UpdateVisible(r)}}resetAvatarFlags(){var e;for(const t of Yr.instances)if(t.avatar&&"flags"in t.avatar){const r=t.avatar.flags;if(!r)continue;for(const s of r)"isLocalAvatar"in t.avatar&&(e=t.avatar)!=null&&e.isLocalAvatar?s.UpdateVisible(rc.FirstPerson):s.UpdateVisible(rc.ThirdPerson)}}}mbe([w()],pE.prototype,"useKeys",2);class fbe{constructor(e,t,r){d(this,"context"),d(this,"cam"),d(this,"spectator"),d(this,"follow"),d(this,"target"),d(this,"view"),d(this,"currentObject"),this.context=e,this.cam=t,this.spectator=r}get currentTarget(){return this.view}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=ie.addNewComponent(this.cam.gameObject,Md)),this.target||(this.target=new ye),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Ko&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Ko&&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 e;(e=this.target)==null||e.removeFromParent(),this.follow&&ie.destroy(this.follow)}update(e){var t,r,s,o,a,l;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((r=this.currentTarget)==null?void 0:r.removed)===!0){Ko&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((s=this.currentTarget)==null?void 0:s.currentObject)!==this.currentObject&&(Ko&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const c=this.context.mainCamera;c&&(this.cam.cam.near!==c.near||this.cam.cam.far!==c.far)&&(this.cam.cam.near=c.near,this.cam.cam.far=c.far,this.cam.cam.updateProjectionMatrix());const h=(o=this.follow)==null?void 0:o.target;if(!(!h||!this.follow)){switch(e){case 0:((a=this.view)==null?void 0:a.viewDevice)!==Wu.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),h.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,h.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((l=this.view)==null?void 0:l.viewDevice)!==Wu.Browser?h.quaternion.copy(gbe):h.quaternion.identity()}}}const gbe=new Ce().setFromAxisAngle(new C(0,1,0),Math.PI);class vbe{constructor(e,t){d(this,"context"),d(this,"spectator"),this.context=e,this.spectator=t,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",s=>{!this.spectator.useKeys||s.key==="Escape"&&this.spectator.stopSpectating()});let r=0;this.context.input.addEventListener(an.PointerDown,s=>{r=this.context.time.time}),this.context.input.addEventListener(an.PointerUp,s=>{const o=this.context.time.time-r;o>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&o<.3&&this.trySelectObject()})}trySelectObject(){const e=new ml;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Ko&&console.log(...t),t!=null&&t.length)for(const r of t){if(r.distance<.2)continue;const s=r.object,o=ie.getComponentInParent(s,Yr),a=o?.connectionId;if(a){const l=this.context.players.getPlayerView(a);this.spectator.target=l,Ko&&console.log("spectate",a,o);break}}}}class ybe{constructor(e,t,r){d(this,"guid"),d(this,"dontSave",!0),d(this,"targetUserId"),d(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=r}}class Abe{constructor(e,t){d(this,"guid"),d(this,"userId"),this.guid=e.guid,this.userId=t}}class bbe{constructor(e,t){d(this,"followers",[]),d(this,"context"),d(this,"spectator"),d(this,"_followerEventMethod"),d(this,"_requestFollowMethod"),d(this,"_joinedRoomMethod"),d(this,"_lastRequestFollowUser"),d(this,"_enforceFollowInterval"),this.context=e,this.spectator=t,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(Vt.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.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(Vt.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Ko&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const r=e?.userId===void 0,s=r?t:e?.userId,o=new ybe(this.context.connection.connectionId,s,r);this.context.connection.send("spectator-follower-changed",o)}}onRequestFollowMe(e=!1){if(Ko&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,r=new Abe(this.spectator,t);this.context.connection.send("spectator-request-follow",r)}}onUserJoinedRoom(){te("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,r=e.guid;if(Ko&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const s=this.followers.indexOf(r);s!==-1&&(this.followers.splice(s,1),this.removeDisconnectedFollowers(),console.log(r,"unfollows you",this.followers.length))}else this.followers.includes(r)||(this.followers.push(r),this.removeDisconnectedFollowers(),console.log(r,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Ko&&console.warn("Could not find view",e.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):(Ko&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class Ic{constructor(){d(this,"bb",null),d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Ic).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+bB),(t||new Ic).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new rm).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new rm).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var _be=Object.defineProperty,xbe=Object.getOwnPropertyDescriptor,wbe=(n,e,t,r)=>{for(var s=r>1?void 0:r?xbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&_be(e,t,s),s};const mE="SCAM";wB(mE,Ic.getRootAsSyncedCameraModel);const Zo=new s_;class Sbe{constructor(e,t){d(this,"userId"),d(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){Zo.clear();const r=Zo.createString(this.guid),s=Zo.createString(this.userId);Ic.startSyncedCameraModel(Zo),Ic.addGuid(Zo,r),Ic.addUserId(Zo,s);const o=Bt(e),a=Wv(e);Ic.addPos(Zo,rm.createVec3(Zo,o.x,o.y,o.z)),Ic.addRot(Zo,rm.createVec3(Zo,a.x,a.y,a.z));const l=Ic.endSyncedCameraModel(Zo);Zo.finish(l,mE),t.sendBinary(Zo.asUint8Array())}}}var yO;const AO=(yO=class extends Be{constructor(){super(...arguments),d(this,"cameraPrefab",null),d(this,"_lastWorldPosition"),d(this,"_lastWorldQuaternion"),d(this,"_model",null),d(this,"_needsUpdate",!0),d(this,"_lastUpdateTime",0),d(this,"remoteCams",{}),d(this,"userToCamMap",{}),d(this,"_camTimeoutInSeconds",10),d(this,"_receiveCallback",null)}getCameraObject(n){const e=this.userToCamMap[n];return e?this.remoteCams[e].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(mE,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(mE,this._receiveCallback)}update(){for(const r in this.remoteCams){const s=this.remoteCams[r],o=this.context.time.realtimeSinceStartup-s.lastUpdate;if(!s||o>this._camTimeoutInSeconds){st()&&console.log("Remote cam timeout",r),s!=null&&s.obj&&ie.destroy(s.obj),delete this.remoteCams[r],s&&delete this.userToCamMap[s.userId],AO.instances.push(s),this.context.players.removePlayerView(s.userId,Wu.Browser);continue}}if(this.context.isInXR)return;const n=this.context.mainCamera;if(n===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new Sbe(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=Bt(n),t=Mi(n);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!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(n,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,n,Wu.Browser))}onReceivedRemoteCameraInfoBin(n){const e=n.guid();if(!e)return;const t=n.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let r=this.remoteCams[e];if(!r)if("isObject3D"in this.cameraPrefab){const l=new Ml;l.context=this.context;const c=ie.instantiate(this.cameraPrefab,l);r=this.remoteCams[e]={obj:c,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},r.obj.visible=!0,this.gameObject.add(c),this.userToCamMap[t]=e,AO.instances.push(r);const h=ie.getOrAddComponent(c,Yr);h.connectionId=t,h.avatar=c}else return;const s=r.obj;this.context.players.setPlayerView(t,s,Wu.Browser),r.lastUpdate=this.context.time.realtimeSinceStartup,Qa.markDirty(s);const o=n.pos();o&&_p(s,o.x(),o.y(),o.z());const a=n.rot();a&&Xv(s,a.x(),a.y(),a.z())}},d(yO,"instances",[]),yO);let fE=AO;wbe([w([ye,ti])],fE.prototype,"cameraPrefab",2);var Cbe=Object.defineProperty,Ebe=Object.getOwnPropertyDescriptor,Om=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ebe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Cbe(e,t,s),s};const bO="view",_O=te("debugsyncedroom");class Cc extends Be{constructor(){super(...arguments),d(this,"roomName"),d(this,"urlParameterName","room"),d(this,"joinRandomRoom",!0),d(this,"requireRoomParameter",!1),d(this,"autoRejoin",!0),d(this,"createJoinButton",!0),d(this,"createViewOnlyButton",!1),d(this,"_roomPrefix"),d(this,"_lastJoinedRoom",""),d(this,"_lastPingTime",0),d(this,"_lastRoomTime",-1),d(this,"_userWantsToBeInARoom",!1),d(this,"_roomButton"),d(this,"_roomButtonIconJoin"),d(this,"_roomButtonIconLeave"),d(this,"updateRoomButtonState",()=>{var e,t;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",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),d(this,"_viewOnlyButton"),d(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 t;const r=this.getViewOnlyUrl();r!=null&&r.length?navigator.canShare({url:r})?(t=navigator.share({url:r}))==null||t.catch(s=>{console.warn(s)}):(navigator.clipboard.writeText(r),rn("View only URL copied to clipboard")):Di("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(Ao("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get roomPrefix(){return this._roomPrefix}get RoomPrefix(){return this._roomPrefix}awake(){_O&&console.log("Room",this.roomName,this.urlParameterName,this.joinRandomRoom,this.requireRoomParameter,this.autoRejoin),this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){const e=te(bO);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if((this.joinRandomRoom||te(this.urlParameterName))&&this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}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){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){const r=te(this.urlParameterName);if(r&&typeof r=="string"||r==="number"){t=!0;const s=UU(r);this.roomName=s}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)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(_O&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):(this.context.connection.isConnected||this.context.connection.connect(),_O&&console.log("Join "+this.roomName),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+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()):st()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}get currentRoomName(){return te(bO)||te(this.urlParameterName)}setRandomRoomUrlParameter(){const e=Uv(),t=this.generateRoomName();te(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),II(t,e)}generateRoomName(){return RI()+"_"+Math.floor(it.random(100,999))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(bO,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}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=()=>{this.context.connection.isInRoom?(this.urlParameterName&&Jx(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1):(this.urlParameterName&&(te(this.urlParameterName)||(this._lastJoinedRoom?Jx(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())),this.tryJoinRoom())},this._roomButtonIconJoin=Ao("group"),this._roomButtonIconLeave=Ao("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(Vt.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(Vt.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(Vt.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(Vt.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(Vt.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(Vt.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var e;this.context.connection.stopListen(Vt.JoinedRoom,this.onCreateViewOnlyButton),(e=this._viewOnlyButton)==null||e.remove()}}Om([w()],Cc.prototype,"roomName",2),Om([w()],Cc.prototype,"urlParameterName",2),Om([w()],Cc.prototype,"joinRandomRoom",2),Om([w()],Cc.prototype,"requireRoomParameter",2),Om([w()],Cc.prototype,"autoRejoin",2),Om([w()],Cc.prototype,"createJoinButton",2),Om([w()],Cc.prototype,"createViewOnlyButton",2);function Mbe(){const n=te("testwindowcount")||0;n&&n>0&&Tbe(n)}function Tbe(n){if(te("testwindow"))return null;const e=new URL(window.location.href);TI(e.searchParams,efe,1),TI(e.searchParams,"testwindow",1);const t=e.toString(),r=[];window.onbeforeunload=()=>{for(const c of r)c.close()};const s=.05,o=128;let a=0,l=0;for(let c=0;c<n;c++){a*o+o*.01>=window.innerWidth&&(l+=1,a=0);const h=a*(o*(1+s))+window.screenLeft,u=l*(o*(1+s))+window.screenTop+90+60*l;a+=1;const p=window.open(t,"test window "+c,`popup=yes width=${o} height=${o} top=${u} left=${h}`);if(!p){console.warn("Failed to open window");continue}r.push(p),p.onload=()=>{p.onbeforeunload=()=>{for(let m=0;m<r.length;m++){const f=r[m];f!==p&&f.close()}r.length=0}}}return r}class xO extends Be{awake(){Mbe()}}class wO extends Be{constructor(){super(...arguments),d(this,"transformsPerFrame",10),d(this,"interval",0),d(this,"useFlatbuffers",!0),d(this,"builder",null),d(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(AA,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new o9(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 s_(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const r=y8(this.context.connection.connectionId,this);this.context.connection.sendBinary(r)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class o9{constructor(e,t){d(this,"guid"),d(this,"fast",!1),d(this,"position"),d(this,"rotation"),d(this,"velocity"),d(this,"dontSave"),this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(e,t){const r=e.worldPosition;this.position.x=r.x,this.position.y=r.y,this.position.z=r.z;const s=e.worldQuaternion;if(this.rotation.x=s.x,this.rotation.y=s.y,this.rotation.z=s.z,this.rotation.w=s.w,this.fast=!1,t){const o=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=o.x,this.velocity.y=o.y,this.velocity.z=o.z}}}d(o9,"temp",new C);var Ibe=Object.defineProperty,Rbe=Object.getOwnPropertyDescriptor,k0=(n,e,t,r)=>{for(var s=r>1?void 0:r?Rbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Ibe(e,t,s),s};class Ec extends Xr{constructor(){super(...arguments),d(this,"offset",new qe(0)),d(this,"rotation",new qe(0)),d(this,"focusArea",new qe(.4)),d(this,"feather",new qe(.3)),d(this,"kernelSize",new qe(Ql.MEDIUM)),d(this,"resolutionScale",new qe(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=Ql.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new l6({kernelSize:Ql.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}k0([w(qe)],Ec.prototype,"offset",2),k0([w(qe)],Ec.prototype,"rotation",2),k0([w(qe)],Ec.prototype,"focusArea",2),k0([w(qe)],Ec.prototype,"feather",2),k0([w(qe)],Ec.prototype,"kernelSize",2),k0([w(qe)],Ec.prototype,"resolutionScale",2),Ra("TiltShiftEffect",Ec);var Pbe=Object.defineProperty,Bbe=Object.getOwnPropertyDescriptor,gE=(n,e,t,r)=>{for(var s=r>1?void 0:r?Bbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Pbe(e,t,s),s};class Lm extends Be{constructor(){super(...arguments),d(this,"isGizmo",!1),d(this,"translationSnap",1),d(this,"rotationSnapAngle",15),d(this,"scaleSnap",.25),d(this,"control"),d(this,"orbit"),d(this,"onControlChangedEvent",e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const r=ie.getComponentInParent(this.gameObject,Ku);r&&r.requestOwnership()}}),d(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}}),d(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}onEnable(){var e;this.isGizmo&&!Wy||this.context.mainCamera&&(this.control||(this.control=new mle(this.context.mainCamera,this.context.renderer.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=1,this.control.traverse(t=>{const r=t;if(r.layers.set(2),r){const s=r.material;s&&(s.opacity=.3)}}),this.orbit=ie.getComponentInParent(this.context.mainCamera,bi)??void 0),this.control&&(this.context.scene.add(this.control),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,t;(e=this.control)==null||e.removeFromParent(),(t=this.control)==null||t.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(ui.degToRad(this.rotationSnapAngle)),this.control.setScaleSnap(this.scaleSnap))}disableSnapping(){this.control&&(this.control.setTranslationSnap(null),this.control.setRotationSnap(null),this.control.setScaleSnap(null))}}gE([w()],Lm.prototype,"isGizmo",2),gE([w()],Lm.prototype,"translationSnap",2),gE([w()],Lm.prototype,"rotationSnapAngle",2),gE([w()],Lm.prototype,"scaleSnap",2);var kbe=Object.defineProperty,Dbe=Object.getOwnPropertyDescriptor,SO=(n,e,t,r)=>{for(var s=r>1?void 0:r?Dbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&kbe(e,t,s),s};class Fm extends Xr{constructor(){super(...arguments),d(this,"color",new qe({r:0,g:0,b:0,a:1})),d(this,"intensity",new qe(0)),d(this,"center",new qe({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 c6;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}SO([w(qe)],Fm.prototype,"color",2),SO([w(qe)],Fm.prototype,"intensity",2),SO([w(qe)],Fm.prototype,"center",2),Ra("Vignette",Fm);var Obe=Object.defineProperty,Lbe=Object.getOwnPropertyDescriptor,Fbe=(n,e,t,r)=>{for(var s=r>1?void 0:r?Lbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Obe(e,t,s),s};const CO=te("debugpost");class D0 extends Be{constructor(){super(...arguments),d(this,"sharedProfile"),d(this,"_postprocessing"),d(this,"_activeEffects",[]),d(this,"_effects",[]),d(this,"_lastApplyTime"),d(this,"_rapidApplyCount",0),d(this,"_isDirty",!1),d(this,"_modificationQueue"),d(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}addEffect(e){let t=e;return t instanceof Ys&&(t=new mb(t)),this._effects.includes(t)||(this._effects.push(t),this._isDirty=!0),e}removeEffect(e){let t=-1;return e instanceof Ys?t=this._effects.findIndex(r=>r instanceof mb&&r.effect===e):t=this._effects.indexOf(e),t!==-1&&(this._effects.splice(t,1),this._isDirty=!0),e}markDirty(){this._isDirty=!0}awake(){var e;CO&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",t=>{t.key==="p"&&(this.enabled=!this.enabled,rn("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.init()}onEnable(){this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){var e;if(!this.context.isInXR){if(this.context.composer&&!(this.context.composer instanceof JP)){CO&&console.warn("PostProcessing: The current composer is not an EffectComposer - this is not supported");return}this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&((e=this._postprocessing)==null?void 0:e.composer)===this.context.composer&&(this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.context.mainCamera&&this.context.composer.setMainCamera(this.context.mainCamera))}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e;if(CO&&console.log("Apply PostProcessing "+this.name),st()&&(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.unapply(),this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const t=this.sharedProfile.components;for(const r of t)r.active&&!this._activeEffects.includes(r)&&this._activeEffects.push(r)}for(const t of this._effects)t.active&&!this._activeEffects.includes(t)&&this._activeEffects.push(t);this._activeEffects.length>0&&(this._postprocessing||(this._postprocessing=new lE(this.context)),this._postprocessing.apply(this._activeEffects),this._applyPostQueue())}unapply(){var e;(e=this._postprocessing)==null||e.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var t,r;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((t=this._activeEffects)!=null&&t.length))return;const s=e.propertyName.split(".");if(s.length===3||s.length===4){const o=s[1],a=s[2];for(const l of this._activeEffects)if(((r=l.typeName)==null?void 0:r.toLowerCase())===o.toLowerCase()){if(a==="active"){l.active=e.value,this.scheduleRecreate();return}if(!vE.has(o)){const c=new Array;vE.set(o,c);const h=Object.keys(l);for(const u of h)l[u]instanceof qe&&c.push(u)}if(vE.has(o)){const c=a.toLowerCase(),h=vE.get(o);for(const u of h)if(u.toLowerCase()===c){const p=l[u];p instanceof qe&&(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",a);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}Fbe([Eg(kA)],D0.prototype,"sharedProfile",2);const vE=new Map;gme(D0);var Ube=Object.defineProperty,Nbe=Object.getOwnPropertyDescriptor,zbe=(n,e,t,r)=>{for(var s=r>1?void 0:r?Nbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Ube(e,t,s),s};const yE=te("debugarcamera");class AE extends Be{constructor(){super(...arguments),d(this,"backgroundTint",new Si(1,1,1,1)),d(this,"backgroundPlane"),d(this,"threeTexture"),d(this,"forceTextureInitialization",function(){const e=new $t,t=new tr,r=new Ur;r.add(new me(t,e));const s=new Lt;return function(o,a){e.map=a,o.render(r,s),yE&&console.warn("Force texture initialization")}}()),d(this,"preRender",()=>{if(!this||!this.gameObject)return;const e=this.context.renderer.xr.getFrame();e&&(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new zt,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0&&(this.backgroundPlane=Gbe(this.backgroundTint)),this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.updateFromFrame(e))})}onBeforeXR(e,t){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("camera-access"),yE&&console.warn("Requesting camera-access")}onEnterXR(e){this.backgroundPlane&&(this.context.scene.add(this.backgroundPlane),this.backgroundPlane.visible=!1),this.backgroundPlane&&this.context.scene.add(this.backgroundPlane),this.context.pre_render_callbacks.push(this.preRender)}onLeaveXR(e){this.backgroundPlane&&this.backgroundPlane.removeFromParent();const t=this.context.pre_render_callbacks.indexOf(this.preRender);t>=0&&this.context.pre_render_callbacks.splice(t,1)}get background(){return this.backgroundPlane}onBeforeRender(e){this.updateFromFrame(e)}updateFromFrame(e){if(!e)return;const t=e.session.enabledFeatures;if(t&&!t.some(s=>s==="camera-access")){this.background&&(this.background.visible=!1);return}const r=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(r){for(const s of r.views)if("camera"in s&&s.camera){let o=this.context.renderer.xr.getBinding();if(o||(o=new XRWebGLBinding(e.session,this.context.renderer.getContext())),o){let a=null;if("getCameraImage"in o){a=o.getCameraImage(s.camera);const l=this.context.renderer.properties.get(this.threeTexture);l.__webglTexture=a,this.backgroundPlane?(this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0):yE&&console.warn("No background plane to set texture on")}}}}}}zbe([w(Si)],AE.prototype,"backgroundTint",2);const jbe=`
7654
+ `)}}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new Rx;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e)}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new $t;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}$H([w()],Lb.prototype,"mode",2),$H([w(Si)],Lb.prototype,"shadowColor",2);var tbe=Object.defineProperty,ibe=Object.getOwnPropertyDescriptor,hE=(n,e,t,r)=>{for(var s=r>1?void 0:r?ibe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&tbe(e,t,s),s},fO;const e9=(fO=class extends Be{constructor(){super(...arguments),d(this,"target",null),d(this,"followFactor",.1),d(this,"rotateFactor",.1),d(this,"positionAxes",Wg.All),d(this,"flipForward",!1),d(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(n){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=Bt(this.target),t=this._firstUpdate||n?1:it.clamp01(this.context.time.deltaTime*this.followFactor),r=this.worldPosition;this.positionAxes&Wg.X&&(r.x=it.lerp(r.x,e.x,t)),this.positionAxes&Wg.Y&&(r.y=it.lerp(r.y,e.y,t)),this.positionAxes&Wg.Z&&(r.z=it.lerp(r.z,e.z,t)),this.worldPosition=r}if(this.rotateFactor>0){const e=Mi(this.target);this.flipForward&&e.premultiply(e9._invertForward);const t=this._firstUpdate||n?1:it.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},d(fO,"_invertForward",new Ce().setFromAxisAngle(new C(0,1,0),Math.PI)),fO);let Md=e9;hE([w(ye)],Md.prototype,"target",2),hE([w()],Md.prototype,"followFactor",2),hE([w()],Md.prototype,"rotateFactor",2),hE([w()],Md.prototype,"positionAxes",2);class nbe extends me{constructor(e){const t=new rbe(e),r=new tr(t.image.width*.001,t.image.height*.001),s=new $t({map:t,toneMapped:!1,transparent:!0});super(r,s);function o(a){s.map.dispatchDOMEvent(a)}this.addEventListener("mousedown",o),this.addEventListener("mousemove",o),this.addEventListener("mouseup",o),this.addEventListener("click",o),this.dispose=function(){r.dispose(),s.dispose(),s.map.dispose(),gO.delete(e),this.removeEventListener("mousedown",o),this.removeEventListener("mousemove",o),this.removeEventListener("mouseup",o),this.removeEventListener("click",o)}}}class rbe extends HT{constructor(e){super(t9(e)),this.dom=e,this.anisotropy=16,this.colorSpace=ft,this.minFilter=Pt,this.magFilter=Pt;const t=new MutationObserver(()=>{this.scheduleUpdate||(this.scheduleUpdate=setTimeout(()=>this.update(),16))}),r={attributes:!0,childList:!0,subtree:!0,characterData:!0};t.observe(e,r),this.observer=t}dispatchDOMEvent(e){e.data&&sbe(this.dom,e.type,e.data.x,e.data.y)}update(){this.image=t9(this.dom),this.needsUpdate=!0,this.scheduleUpdate=null}dispose(){this.observer&&this.observer.disconnect(),this.scheduleUpdate=clearTimeout(this.scheduleUpdate),super.dispose()}}const gO=new WeakMap;function t9(n){const e=document.createRange(),t=new xe;function r(m){const f=[];let g=!1;function v(){if(g&&(g=!1,m.restore()),f.length===0)return;let y=-1/0,A=-1/0,_=1/0,b=1/0;for(let x=0;x<f.length;x++){const E=f[x];y=Math.max(y,E.x),A=Math.max(A,E.y),_=Math.min(_,E.x+E.width),b=Math.min(b,E.y+E.height)}m.save(),m.beginPath(),m.rect(y,A,_-y,b-A),m.clip(),g=!0}return{add:function(y){f.push(y),v()},remove:function(){f.pop(),v()}}}function s(m,f,g,v){v!==""&&(m.textTransform==="uppercase"&&(v=v.toUpperCase()),u.font=m.fontWeight+" "+m.fontSize+" "+m.fontFamily,u.textBaseline="top",u.fillStyle=m.color,u.fillText(v,f,g+parseFloat(m.fontSize)*.1))}function o(m,f,g,v,y){g<2*y&&(y=g/2),v<2*y&&(y=v/2),u.beginPath(),u.moveTo(m+y,f),u.arcTo(m+g,f,m+g,f+v,y),u.arcTo(m+g,f+v,m,f+v,y),u.arcTo(m,f+v,m,f,y),u.arcTo(m,f,m+g,f,y),u.closePath()}function a(m,f,g,v,y,A){const _=m[f+"Width"],b=m[f+"Style"],x=m[f+"Color"];_!=="0px"&&b!=="none"&&x!=="transparent"&&x!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=x,u.lineWidth=parseFloat(_),u.beginPath(),u.moveTo(g,v),u.lineTo(g+y,v+A),u.stroke())}function l(m,f){let g=0,v=0,y=0,A=0;if(m.nodeType===Node.TEXT_NODE){e.selectNode(m);const b=e.getBoundingClientRect();g=b.left-c.left-.5,v=b.top-c.top-.5,y=b.width,A=b.height,s(f,g,v,m.nodeValue.trim())}else{if(m.nodeType===Node.COMMENT_NODE)return;if(m instanceof HTMLCanvasElement){if(m.style.display==="none")return;const b=m.getBoundingClientRect();g=b.left-c.left-.5,v=b.top-c.top-.5,u.save();const x=window.devicePixelRatio;u.scale(1/x,1/x),u.drawImage(m,g,v),u.restore()}else if(m instanceof HTMLImageElement){if(m.style.display==="none")return;const b=m.getBoundingClientRect();g=b.left-c.left-.5,v=b.top-c.top-.5,y=b.width,A=b.height,u.drawImage(m,g,v,y,A)}else{if(m.style.display==="none")return;const b=m.getBoundingClientRect();g=b.left-c.left-.5,v=b.top-c.top-.5,y=b.width,A=b.height,f=window.getComputedStyle(m),o(g,v,y,A,parseFloat(f.borderRadius));const x=f.backgroundColor;x!=="transparent"&&x!=="rgba(0, 0, 0, 0)"&&(u.fillStyle=x,u.fill());const E=["borderTop","borderLeft","borderBottom","borderRight"];let I=!0,T=null;for(const R of E){if(T!==null&&(I=f[R+"Width"]===f[T+"Width"]&&f[R+"Color"]===f[T+"Color"]&&f[R+"Style"]===f[T+"Style"]),I===!1)break;T=R}if(I===!0){const R=parseFloat(f.borderTopWidth);f.borderTopWidth!=="0px"&&f.borderTopStyle!=="none"&&f.borderTopColor!=="transparent"&&f.borderTopColor!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=f.borderTopColor,u.lineWidth=R,u.stroke())}else a(f,"borderTop",g,v,y,0),a(f,"borderLeft",g,v,0,A),a(f,"borderBottom",g,v+A,y,0),a(f,"borderRight",g+y,v,0,A);if(m instanceof HTMLInputElement){let R=f.accentColor;(R===void 0||R==="auto")&&(R=f.color),t.set(R);const D=Math.sqrt(.299*t.r**2+.587*t.g**2+.114*t.b**2)<.5?"white":"#111111";if(m.type==="radio"&&(o(g,v,y,A,A),u.fillStyle="white",u.strokeStyle=R,u.lineWidth=1,u.fill(),u.stroke(),m.checked&&(o(g+2,v+2,y-4,A-4,A),u.fillStyle=R,u.strokeStyle=D,u.lineWidth=2,u.fill(),u.stroke())),m.type==="checkbox"&&(o(g,v,y,A,2),u.fillStyle=m.checked?R:"white",u.strokeStyle=m.checked?D:R,u.lineWidth=1,u.stroke(),u.fill(),m.checked)){const M=u.textAlign;u.textAlign="center";const P={color:D,fontFamily:f.fontFamily,fontSize:A+"px",fontWeight:"bold"};s(P,g+y/2,v,"\u2714"),u.textAlign=M}if(m.type==="range"){const[M,P,z]=["min","max","value"].map(L=>parseFloat(m[L])),V=(z-M)/(P-M)*(y-A);o(g,v+A/4,y,A/2,A/4),u.fillStyle=D,u.strokeStyle=R,u.lineWidth=1,u.fill(),u.stroke(),o(g,v+A/4,V+A/2,A/2,A/4),u.fillStyle=R,u.fill(),o(g+V,v,A,A,A/2),u.fillStyle=R,u.fill()}(m.type==="color"||m.type==="text"||m.type==="number")&&(p.add({x:g,y:v,width:y,height:A}),s(f,g+parseInt(f.paddingLeft),v+parseInt(f.paddingTop),m.value),p.remove())}}}const _=f.overflow==="auto"||f.overflow==="hidden";_&&p.add({x:g,y:v,width:y,height:A});for(let b=0;b<m.childNodes.length;b++)l(m.childNodes[b],f);_&&p.remove()}const c=n.getBoundingClientRect();let h=gO.get(n);h===void 0&&(h=document.createElement("canvas"),h.width=c.width,h.height=c.height,gO.set(n,h));const u=h.getContext("2d"),p=new r(u);return u.clearRect(0,0,h.width,h.height),l(n),h}function sbe(n,e,t,r){const s={clientX:t*n.offsetWidth+n.offsetLeft,clientY:r*n.offsetHeight+n.offsetTop,view:n.ownerDocument.defaultView};window.dispatchEvent(new MouseEvent(e,s));const o=n.getBoundingClientRect();t=t*o.width+o.left,r=r*o.height+o.top;function a(l){if(l.nodeType!==Node.TEXT_NODE&&l.nodeType!==Node.COMMENT_NODE){const c=l.getBoundingClientRect();if(t>c.left&&t<c.right&&r>c.top&&r<c.bottom&&(l.dispatchEvent(new MouseEvent(e,s)),l instanceof HTMLInputElement&&l.type==="range"&&(e==="mousedown"||e==="click"))){const[h,u]=["min","max"].map(f=>parseFloat(l[f])),p=c.width,m=(t-c.x)/p;l.value=h+(u-h)*m,l.dispatchEvent(new InputEvent("input",{bubbles:!0}))}for(let h=0;h<l.childNodes.length;h++)a(l.childNodes[h])}}a(n)}const uE=new Z,B0={type:"",data:uE},i9=new pp;class obe extends Fr{listenToPointerEvents(e,t){const r=this,s=new pp,o=e.domElement;function a(l){l.stopPropagation();const c=e.domElement.getBoundingClientRect();uE.x=(l.clientX-c.left)/c.width*2-1,uE.y=-(l.clientY-c.top)/c.height*2+1,s.setFromCamera(uE,t);const h=s.intersectObjects(r.children,!1);if(h.length>0){const u=h[0],p=u.object,m=u.uv;B0.type=l.type,B0.data.set(m.x,1-m.y),p.dispatchEvent(B0)}}o.addEventListener("pointerdown",a),o.addEventListener("pointerup",a),o.addEventListener("pointermove",a),o.addEventListener("mousedown",a),o.addEventListener("mouseup",a),o.addEventListener("mousemove",a),o.addEventListener("click",a)}listenToXRControllerEvents(e){const t=this,r={move:"mousemove",select:"click",selectstart:"mousedown",selectend:"mouseup"};function s(o){const a=o.target;i9.setFromXRController(a);const l=i9.intersectObjects(t.children,!1);if(l.length>0){const c=l[0],h=c.object,u=c.uv;B0.type=r[o.type],B0.data.set(u.x,1-u.y),h.dispatchEvent(B0)}}e.addEventListener("move",s),e.addEventListener("select",s),e.addEventListener("selectstart",s),e.addEventListener("selectend",s)}}var abe=Object.defineProperty,lbe=Object.getOwnPropertyDescriptor,n9=(n,e,t,r)=>{for(var s=r>1?void 0:r?lbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&abe(e,t,s),s};class Fb extends Be{constructor(){super(...arguments),d(this,"id",null),d(this,"keepAspect",!1),d(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 t=new obe;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const r=new nbe(e);t.add(r),r.visible=!1;const s=r.material;s.transparent=!0,setTimeout(()=>{r.visible=!0;const o=Wv(this.gameObject).clone();Xv(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const a=new xi;a.setFromObject(t),this.setWorldRotation(o.x,o.y,o.z);const l=a.max.x-a.min.x,c=a.max.y-a.min.y;if(this.keepAspect){const u=l/c;l>c?r.scale.set(1/l,1/c/u,1):r.scale.set(1/l*u,1/c,1)}else r.scale.set(1/l,1/c,1);const h=this.gameObject.scale;r.scale.multiply(h)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}n9([w()],Fb.prototype,"id",2),n9([w()],Fb.prototype,"keepAspect",2);var cbe=Object.defineProperty,hbe=Object.getOwnPropertyDescriptor,Ub=(n,e,t,r)=>{for(var s=r>1?void 0:r?hbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&cbe(e,t,s),s};const Nb=te("debugspatialtrigger"),r9=new ds,s9=new ds;function ube(n,e){return r9.mask=n,s9.mask=e,r9.test(s9)}class Sc extends Be{constructor(){super(...arguments),d(this,"triggerMask",0),d(this,"onEnter"),d(this,"onStay"),d(this,"onExit"),d(this,"currentIntersected",[]),d(this,"lastIntersected",[])}start(){Nb&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of zb.triggers)ube(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),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 t;Nb&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke(this,e)}onExitTrigger(e){var t;Nb&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke(this,e)}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke(this,e)}}Ub([w()],Sc.prototype,"triggerMask",2),Ub([w(Un)],Sc.prototype,"onEnter",2),Ub([w(Un)],Sc.prototype,"onStay",2),Ub([w(Un)],Sc.prototype,"onExit",2);var vO;const dE=(vO=class extends Be{constructor(){super(...arguments),d(this,"triggerMask"),d(this,"boxHelper")}start(){Nb&&console.log(this.name,this.triggerMask,this)}onEnable(){var n;dE.triggers.push(this),this.boxHelper||(this.boxHelper=ie.addNewComponent(this.gameObject,ac),(n=this.boxHelper)==null||n.showHelper(null,Nb))}onDisable(){dE.triggers.splice(dE.triggers.indexOf(this),1)}test(n){return this.boxHelper?this.boxHelper.isInBox(n)??!1:!1}raiseOnEnterEvent(n){ie.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof Sc&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(n){ie.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof Sc&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(n){ie.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof Sc&&e.onExitTrigger(this)},!1)}},d(vO,"triggers",[]),vO);let zb=dE;Ub([w()],zb.prototype,"triggerMask",2);var dbe=Object.defineProperty,pbe=Object.getOwnPropertyDescriptor,mbe=(n,e,t,r)=>{for(var s=r>1?void 0:r?pbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&dbe(e,t,s),s};const Ko=te("debugspectator");class pE extends Be{constructor(){super(...arguments),d(this,"cam",null),d(this,"useKeys",!0),d(this,"_mode",0),d(this,"orbit",null),d(this,"_handler"),d(this,"eventSub_WebXRRequestStartEvent",null),d(this,"eventSub_WebXRStartEvent",null),d(this,"eventSub_WebXREndEvent",null),d(this,"_debug"),d(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 t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.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 t;if(this._handler){const r=(t=this._handler.currentTarget)==null?void 0:t.userId,s=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&s?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),ie.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,r)):this._handler.currentTarget!==e&&(this._handler.set(e),ie.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,r))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new vbe(this.context,this),this._networking=new bbe(this.context,this),this._networking.awake(),ie.setActive(this.gameObject,!1),this.cam=ie.getComponent(this.gameObject,Li),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new fbe(this.context,this.cam,this)),this.orbit=ie.getComponent(this.context.mainCamera,bi)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),r=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!r}onBeforeXR(e){this.isSupportedPlatform()&&ie.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Ko&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,r;this.context.removeCamera(this.cam),ie.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(r=this._handler)==null||r.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,Wu.Headset),this.target=this.context.players.getPlayerView(this.localId)),Ko&&console.log("Follow self",this.target)}onAfterRender(){var e,t,r;if(!this.cam)return;const s=this.context.renderer,o=s.xr.enabled;if(!s.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const a=s.getRenderTarget();let l=null;const c=s.state;if(!a){if(!s.state.bindFramebuffer||!c.bindXRFramebuffer)return;l=s._framebuffer,c.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const h=this.context.mainCameraComponent;if(h){const m=h.backgroundColor;m&&s.setClearColor(m,m.alpha),this.cam.backgroundColor=m,this.cam.clearFlags=h.clearFlags,this.cam.nearClipPlane=h.nearClipPlane,this.cam.farClipPlane=h.farClipPlane}else s.setClearColor(new xe(1,1,1));s.setRenderTarget(null),s.xr.enabled=!1;const u=(r=this.cam)==null?void 0:r.cam;this.context.updateAspect(u);const p=s.xr.isPresenting;s.xr.isPresenting=!1,s.setSize(this.context.domWidth,this.context.domHeight),s.render(this.context.scene,u),s.xr.isPresenting=p,s.xr.enabled=o,a?s.setRenderTarget(a):c.bindXRFramebuffer&&c.bindXRFramebuffer(l),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of Yr.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let r=rc.All;this.isSpectatingSelf&&(r=e&&t.avatar.isLocalAvatar?rc.FirstPerson:rc.ThirdPerson);const s=t.avatar.flags;if(!s)continue;for(const o of s)o.UpdateVisible(r)}}resetAvatarFlags(){var e;for(const t of Yr.instances)if(t.avatar&&"flags"in t.avatar){const r=t.avatar.flags;if(!r)continue;for(const s of r)"isLocalAvatar"in t.avatar&&(e=t.avatar)!=null&&e.isLocalAvatar?s.UpdateVisible(rc.FirstPerson):s.UpdateVisible(rc.ThirdPerson)}}}mbe([w()],pE.prototype,"useKeys",2);class fbe{constructor(e,t,r){d(this,"context"),d(this,"cam"),d(this,"spectator"),d(this,"follow"),d(this,"target"),d(this,"view"),d(this,"currentObject"),this.context=e,this.cam=t,this.spectator=r}get currentTarget(){return this.view}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=ie.addNewComponent(this.cam.gameObject,Md)),this.target||(this.target=new ye),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Ko&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Ko&&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 e;(e=this.target)==null||e.removeFromParent(),this.follow&&ie.destroy(this.follow)}update(e){var t,r,s,o,a,l;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((r=this.currentTarget)==null?void 0:r.removed)===!0){Ko&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((s=this.currentTarget)==null?void 0:s.currentObject)!==this.currentObject&&(Ko&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const c=this.context.mainCamera;c&&(this.cam.cam.near!==c.near||this.cam.cam.far!==c.far)&&(this.cam.cam.near=c.near,this.cam.cam.far=c.far,this.cam.cam.updateProjectionMatrix());const h=(o=this.follow)==null?void 0:o.target;if(!(!h||!this.follow)){switch(e){case 0:((a=this.view)==null?void 0:a.viewDevice)!==Wu.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),h.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,h.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((l=this.view)==null?void 0:l.viewDevice)!==Wu.Browser?h.quaternion.copy(gbe):h.quaternion.identity()}}}const gbe=new Ce().setFromAxisAngle(new C(0,1,0),Math.PI);class vbe{constructor(e,t){d(this,"context"),d(this,"spectator"),this.context=e,this.spectator=t,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",s=>{!this.spectator.useKeys||s.key==="Escape"&&this.spectator.stopSpectating()});let r=0;this.context.input.addEventListener(an.PointerDown,s=>{r=this.context.time.time}),this.context.input.addEventListener(an.PointerUp,s=>{const o=this.context.time.time-r;o>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&o<.3&&this.trySelectObject()})}trySelectObject(){const e=new ml;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Ko&&console.log(...t),t!=null&&t.length)for(const r of t){if(r.distance<.2)continue;const s=r.object,o=ie.getComponentInParent(s,Yr),a=o?.connectionId;if(a){const l=this.context.players.getPlayerView(a);this.spectator.target=l,Ko&&console.log("spectate",a,o);break}}}}class ybe{constructor(e,t,r){d(this,"guid"),d(this,"dontSave",!0),d(this,"targetUserId"),d(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=r}}class Abe{constructor(e,t){d(this,"guid"),d(this,"userId"),this.guid=e.guid,this.userId=t}}class bbe{constructor(e,t){d(this,"followers",[]),d(this,"context"),d(this,"spectator"),d(this,"_followerEventMethod"),d(this,"_requestFollowMethod"),d(this,"_joinedRoomMethod"),d(this,"_lastRequestFollowUser"),d(this,"_enforceFollowInterval"),this.context=e,this.spectator=t,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(Vt.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.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(Vt.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Ko&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const r=e?.userId===void 0,s=r?t:e?.userId,o=new ybe(this.context.connection.connectionId,s,r);this.context.connection.send("spectator-follower-changed",o)}}onRequestFollowMe(e=!1){if(Ko&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,r=new Abe(this.spectator,t);this.context.connection.send("spectator-request-follow",r)}}onUserJoinedRoom(){te("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,r=e.guid;if(Ko&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const s=this.followers.indexOf(r);s!==-1&&(this.followers.splice(s,1),this.removeDisconnectedFollowers(),console.log(r,"unfollows you",this.followers.length))}else this.followers.includes(r)||(this.followers.push(r),this.removeDisconnectedFollowers(),console.log(r,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Ko&&console.warn("Could not find view",e.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):(Ko&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class Ic{constructor(){d(this,"bb",null),d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Ic).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+bB),(t||new Ic).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new rm).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new rm).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var _be=Object.defineProperty,xbe=Object.getOwnPropertyDescriptor,wbe=(n,e,t,r)=>{for(var s=r>1?void 0:r?xbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&_be(e,t,s),s};const mE="SCAM";wB(mE,Ic.getRootAsSyncedCameraModel);const Zo=new s_;class Sbe{constructor(e,t){d(this,"userId"),d(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){Zo.clear();const r=Zo.createString(this.guid),s=Zo.createString(this.userId);Ic.startSyncedCameraModel(Zo),Ic.addGuid(Zo,r),Ic.addUserId(Zo,s);const o=Bt(e),a=Wv(e);Ic.addPos(Zo,rm.createVec3(Zo,o.x,o.y,o.z)),Ic.addRot(Zo,rm.createVec3(Zo,a.x,a.y,a.z));const l=Ic.endSyncedCameraModel(Zo);Zo.finish(l,mE),t.sendBinary(Zo.asUint8Array())}}}var yO;const AO=(yO=class extends Be{constructor(){super(...arguments),d(this,"cameraPrefab",null),d(this,"_lastWorldPosition"),d(this,"_lastWorldQuaternion"),d(this,"_model",null),d(this,"_needsUpdate",!0),d(this,"_lastUpdateTime",0),d(this,"remoteCams",{}),d(this,"userToCamMap",{}),d(this,"_camTimeoutInSeconds",10),d(this,"_receiveCallback",null)}getCameraObject(n){const e=this.userToCamMap[n];return e?this.remoteCams[e].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(mE,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(mE,this._receiveCallback)}update(){for(const r in this.remoteCams){const s=this.remoteCams[r],o=this.context.time.realtimeSinceStartup-s.lastUpdate;if(!s||o>this._camTimeoutInSeconds){st()&&console.log("Remote cam timeout",r),s!=null&&s.obj&&ie.destroy(s.obj),delete this.remoteCams[r],s&&delete this.userToCamMap[s.userId],AO.instances.push(s),this.context.players.removePlayerView(s.userId,Wu.Browser);continue}}if(this.context.isInXR)return;const n=this.context.mainCamera;if(n===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new Sbe(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=Bt(n),t=Mi(n);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!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(n,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,n,Wu.Browser))}onReceivedRemoteCameraInfoBin(n){const e=n.guid();if(!e)return;const t=n.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let r=this.remoteCams[e];if(!r)if("isObject3D"in this.cameraPrefab){const l=new Ml;l.context=this.context;const c=ie.instantiate(this.cameraPrefab,l);r=this.remoteCams[e]={obj:c,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},r.obj.visible=!0,this.gameObject.add(c),this.userToCamMap[t]=e,AO.instances.push(r);const h=ie.getOrAddComponent(c,Yr);h.connectionId=t,h.avatar=c}else return;const s=r.obj;this.context.players.setPlayerView(t,s,Wu.Browser),r.lastUpdate=this.context.time.realtimeSinceStartup,Qa.markDirty(s);const o=n.pos();o&&_p(s,o.x(),o.y(),o.z());const a=n.rot();a&&Xv(s,a.x(),a.y(),a.z())}},d(yO,"instances",[]),yO);let fE=AO;wbe([w([ye,ti])],fE.prototype,"cameraPrefab",2);var Cbe=Object.defineProperty,Ebe=Object.getOwnPropertyDescriptor,Om=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ebe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Cbe(e,t,s),s};const bO="view",_O=te("debugsyncedroom");class Cc extends Be{constructor(){super(...arguments),d(this,"roomName"),d(this,"urlParameterName","room"),d(this,"joinRandomRoom",!0),d(this,"requireRoomParameter",!1),d(this,"autoRejoin",!0),d(this,"createJoinButton",!0),d(this,"createViewOnlyButton",!1),d(this,"_roomPrefix"),d(this,"_lastJoinedRoom",""),d(this,"_lastPingTime",0),d(this,"_lastRoomTime",-1),d(this,"_userWantsToBeInARoom",!1),d(this,"_roomButton"),d(this,"_roomButtonIconJoin"),d(this,"_roomButtonIconLeave"),d(this,"updateRoomButtonState",()=>{var e,t;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",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),d(this,"_viewOnlyButton"),d(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 t;const r=this.getViewOnlyUrl();r!=null&&r.length?navigator.canShare({url:r})?(t=navigator.share({url:r}))==null||t.catch(s=>{console.warn(s)}):(navigator.clipboard.writeText(r),rn("View only URL copied to clipboard")):Di("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(Ao("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get roomPrefix(){return this._roomPrefix}get RoomPrefix(){return this._roomPrefix}awake(){_O&&console.log("Room",this.roomName,this.urlParameterName,this.joinRandomRoom,this.requireRoomParameter,this.autoRejoin),this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){const e=te(bO);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if((this.joinRandomRoom||te(this.urlParameterName))&&this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}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){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){const r=te(this.urlParameterName);if(r&&typeof r=="string"||r==="number"){t=!0;const s=UU(r);this.roomName=s}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)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(_O&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):(this.context.connection.isConnected||this.context.connection.connect(),_O&&console.log("Join "+this.roomName),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+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()):st()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}get currentRoomName(){return te(bO)||te(this.urlParameterName)}setRandomRoomUrlParameter(){const e=Uv(),t=this.generateRoomName();te(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),II(t,e)}generateRoomName(){return RI()+"_"+Math.floor(it.random(100,999))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(bO,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}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=()=>{this.context.connection.isInRoom?(this.urlParameterName&&Jx(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1):(this.urlParameterName&&(te(this.urlParameterName)||(this._lastJoinedRoom?Jx(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())),this.tryJoinRoom())},this._roomButtonIconJoin=Ao("group"),this._roomButtonIconLeave=Ao("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(Vt.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(Vt.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(Vt.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(Vt.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(Vt.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(Vt.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var e;this.context.connection.stopListen(Vt.JoinedRoom,this.onCreateViewOnlyButton),(e=this._viewOnlyButton)==null||e.remove()}}Om([w()],Cc.prototype,"roomName",2),Om([w()],Cc.prototype,"urlParameterName",2),Om([w()],Cc.prototype,"joinRandomRoom",2),Om([w()],Cc.prototype,"requireRoomParameter",2),Om([w()],Cc.prototype,"autoRejoin",2),Om([w()],Cc.prototype,"createJoinButton",2),Om([w()],Cc.prototype,"createViewOnlyButton",2);function Mbe(){const n=te("testwindowcount")||0;n&&n>0&&Tbe(n)}function Tbe(n){if(te("testwindow"))return null;const e=new URL(window.location.href);TI(e.searchParams,efe,1),TI(e.searchParams,"testwindow",1);const t=e.toString(),r=[];window.onbeforeunload=()=>{for(const c of r)c.close()};const s=.05,o=128;let a=0,l=0;for(let c=0;c<n;c++){a*o+o*.01>=window.innerWidth&&(l+=1,a=0);const h=a*(o*(1+s))+window.screenLeft,u=l*(o*(1+s))+window.screenTop+90+60*l;a+=1;const p=window.open(t,"test window "+c,`popup=yes width=${o} height=${o} top=${u} left=${h}`);if(!p){console.warn("Failed to open window");continue}r.push(p),p.onload=()=>{p.onbeforeunload=()=>{for(let m=0;m<r.length;m++){const f=r[m];f!==p&&f.close()}r.length=0}}}return r}class xO extends Be{awake(){Mbe()}}class wO extends Be{constructor(){super(...arguments),d(this,"transformsPerFrame",10),d(this,"interval",0),d(this,"useFlatbuffers",!0),d(this,"builder",null),d(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(AA,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new o9(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 s_(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const r=yV(this.context.connection.connectionId,this);this.context.connection.sendBinary(r)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class o9{constructor(e,t){d(this,"guid"),d(this,"fast",!1),d(this,"position"),d(this,"rotation"),d(this,"velocity"),d(this,"dontSave"),this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(e,t){const r=e.worldPosition;this.position.x=r.x,this.position.y=r.y,this.position.z=r.z;const s=e.worldQuaternion;if(this.rotation.x=s.x,this.rotation.y=s.y,this.rotation.z=s.z,this.rotation.w=s.w,this.fast=!1,t){const o=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=o.x,this.velocity.y=o.y,this.velocity.z=o.z}}}d(o9,"temp",new C);var Ibe=Object.defineProperty,Rbe=Object.getOwnPropertyDescriptor,k0=(n,e,t,r)=>{for(var s=r>1?void 0:r?Rbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Ibe(e,t,s),s};class Ec extends Xr{constructor(){super(...arguments),d(this,"offset",new qe(0)),d(this,"rotation",new qe(0)),d(this,"focusArea",new qe(.4)),d(this,"feather",new qe(.3)),d(this,"kernelSize",new qe(Ql.MEDIUM)),d(this,"resolutionScale",new qe(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=Ql.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new l6({kernelSize:Ql.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}k0([w(qe)],Ec.prototype,"offset",2),k0([w(qe)],Ec.prototype,"rotation",2),k0([w(qe)],Ec.prototype,"focusArea",2),k0([w(qe)],Ec.prototype,"feather",2),k0([w(qe)],Ec.prototype,"kernelSize",2),k0([w(qe)],Ec.prototype,"resolutionScale",2),Ra("TiltShiftEffect",Ec);var Pbe=Object.defineProperty,Bbe=Object.getOwnPropertyDescriptor,gE=(n,e,t,r)=>{for(var s=r>1?void 0:r?Bbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Pbe(e,t,s),s};class Lm extends Be{constructor(){super(...arguments),d(this,"isGizmo",!1),d(this,"translationSnap",1),d(this,"rotationSnapAngle",15),d(this,"scaleSnap",.25),d(this,"control"),d(this,"orbit"),d(this,"onControlChangedEvent",e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const r=ie.getComponentInParent(this.gameObject,Ku);r&&r.requestOwnership()}}),d(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}}),d(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}onEnable(){var e;this.isGizmo&&!Wy||this.context.mainCamera&&(this.control||(this.control=new mle(this.context.mainCamera,this.context.renderer.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=1,this.control.traverse(t=>{const r=t;if(r.layers.set(2),r){const s=r.material;s&&(s.opacity=.3)}}),this.orbit=ie.getComponentInParent(this.context.mainCamera,bi)??void 0),this.control&&(this.context.scene.add(this.control),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,t;(e=this.control)==null||e.removeFromParent(),(t=this.control)==null||t.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(ui.degToRad(this.rotationSnapAngle)),this.control.setScaleSnap(this.scaleSnap))}disableSnapping(){this.control&&(this.control.setTranslationSnap(null),this.control.setRotationSnap(null),this.control.setScaleSnap(null))}}gE([w()],Lm.prototype,"isGizmo",2),gE([w()],Lm.prototype,"translationSnap",2),gE([w()],Lm.prototype,"rotationSnapAngle",2),gE([w()],Lm.prototype,"scaleSnap",2);var kbe=Object.defineProperty,Dbe=Object.getOwnPropertyDescriptor,SO=(n,e,t,r)=>{for(var s=r>1?void 0:r?Dbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&kbe(e,t,s),s};class Fm extends Xr{constructor(){super(...arguments),d(this,"color",new qe({r:0,g:0,b:0,a:1})),d(this,"intensity",new qe(0)),d(this,"center",new qe({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 c6;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}SO([w(qe)],Fm.prototype,"color",2),SO([w(qe)],Fm.prototype,"intensity",2),SO([w(qe)],Fm.prototype,"center",2),Ra("Vignette",Fm);var Obe=Object.defineProperty,Lbe=Object.getOwnPropertyDescriptor,Fbe=(n,e,t,r)=>{for(var s=r>1?void 0:r?Lbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Obe(e,t,s),s};const CO=te("debugpost");class D0 extends Be{constructor(){super(...arguments),d(this,"sharedProfile"),d(this,"_postprocessing"),d(this,"_activeEffects",[]),d(this,"_effects",[]),d(this,"_lastApplyTime"),d(this,"_rapidApplyCount",0),d(this,"_isDirty",!1),d(this,"_modificationQueue"),d(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}addEffect(e){let t=e;return t instanceof Ys&&(t=new mb(t)),this._effects.includes(t)||(this._effects.push(t),this._isDirty=!0),e}removeEffect(e){let t=-1;return e instanceof Ys?t=this._effects.findIndex(r=>r instanceof mb&&r.effect===e):t=this._effects.indexOf(e),t!==-1&&(this._effects.splice(t,1),this._isDirty=!0),e}markDirty(){this._isDirty=!0}awake(){var e;CO&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",t=>{t.key==="p"&&(this.enabled=!this.enabled,rn("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.init()}onEnable(){this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){var e;if(!this.context.isInXR){if(this.context.composer&&!(this.context.composer instanceof JP)){CO&&console.warn("PostProcessing: The current composer is not an EffectComposer - this is not supported");return}this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&((e=this._postprocessing)==null?void 0:e.composer)===this.context.composer&&(this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.context.mainCamera&&this.context.composer.setMainCamera(this.context.mainCamera))}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e;if(CO&&console.log("Apply PostProcessing "+this.name),st()&&(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.unapply(),this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const t=this.sharedProfile.components;for(const r of t)r.active&&!this._activeEffects.includes(r)&&this._activeEffects.push(r)}for(const t of this._effects)t.active&&!this._activeEffects.includes(t)&&this._activeEffects.push(t);this._activeEffects.length>0&&(this._postprocessing||(this._postprocessing=new lE(this.context)),this._postprocessing.apply(this._activeEffects),this._applyPostQueue())}unapply(){var e;(e=this._postprocessing)==null||e.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var t,r;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((t=this._activeEffects)!=null&&t.length))return;const s=e.propertyName.split(".");if(s.length===3||s.length===4){const o=s[1],a=s[2];for(const l of this._activeEffects)if(((r=l.typeName)==null?void 0:r.toLowerCase())===o.toLowerCase()){if(a==="active"){l.active=e.value,this.scheduleRecreate();return}if(!vE.has(o)){const c=new Array;vE.set(o,c);const h=Object.keys(l);for(const u of h)l[u]instanceof qe&&c.push(u)}if(vE.has(o)){const c=a.toLowerCase(),h=vE.get(o);for(const u of h)if(u.toLowerCase()===c){const p=l[u];p instanceof qe&&(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",a);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}Fbe([Eg(kA)],D0.prototype,"sharedProfile",2);const vE=new Map;gme(D0);var Ube=Object.defineProperty,Nbe=Object.getOwnPropertyDescriptor,zbe=(n,e,t,r)=>{for(var s=r>1?void 0:r?Nbe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Ube(e,t,s),s};const yE=te("debugarcamera");class AE extends Be{constructor(){super(...arguments),d(this,"backgroundTint",new Si(1,1,1,1)),d(this,"backgroundPlane"),d(this,"threeTexture"),d(this,"forceTextureInitialization",function(){const e=new $t,t=new tr,r=new Ur;r.add(new me(t,e));const s=new Lt;return function(o,a){e.map=a,o.render(r,s),yE&&console.warn("Force texture initialization")}}()),d(this,"preRender",()=>{if(!this||!this.gameObject)return;const e=this.context.renderer.xr.getFrame();e&&(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new zt,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0&&(this.backgroundPlane=Gbe(this.backgroundTint)),this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.updateFromFrame(e))})}onBeforeXR(e,t){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("camera-access"),yE&&console.warn("Requesting camera-access")}onEnterXR(e){this.backgroundPlane&&(this.context.scene.add(this.backgroundPlane),this.backgroundPlane.visible=!1),this.backgroundPlane&&this.context.scene.add(this.backgroundPlane),this.context.pre_render_callbacks.push(this.preRender)}onLeaveXR(e){this.backgroundPlane&&this.backgroundPlane.removeFromParent();const t=this.context.pre_render_callbacks.indexOf(this.preRender);t>=0&&this.context.pre_render_callbacks.splice(t,1)}get background(){return this.backgroundPlane}onBeforeRender(e){this.updateFromFrame(e)}updateFromFrame(e){if(!e)return;const t=e.session.enabledFeatures;if(t&&!t.some(s=>s==="camera-access")){this.background&&(this.background.visible=!1);return}const r=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(r){for(const s of r.views)if("camera"in s&&s.camera){let o=this.context.renderer.xr.getBinding();if(o||(o=new XRWebGLBinding(e.session,this.context.renderer.getContext())),o){let a=null;if("getCameraImage"in o){a=o.getCameraImage(s.camera);const l=this.context.renderer.properties.get(this.threeTexture);l.__webglTexture=a,this.backgroundPlane?(this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0):yE&&console.warn("No background plane to set texture on")}}}}}}zbe([w(Si)],AE.prototype,"backgroundTint",2);const jbe=`
7655
7655
  uniform sampler2D t2D;
7656
7656
 
7657
7657
  varying vec2 vUv;
@@ -7678,7 +7678,7 @@ This could mean you forgot to add a npmdef to your ExportInfo
7678
7678
  <a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,Bo.Warn)}}if(e.children)for(const o of e.children)await BO(n,o,t)}function o_e(n,e){const{instance:t,compData:r,obj:s}=n;e.object=s,e.target=t,j1(t,r,e),Hb&&console.debug("add "+r.name,r,t)}const h9=te("debugfileformat");async function u9(n,e=!0){var t;if(e){const s=n,o=new URL(s,globalThis.location.origin);let a=null;const l=o.searchParams.get("filetype");switch(l&&(a=l.toUpperCase()),a!=null&&a.length||(a=(t=o.pathname.split(".").pop())==null?void 0:t.toUpperCase()),a){case"GLTF":return"gltf";case"VRM":return"vrm";case"GLB":return"glb";case"FBX":return"fbx";case"USD":return"usd";case"USDA":return"usda";case"USDZ":return"usdz"}}const r=await fetch(n,{method:"GET",headers:{range:"bytes=0-32"}}).catch(s=>null);if(r!=null&&r.ok){const s=await r.arrayBuffer(),o=d9(s);return h9&&console.log("Determined file type from header: "+o),o}return"unknown"}function d9(n){if(n.byteLength<4)return"unknown";const e=new Uint8Array(n);return h9&&console.warn(`Trying to determine file type from binary data
7679
7679
  `,'"'+new TextDecoder().decode(n)+`"
7680
7680
  `,e),e[0]==103&&e[1]==108&&e[2]==84&&e[3]==70?"glb":e[0]==80&&e[1]==75&&e[2]==3&&e[3]==4?"usdz":e[0]==80&&e[1]==88&&e[2]==82&&e[3]==45&&e[4]==85&&e[5]==83&&e[6]==68&&e[7]==67?"usd":e[0]==35&&e[1]==117&&e[2]==115&&e[3]==100&&e[4]==97?"usda":e[0]==75&&e[1]==97&&e[2]==121&&e[3]==100&&e[4]==97&&e[5]==114&&e[6]==97&&e[7]==32?"fbx":e[0]==35&&e[1]==32&&e[2]==66&&e[3]==108&&e[4]==101&&e[5]==110&&e[6]==100&&e[7]==101&&e[8]==114&&e[9]==32?"obj":"unknown"}class kO{createBuiltinComponents(e,t,r,s,o){return s_e(e,t,r,s,o)}writeBuiltinComponentData(e,t){return n_e(e,t)}parseSync(e,t,r,s){return v9(e,t,r,s)}loadSync(e,t,r,s,o){return OO(e,t,r,s,o)}}CI(kO);const p9=te("printGltf")||te("printgltf"),m9=te("downloadgltf");var f9=(n=>(n[n.BeforeLoad=0]="BeforeLoad",n[n.AfterLoaded=1]="AfterLoaded",n[n.FinishedSetup=10]="FinishedSetup",n))(f9||{});class Nm{constructor(e,t,r,s){d(this,"context"),d(this,"loader"),d(this,"path"),d(this,"gltf"),this.context=e,this.path=t,this.loader=r,this.gltf=s}}const Id={};function a_e(n,e){Id[n]=Id[n]||[],Id[n].push(e)}function l_e(n,e){if(Id[n]){const t=Id[n].indexOf(e);t>=0&&Id[n].splice(t,1)}}function z0(n,e){if(Id[n])for(const t of Id[n])t(e)}async function g9(n,e,t,r,s){p9&&console.warn("glTF",e,t),e.includes("?")&&(e=e.split("?")[0]),await Ka().createBuiltinComponents(n,e,t,r,s)}async function DO(n,e){const t=await u9(n)||"unknown";switch(t){case"unknown":return console.warn("Unknown file type:",n),new Ru;case"fbx":return new kj;case"obj":return new bP;case"usd":case"usda":case"usdz":return console.warn("USD files are not supported."),null;default:console.warn("Unknown file type:",t);case"gltf":case"glb":case"vrm":const r=new Ru;return await nD(r,e,n),r}}async function v9(n,e,t,r){typeof t!="string"&&(console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t),t=""),p9&&console.log("Parse glTF",t);const s=await DO(t,n);if(!s)return;if(s instanceof bP){typeof e!="string"&&(e=new TextDecoder().decode(e));const a=s.parse(e);return{animations:a.animations,scene:a,scenes:[a]}}if(!(s instanceof Ru)){const a=s.parse(e,t);return b9(s,a),{animations:a.animations,scene:a,scenes:[a]}}const o=iD(s);return new Promise((a,l)=>{try{let c=t.split("?")[0].trimEnd();if(c.endsWith(".glb")||c.endsWith(".gltf")){const u=c.split("/");u.pop(),c=u.join("/"),c.endsWith("/")||(c+="/")}s.resourcePath=c,u1(s,n),z0(0,new Nm(n,t,s));const h=n.mainCamera;s.parse(e,"",async u=>{sD(t,u,n),z0(1,new Nm(n,t,s,u)),await g9(n,t,u,r,o),await y9(u.scene,n,h),z0(10,new Nm(n,t,s,u)),a(u),m9&&A9(e)},u=>{console.error("failed loading "+t,u),a(void 0)})}catch(c){console.error(c),l(c)}})}async function OO(n,e,t,r,s){c_e(e);const o=await DO(e,n);if(!o)return;if(!(o instanceof Ru)){const l=await o.loadAsync(e,s);return b9(o,l),{animations:l.animations,scene:l,scenes:[l]}}const a=iD(o);return new Promise((l,c)=>{try{u1(o,n),z0(0,new Nm(n,e,o));const h=n.mainCamera;o.load(e,async u=>{sD(e,u,n),z0(1,new Nm(n,e,o,u)),await g9(n,t,u,r,a),await y9(u.scene,n,h),z0(10,new Nm(n,e,o,u)),l(u),m9&&A9(e)},u=>{s?.call(o,u)},u=>{console.error("failed loading "+e,u),l(void 0)})}catch(h){console.error(h),c(h)}})}async function y9(n,e,t){t||(t=e.mainCamera),t?await e.renderer.compileAsync(n,t,e.scene):Dle(n,e)}function c_e(n){if(new URL(n,window.location.href).href.startsWith("file://")){const e=`Hi - it looks like you are trying to load a local file which will not work. You need to use a webserver to serve your files.
7681
- Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;rn(e),console.warn(e)}}function A9(n){if(typeof n=="string"){const e=document.createElement("a");e.href=n,e.download=n.split("/").pop(),e.click()}else{const e=new Blob([n],{type:"application/octet-stream"}),t=window.URL.createObjectURL(e),r=document.createElement("a");r.href=t,r.download="download.glb",r.click()}}function b9(n,e){if(e!=null&&e.isObject3D){const t=e;n instanceof kj?t.traverse(r=>{const s=r;s!=null&&s.isMesh&&TR(s,s.material)}):n instanceof bP&&t.traverse(r=>{})}}CI(kO);const hn=te("debugwebcomponent"),_9="needle-engine",x9="vr",w9="desktop",h_e=[xz,x9,w9],Xb="ar-session-active",qb="desktop-session-active",u_e=["hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure"];class LO extends HTMLElement{constructor(){super(),d(this,"_context"),d(this,"_overlay_ar"),d(this,"_loadingProgress01",0),d(this,"_loadingView"),d(this,"_previousSrc",null),d(this,"_didFullyLoad",!1),d(this,"_loadId",0),d(this,"_abortController",null),d(this,"_lastSourceFiles",null),d(this,"_createContextPromise",null),d(this,"onXRSessionStarted",()=>{var t;const r=this.context.xrSessionMode;r==="immersive-ar"?this.onEnterAR(this.context.xrSession):r==="immersive-vr"&&this.onEnterVR(this.context.xrSession),(t=this.context.xrSession)==null||t.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:r}})),r==="immersive-ar"?this.onExitAR(this.context.xrSession):r==="immersive-vr"&&this.onExitVR(this.context.xrSession)})}),d(this,"onReady",()=>{var t;return(t=this._loadingView)==null?void 0:t.onLoadingFinished()}),d(this,"onError",()=>{var t;return(t=this._loadingView)==null?void 0:t.setMessage("Loading failed!")}),d(this,"_previouslyRegisteredMap",new Map),this._overlay_ar=new Mne,this.addEventListener("ready",this.onReady),PV(),this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>
7681
+ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;rn(e),console.warn(e)}}function A9(n){if(typeof n=="string"){const e=document.createElement("a");e.href=n,e.download=n.split("/").pop(),e.click()}else{const e=new Blob([n],{type:"application/octet-stream"}),t=window.URL.createObjectURL(e),r=document.createElement("a");r.href=t,r.download="download.glb",r.click()}}function b9(n,e){if(e!=null&&e.isObject3D){const t=e;n instanceof kj?t.traverse(r=>{const s=r;s!=null&&s.isMesh&&TR(s,s.material)}):n instanceof bP&&t.traverse(r=>{})}}CI(kO);const hn=te("debugwebcomponent"),_9="needle-engine",x9="vr",w9="desktop",h_e=[xz,x9,w9],Xb="ar-session-active",qb="desktop-session-active",u_e=["hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure"];class LO extends HTMLElement{constructor(){super(),d(this,"_context"),d(this,"_overlay_ar"),d(this,"_loadingProgress01",0),d(this,"_loadingView"),d(this,"_previousSrc",null),d(this,"_didFullyLoad",!1),d(this,"_loadId",0),d(this,"_abortController",null),d(this,"_lastSourceFiles",null),d(this,"_createContextPromise",null),d(this,"onXRSessionStarted",()=>{var t;const r=this.context.xrSessionMode;r==="immersive-ar"?this.onEnterAR(this.context.xrSession):r==="immersive-vr"&&this.onEnterVR(this.context.xrSession),(t=this.context.xrSession)==null||t.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:r}})),r==="immersive-ar"?this.onExitAR(this.context.xrSession):r==="immersive-vr"&&this.onExitVR(this.context.xrSession)})}),d(this,"onReady",()=>{var t;return(t=this._loadingView)==null?void 0:t.onLoadingFinished()}),d(this,"onError",()=>{var t;return(t=this._loadingView)==null?void 0:t.setMessage("Loading failed!")}),d(this,"_previouslyRegisteredMap",new Map),this._overlay_ar=new Mne,this.addEventListener("ready",this.onReady),P8(),this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>
7682
7682
  @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
7683
7683
 
7684
7684
  :host {
@@ -7744,7 +7744,7 @@ Needle Engine: Begin loading `+s+`
7744
7744
  Needle Engine: finished loading `+s+`
7745
7745
  `,r,`Aborted? ${m.signal.aborted}`),this._loadId!==s||m.signal.aborted){console.log("Loading finished but aborted...");return}this._loadingProgress01=1,l&&((t=this._loadingView)==null||t.onLoadingUpdate(1,"creating scene")),this._didFullyLoad=!0,this.classList.remove("loading"),this.classList.add("loading-finished"),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:o,loadedFiles:c}}))}applyTonemapping(){var e;if(!((e=this._context)!=null&&e.renderer))return;const t=this.getAttribute("tonemapping")||this.getAttribute("tone-mapping");switch(t?.toLowerCase()){case"none":this._context.renderer.toneMapping=Ls;break;case"linear":this._context.renderer.toneMapping=Xm;break;case"neutral":this._context.renderer.toneMapping=Ud;break;case"agx":this._context.renderer.toneMapping=qm;break;default:t!=null&&console.warn("Invalid tone-mapping attribute: "+t)}const r=this.getAttribute("tone-mapping-exposure");if(r!=null){const s=parseFloat(r);isNaN(s)||(this._context.renderer.toneMappingExposure=s)}}internalSetLoadingMessage(e){var t;(t=this._loadingView)==null||t.setMessage(e)}getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let t;Array.isArray(e)?t=e:e.startsWith("[")&&e.endsWith("]")?t=JSON.parse(e):e.includes(",")?t=e.split(","):t=[e];for(let r=t.length-1;r>=0;r--){const s=t[r];(s==="null"||s==="undefined"||s?.length<=0)&&t.splice(r,1)}return t}checkIfSourceHasChanged(e,t){if(e?.length!==t?.length||e==null&&t!==null||e!==null&&t==null)return!0;if(e!==null&&t!==null){for(let r=0;r<e?.length;r++)if(e[r]!==t[r])return!0}return!1}ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,t){const r=this._previouslyRegisteredMap.get(e);if(r&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,r)),typeof t=="string"&&t.length>0)try{const s=(0,eval)(t);typeof s=="function"&&(this._previouslyRegisteredMap.set(e,s),this.addEventListener(e,o=>s?.call(globalThis,this._context,o)))}catch(s){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
7746
7746
  `,s)}}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e){var t;this.onSetupAR();const r=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,r,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:(t=this._overlay_ar)==null?void 0:t.ARContainer}}))}onExitAR(e){var t;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:(t=this._overlay_ar)==null?void 0:t.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onSetupAR(){this.classList.add(Xb),this.classList.remove(qb);const e=this.getAROverlayContainer();hn&&console.warn("onSetupAR:",e),e&&(e.classList.add(Xb),e.classList.remove(qb)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,xz))}onSetupVR(){this.classList.remove(Xb),this.classList.remove(qb),this.foreachHtmlElement(e=>this.setupElementsForMode(e,x9))}onSetupDesktop(){this.classList.remove(Xb),this.classList.add(qb);const e=this.getAROverlayContainer();e&&(e.classList.remove(Xb),e.classList.add(qb)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,w9))}setupElementsForMode(e,t,r=null){var s,o;if(!(e===((o=(s=this._context)==null?void 0:s.renderer)==null?void 0:o.domElement)||e.id==="VRButton"||e.id==="ARButton"))if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const a of h_e)e.classList.contains(a)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const r=this.children[t];r.style&&e(r)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(hn&&console.log("using custom draco decoder path",e),vj(e));const t=this.getAttribute("dracoDecoderType");t&&(hn&&console.log("using custom draco decoder type",t),yj(t));const r=this.getAttribute("ktx2DecoderPath");r&&(hn&&console.log("using custom ktx2 decoder path",r),Aj(r))}}typeof window<"u"&&!window.customElements.get(_9)&&window.customElements.define(_9,LO);function d_e(n){if(n.startsWith("blob:"))return"blob";const e=n.split("/");let t=e[e.length-1];const r=t.indexOf("?");r>0&&(t=t.substring(0,r));const s=t.indexOf("=");s>0&&(t=t.substring(s));const o=t.split(".").pop();if((o==="glb"||o==="gltf")&&(t=t.substring(0,t.length-4)),t=decodeURIComponent(t),t.length>3){let a="";for(let l=0;l<t.length;l++){let c=t[l];if(c===" "&&a.length<=0)continue;const h=a.length===0,u=c>="0"&&c<="9";h==!1&&c===c.toUpperCase()&&!u?a+=" "+c:(h&&(c=c.toUpperCase()),a+=c)}return hn&&console.log("displayName",t,a),a}return hn&&console.log("displayName",t),t}const p_e=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineHTMLElement:LO},Symbol.toStringTag,{value:"Module"}));function m_e(){Qu.registerWaitForAllowAudio(()=>{const n=Ux.getContext();n.addEventListener("statechange",()=>{setTimeout(()=>{const e=n.state;(e==="suspended"||e==="interrupted")&&n.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(m_e,1e3);const _E=te("debughotreload");let Yb=!1;const Jb=new Map;function f_e(){return Yb}function g_e(n){var e;if(Yb)return;const t=n.constructor.name;Jb.has(t)?(e=Jb.get(t))==null||e.push(n):Jb.set(t,[n])}function v_e(n){if(Yb)return;const e=n.constructor.name,t=Jb.get(e);if(!t)return;const r=t.indexOf(n);r!==-1&&t.splice(r,1)}let S9=!1;function y_e(){if(_E||S9)return;S9=!0;const n=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}n.apply(console,e)}}function A_e(n){_E&&console.log("[HMR] Apply changes",n,Object.keys(n)),y_e();for(const e of Object.keys(n))try{Yb=!0;const t=q.get(e);if(!t){_E&&console.log("[HMR] Type not found: "+e);continue}const r=n[e],s=Jb.get(r.name);let o="[Needle Engine] Updating type: "+e;const a=s?.length??-1;a>0?o+=" x"+a:o+=" - no instances",console.log(o);const l=Object.getOwnPropertyNames(t.prototype),c=Object.getOwnPropertyDescriptors(r.prototype);for(const h in c)c[h].writable&&(t.prototype[h]=n[e].prototype[h]);for(const h of l)c[h]||delete t.prototype[h];if(s){const h=new r,u=Object.getOwnPropertyDescriptors(h);for(const p of s){const m=p,f=m.isComponent===!0,g=f?m.activeAndEnabled:!0,v=f?m.context:void 0;try{if(f&&v&&dh(m,v),f&&g&&(m.enabled=!1),p.onBeforeHotReloadFields&&p.onBeforeHotReloadFields()===!1)continue;for(const y in u)if(u[y].writable){if(p[y]===void 0)p[y]=h[y];else if(typeof p[y]=="function"&&!p[y].prototype){const A=p[y],_=A.name,b="bound ";if(_===b)continue;const x=A.name.substring(b.length),E=r.prototype[x];E&&(p[y]=E.bind(p))}}p.onAfterHotReloadFields&&p.onAfterHotReloadFields()}finally{f&&v&&GP(m,v),f&&g&&(m.enabled=!0)}}}}catch(t){if(_E)console.error(t);else return!1}finally{Yb=!1,Fl(Bo.Log,"Script changes applied (HMR)")}return!0}let Ne;const Kb=new Array(128).fill(void 0);Kb.push(void 0,null,!0,!1),Kb.length;let xE=null;function C9(){return xE!==null&&xE.byteLength!==0||(xE=new Int32Array(Ne.memory.buffer)),xE}const b_e=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder<"u"&&b_e.decode();function mt(n,e){if(!(n instanceof e))throw new Error(`expected instance of ${e.name}`);return n.ptr}let wE=null;function __e(){return wE!==null&&wE.byteLength!==0||(wE=new Float32Array(Ne.memory.buffer)),wE}let Zb=128;function E9(n){if(Zb==1)throw new Error("out of js stack");return Kb[--Zb]=n,Zb}let SE=null;function x_e(){return SE!==null&&SE.byteLength!==0||(SE=new Uint32Array(Ne.memory.buffer)),SE}let $o=0;function zm(n,e){const t=e(4*n.length,4)>>>0;return __e().set(n,t/4),$o=n.length,t}function CE(n,e){const t=e(4*n.length,4)>>>0;return x_e().set(n,t/4),$o=n.length,t}const ss=Object.freeze({Ball:0,0:"Ball",Cuboid:1,1:"Cuboid",Capsule:2,2:"Capsule",Segment:3,3:"Segment",Polyline:4,4:"Polyline",Triangle:5,5:"Triangle",TriMesh:6,6:"TriMesh",HeightField:7,7:"HeightField",Compound:8,8:"Compound",ConvexPolyhedron:9,9:"ConvexPolyhedron",Cylinder:10,10:"Cylinder",Cone:11,11:"Cone",RoundCuboid:12,12:"RoundCuboid",RoundTriangle:13,13:"RoundTriangle",RoundCylinder:14,14:"RoundCylinder",RoundCone:15,15:"RoundCone",RoundConvexPolyhedron:16,16:"RoundConvexPolyhedron",HalfSpace:17,17:"HalfSpace"});class w_e{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,e}free(){const e=this.__destroy_into_raw();Ne.__wbg_raweventqueue_free(e)}constructor(e){const t=Ne.raweventqueue_new(e);return this.__wbg_ptr=t>>>0,this}drainCollisionEvents(e){try{Ne.raweventqueue_drainCollisionEvents(this.__wbg_ptr,E9(e))}finally{Kb[Zb++]=void 0}}drainContactForceEvents(e){try{Ne.raweventqueue_drainContactForceEvents(this.__wbg_ptr,E9(e))}finally{Kb[Zb++]=void 0}}clear(){Ne.raweventqueue_clear(this.__wbg_ptr)}}class Os{static __wrap(e){e>>>=0;const t=Object.create(Os.prototype);return t.__wbg_ptr=e,t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,e}free(){const e=this.__destroy_into_raw();Ne.__wbg_rawgenericjoint_free(e)}static generic(e,t,r,s){mt(e,at),mt(t,at),mt(r,at);const o=Ne.rawgenericjoint_generic(e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s);return o===0?void 0:Os.__wrap(o)}static spring(e,t,r,s,o){mt(s,at),mt(o,at);const a=Ne.rawgenericjoint_spring(e,t,r,s.__wbg_ptr,o.__wbg_ptr);return Os.__wrap(a)}static rope(e,t,r){mt(t,at),mt(r,at);const s=Ne.rawgenericjoint_rope(e,t.__wbg_ptr,r.__wbg_ptr);return Os.__wrap(s)}static spherical(e,t){mt(e,at),mt(t,at);const r=Ne.rawgenericjoint_spherical(e.__wbg_ptr,t.__wbg_ptr);return Os.__wrap(r)}static prismatic(e,t,r,s,o,a){mt(e,at),mt(t,at),mt(r,at);const l=Ne.rawgenericjoint_prismatic(e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s,o,a);return l===0?void 0:Os.__wrap(l)}static fixed(e,t,r,s){mt(e,at),mt(t,as),mt(r,at),mt(s,as);const o=Ne.rawgenericjoint_fixed(e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s.__wbg_ptr);return Os.__wrap(o)}static revolute(e,t,r){mt(e,at),mt(t,at),mt(r,at);const s=Ne.rawgenericjoint_revolute(e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr);return s===0?void 0:Os.__wrap(s)}}class iL{static __wrap(e){e>>>=0;const t=Object.create(iL.prototype);return t.__wbg_ptr=e,t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,e}free(){const e=this.__destroy_into_raw();Ne.__wbg_rawpointprojection_free(e)}point(){const e=Ne.rawpointprojection_point(this.__wbg_ptr);return at.__wrap(e)}isInside(){return Ne.rawpointprojection_isInside(this.__wbg_ptr)!==0}}class nL{static __wrap(e){e>>>=0;const t=Object.create(nL.prototype);return t.__wbg_ptr=e,t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,e}free(){const e=this.__destroy_into_raw();Ne.__wbg_rawrayintersection_free(e)}normal(){const e=Ne.rawraycolliderintersection_normal(this.__wbg_ptr);return at.__wrap(e)}toi(){return Ne.rawraycolliderintersection_toi(this.__wbg_ptr)}featureType(){return Ne.rawpointcolliderprojection_featureType(this.__wbg_ptr)}featureId(){try{const r=Ne.__wbindgen_add_to_stack_pointer(-16);Ne.rawpointcolliderprojection_featureId(r,this.__wbg_ptr);var e=C9()[r/4+0],t=C9()[r/4+1];return e===0?void 0:t>>>0}finally{Ne.__wbindgen_add_to_stack_pointer(16)}}}class as{static __wrap(e){e>>>=0;const t=Object.create(as.prototype);return t.__wbg_ptr=e,t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,e}free(){const e=this.__destroy_into_raw();Ne.__wbg_rawrotation_free(e)}constructor(e,t,r,s){const o=Ne.rawrotation_new(e,t,r,s);return this.__wbg_ptr=o>>>0,this}static identity(){const e=Ne.rawrotation_identity();return as.__wrap(e)}get x(){return Ne.rawrotation_x(this.__wbg_ptr)}get y(){return Ne.rawintegrationparameters_dt(this.__wbg_ptr)}get z(){return Ne.rawraycolliderintersection_toi(this.__wbg_ptr)}get w(){return Ne.rawintegrationparameters_erp(this.__wbg_ptr)}}class Qt{static __wrap(e){e>>>=0;const t=Object.create(Qt.prototype);return t.__wbg_ptr=e,t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,e}free(){const e=this.__destroy_into_raw();Ne.__wbg_rawshape_free(e)}static cuboid(e,t,r){const s=Ne.rawshape_cuboid(e,t,r);return Qt.__wrap(s)}static roundCuboid(e,t,r,s){const o=Ne.rawshape_roundCuboid(e,t,r,s);return Qt.__wrap(o)}static ball(e){const t=Ne.rawshape_ball(e);return Qt.__wrap(t)}static halfspace(e){mt(e,at);const t=Ne.rawshape_halfspace(e.__wbg_ptr);return Qt.__wrap(t)}static capsule(e,t){const r=Ne.rawshape_capsule(e,t);return Qt.__wrap(r)}static cylinder(e,t){const r=Ne.rawshape_cylinder(e,t);return Qt.__wrap(r)}static roundCylinder(e,t,r){const s=Ne.rawshape_roundCylinder(e,t,r);return Qt.__wrap(s)}static cone(e,t){const r=Ne.rawshape_cone(e,t);return Qt.__wrap(r)}static roundCone(e,t,r){const s=Ne.rawshape_roundCone(e,t,r);return Qt.__wrap(s)}static polyline(e,t){const r=zm(e,Ne.__wbindgen_malloc),s=$o,o=CE(t,Ne.__wbindgen_malloc),a=$o,l=Ne.rawshape_polyline(r,s,o,a);return Qt.__wrap(l)}static trimesh(e,t){const r=zm(e,Ne.__wbindgen_malloc),s=$o,o=CE(t,Ne.__wbindgen_malloc),a=$o,l=Ne.rawshape_trimesh(r,s,o,a);return Qt.__wrap(l)}static heightfield(e,t,r,s){const o=zm(r,Ne.__wbindgen_malloc),a=$o;mt(s,at);const l=Ne.rawshape_heightfield(e,t,o,a,s.__wbg_ptr);return Qt.__wrap(l)}static segment(e,t){mt(e,at),mt(t,at);const r=Ne.rawshape_segment(e.__wbg_ptr,t.__wbg_ptr);return Qt.__wrap(r)}static triangle(e,t,r){mt(e,at),mt(t,at),mt(r,at);const s=Ne.rawshape_triangle(e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr);return Qt.__wrap(s)}static roundTriangle(e,t,r,s){mt(e,at),mt(t,at),mt(r,at);const o=Ne.rawshape_roundTriangle(e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s);return Qt.__wrap(o)}static convexHull(e){const t=zm(e,Ne.__wbindgen_malloc),r=$o,s=Ne.rawshape_convexHull(t,r);return s===0?void 0:Qt.__wrap(s)}static roundConvexHull(e,t){const r=zm(e,Ne.__wbindgen_malloc),s=$o,o=Ne.rawshape_roundConvexHull(r,s,t);return o===0?void 0:Qt.__wrap(o)}static convexMesh(e,t){const r=zm(e,Ne.__wbindgen_malloc),s=$o,o=CE(t,Ne.__wbindgen_malloc),a=$o,l=Ne.rawshape_convexMesh(r,s,o,a);return l===0?void 0:Qt.__wrap(l)}static roundConvexMesh(e,t,r){const s=zm(e,Ne.__wbindgen_malloc),o=$o,a=CE(t,Ne.__wbindgen_malloc),l=$o,c=Ne.rawshape_roundConvexMesh(s,o,a,l,r);return c===0?void 0:Qt.__wrap(c)}castShape(e,t,r,s,o,a,l,c,h){mt(e,at),mt(t,as),mt(r,at),mt(s,Qt),mt(o,at),mt(a,as),mt(l,at);const u=Ne.rawshape_castShape(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s.__wbg_ptr,o.__wbg_ptr,a.__wbg_ptr,l.__wbg_ptr,c,h);return u===0?void 0:sL.__wrap(u)}intersectsShape(e,t,r,s,o){return mt(e,at),mt(t,as),mt(r,Qt),mt(s,at),mt(o,as),Ne.rawshape_intersectsShape(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s.__wbg_ptr,o.__wbg_ptr)!==0}contactShape(e,t,r,s,o,a){mt(e,at),mt(t,as),mt(r,Qt),mt(s,at),mt(o,as);const l=Ne.rawshape_contactShape(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s.__wbg_ptr,o.__wbg_ptr,a);return l===0?void 0:rL.__wrap(l)}containsPoint(e,t,r){return mt(e,at),mt(t,as),mt(r,at),Ne.rawshape_containsPoint(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr)!==0}projectPoint(e,t,r,s){mt(e,at),mt(t,as),mt(r,at);const o=Ne.rawshape_projectPoint(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s);return iL.__wrap(o)}intersectsRay(e,t,r,s,o){return mt(e,at),mt(t,as),mt(r,at),mt(s,at),Ne.rawshape_intersectsRay(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s.__wbg_ptr,o)!==0}castRay(e,t,r,s,o,a){return mt(e,at),mt(t,as),mt(r,at),mt(s,at),Ne.rawshape_castRay(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s.__wbg_ptr,o,a)}castRayAndGetNormal(e,t,r,s,o,a){mt(e,at),mt(t,as),mt(r,at),mt(s,at);const l=Ne.rawshape_castRayAndGetNormal(this.__wbg_ptr,e.__wbg_ptr,t.__wbg_ptr,r.__wbg_ptr,s.__wbg_ptr,o,a);return l===0?void 0:nL.__wrap(l)}}class rL{static __wrap(e){e>>>=0;const t=Object.create(rL.prototype);return t.__wbg_ptr=e,t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,e}free(){const e=this.__destroy_into_raw();Ne.__wbg_rawshapecontact_free(e)}distance(){return Ne.rawkinematiccharactercontroller_maxSlopeClimbAngle(this.__wbg_ptr)}point1(){const e=Ne.rawpointprojection_point(this.__wbg_ptr);return at.__wrap(e)}point2(){const e=Ne.rawraycolliderintersection_normal(this.__wbg_ptr);return at.__wrap(e)}normal1(){const e=Ne.rawshapecollidertoi_witness2(this.__wbg_ptr);return at.__wrap(e)}normal2(){const e=Ne.rawcharactercollision_translationDeltaApplied(this.__wbg_ptr);return at.__wrap(e)}}class sL{static __wrap(e){e>>>=0;const t=Object.create(sL.prototype);return t.__wbg_ptr=e,t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,e}free(){const e=this.__destroy_into_raw();Ne.__wbg_rawshapetoi_free(e)}toi(){return Ne.rawrotation_x(this.__wbg_ptr)}witness1(){const e=Ne.rawshapetoi_witness1(this.__wbg_ptr);return at.__wrap(e)}witness2(){const e=Ne.rawcontactforceevent_total_force(this.__wbg_ptr);return at.__wrap(e)}normal1(){const e=Ne.rawshapetoi_normal1(this.__wbg_ptr);return at.__wrap(e)}normal2(){const e=Ne.rawshapetoi_normal2(this.__wbg_ptr);return at.__wrap(e)}}class at{static __wrap(e){e>>>=0;const t=Object.create(at.prototype);return t.__wbg_ptr=e,t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,e}free(){const e=this.__destroy_into_raw();Ne.__wbg_rawvector_free(e)}static zero(){const e=Ne.rawvector_zero();return at.__wrap(e)}constructor(e,t,r){const s=Ne.rawvector_new(e,t,r);return this.__wbg_ptr=s>>>0,this}get x(){return Ne.rawrotation_x(this.__wbg_ptr)}set x(e){Ne.rawvector_set_x(this.__wbg_ptr,e)}get y(){return Ne.rawintegrationparameters_dt(this.__wbg_ptr)}set y(e){Ne.rawintegrationparameters_set_dt(this.__wbg_ptr,e)}get z(){return Ne.rawraycolliderintersection_toi(this.__wbg_ptr)}set z(e){Ne.rawvector_set_z(this.__wbg_ptr,e)}xyz(){const e=Ne.rawvector_xyz(this.__wbg_ptr);return at.__wrap(e)}yxz(){const e=Ne.rawvector_yxz(this.__wbg_ptr);return at.__wrap(e)}zxy(){const e=Ne.rawvector_zxy(this.__wbg_ptr);return at.__wrap(e)}xzy(){const e=Ne.rawvector_xzy(this.__wbg_ptr);return at.__wrap(e)}yzx(){const e=Ne.rawvector_yzx(this.__wbg_ptr);return at.__wrap(e)}zyx(){const e=Ne.rawvector_zyx(this.__wbg_ptr);return at.__wrap(e)}}class S_e{constructor(e,t,r){this.x=e,this.y=t,this.z=r}}class ke{static new(e,t,r){return new S_e(e,t,r)}static intoRaw(e){return new at(e.x,e.y,e.z)}static zeros(){return ke.new(0,0,0)}static fromRaw(e){if(!e)return null;let t=ke.new(e.x,e.y,e.z);return e.free(),t}static copy(e,t){e.x=t.x,e.y=t.y,e.z=t.z}}class M9{constructor(e,t,r,s){this.x=e,this.y=t,this.z=r,this.w=s}}class Xi{static identity(){return new M9(0,0,0,1)}static fromRaw(e){if(!e)return null;let t=new M9(e.x,e.y,e.z,e.w);return e.free(),t}static intoRaw(e){return new as(e.x,e.y,e.z,e.w)}static copy(e,t){e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w}}class C_e{constructor(e){this.elements=e}get m11(){return this.elements[0]}get m12(){return this.elements[1]}get m21(){return this.m12}get m13(){return this.elements[2]}get m31(){return this.m13}get m22(){return this.elements[3]}get m23(){return this.elements[4]}get m32(){return this.m23}get m33(){return this.elements[5]}}class T9{static fromRaw(e){const t=new C_e(e.elements());return e.free(),t}}var $b,Ds,I9,R9,er,FO,zn,P9,EE,UO,B9,ME,j0;(function(n){n[n.Dynamic=0]="Dynamic",n[n.Fixed=1]="Fixed",n[n.KinematicPositionBased=2]="KinematicPositionBased",n[n.KinematicVelocityBased=3]="KinematicVelocityBased"})($b||($b={}));class k9{constructor(e,t,r){this.rawSet=e,this.colliderSet=t,this.handle=r}finalizeDeserialization(e){this.colliderSet=e}isValid(){return this.rawSet.contains(this.handle)}lockTranslations(e,t){return this.rawSet.rbLockTranslations(this.handle,e,t)}lockRotations(e,t){return this.rawSet.rbLockRotations(this.handle,e,t)}setEnabledTranslations(e,t,r,s){return this.rawSet.rbSetEnabledTranslations(this.handle,e,t,r,s)}restrictTranslations(e,t,r,s){this.setEnabledTranslations(e,t,r,s)}setEnabledRotations(e,t,r,s){return this.rawSet.rbSetEnabledRotations(this.handle,e,t,r,s)}restrictRotations(e,t,r,s){this.setEnabledRotations(e,t,r,s)}dominanceGroup(){return this.rawSet.rbDominanceGroup(this.handle)}setDominanceGroup(e){this.rawSet.rbSetDominanceGroup(this.handle,e)}additionalSolverIterations(){return this.rawSet.rbAdditionalSolverIterations(this.handle)}setAdditionalSolverIterations(e){this.rawSet.rbSetAdditionalSolverIterations(this.handle,e)}enableCcd(e){this.rawSet.rbEnableCcd(this.handle,e)}translation(){let e=this.rawSet.rbTranslation(this.handle);return ke.fromRaw(e)}rotation(){let e=this.rawSet.rbRotation(this.handle);return Xi.fromRaw(e)}nextTranslation(){let e=this.rawSet.rbNextTranslation(this.handle);return ke.fromRaw(e)}nextRotation(){let e=this.rawSet.rbNextRotation(this.handle);return Xi.fromRaw(e)}setTranslation(e,t){this.rawSet.rbSetTranslation(this.handle,e.x,e.y,e.z,t)}setLinvel(e,t){let r=ke.intoRaw(e);this.rawSet.rbSetLinvel(this.handle,r,t),r.free()}gravityScale(){return this.rawSet.rbGravityScale(this.handle)}setGravityScale(e,t){this.rawSet.rbSetGravityScale(this.handle,e,t)}setRotation(e,t){this.rawSet.rbSetRotation(this.handle,e.x,e.y,e.z,e.w,t)}setAngvel(e,t){let r=ke.intoRaw(e);this.rawSet.rbSetAngvel(this.handle,r,t),r.free()}setNextKinematicTranslation(e){this.rawSet.rbSetNextKinematicTranslation(this.handle,e.x,e.y,e.z)}setNextKinematicRotation(e){this.rawSet.rbSetNextKinematicRotation(this.handle,e.x,e.y,e.z,e.w)}linvel(){return ke.fromRaw(this.rawSet.rbLinvel(this.handle))}angvel(){return ke.fromRaw(this.rawSet.rbAngvel(this.handle))}mass(){return this.rawSet.rbMass(this.handle)}effectiveInvMass(){return ke.fromRaw(this.rawSet.rbEffectiveInvMass(this.handle))}invMass(){return this.rawSet.rbInvMass(this.handle)}localCom(){return ke.fromRaw(this.rawSet.rbLocalCom(this.handle))}worldCom(){return ke.fromRaw(this.rawSet.rbWorldCom(this.handle))}invPrincipalInertiaSqrt(){return ke.fromRaw(this.rawSet.rbInvPrincipalInertiaSqrt(this.handle))}principalInertia(){return ke.fromRaw(this.rawSet.rbPrincipalInertia(this.handle))}principalInertiaLocalFrame(){return Xi.fromRaw(this.rawSet.rbPrincipalInertiaLocalFrame(this.handle))}effectiveWorldInvInertiaSqrt(){return T9.fromRaw(this.rawSet.rbEffectiveWorldInvInertiaSqrt(this.handle))}effectiveAngularInertia(){return T9.fromRaw(this.rawSet.rbEffectiveAngularInertia(this.handle))}sleep(){this.rawSet.rbSleep(this.handle)}wakeUp(){this.rawSet.rbWakeUp(this.handle)}isCcdEnabled(){return this.rawSet.rbIsCcdEnabled(this.handle)}numColliders(){return this.rawSet.rbNumColliders(this.handle)}collider(e){return this.colliderSet.get(this.rawSet.rbCollider(this.handle,e))}setEnabled(e){this.rawSet.rbSetEnabled(this.handle,e)}isEnabled(){return this.rawSet.rbIsEnabled(this.handle)}bodyType(){return this.rawSet.rbBodyType(this.handle)}setBodyType(e,t){return this.rawSet.rbSetBodyType(this.handle,e,t)}isSleeping(){return this.rawSet.rbIsSleeping(this.handle)}isMoving(){return this.rawSet.rbIsMoving(this.handle)}isFixed(){return this.rawSet.rbIsFixed(this.handle)}isKinematic(){return this.rawSet.rbIsKinematic(this.handle)}isDynamic(){return this.rawSet.rbIsDynamic(this.handle)}linearDamping(){return this.rawSet.rbLinearDamping(this.handle)}angularDamping(){return this.rawSet.rbAngularDamping(this.handle)}setLinearDamping(e){this.rawSet.rbSetLinearDamping(this.handle,e)}recomputeMassPropertiesFromColliders(){this.rawSet.rbRecomputeMassPropertiesFromColliders(this.handle,this.colliderSet.raw)}setAdditionalMass(e,t){this.rawSet.rbSetAdditionalMass(this.handle,e,t)}setAdditionalMassProperties(e,t,r,s,o){let a=ke.intoRaw(t),l=ke.intoRaw(r),c=Xi.intoRaw(s);this.rawSet.rbSetAdditionalMassProperties(this.handle,e,a,l,c,o),a.free(),l.free(),c.free()}setAngularDamping(e){this.rawSet.rbSetAngularDamping(this.handle,e)}resetForces(e){this.rawSet.rbResetForces(this.handle,e)}resetTorques(e){this.rawSet.rbResetTorques(this.handle,e)}addForce(e,t){const r=ke.intoRaw(e);this.rawSet.rbAddForce(this.handle,r,t),r.free()}applyImpulse(e,t){const r=ke.intoRaw(e);this.rawSet.rbApplyImpulse(this.handle,r,t),r.free()}addTorque(e,t){const r=ke.intoRaw(e);this.rawSet.rbAddTorque(this.handle,r,t),r.free()}applyTorqueImpulse(e,t){const r=ke.intoRaw(e);this.rawSet.rbApplyTorqueImpulse(this.handle,r,t),r.free()}addForceAtPoint(e,t,r){const s=ke.intoRaw(e),o=ke.intoRaw(t);this.rawSet.rbAddForceAtPoint(this.handle,s,o,r),s.free(),o.free()}applyImpulseAtPoint(e,t,r){const s=ke.intoRaw(e),o=ke.intoRaw(t);this.rawSet.rbApplyImpulseAtPoint(this.handle,s,o,r),s.free(),o.free()}}(function(n){n[n.Revolute=0]="Revolute",n[n.Fixed=1]="Fixed",n[n.Prismatic=2]="Prismatic",n[n.Rope=3]="Rope",n[n.Spring=4]="Spring",n[n.Spherical=5]="Spherical",n[n.Generic=6]="Generic"})(Ds||(Ds={})),function(n){n[n.AccelerationBased=0]="AccelerationBased",n[n.ForceBased=1]="ForceBased"}(I9||(I9={})),function(n){n[n.X=1]="X",n[n.Y=2]="Y",n[n.Z=4]="Z",n[n.AngX=8]="AngX",n[n.AngY=16]="AngY",n[n.AngZ=32]="AngZ"}(R9||(R9={}));class jh{constructor(){}static fixed(e,t,r,s){let o=new jh;return o.anchor1=e,o.anchor2=r,o.frame1=t,o.frame2=s,o.jointType=Ds.Fixed,o}static spring(e,t,r,s,o){let a=new jh;return a.anchor1=s,a.anchor2=o,a.length=e,a.stiffness=t,a.damping=r,a.jointType=Ds.Spring,a}static rope(e,t,r){let s=new jh;return s.anchor1=t,s.anchor2=r,s.length=e,s.jointType=Ds.Rope,s}static generic(e,t,r,s){let o=new jh;return o.anchor1=e,o.anchor2=t,o.axis=r,o.axesMask=s,o.jointType=Ds.Generic,o}static spherical(e,t){let r=new jh;return r.anchor1=e,r.anchor2=t,r.jointType=Ds.Spherical,r}static prismatic(e,t,r){let s=new jh;return s.anchor1=e,s.anchor2=t,s.axis=r,s.jointType=Ds.Prismatic,s}static revolute(e,t,r){let s=new jh;return s.anchor1=e,s.anchor2=t,s.axis=r,s.jointType=Ds.Revolute,s}intoRaw(){let e,t,r=ke.intoRaw(this.anchor1),s=ke.intoRaw(this.anchor2),o=!1,a=0,l=0;switch(this.jointType){case Ds.Fixed:let c=Xi.intoRaw(this.frame1),h=Xi.intoRaw(this.frame2);t=Os.fixed(r,c,s,h),c.free(),h.free();break;case Ds.Spring:t=Os.spring(this.length,this.stiffness,this.damping,r,s);break;case Ds.Rope:t=Os.rope(this.length,r,s);break;case Ds.Prismatic:e=ke.intoRaw(this.axis),this.limitsEnabled&&(o=!0,a=this.limits[0],l=this.limits[1]),t=Os.prismatic(r,s,e,o,a,l),e.free();break;case Ds.Generic:e=ke.intoRaw(this.axis);let u=this.axesMask;t=Os.generic(r,s,e,u);break;case Ds.Spherical:t=Os.spherical(r,s);break;case Ds.Revolute:e=ke.intoRaw(this.axis),t=Os.revolute(r,s,e),e.free()}return r.free(),s.free(),t}}(function(n){n[n.Average=0]="Average",n[n.Min=1]="Min",n[n.Multiply=2]="Multiply",n[n.Max=3]="Max"})(er||(er={}));class a_{constructor(e,t,r,s,o){this.distance=e,this.point1=t,this.point2=r,this.normal1=s,this.normal2=o}static fromRaw(e){if(!e)return null;const t=new a_(e.distance(),ke.fromRaw(e.point1()),ke.fromRaw(e.point2()),ke.fromRaw(e.normal1()),ke.fromRaw(e.normal2()));return e.free(),t}}(function(n){n[n.Vertex=0]="Vertex",n[n.Edge=1]="Edge",n[n.Face=2]="Face",n[n.Unknown=3]="Unknown"})(FO||(FO={}));class YE{constructor(e,t){this.point=e,this.isInside=t}static fromRaw(e){if(!e)return null;const t=new YE(ke.fromRaw(e.point()),e.isInside());return e.free(),t}}class E_e{constructor(e,t){this.origin=e,this.dir=t}pointAt(e){return{x:this.origin.x+this.dir.x*e,y:this.origin.y+this.dir.y*e,z:this.origin.z+this.dir.z*e}}}class JE{constructor(e,t,r,s){this.featureType=FO.Unknown,this.featureId=void 0,this.toi=e,this.normal=t,s!==void 0&&(this.featureId=s),r!==void 0&&(this.featureType=r)}static fromRaw(e){if(!e)return null;const t=new JE(e.toi(),ke.fromRaw(e.normal()),e.featureType(),e.featureId());return e.free(),t}}class l_{constructor(e,t,r,s,o){this.toi=e,this.witness1=t,this.witness2=r,this.normal1=s,this.normal2=o}static fromRaw(e,t){if(!t)return null;const r=new l_(t.toi(),ke.fromRaw(t.witness1()),ke.fromRaw(t.witness2()),ke.fromRaw(t.normal1()),ke.fromRaw(t.normal2()));return t.free(),r}}class oL extends l_{constructor(e,t,r,s,o,a){super(t,r,s,o,a),this.collider=e}static fromRaw(e,t){if(!t)return null;const r=new oL(e.get(t.colliderHandle()),t.toi(),ke.fromRaw(t.witness1()),ke.fromRaw(t.witness2()),ke.fromRaw(t.normal1()),ke.fromRaw(t.normal2()));return t.free(),r}}class Br{static fromRaw(e,t){const r=e.coShapeType(t);let s,o,a,l,c,h,u;switch(r){case ss.Ball:return new NO(e.coRadius(t));case ss.Cuboid:return s=e.coHalfExtents(t),new D9(s.x,s.y,s.z);case ss.RoundCuboid:return s=e.coHalfExtents(t),o=e.coRoundRadius(t),new O9(s.x,s.y,s.z,o);case ss.Capsule:return c=e.coHalfHeight(t),h=e.coRadius(t),new L9(c,h);case ss.Segment:return a=e.coVertices(t),new F9(ke.new(a[0],a[1],a[2]),ke.new(a[3],a[4],a[5]));case ss.Polyline:return a=e.coVertices(t),l=e.coIndices(t),new z9(a,l);case ss.Triangle:return a=e.coVertices(t),new U9(ke.new(a[0],a[1],a[2]),ke.new(a[3],a[4],a[5]),ke.new(a[6],a[7],a[8]));case ss.RoundTriangle:return a=e.coVertices(t),o=e.coRoundRadius(t),new N9(ke.new(a[0],a[1],a[2]),ke.new(a[3],a[4],a[5]),ke.new(a[6],a[7],a[8]),o);case ss.HalfSpace:return u=ke.fromRaw(e.coHalfspaceNormal(t)),new M_e(u);case ss.TriMesh:return a=e.coVertices(t),l=e.coIndices(t),new j9(a,l);case ss.HeightField:const p=e.coHeightfieldScale(t),m=e.coHeightfieldHeights(t),f=e.coHeightfieldNRows(t),g=e.coHeightfieldNCols(t);return new G9(f,g,m,p);case ss.ConvexPolyhedron:return a=e.coVertices(t),l=e.coIndices(t),new zO(a,l);case ss.RoundConvexPolyhedron:return a=e.coVertices(t),l=e.coIndices(t),o=e.coRoundRadius(t),new jO(a,l,o);case ss.Cylinder:return c=e.coHalfHeight(t),h=e.coRadius(t),new V9(c,h);case ss.RoundCylinder:return c=e.coHalfHeight(t),h=e.coRadius(t),o=e.coRoundRadius(t),new Q9(c,h,o);case ss.Cone:return c=e.coHalfHeight(t),h=e.coRadius(t),new H9(c,h);case ss.RoundCone:return c=e.coHalfHeight(t),h=e.coRadius(t),o=e.coRoundRadius(t),new W9(c,h,o);default:throw new Error("unknown shape type: "+r)}}castShape(e,t,r,s,o,a,l,c,h){let u=ke.intoRaw(e),p=Xi.intoRaw(t),m=ke.intoRaw(r),f=ke.intoRaw(o),g=Xi.intoRaw(a),v=ke.intoRaw(l),y=this.intoRaw(),A=s.intoRaw(),_=l_.fromRaw(null,y.castShape(u,p,m,A,f,g,v,c,h));return u.free(),p.free(),m.free(),f.free(),g.free(),v.free(),y.free(),A.free(),_}intersectsShape(e,t,r,s,o){let a=ke.intoRaw(e),l=Xi.intoRaw(t),c=ke.intoRaw(s),h=Xi.intoRaw(o),u=this.intoRaw(),p=r.intoRaw(),m=u.intersectsShape(a,l,p,c,h);return a.free(),l.free(),c.free(),h.free(),u.free(),p.free(),m}contactShape(e,t,r,s,o,a){let l=ke.intoRaw(e),c=Xi.intoRaw(t),h=ke.intoRaw(s),u=Xi.intoRaw(o),p=this.intoRaw(),m=r.intoRaw(),f=a_.fromRaw(p.contactShape(l,c,m,h,u,a));return l.free(),c.free(),h.free(),u.free(),p.free(),m.free(),f}containsPoint(e,t,r){let s=ke.intoRaw(e),o=Xi.intoRaw(t),a=ke.intoRaw(r),l=this.intoRaw(),c=l.containsPoint(s,o,a);return s.free(),o.free(),a.free(),l.free(),c}projectPoint(e,t,r,s){let o=ke.intoRaw(e),a=Xi.intoRaw(t),l=ke.intoRaw(r),c=this.intoRaw(),h=YE.fromRaw(c.projectPoint(o,a,l,s));return o.free(),a.free(),l.free(),c.free(),h}intersectsRay(e,t,r,s){let o=ke.intoRaw(t),a=Xi.intoRaw(r),l=ke.intoRaw(e.origin),c=ke.intoRaw(e.dir),h=this.intoRaw(),u=h.intersectsRay(o,a,l,c,s);return o.free(),a.free(),l.free(),c.free(),h.free(),u}castRay(e,t,r,s,o){let a=ke.intoRaw(t),l=Xi.intoRaw(r),c=ke.intoRaw(e.origin),h=ke.intoRaw(e.dir),u=this.intoRaw(),p=u.castRay(a,l,c,h,s,o);return a.free(),l.free(),c.free(),h.free(),u.free(),p}castRayAndGetNormal(e,t,r,s,o){let a=ke.intoRaw(t),l=Xi.intoRaw(r),c=ke.intoRaw(e.origin),h=ke.intoRaw(e.dir),u=this.intoRaw(),p=JE.fromRaw(u.castRayAndGetNormal(a,l,c,h,s,o));return a.free(),l.free(),c.free(),h.free(),u.free(),p}}(function(n){n[n.Ball=0]="Ball",n[n.Cuboid=1]="Cuboid",n[n.Capsule=2]="Capsule",n[n.Segment=3]="Segment",n[n.Polyline=4]="Polyline",n[n.Triangle=5]="Triangle",n[n.TriMesh=6]="TriMesh",n[n.HeightField=7]="HeightField",n[n.ConvexPolyhedron=9]="ConvexPolyhedron",n[n.Cylinder=10]="Cylinder",n[n.Cone=11]="Cone",n[n.RoundCuboid=12]="RoundCuboid",n[n.RoundTriangle=13]="RoundTriangle",n[n.RoundCylinder=14]="RoundCylinder",n[n.RoundCone=15]="RoundCone",n[n.RoundConvexPolyhedron=16]="RoundConvexPolyhedron",n[n.HalfSpace=17]="HalfSpace"})(zn||(zn={}));class NO extends Br{constructor(e){super(),this.type=zn.Ball,this.radius=e}intoRaw(){return Qt.ball(this.radius)}}class M_e extends Br{constructor(e){super(),this.type=zn.HalfSpace,this.normal=e}intoRaw(){let e=ke.intoRaw(this.normal),t=Qt.halfspace(e);return e.free(),t}}class D9 extends Br{constructor(e,t,r){super(),this.type=zn.Cuboid,this.halfExtents=ke.new(e,t,r)}intoRaw(){return Qt.cuboid(this.halfExtents.x,this.halfExtents.y,this.halfExtents.z)}}class O9 extends Br{constructor(e,t,r,s){super(),this.type=zn.RoundCuboid,this.halfExtents=ke.new(e,t,r),this.borderRadius=s}intoRaw(){return Qt.roundCuboid(this.halfExtents.x,this.halfExtents.y,this.halfExtents.z,this.borderRadius)}}class L9 extends Br{constructor(e,t){super(),this.type=zn.Capsule,this.halfHeight=e,this.radius=t}intoRaw(){return Qt.capsule(this.halfHeight,this.radius)}}class F9 extends Br{constructor(e,t){super(),this.type=zn.Segment,this.a=e,this.b=t}intoRaw(){let e=ke.intoRaw(this.a),t=ke.intoRaw(this.b),r=Qt.segment(e,t);return e.free(),t.free(),r}}class U9 extends Br{constructor(e,t,r){super(),this.type=zn.Triangle,this.a=e,this.b=t,this.c=r}intoRaw(){let e=ke.intoRaw(this.a),t=ke.intoRaw(this.b),r=ke.intoRaw(this.c),s=Qt.triangle(e,t,r);return e.free(),t.free(),r.free(),s}}class N9 extends Br{constructor(e,t,r,s){super(),this.type=zn.RoundTriangle,this.a=e,this.b=t,this.c=r,this.borderRadius=s}intoRaw(){let e=ke.intoRaw(this.a),t=ke.intoRaw(this.b),r=ke.intoRaw(this.c),s=Qt.roundTriangle(e,t,r,this.borderRadius);return e.free(),t.free(),r.free(),s}}class z9 extends Br{constructor(e,t){super(),this.type=zn.Polyline,this.vertices=e,this.indices=t??new Uint32Array(0)}intoRaw(){return Qt.polyline(this.vertices,this.indices)}}class j9 extends Br{constructor(e,t){super(),this.type=zn.TriMesh,this.vertices=e,this.indices=t}intoRaw(){return Qt.trimesh(this.vertices,this.indices)}}class zO extends Br{constructor(e,t){super(),this.type=zn.ConvexPolyhedron,this.vertices=e,this.indices=t}intoRaw(){return this.indices?Qt.convexMesh(this.vertices,this.indices):Qt.convexHull(this.vertices)}}class jO extends Br{constructor(e,t,r){super(),this.type=zn.RoundConvexPolyhedron,this.vertices=e,this.indices=t,this.borderRadius=r}intoRaw(){return this.indices?Qt.roundConvexMesh(this.vertices,this.indices,this.borderRadius):Qt.roundConvexHull(this.vertices,this.borderRadius)}}class G9 extends Br{constructor(e,t,r,s){super(),this.type=zn.HeightField,this.nrows=e,this.ncols=t,this.heights=r,this.scale=s}intoRaw(){let e=ke.intoRaw(this.scale),t=Qt.heightfield(this.nrows,this.ncols,this.heights,e);return e.free(),t}}class V9 extends Br{constructor(e,t){super(),this.type=zn.Cylinder,this.halfHeight=e,this.radius=t}intoRaw(){return Qt.cylinder(this.halfHeight,this.radius)}}class Q9 extends Br{constructor(e,t,r){super(),this.type=zn.RoundCylinder,this.borderRadius=r,this.halfHeight=e,this.radius=t}intoRaw(){return Qt.roundCylinder(this.halfHeight,this.radius,this.borderRadius)}}class H9 extends Br{constructor(e,t){super(),this.type=zn.Cone,this.halfHeight=e,this.radius=t}intoRaw(){return Qt.cone(this.halfHeight,this.radius)}}class W9 extends Br{constructor(e,t,r){super(),this.type=zn.RoundCone,this.halfHeight=e,this.radius=t,this.borderRadius=r}intoRaw(){return Qt.roundCone(this.halfHeight,this.radius,this.borderRadius)}}(function(n){n[n.EXCLUDE_FIXED=1]="EXCLUDE_FIXED",n[n.EXCLUDE_KINEMATIC=2]="EXCLUDE_KINEMATIC",n[n.EXCLUDE_DYNAMIC=4]="EXCLUDE_DYNAMIC",n[n.EXCLUDE_SENSORS=8]="EXCLUDE_SENSORS",n[n.EXCLUDE_SOLIDS=16]="EXCLUDE_SOLIDS",n[n.ONLY_DYNAMIC=3]="ONLY_DYNAMIC",n[n.ONLY_KINEMATIC=5]="ONLY_KINEMATIC",n[n.ONLY_FIXED=6]="ONLY_FIXED"})(P9||(P9={})),function(n){n[n.NONE=0]="NONE",n[n.COLLISION_EVENTS=1]="COLLISION_EVENTS",n[n.CONTACT_FORCE_EVENTS=2]="CONTACT_FORCE_EVENTS"}(EE||(EE={}));class T_e{free(){this.raw&&this.raw.free(),this.raw=void 0}collider1(){return this.raw.collider1()}collider2(){return this.raw.collider2()}totalForce(){return ke.fromRaw(this.raw.total_force())}totalForceMagnitude(){return this.raw.total_force_magnitude()}maxForceDirection(){return ke.fromRaw(this.raw.max_force_direction())}maxForceMagnitude(){return this.raw.max_force_magnitude()}}class I_e{constructor(e,t){this.raw=t||new w_e(e)}free(){this.raw&&this.raw.free(),this.raw=void 0}drainCollisionEvents(e){this.raw.drainCollisionEvents(e)}drainContactForceEvents(e){let t=new T_e;this.raw.drainContactForceEvents(r=>{t.raw=r,e(t),t.free()})}clear(){this.raw.clear()}}(function(n){n[n.NONE=0]="NONE",n[n.FILTER_CONTACT_PAIRS=1]="FILTER_CONTACT_PAIRS",n[n.FILTER_INTERSECTION_PAIRS=2]="FILTER_INTERSECTION_PAIRS"})(UO||(UO={})),function(n){n[n.EMPTY=0]="EMPTY",n[n.COMPUTE_IMPULSE=1]="COMPUTE_IMPULSE"}(B9||(B9={})),function(n){n[n.DYNAMIC_DYNAMIC=1]="DYNAMIC_DYNAMIC",n[n.DYNAMIC_KINEMATIC=12]="DYNAMIC_KINEMATIC",n[n.DYNAMIC_FIXED=2]="DYNAMIC_FIXED",n[n.KINEMATIC_KINEMATIC=52224]="KINEMATIC_KINEMATIC",n[n.KINEMATIC_FIXED=8704]="KINEMATIC_FIXED",n[n.FIXED_FIXED=32]="FIXED_FIXED",n[n.DEFAULT=15]="DEFAULT",n[n.ALL=60943]="ALL"}(ME||(ME={}));class X9{constructor(e,t,r,s){this.colliderSet=e,this.handle=t,this._parent=r,this._shape=s}finalizeDeserialization(e){this.handle!=null&&(this._parent=e.get(this.colliderSet.raw.coParent(this.handle)))}ensureShapeIsCached(){this._shape||(this._shape=Br.fromRaw(this.colliderSet.raw,this.handle))}get shape(){return this.ensureShapeIsCached(),this._shape}isValid(){return this.colliderSet.raw.contains(this.handle)}translation(){return ke.fromRaw(this.colliderSet.raw.coTranslation(this.handle))}rotation(){return Xi.fromRaw(this.colliderSet.raw.coRotation(this.handle))}isSensor(){return this.colliderSet.raw.coIsSensor(this.handle)}setSensor(e){this.colliderSet.raw.coSetSensor(this.handle,e)}setShape(e){let t=e.intoRaw();this.colliderSet.raw.coSetShape(this.handle,t),t.free(),this._shape=e}setEnabled(e){this.colliderSet.raw.coSetEnabled(this.handle,e)}isEnabled(){return this.colliderSet.raw.coIsEnabled(this.handle)}setRestitution(e){this.colliderSet.raw.coSetRestitution(this.handle,e)}setFriction(e){this.colliderSet.raw.coSetFriction(this.handle,e)}frictionCombineRule(){return this.colliderSet.raw.coFrictionCombineRule(this.handle)}setFrictionCombineRule(e){this.colliderSet.raw.coSetFrictionCombineRule(this.handle,e)}restitutionCombineRule(){return this.colliderSet.raw.coRestitutionCombineRule(this.handle)}setRestitutionCombineRule(e){this.colliderSet.raw.coSetRestitutionCombineRule(this.handle,e)}setCollisionGroups(e){this.colliderSet.raw.coSetCollisionGroups(this.handle,e)}setSolverGroups(e){this.colliderSet.raw.coSetSolverGroups(this.handle,e)}activeHooks(){return this.colliderSet.raw.coActiveHooks(this.handle)}setActiveHooks(e){this.colliderSet.raw.coSetActiveHooks(this.handle,e)}activeEvents(){return this.colliderSet.raw.coActiveEvents(this.handle)}setActiveEvents(e){this.colliderSet.raw.coSetActiveEvents(this.handle,e)}activeCollisionTypes(){return this.colliderSet.raw.coActiveCollisionTypes(this.handle)}setContactForceEventThreshold(e){return this.colliderSet.raw.coSetContactForceEventThreshold(this.handle,e)}contactForceEventThreshold(){return this.colliderSet.raw.coContactForceEventThreshold(this.handle)}setActiveCollisionTypes(e){this.colliderSet.raw.coSetActiveCollisionTypes(this.handle,e)}setDensity(e){this.colliderSet.raw.coSetDensity(this.handle,e)}setMass(e){this.colliderSet.raw.coSetMass(this.handle,e)}setMassProperties(e,t,r,s){let o=ke.intoRaw(t),a=ke.intoRaw(r),l=Xi.intoRaw(s);this.colliderSet.raw.coSetMassProperties(this.handle,e,o,a,l),o.free(),a.free(),l.free()}setTranslation(e){this.colliderSet.raw.coSetTranslation(this.handle,e.x,e.y,e.z)}setTranslationWrtParent(e){this.colliderSet.raw.coSetTranslationWrtParent(this.handle,e.x,e.y,e.z)}setRotation(e){this.colliderSet.raw.coSetRotation(this.handle,e.x,e.y,e.z,e.w)}setRotationWrtParent(e){this.colliderSet.raw.coSetRotationWrtParent(this.handle,e.x,e.y,e.z,e.w)}shapeType(){return this.colliderSet.raw.coShapeType(this.handle)}halfExtents(){return ke.fromRaw(this.colliderSet.raw.coHalfExtents(this.handle))}setHalfExtents(e){const t=ke.intoRaw(e);this.colliderSet.raw.coSetHalfExtents(this.handle,t)}radius(){return this.colliderSet.raw.coRadius(this.handle)}setRadius(e){this.colliderSet.raw.coSetRadius(this.handle,e)}roundRadius(){return this.colliderSet.raw.coRoundRadius(this.handle)}setRoundRadius(e){this.colliderSet.raw.coSetRoundRadius(this.handle,e)}halfHeight(){return this.colliderSet.raw.coHalfHeight(this.handle)}setHalfHeight(e){this.colliderSet.raw.coSetHalfHeight(this.handle,e)}vertices(){return this.colliderSet.raw.coVertices(this.handle)}indices(){return this.colliderSet.raw.coIndices(this.handle)}heightfieldHeights(){return this.colliderSet.raw.coHeightfieldHeights(this.handle)}heightfieldScale(){let e=this.colliderSet.raw.coHeightfieldScale(this.handle);return ke.fromRaw(e)}heightfieldNRows(){return this.colliderSet.raw.coHeightfieldNRows(this.handle)}heightfieldNCols(){return this.colliderSet.raw.coHeightfieldNCols(this.handle)}parent(){return this._parent}friction(){return this.colliderSet.raw.coFriction(this.handle)}restitution(){return this.colliderSet.raw.coRestitution(this.handle)}density(){return this.colliderSet.raw.coDensity(this.handle)}mass(){return this.colliderSet.raw.coMass(this.handle)}volume(){return this.colliderSet.raw.coVolume(this.handle)}collisionGroups(){return this.colliderSet.raw.coCollisionGroups(this.handle)}solverGroups(){return this.colliderSet.raw.coSolverGroups(this.handle)}containsPoint(e){let t=ke.intoRaw(e),r=this.colliderSet.raw.coContainsPoint(this.handle,t);return t.free(),r}projectPoint(e,t){let r=ke.intoRaw(e),s=YE.fromRaw(this.colliderSet.raw.coProjectPoint(this.handle,r,t));return r.free(),s}intersectsRay(e,t){let r=ke.intoRaw(e.origin),s=ke.intoRaw(e.dir),o=this.colliderSet.raw.coIntersectsRay(this.handle,r,s,t);return r.free(),s.free(),o}castShape(e,t,r,s,o,a,l){let c=ke.intoRaw(e),h=ke.intoRaw(r),u=Xi.intoRaw(s),p=ke.intoRaw(o),m=t.intoRaw(),f=l_.fromRaw(this.colliderSet,this.colliderSet.raw.coCastShape(this.handle,c,m,h,u,p,a,l));return c.free(),h.free(),u.free(),p.free(),m.free(),f}castCollider(e,t,r,s,o){let a=ke.intoRaw(e),l=ke.intoRaw(r),c=oL.fromRaw(this.colliderSet,this.colliderSet.raw.coCastCollider(this.handle,a,t.handle,l,s,o));return a.free(),l.free(),c}intersectsShape(e,t,r){let s=ke.intoRaw(t),o=Xi.intoRaw(r),a=e.intoRaw(),l=this.colliderSet.raw.coIntersectsShape(this.handle,a,s,o);return s.free(),o.free(),a.free(),l}contactShape(e,t,r,s){let o=ke.intoRaw(t),a=Xi.intoRaw(r),l=e.intoRaw(),c=a_.fromRaw(this.colliderSet.raw.coContactShape(this.handle,l,o,a,s));return o.free(),a.free(),l.free(),c}contactCollider(e,t){return a_.fromRaw(this.colliderSet.raw.coContactCollider(this.handle,e.handle,t))}castRay(e,t,r){let s=ke.intoRaw(e.origin),o=ke.intoRaw(e.dir),a=this.colliderSet.raw.coCastRay(this.handle,s,o,t,r);return s.free(),o.free(),a}castRayAndGetNormal(e,t,r){let s=ke.intoRaw(e.origin),o=ke.intoRaw(e.dir),a=JE.fromRaw(this.colliderSet.raw.coCastRayAndGetNormal(this.handle,s,o,t,r));return s.free(),o.free(),a}}(function(n){n[n.Density=0]="Density",n[n.Mass=1]="Mass",n[n.MassProps=2]="MassProps"})(j0||(j0={}));class un{constructor(e){this.enabled=!0,this.shape=e,this.massPropsMode=j0.Density,this.density=1,this.friction=.5,this.restitution=0,this.rotation=Xi.identity(),this.translation=ke.zeros(),this.isSensor=!1,this.collisionGroups=4294967295,this.solverGroups=4294967295,this.frictionCombineRule=er.Average,this.restitutionCombineRule=er.Average,this.activeCollisionTypes=ME.DEFAULT,this.activeEvents=EE.NONE,this.activeHooks=UO.NONE,this.mass=0,this.centerOfMass=ke.zeros(),this.contactForceEventThreshold=0,this.principalAngularInertia=ke.zeros(),this.angularInertiaLocalFrame=Xi.identity()}static ball(e){const t=new NO(e);return new un(t)}static capsule(e,t){const r=new L9(e,t);return new un(r)}static segment(e,t){const r=new F9(e,t);return new un(r)}static triangle(e,t,r){const s=new U9(e,t,r);return new un(s)}static roundTriangle(e,t,r,s){const o=new N9(e,t,r,s);return new un(o)}static polyline(e,t){const r=new z9(e,t);return new un(r)}static trimesh(e,t){const r=new j9(e,t);return new un(r)}static cuboid(e,t,r){const s=new D9(e,t,r);return new un(s)}static roundCuboid(e,t,r,s){const o=new O9(e,t,r,s);return new un(o)}static heightfield(e,t,r,s){const o=new G9(e,t,r,s);return new un(o)}static cylinder(e,t){const r=new V9(e,t);return new un(r)}static roundCylinder(e,t,r){const s=new Q9(e,t,r);return new un(s)}static cone(e,t){const r=new H9(e,t);return new un(r)}static roundCone(e,t,r){const s=new W9(e,t,r);return new un(s)}static convexHull(e){const t=new zO(e,null);return new un(t)}static convexMesh(e,t){const r=new zO(e,t);return new un(r)}static roundConvexHull(e,t){const r=new jO(e,null,t);return new un(r)}static roundConvexMesh(e,t,r){const s=new jO(e,t,r);return new un(s)}setTranslation(e,t,r){if(typeof e!="number"||typeof t!="number"||typeof r!="number")throw TypeError("The translation components must be numbers.");return this.translation={x:e,y:t,z:r},this}setRotation(e){return Xi.copy(this.rotation,e),this}setSensor(e){return this.isSensor=e,this}setEnabled(e){return this.enabled=e,this}setDensity(e){return this.massPropsMode=j0.Density,this.density=e,this}setMass(e){return this.massPropsMode=j0.Mass,this.mass=e,this}setMassProperties(e,t,r,s){return this.massPropsMode=j0.MassProps,this.mass=e,ke.copy(this.centerOfMass,t),ke.copy(this.principalAngularInertia,r),Xi.copy(this.angularInertiaLocalFrame,s),this}setRestitution(e){return this.restitution=e,this}setFriction(e){return this.friction=e,this}setFrictionCombineRule(e){return this.frictionCombineRule=e,this}setRestitutionCombineRule(e){return this.restitutionCombineRule=e,this}setCollisionGroups(e){return this.collisionGroups=e,this}setSolverGroups(e){return this.solverGroups=e,this}setActiveHooks(e){return this.activeHooks=e,this}setActiveEvents(e){return this.activeEvents=e,this}setActiveCollisionTypes(e){return this.activeCollisionTypes=e,this}setContactForceEventThreshold(e){return this.contactForceEventThreshold=e,this}}for(var txe={byteLength:function(n){var e=q9(n),t=e[0],r=e[1];return 3*(t+r)/4-r},toByteArray:function(n){var e,t,r=q9(n),s=r[0],o=r[1],a=new R_e(function(h,u,p){return 3*(u+p)/4-p}(0,s,o)),l=0,c=o>0?s-4:s;for(t=0;t<c;t+=4)e=Na[n.charCodeAt(t)]<<18|Na[n.charCodeAt(t+1)]<<12|Na[n.charCodeAt(t+2)]<<6|Na[n.charCodeAt(t+3)],a[l++]=e>>16&255,a[l++]=e>>8&255,a[l++]=255&e;return o===2&&(e=Na[n.charCodeAt(t)]<<2|Na[n.charCodeAt(t+1)]>>4,a[l++]=255&e),o===1&&(e=Na[n.charCodeAt(t)]<<10|Na[n.charCodeAt(t+1)]<<4|Na[n.charCodeAt(t+2)]>>2,a[l++]=e>>8&255,a[l++]=255&e),a},fromByteArray:function(n){for(var e,t=n.length,r=t%3,s=[],o=16383,a=0,l=t-r;a<l;a+=o)s.push(B_e(n,a,a+o>l?l:a+o));return r===1?(e=n[t-1],s.push(Tc[e>>2]+Tc[e<<4&63]+"==")):r===2&&(e=(n[t-2]<<8)+n[t-1],s.push(Tc[e>>10]+Tc[e>>4&63]+Tc[e<<2&63]+"=")),s.join("")}},Tc=[],Na=[],R_e=typeof Uint8Array<"u"?Uint8Array:Array,GO="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",G0=0,P_e=GO.length;G0<P_e;++G0)Tc[G0]=GO[G0],Na[GO.charCodeAt(G0)]=G0;function q9(n){var e=n.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=n.indexOf("=");return t===-1&&(t=e),[t,t===e?0:4-t%4]}function B_e(n,e,t){for(var r,s,o=[],a=e;a<t;a+=3)r=(n[a]<<16&16711680)+(n[a+1]<<8&65280)+(255&n[a+2]),o.push(Tc[(s=r)>>18&63]+Tc[s>>12&63]+Tc[s>>6&63]+Tc[63&s]);return o.join("")}Na["-".charCodeAt(0)]=62,Na["_".charCodeAt(0)]=63;const k_e=Symbol("object"),VO=new oa(()=>new C,20);class Y9{constructor(e,t,r,s,o,a){d(this,"_point"),d(this,"_normal"),d(this,"_tangentVelocity"),d(this,"distance"),d(this,"impulse"),d(this,"friction"),this._point=e,this.distance=t,this._normal=r,this.impulse=s,this.friction=o,this._tangentVelocity=a}get point(){return VO.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return VO.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return VO.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}}class J9{constructor(e,t,r){d(this,"contacts"),d(this,"me"),d(this,"_collider"),d(this,"_gameObject"),this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=r}get collider(){return this._collider}get gameObject(){return this._gameObject}get rigidBody(){var e;return(e=this.collider)==null?void 0:e.attachedRigidbody}}class K9{constructor(e,t){d(this,"object"),d(this,"collider"),this.object=e,this.collider=t}}const os=te("debugphysics"),QO=te("debugcolliderplacement"),HO=te("debugcollisions"),D_e=te("showcolliders"),WO=te("debugraycasts"),So=Symbol("needle component"),no=Symbol("physics body"),Z9=Symbol("rigidbody");let jm;globalThis.false=globalThis.false!==void 0?globalThis.false:!0,os&&console.log("Use Rapier",!1,globalThis.false);const TE=class{constructor(){d(this,"debugRenderColliders",!1),d(this,"debugRenderRaycasts",!1),d(this,"context"),d(this,"_initializePromise"),d(this,"_isInitialized",!1),d(this,"rapierRay",new E_e({x:0,y:0,z:0},{x:0,y:0,z:1})),d(this,"raycastVectorsBuffer",new oa(()=>new C,10)),d(this,"rapierSphere",null),d(this,"rapierColliderArray",[]),d(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1}),d(this,"rapierForwardVector",{x:0,y:0,z:1}),d(this,"enabled",!1),d(this,"_tempPosition",new C),d(this,"_tempQuaternion",new Ce),d(this,"_tempScale",new C),d(this,"_tempMatrix",new ve),d(this,"_isUpdatingPhysicsWorld",!1),d(this,"_world"),d(this,"_hasCreatedWorld",!1),d(this,"eventQueue"),d(this,"collisionHandler"),d(this,"objects",[]),d(this,"bodies",[]),d(this,"_meshCache",new Map),d(this,"_gravity",{x:0,y:-9.81,z:0}),d(this,"lines"),d(this,"_tempCenterPos",new C),d(this,"_tempCenterVec",new C),d(this,"_tempCenterQuaternion",new Ce)}removeBody(n){var e,t,r;if(!n)return;this.validate();const s=n[no];if(n[no]=null,s&&this.world){const o=this.objects.findIndex(a=>a===n);if(o>=0){const a=this.bodies[o];if(this.bodies.splice(o,1),this.objects.splice(o,1),a instanceof X9){const l=a;(e=this.world)==null||e.removeCollider(l,!0);const c=l.parent();c&&c.numColliders()<=0&&(c[So]||(t=this.world)==null||t.removeRigidBody(c))}else a instanceof k9&&(a.numColliders()<=0?(r=this.world)==null||r.removeRigidBody(a):st()&&(a.did_log_removing||setTimeout(()=>{a.numColliders()>0&&(a.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}updateBody(n,e,t){if(this.validate(),!!this.enabled&&!(n.destroyed||!n.gameObject)&&!(!e&&!t))if(n.isCollider===!0)console.warn("TODO: implement updating collider position");else{const r=n,s=r[no];s&&this.syncPhysicsBody(r.gameObject,s,e,t)}}updateProperties(n){if(this.validate(),n.isCollider){const e=n,t=e[no];t&&(this.internalUpdateColliderProperties(e,t),e.sharedMaterial&&this.updatePhysicsMaterial(e))}else{const e=n,t=this.internal_getRigidbody(e);t&&this.internalUpdateRigidbodyProperties(e,t)}}addForce(n,e,t){this.validate();const r=this.internal_getRigidbody(n);r?r.addForce(e,t):console.warn("Rigidbody doesn't exist: can not apply force")}addImpulse(n,e,t){this.validate();const r=this.internal_getRigidbody(n);r?r.applyImpulse(e,t):console.warn("Rigidbody doesn't exist: can not apply impulse")}getLinearVelocity(n){this.validate();const e=this.internal_getRigidbody(n);return e?e.linvel():null}getAngularVelocity(n){this.validate();const e=this.internal_getRigidbody(n);return e?e.angvel():null}resetForces(n,e){this.validate();const t=this.internal_getRigidbody(n);t?.resetForces(e)}resetTorques(n,e){this.validate();const t=this.internal_getRigidbody(n);t?.resetTorques(e)}applyImpulse(n,e,t){this.validate();const r=this.internal_getRigidbody(n);r?r.applyImpulse(e,t):console.warn("Rigidbody doesn't exist: can not apply impulse")}wakeup(n){this.validate();const e=this.internal_getRigidbody(n);e?e.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up")}isSleeping(n){this.validate();const e=this.internal_getRigidbody(n);return e?.isSleeping()}setAngularVelocity(n,e,t){this.validate();const r=this.internal_getRigidbody(n);r?r.setAngvel(e,t):console.warn("Rigidbody doesn't exist: can not set angular velocity")}setLinearVelocity(n,e,t){this.validate();const r=this.internal_getRigidbody(n);r?r.setLinvel(e,t):console.warn("Rigidbody doesn't exist: can not set linear velocity")}async initialize(n){return this.context=n,this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return os&&console.log("Initialize rapier physics engine"),"env"in import.meta&&{}.VITE_NEEDLE_USE_RAPIER==="false"&&os&&console.log("Rapier disabled"),!1}validate(){this._isInitialized||os&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(n,e,t){var r;let s=t?.maxDistance,o=t?.solid;s===void 0&&(s=1/0),o===void 0&&(o=!0);const a=this.getPhysicsRay(this.rapierRay,n,e);if(!a)return null;(this.debugRenderRaycasts||WO)&&At.DrawRay(a.origin,a.dir,255,1);const l=(r=this.world)==null?void 0:r.castRay(a,s,o,t?.queryFilterFlags,t?.filterGroups,void 0,void 0,c=>{const h=c[So];return t!=null&&t.filterPredicate?t.filterPredicate(h):!(h!=null&&h.gameObject.layers.isEnabled(2))});if(l){const c=a.pointAt(l.toi),h=this.raycastVectorsBuffer.get();return h.set(c.x,c.y,c.z),{point:h,collider:l.collider[So]}}return null}raycastAndGetNormal(n,e,t){var r;let s=t?.maxDistance,o=t?.solid;s===void 0&&(s=1/0),o===void 0&&(o=!0);const a=this.getPhysicsRay(this.rapierRay,n,e);if(!a)return null;(this.debugRenderRaycasts||WO)&&At.DrawRay(a.origin,a.dir,255,1);const l=(r=this.world)==null?void 0:r.castRayAndGetNormal(a,s,o,t?.queryFilterFlags,t?.filterGroups,void 0,void 0,c=>{const h=c[So];return t!=null&&t.filterPredicate?t.filterPredicate(h):!(h!=null&&h.gameObject.layers.isEnabled(2))});if(l){const c=a.pointAt(l.toi),h=l.normal,u=this.raycastVectorsBuffer.get(),p=this.raycastVectorsBuffer.get();return u.set(c.x,c.y,c.z),p.set(h.x,h.y,h.z),{point:u,normal:p,collider:l.collider[So]}}return null}getPhysicsRay(n,e,t){var r,s,o;const a=(r=this.context)==null?void 0:r.mainCamera;if(e===void 0){const h=(s=this.context)==null?void 0:s.input.getPointerPosition(0);if(h)e=h;else return null}if(e.z===void 0){if(!a)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const h=this.raycastVectorsBuffer.get();h.x=e.x,h.y=e.y,h.z=0,(h.x>1||h.y>1||h.y<-1||h.x<-1)&&(os&&console.warn("Converting screenspace to raycast space",h),(o=this.context)==null||o.input.convertScreenspaceToRaycastSpace(h)),h.unproject(a),e=h}const l=e;n.origin.x=l.x,n.origin.y=l.y,n.origin.z=l.z;const c=this.raycastVectorsBuffer.get();if(t)c.set(t.x,t.y,t.z);else{if(!a)return console.error("Can not perform raycast - no camera found"),null;c.set(n.origin.x,n.origin.y,n.origin.z);const h=Bt(a);c.sub(h)}return c.normalize(),n.dir.x=c.x,n.dir.y=c.y,n.dir.z=c.z,n}sphereOverlap(n,e){return this.rapierColliderArray.length=0,this.world?(this.rapierSphere||(this.rapierSphere=new NO(e)),this.rapierSphere.radius=e,(this.debugRenderRaycasts||WO)&&At.DrawWireSphere(n,e,3359999,1),this.world.intersectionsWithShape(n,this.rapierIdentityRotation,this.rapierSphere,t=>{const r=t[So],s=new K9(r.gameObject,r);return this.rapierColliderArray.push(s),!0},void 0,void 0,void 0,void 0,t=>t.isSensor()?!1:t[So].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var n;return((n=this.world)==null?void 0:n.gravity)??this._gravity}set gravity(n){this.world?this.world.gravity=n:this._gravity=n}clearCaches(){var n,e,t,r;this._meshCache.clear(),(n=this.eventQueue)!=null&&n.raw&&((e=this.eventQueue)==null||e.free()),(t=this.world)!=null&&t.bodies&&((r=this.world)==null||r.free())}async addBoxCollider(n,e){if(this._isInitialized||await this.initialize(n.context),!n.activeAndEnabled)return;if(!this.enabled){os&&console.warn("Physics are disabled");return}const t=n.gameObject,r=Vi(t,this._tempPosition).multiply(e);r.multiplyScalar(.5),r.x<0&&(r.x=Math.abs(r.x)),r.y<0&&(r.y=Math.abs(r.y)),r.z<0&&(r.z=Math.abs(r.z)),r.x==0&&(r.x=1e-7),r.y==0&&(r.y=1e-7),r.z==0&&(r.z=1e-7);const s=un.cuboid(r.x,r.y,r.z);this.createCollider(n,s)}async addSphereCollider(n){if(this._isInitialized||await this.initialize(n.context),!n.activeAndEnabled)return;if(!this.enabled){os&&console.warn("Physics are disabled");return}const e=un.ball(.5);this.createCollider(n,e),this.updateProperties(n)}async addCapsuleCollider(n,e,t){if(this._isInitialized||await this.initialize(n.context),!n.activeAndEnabled)return;if(!this.enabled){os&&console.warn("Physics are disabled");return}const r=n.gameObject,s=Vi(r,this._tempPosition);s.x=Math.abs(s.x),s.y=Math.abs(s.y);const o=t*s.x;e=Math.max(e,o*2);const a=it.clamp(e*.5*s.y-t*s.x,0,Number.MAX_SAFE_INTEGER),l=un.capsule(a,o);this.createCollider(n,l)}async addMeshCollider(n,e,t,r){var s,o,a;if(this._isInitialized||await this.initialize(n.context),!n.activeAndEnabled)return;if(!this.enabled){os&&console.warn("Physics are disabled");return}let l=e.geometry;if(!l){os&&console.warn("Missing mesh geometry",e.name);return}(o=(s=l.index)==null?void 0:s.array)!=null&&o.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${e.name}". Consider providing an indexed geometry.`),l=dae(l));let c=l.getAttribute("position").array;const h=(a=l.index)==null?void 0:a.array;if(Math.abs(r.x-1)>1e-4||Math.abs(r.y-1)>1e-4||Math.abs(r.z-1)>1e-4){const p=l.uuid+"_"+r.x+"_"+r.y+"_"+r.z+"_"+t;if(this._meshCache.has(p))os&&console.warn("Use cached mesh collider"),c=this._meshCache.get(p);else{(os||st())&&console.warn(`Your MeshCollider "${n.name}" is scaled: consider applying the scale to the collider mesh instead (${r.x}, ${r.y}, ${r.z})`);const m=new Float32Array(c.length);for(let f=0;f<c.length;f+=3)m[f]=c[f]*r.x,m[f+1]=c[f+1]*r.y,m[f+2]=c[f+2]*r.z;c=m,this._meshCache.set(p,m)}}const u=t?un.convexHull(c):un.trimesh(c,h);u&&this.createCollider(n,u)}updatePhysicsMaterial(n){if(!n)return;const e=n.sharedMaterial,t=n[no];if(t&&e){if(e.bounciness!==void 0&&t.setRestitution(e.bounciness),e.bounceCombine!==void 0)switch(e.bounceCombine){case Cr.Average:t.setRestitutionCombineRule(er.Average);break;case Cr.Maximum:t.setRestitutionCombineRule(er.Max);break;case Cr.Minimum:t.setRestitutionCombineRule(er.Min);break;case Cr.Multiply:t.setRestitutionCombineRule(er.Multiply);break}if(e.dynamicFriction!==void 0&&t.setFriction(e.dynamicFriction),e.frictionCombine!==void 0)switch(e.frictionCombine){case Cr.Average:t.setFrictionCombineRule(er.Average);break;case Cr.Maximum:t.setFrictionCombineRule(er.Max);break;case Cr.Minimum:t.setFrictionCombineRule(er.Min);break;case Cr.Multiply:t.setFrictionCombineRule(er.Multiply);break}}}getBody(n){return n?n[no]:null}getComponent(n){return n?n[So]:null}createCollider(n,e){var t;if(!this.world)throw new Error("Physics world not initialized");const r=this._tempMatrix;let s;n.attachedRigidbody?s=this.getRigidbody(n,this._tempMatrix):(os&&console.log("Create collider without rigidbody",n.name),r.makeRotationFromQuaternion(Mi(n.gameObject)),r.setPosition(Bt(n.gameObject))),r.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(n,this._tempPosition),e.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),e.setRotation(this._tempQuaternion),e.setSensor(n.isTrigger);const o=n.sharedMaterial;if(o){if(o.bounciness!==void 0&&e.setRestitution(o.bounciness),o.bounceCombine!==void 0)switch(o.bounceCombine){case Cr.Average:e.setRestitutionCombineRule(er.Average);break;case Cr.Maximum:e.setRestitutionCombineRule(er.Max);break;case Cr.Minimum:e.setRestitutionCombineRule(er.Min);break;case Cr.Multiply:e.setRestitutionCombineRule(er.Multiply);break}if(o.dynamicFriction!==void 0&&e.setFriction(o.dynamicFriction),o.frictionCombine!==void 0)switch(o.frictionCombine){case Cr.Average:e.setFrictionCombineRule(er.Average);break;case Cr.Maximum:e.setFrictionCombineRule(er.Max);break;case Cr.Minimum:e.setFrictionCombineRule(er.Min);break;case Cr.Multiply:e.setFrictionCombineRule(er.Multiply);break}}((t=n.attachedRigidbody)==null?void 0:t.autoMass)===!1&&(e.setDensity(1e-6),e.setMass(1e-6));try{const a=this.world.createCollider(e,s);return a[So]=n,n[no]=a,a.setActiveEvents(EE.COLLISION_EVENTS),a.setActiveCollisionTypes(ME.ALL),this.objects.push(n),this.bodies.push(a),this.updateColliderCollisionGroups(n),a}catch(a){return console.error('Error creating collider "'+n.name+`"
7747
- Error:`,a),null}}updateColliderCollisionGroups(n){const e=n[no],t=n.membership;let r=0;if(t==null)r=65535;else for(let a=0;a<t.length;a++){const l=t[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}const s=n.filter;let o=0;if(s==null)o=65535;else for(let a=0;a<s.length;a++){const l=s[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):o|=1<<Math.floor(l)}e.setCollisionGroups(r<<16|o)}getRigidbody(n,e){if(!this.world)throw new Error("Physics world not initialized");let t=null;if(n.attachedRigidbody){const r=n.attachedRigidbody;if(t=r[no],!t){const s=r.isKinematic&&!QO;os&&console.log("Create rigidbody",s);const o=s?jm.RigidBodyDesc.kinematicPositionBased():jm.RigidBodyDesc.dynamic(),a=Bt(n.attachedRigidbody.gameObject);o.setTranslation(a.x,a.y,a.z),o.setRotation(Mi(n.attachedRigidbody.gameObject)),o.centerOfMass=new jm.Vector3(r.centerOfMass.x,r.centerOfMass.y,r.centerOfMass.z),t=this.world.createRigidBody(o),this.bodies.push(t),this.objects.push(r)}t[So]=r,r[no]=t,this.internalUpdateRigidbodyProperties(r,t),this.getRigidbodyRelativeMatrix(n.gameObject,r.gameObject,e),n[Z9]=t}else{const r=jm.RigidBodyDesc.kinematicPositionBased(),s=Bt(n.gameObject);r.setTranslation(s.x,s.y,s.z),r.setRotation(Mi(n.gameObject)),t=this.world.createRigidBody(r),e.identity(),t[So]=null}return t}internal_getRigidbody(n){return n.isCollider===!0?n[Z9]:n[no]}internalUpdateColliderProperties(n,e){const t=e.shape;let r=!1;switch(t.type){case zn.Ball:{const p=t,m=n,f=n.gameObject,g=Vi(f,this._tempPosition),v=Math.abs(m.radius*g.x);r=p.radius!==v,p.radius=v,r&&e.setShape(p);break}case zn.Cuboid:const s=t,o=n,a=n.gameObject,l=Vi(a,this._tempPosition),c=o.size.x*.5*l.x,h=o.size.y*.5*l.y,u=o.size.z*.5*l.z;r=s.halfExtents.x!==c||s.halfExtents.y!==h||s.halfExtents.z!==u,s.halfExtents.x=c,s.halfExtents.y=h,s.halfExtents.z=u,r&&e.setShape(s);break}if(r){const s=n.attachedRigidbody;if(s!=null&&s.autoMass){const o=this.getBody(s);o?.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(n),n.isTrigger!==e.isSensor()&&e.setSensor(n.isTrigger)}internalUpdateRigidbodyProperties(n,e){if(e.enableCcd(n.collisionDetectionMode!==LS.Discrete),e.setLinearDamping(n.drag),e.setAngularDamping(n.angularDrag),e.setGravityScale(n.useGravity?n.gravityScale:0,!0),n.dominanceGroup<=127&&n.dominanceGroup>=-127?e.setDominanceGroup(Math.floor(n.dominanceGroup)):e.setDominanceGroup(0),n.autoMass){e.setAdditionalMass(0,!1);for(let t=0;t<e.numColliders();t++)e.collider(t).setDensity(1);e.recomputeMassPropertiesFromColliders()}else{e.setAdditionalMass(n.mass,!1);for(let t=0;t<e.numColliders();t++)e.collider(t).setDensity(1e-7);e.recomputeMassPropertiesFromColliders()}e.setEnabledRotations(!n.lockRotationX,!n.lockRotationY,!n.lockRotationZ,!1),e.setEnabledTranslations(!n.lockPositionX,!n.lockPositionY,!n.lockPositionZ,!1),n.isKinematic?e.setBodyType(jm.RigidBodyType.KinematicPositionBased,!1):e.setBodyType(jm.RigidBodyType.Dynamic,!1)}step(n){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new I_e(!1)),n===void 0||n<=0){this._isUpdatingPhysicsWorld=!1;return}else n!==void 0&&(this.world.timestep=it.lerp(this.world.timestep,n,.8));try{this.world.step(this.eventQueue)}catch(e){console.warn("Error running physics step",e)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new O_e(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(n){var e,t,r,s;if(os||QO||D_e||this.debugRenderColliders===!0){if(!this.lines){const a=new Gi({color:7855479,fog:!1}),l=new yt;this.lines=new gs(l,a),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((e=this.context)==null?void 0:e.scene)&&((t=this.context)==null||t.scene.add(this.lines));const o=n.debugRender();this.lines.geometry.setAttribute("position",new nt(o.vertices,3)),this.lines.geometry.setAttribute("color",new nt(o.colors,4)),(this.context.time.frame%30===0||((r=this.lines.geometry.boundingSphere)==null?void 0:r.radius)===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&((s=this.context)==null||s.scene.remove(this.lines))}syncObjects(){if(!QO)for(let n=0;n<this.bodies.length;n++){const e=this.objects[n],t=this.bodies[n],r=e;if(r?.isCollider===!0&&!r.attachedRigidbody){const l=t.parent();l?this.syncPhysicsBody(e.gameObject,l,!0,!0):this.syncPhysicsBody(e.gameObject,t,!0,!0);continue}const s=t.translation(),o=t.rotation();if(Number.isNaN(s.x)||Number.isNaN(o.x)){!r.__COLLIDER_NAN&&st()&&(console.warn("Collider has NaN values",r.name,r.gameObject,t),r.__COLLIDER_NAN=!0);continue}const a=e.center;if(a&&a.isVector3){this._tempQuaternion.set(o.x,o.y,o.z,o.w);const l=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),c=Vi(e.gameObject);l.multiply(c),s.x-=l.x,s.y-=l.y,s.z-=l.z}_p(e.gameObject,s.x,s.y,s.z),wR(e.gameObject,o.x,o.y,o.z,o.w)}}syncPhysicsBody(n,e,t,r){if(e instanceof k9){const s=Bt(n,this._tempPosition),o=Mi(n,this._tempQuaternion);switch(e.bodyType()){case $b.Fixed:case $b.KinematicPositionBased:case $b.KinematicVelocityBased:t&&e.setNextKinematicTranslation(s),r&&e.setNextKinematicRotation(o);break;default:t&&e.setTranslation(s,!1),r&&e.setRotation(o,!1);break}}else if(e instanceof X9){const s=Bt(n,this._tempPosition),o=Mi(n,this._tempQuaternion),a=e[So];if(this.tryApplyCenter(a,s),t){const l=e.translation();(l.x!==s.x||l.y!==s.y||l.z!==s.z)&&e.setTranslation(s)}if(r){const l=e.rotation();(l.x!==o.x||l.y!==o.y||l.z!==o.z||l.w!==o.w)&&e.setRotation(o)}}}tryApplyCenter(n,e){const t=n.center;t&&n.gameObject&&(t.x!==0||t.y!==0||t.z!==0)&&(this._tempCenterPos.x=-t.x,this._tempCenterPos.y=t.y,this._tempCenterPos.z=t.z,Vi(n.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),n.attachedRigidbody?this._tempCenterPos.applyQuaternion(n.gameObject.quaternion):(Mi(n.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),e.x+=this._tempCenterPos.x,e.y+=this._tempCenterPos.y,e.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(n,e,t,r){if(r===void 0&&(r=TE._matricesBuffer,r.length=0),n===e){const s=Vi(n,this._tempPosition);t.makeScale(s.x,s.y,s.z);for(let o=r.length-1;o>=0;o--)t.multiply(r[o]);return t}return r.push(n.matrix),n.parent&&this.getRigidbodyRelativeMatrix(n.parent,e,t,r),t}addFixedJoint(n,e){if(!this.world){console.error("Physics world not initialized");return}const t=n[no],r=e[no];this.calculateJointRelativeMatrices(n.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const s=jh.fixed(TE.centerConnectionPos,TE.centerConnectionRot,this._tempPosition,this._tempQuaternion),o=this.world.createImpulseJoint(s,t,r,!0);os&&console.log("ADD FIXED JOINT",o)}addHingeJoint(n,e,t,r){if(!this.world){console.error("Physics world not initialized");return}const s=n[no],o=e[no];this.calculateJointRelativeMatrices(n.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=jm.JointData.revolute(t,this._tempPosition,r),l=this.world.createImpulseJoint(a,s,o,!0);os&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(n,e,t){n.updateWorldMatrix(!0,!1),e.updateWorldMatrix(!0,!1);const r=n.matrixWorld,s=e.matrixWorld;r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,s.elements[0]=1,s.elements[5]=1,s.elements[10]=1,t.copy(s).premultiply(r.invert()).invert()}};let e_=TE;d(e_,"_didLoadPhysicsEngine",!1),d(e_,"_matricesBuffer",[]),d(e_,"centerConnectionPos",{x:0,y:0,z:0}),d(e_,"centerConnectionRot",{x:0,y:0,z:0,w:1});class O_e{constructor(e,t){d(this,"world"),d(this,"eventQueue"),d(this,"activeCollisions",[]),d(this,"activeCollisionsStay",[]),d(this,"activeTriggers",[]),this.world=e,this.eventQueue=t}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,r)=>{const s=this.world.getCollider(e),o=this.world.getCollider(t);if(!s||!o)return;const a=s[So],l=o[So];HO&&console.log("EVT",a.name,l.name,r,s,o),a&&l&&(r?(this.onCollisionStarted(a,s,l,o),this.onCollisionStarted(l,o,a,s)):(this.onCollisionEnded(a,l),this.onCollisionEnded(l,a)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,r,s){let o=null;if(e.isTrigger||r.isTrigger)Kp(e.gameObject,a=>{a.onTriggerEnter&&!a.destroyed&&a.onTriggerEnter(r),this.activeTriggers.push({collider:e,component:a,otherCollider:r})});else{const a=e.gameObject;this.world.contactPair(t,s,(l,c)=>{Kp(a,h=>{var u;if(h.destroyed)return;const p=h.onCollisionEnter||h.onCollisionStay||h.onCollisionExit;if(p||HO){if(!o){const m=[],f=l.normal();for(let g=0;g<l.numSolverContacts();g++){const v=l.solverContactPoint(g),y=l.contactImpulse(g);if(v){const A=l.contactDist(g),_=l.solverContactFriction(g),b=l.solverContactTangentVelocity(g),x=new Y9(v,A,f,y,_,b);m.push(x),HO&&At.DrawDirection(v,f,16711680,3,!0)}}o=new J9(a,r,m)}if(p){const m={collider:e,component:h,collision:o};this.activeCollisions.push(m),h.onCollisionStay&&this.activeCollisionsStay.push(m),(u=h.onCollisionEnter)==null||u.call(h,o)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const r=e.collision;t.onCollisionStay(r)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const r=e.otherCollider;if(r.destroyed)continue;t.onTriggerStay(r)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let r=0;r<this.activeCollisions.length;r++){const s=this.activeCollisions[r],o=s.collider;if(o.destroyed||s.collision.collider.destroyed){this.activeCollisions.splice(r,1),r--;continue}if(o===e&&s.collision.collider===t){const a=s.component;if(this.activeCollisions.splice(r,1),r--,a.activeAndEnabled&&a.onCollisionExit){const l=s.collision;a.onCollisionExit(l)}}}for(let r=0;r<this.activeCollisionsStay.length;r++){const s=this.activeCollisionsStay[r],o=s.collider;if(o.destroyed||s.collision.collider.destroyed){this.activeCollisionsStay.splice(r,1),r--;continue}if(o===e&&s.collision.collider===t){const a=s.component;if(this.activeCollisionsStay.splice(r,1),r--,a.activeAndEnabled&&a.onCollisionExit){const l=s.collision;a.onCollisionExit(l)}}}for(let r=0;r<this.activeTriggers.length;r++){const s=this.activeTriggers[r],o=s.collider;if(o.destroyed||s.otherCollider.destroyed){this.activeTriggers.splice(r,1),r--;continue}if(o===e&&s.otherCollider===t){const a=s.component;if(this.activeTriggers.splice(r,1),r--,a.activeAndEnabled&&a.onTriggerExit){const l=s.otherCollider;a.onTriggerExit(l)}}}}}}class L_e{static async createComparisonScene(e){const{files:t}=e,r=await Promise.all(t.map(g=>new ti(g).loadAssetAsync())),s=new Ur;let o=0;for(const g of r)if(g instanceof ye){g.position.y=o,s.add(g);const v=Ul([g]);o+=v.getSize(new C).y,o+=.1}const a=new Lt(20);s.add(a);const l=e.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";if(l){let g=null;if(l.endsWith(".hdr")){const v=(await Promise.resolve().then(()=>Sde)).RGBELoader;g=new v}else if(l.endsWith(".exr")){const v=(await Promise.resolve().then(()=>wde)).EXRLoader;g=new v}if(g){const v=await g.loadAsync(l).catch(y=>(console.error(y),null));v&&(v.mapping=so,v.needsUpdate=!0,s.background=v,s.environment=v,s.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",l)}const c=Ul(s.children),h=c.getCenter(new C),u=c.getSize(new C),p=Math.max(u.x,u.y,u.z)/(2*Math.tan(Math.PI*a.fov/360));a.position.set(h.x,h.y,p),a.lookAt(h);const m=new p8(a,e.domElement||document.body);m.target=h,m.update();const f=(e.domElement||document.body).getBoundingClientRect();return a.aspect=f.width/f.height,a.updateProjectionMatrix(),{scene:s,camera:a}}}function F_e(n,e,t,r="image/webp",s){return $9({context:n,width:e,height:t,mimeType:r,camera:s})}function $9(n={mimeType:"image/png",transparent:!1}){n||(n={});let{context:e,width:t,height:r,camera:s}=n;const{mimeType:o}=n;if(!e&&(e=di.Current,!e))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!s&&(s=e.mainCamera,!s))return console.error("No camera found"),null;const a=e.renderer.domElement.width,l=e.renderer.domElement.height;t||(t=a),r||(r=l);const c=window.devicePixelRatio||1;t/=c,r/=c,e.renderer.domElement.style.width=t+"px",e.renderer.domElement.style.height=r+"px";const h=e.renderer.getClearColor(new xe),u=e.renderer.getClearAlpha();try{n!=null&&n.transparent&&e.renderer.setClearColor(0,0);const p=e.renderer.domElement;e.renderer.setSize(t,r,!1),s instanceof Lt&&e.updateAspect(s,t,r);const m=n.render_events!==!1,f=new Array;m&&(Vg(e.scene,Tn,f),f.forEach(v=>v?.onBeforeRender())),e.renderNow(),m&&f.forEach(v=>v.onAfterRender());const g=p.toDataURL(o);return n.download_filename&&eW(g,n.download_filename),g}finally{e.renderer.setSize(a,l,!1),e.updateSize(),e.renderer.setClearColor(h,u)}return null}let t_=null;function eW(n,e){if(n){if(!n.startsWith("data:image")){console.error("Can not save image: Data url is not an image",n);return}t_||(t_=document.createElement("a")),t_.href=n,t_.download=e,t_.click()}}let XO=0;function tW(n){n?XO++:XO--}function U_e(){return XO>0}class iW{constructor(e){d(this,"writer"),this.writer=e}writeNode(e){}}class N_e extends iW{beforeWriteNode(e,t){At.isGizmo(e)&&(t.keep=!1)}}class z_e extends iW{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=WB(new Si(1,1,1,0)))}}const j_e={binary:!0,animations:!0};async function G_e(n){if(!n.context)throw new Error("No context provided to exportAsGLTF");n.scene||(n.scene=n.context.scene);const e={...j_e,...n},{context:t}=e,r=new zC;r.register(l=>new QQ(l)),r.register(l=>new N_e(l)),r.register(l=>new z_e(l)),rD(r,e.context);const s={binary:e.binary,animations:Q_e(t,e.scene,[])},o=new V_e;console.log("Exporting GLTF",s),o.onBeforeExport(e),tW(!0);const a=await r.parseAsync(e.scene,s).catch(l=>(console.error(l),null));if(tW(!1),o.onAfterExport(e),!a)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let l=null;if(a instanceof ArrayBuffer?l=new Blob([a],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",a),l){const c=URL.createObjectURL(l),h=document.createElement("a");h.href=c;let u=e.downloadAs;!u.endsWith(".glb")&&!u.endsWith(".gltf")&&(u+=e.binary?".glb":".gltf"),h.download=u,h.click()}}return a}const nW=Symbol("needle:weight");class V_e{constructor(){d(this,"_undo",[])}onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const r=Bg.tryGetActionsFromMixer(t);if(r)for(let s=0;s<r.length;s++){const o=r[s];o[nW]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[nW]})}t.update(0)})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function Q_e(n,e,t){n.animations.mixers.forEach(s=>{const o=Bg.tryGetActionsFromMixer(s);if(o)for(let a=0;a<o.length;a++){const l=o[a].getClip();t.push(l)}}),Array.isArray(e)||(e=[e]);for(const s of e)Bg.tryGetAnimationClipsFromObjectHierarchy(s,t);const r=new Set(t);return Array.from(r)}Object.defineProperty(Lt.prototype,"fov",{get:function(){return this._fov},set:function(n){const e=n!==this._fov;this._fov=n,e&&this.view!==void 0&&this.updateProjectionMatrix()}}),Object.defineProperty(Lt.prototype,"near",{get:function(){return this._near},set:function(n){const e=n!==this._near;this._near=n,e&&this.view!==void 0&&this.updateProjectionMatrix()}}),Object.defineProperty(Lt.prototype,"far",{get:function(){return this._far},set:function(n){const e=n!==this._far;this._far=n,e&&this.view!==void 0&&this.updateProjectionMatrix()}});const rW="needle-button",qO=st();var Gm,Vm,Qm,Co,Sl,V0,YO,sW,JO,oW,IE;class KO extends HTMLElement{constructor(){super(),kc(this,YO),kc(this,JO),kc(this,Gm,void 0),kc(this,Vm,void 0),kc(this,Qm,void 0),kc(this,Co,void 0),kc(this,Sl,void 0),kc(this,V0,void 0),kc(this,IE,e=>{qO&&console.log("Needle Button clicked"),!e.defaultPrevented&&vi(this,Co)&&vi(this,Co).click()}),this.removeEventListener("click",vi(this,IE)),this.addEventListener("click",vi(this,IE))}attributeChangedCallback(e,t,r){cL(this,YO,sW).call(this)}}Gm=new WeakMap,Vm=new WeakMap,Qm=new WeakMap,Co=new WeakMap,Sl=new WeakMap,V0=new WeakMap,YO=new WeakSet,sW=function(){var n,e;if((n=vi(this,Co))==null||n.remove(),this.getAttribute("ar")!=null)vi(this,Sl)??Tl(this,Sl,new Am),Tl(this,Co,vi(this,Sl).createARButton());else if(this.getAttribute("vr")!=null)vi(this,Sl)??Tl(this,Sl,new Am),Tl(this,Co,vi(this,Sl).createVRButton());else if(this.getAttribute("quicklook")!=null)vi(this,Sl)??Tl(this,Sl,new Am),Tl(this,Co,vi(this,Sl).createQuicklookButton());else{qO?console.warn("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."):console.debug("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute.");return}vi(this,Gm)??Tl(this,Gm,this.attachShadow({mode:"open"})),vi(this,Vm)??Tl(this,Vm,document.createElement("slot")),vi(this,Qm)??Tl(this,Qm,document.createElement("style")),vi(this,Qm).innerHTML=`
7747
+ Error:`,a),null}}updateColliderCollisionGroups(n){const e=n[no],t=n.membership;let r=0;if(t==null)r=65535;else for(let a=0;a<t.length;a++){const l=t[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}const s=n.filter;let o=0;if(s==null)o=65535;else for(let a=0;a<s.length;a++){const l=s[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):o|=1<<Math.floor(l)}e.setCollisionGroups(r<<16|o)}getRigidbody(n,e){if(!this.world)throw new Error("Physics world not initialized");let t=null;if(n.attachedRigidbody){const r=n.attachedRigidbody;if(t=r[no],!t){const s=r.isKinematic&&!QO;os&&console.log("Create rigidbody",s);const o=s?jm.RigidBodyDesc.kinematicPositionBased():jm.RigidBodyDesc.dynamic(),a=Bt(n.attachedRigidbody.gameObject);o.setTranslation(a.x,a.y,a.z),o.setRotation(Mi(n.attachedRigidbody.gameObject)),o.centerOfMass=new jm.Vector3(r.centerOfMass.x,r.centerOfMass.y,r.centerOfMass.z),t=this.world.createRigidBody(o),this.bodies.push(t),this.objects.push(r)}t[So]=r,r[no]=t,this.internalUpdateRigidbodyProperties(r,t),this.getRigidbodyRelativeMatrix(n.gameObject,r.gameObject,e),n[Z9]=t}else{const r=jm.RigidBodyDesc.kinematicPositionBased(),s=Bt(n.gameObject);r.setTranslation(s.x,s.y,s.z),r.setRotation(Mi(n.gameObject)),t=this.world.createRigidBody(r),e.identity(),t[So]=null}return t}internal_getRigidbody(n){return n.isCollider===!0?n[Z9]:n[no]}internalUpdateColliderProperties(n,e){const t=e.shape;let r=!1;switch(t.type){case zn.Ball:{const p=t,m=n,f=n.gameObject,g=Vi(f,this._tempPosition),v=Math.abs(m.radius*g.x);r=p.radius!==v,p.radius=v,r&&e.setShape(p);break}case zn.Cuboid:const s=t,o=n,a=n.gameObject,l=Vi(a,this._tempPosition),c=o.size.x*.5*l.x,h=o.size.y*.5*l.y,u=o.size.z*.5*l.z;r=s.halfExtents.x!==c||s.halfExtents.y!==h||s.halfExtents.z!==u,s.halfExtents.x=c,s.halfExtents.y=h,s.halfExtents.z=u,r&&e.setShape(s);break}if(r){const s=n.attachedRigidbody;if(s!=null&&s.autoMass){const o=this.getBody(s);o?.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(n),n.isTrigger!==e.isSensor()&&e.setSensor(n.isTrigger)}internalUpdateRigidbodyProperties(n,e){if(e.enableCcd(n.collisionDetectionMode!==LS.Discrete),e.setLinearDamping(n.drag),e.setAngularDamping(n.angularDrag),e.setGravityScale(n.useGravity?n.gravityScale:0,!0),n.dominanceGroup<=127&&n.dominanceGroup>=-127?e.setDominanceGroup(Math.floor(n.dominanceGroup)):e.setDominanceGroup(0),n.autoMass){e.setAdditionalMass(0,!1);for(let t=0;t<e.numColliders();t++)e.collider(t).setDensity(1);e.recomputeMassPropertiesFromColliders()}else{e.setAdditionalMass(n.mass,!1);for(let t=0;t<e.numColliders();t++)e.collider(t).setDensity(1e-7);e.recomputeMassPropertiesFromColliders()}e.setEnabledRotations(!n.lockRotationX,!n.lockRotationY,!n.lockRotationZ,!1),e.setEnabledTranslations(!n.lockPositionX,!n.lockPositionY,!n.lockPositionZ,!1),n.isKinematic?e.setBodyType(jm.RigidBodyType.KinematicPositionBased,!1):e.setBodyType(jm.RigidBodyType.Dynamic,!1)}step(n){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new I_e(!1)),n===void 0||n<=0){this._isUpdatingPhysicsWorld=!1;return}else n!==void 0&&(this.world.timestep=it.lerp(this.world.timestep,n,.8));try{this.world.step(this.eventQueue)}catch(e){console.warn("Error running physics step",e)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new O_e(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(n){var e,t,r,s;if(os||QO||D_e||this.debugRenderColliders===!0){if(!this.lines){const a=new Gi({color:7855479,fog:!1}),l=new yt;this.lines=new gs(l,a),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((e=this.context)==null?void 0:e.scene)&&((t=this.context)==null||t.scene.add(this.lines));const o=n.debugRender();this.lines.geometry.setAttribute("position",new nt(o.vertices,3)),this.lines.geometry.setAttribute("color",new nt(o.colors,4)),(this.context.time.frame%30===0||((r=this.lines.geometry.boundingSphere)==null?void 0:r.radius)===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&((s=this.context)==null||s.scene.remove(this.lines))}syncObjects(){if(!QO)for(let n=0;n<this.bodies.length;n++){const e=this.objects[n],t=this.bodies[n],r=e;if(r?.isCollider===!0&&!r.attachedRigidbody){const l=t.parent();l?this.syncPhysicsBody(e.gameObject,l,!0,!0):this.syncPhysicsBody(e.gameObject,t,!0,!0);continue}const s=t.translation(),o=t.rotation();if(Number.isNaN(s.x)||Number.isNaN(o.x)){!r.__COLLIDER_NAN&&st()&&(console.warn("Collider has NaN values",r.name,r.gameObject,t),r.__COLLIDER_NAN=!0);continue}const a=e.center;if(a&&a.isVector3){this._tempQuaternion.set(o.x,o.y,o.z,o.w);const l=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),c=Vi(e.gameObject);l.multiply(c),s.x-=l.x,s.y-=l.y,s.z-=l.z}_p(e.gameObject,s.x,s.y,s.z),wR(e.gameObject,o.x,o.y,o.z,o.w)}}syncPhysicsBody(n,e,t,r){if(e instanceof k9){const s=Bt(n,this._tempPosition),o=Mi(n,this._tempQuaternion);switch(e.bodyType()){case $b.Fixed:case $b.KinematicPositionBased:case $b.KinematicVelocityBased:t&&e.setNextKinematicTranslation(s),r&&e.setNextKinematicRotation(o);break;default:t&&e.setTranslation(s,!1),r&&e.setRotation(o,!1);break}}else if(e instanceof X9){const s=Bt(n,this._tempPosition),o=Mi(n,this._tempQuaternion),a=e[So];if(this.tryApplyCenter(a,s),t){const l=e.translation();(l.x!==s.x||l.y!==s.y||l.z!==s.z)&&e.setTranslation(s)}if(r){const l=e.rotation();(l.x!==o.x||l.y!==o.y||l.z!==o.z||l.w!==o.w)&&e.setRotation(o)}}}tryApplyCenter(n,e){const t=n.center;t&&n.gameObject&&(t.x!==0||t.y!==0||t.z!==0)&&(this._tempCenterPos.x=-t.x,this._tempCenterPos.y=t.y,this._tempCenterPos.z=t.z,Vi(n.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),n.attachedRigidbody?this._tempCenterPos.applyQuaternion(n.gameObject.quaternion):(Mi(n.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),e.x+=this._tempCenterPos.x,e.y+=this._tempCenterPos.y,e.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(n,e,t,r){if(r===void 0&&(r=TE._matricesBuffer,r.length=0),n===e){const s=Vi(n,this._tempPosition);t.makeScale(s.x,s.y,s.z);for(let o=r.length-1;o>=0;o--)t.multiply(r[o]);return t}return r.push(n.matrix),n.parent&&this.getRigidbodyRelativeMatrix(n.parent,e,t,r),t}addFixedJoint(n,e){if(!this.world){console.error("Physics world not initialized");return}const t=n[no],r=e[no];this.calculateJointRelativeMatrices(n.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const s=jh.fixed(TE.centerConnectionPos,TE.centerConnectionRot,this._tempPosition,this._tempQuaternion),o=this.world.createImpulseJoint(s,t,r,!0);os&&console.log("ADD FIXED JOINT",o)}addHingeJoint(n,e,t,r){if(!this.world){console.error("Physics world not initialized");return}const s=n[no],o=e[no];this.calculateJointRelativeMatrices(n.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=jm.JointData.revolute(t,this._tempPosition,r),l=this.world.createImpulseJoint(a,s,o,!0);os&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(n,e,t){n.updateWorldMatrix(!0,!1),e.updateWorldMatrix(!0,!1);const r=n.matrixWorld,s=e.matrixWorld;r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,s.elements[0]=1,s.elements[5]=1,s.elements[10]=1,t.copy(s).premultiply(r.invert()).invert()}};let e_=TE;d(e_,"_didLoadPhysicsEngine",!1),d(e_,"_matricesBuffer",[]),d(e_,"centerConnectionPos",{x:0,y:0,z:0}),d(e_,"centerConnectionRot",{x:0,y:0,z:0,w:1});class O_e{constructor(e,t){d(this,"world"),d(this,"eventQueue"),d(this,"activeCollisions",[]),d(this,"activeCollisionsStay",[]),d(this,"activeTriggers",[]),this.world=e,this.eventQueue=t}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,r)=>{const s=this.world.getCollider(e),o=this.world.getCollider(t);if(!s||!o)return;const a=s[So],l=o[So];HO&&console.log("EVT",a.name,l.name,r,s,o),a&&l&&(r?(this.onCollisionStarted(a,s,l,o),this.onCollisionStarted(l,o,a,s)):(this.onCollisionEnded(a,l),this.onCollisionEnded(l,a)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,r,s){let o=null;if(e.isTrigger||r.isTrigger)Kp(e.gameObject,a=>{a.onTriggerEnter&&!a.destroyed&&a.onTriggerEnter(r),this.activeTriggers.push({collider:e,component:a,otherCollider:r})});else{const a=e.gameObject;this.world.contactPair(t,s,(l,c)=>{Kp(a,h=>{var u;if(h.destroyed)return;const p=h.onCollisionEnter||h.onCollisionStay||h.onCollisionExit;if(p||HO){if(!o){const m=[],f=l.normal();for(let g=0;g<l.numSolverContacts();g++){const v=l.solverContactPoint(g),y=l.contactImpulse(g);if(v){const A=l.contactDist(g),_=l.solverContactFriction(g),b=l.solverContactTangentVelocity(g),x=new Y9(v,A,f,y,_,b);m.push(x),HO&&At.DrawDirection(v,f,16711680,3,!0)}}o=new J9(a,r,m)}if(p){const m={collider:e,component:h,collision:o};this.activeCollisions.push(m),h.onCollisionStay&&this.activeCollisionsStay.push(m),(u=h.onCollisionEnter)==null||u.call(h,o)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const r=e.collision;t.onCollisionStay(r)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const r=e.otherCollider;if(r.destroyed)continue;t.onTriggerStay(r)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let r=0;r<this.activeCollisions.length;r++){const s=this.activeCollisions[r],o=s.collider;if(o.destroyed||s.collision.collider.destroyed){this.activeCollisions.splice(r,1),r--;continue}if(o===e&&s.collision.collider===t){const a=s.component;if(this.activeCollisions.splice(r,1),r--,a.activeAndEnabled&&a.onCollisionExit){const l=s.collision;a.onCollisionExit(l)}}}for(let r=0;r<this.activeCollisionsStay.length;r++){const s=this.activeCollisionsStay[r],o=s.collider;if(o.destroyed||s.collision.collider.destroyed){this.activeCollisionsStay.splice(r,1),r--;continue}if(o===e&&s.collision.collider===t){const a=s.component;if(this.activeCollisionsStay.splice(r,1),r--,a.activeAndEnabled&&a.onCollisionExit){const l=s.collision;a.onCollisionExit(l)}}}for(let r=0;r<this.activeTriggers.length;r++){const s=this.activeTriggers[r],o=s.collider;if(o.destroyed||s.otherCollider.destroyed){this.activeTriggers.splice(r,1),r--;continue}if(o===e&&s.otherCollider===t){const a=s.component;if(this.activeTriggers.splice(r,1),r--,a.activeAndEnabled&&a.onTriggerExit){const l=s.otherCollider;a.onTriggerExit(l)}}}}}}class L_e{static async createComparisonScene(e){const{files:t}=e,r=await Promise.all(t.map(g=>new ti(g).loadAssetAsync())),s=new Ur;let o=0;for(const g of r)if(g instanceof ye){g.position.y=o,s.add(g);const v=Ul([g]);o+=v.getSize(new C).y,o+=.1}const a=new Lt(20);s.add(a);const l=e.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";if(l){let g=null;if(l.endsWith(".hdr")){const v=(await Promise.resolve().then(()=>Sde)).RGBELoader;g=new v}else if(l.endsWith(".exr")){const v=(await Promise.resolve().then(()=>wde)).EXRLoader;g=new v}if(g){const v=await g.loadAsync(l).catch(y=>(console.error(y),null));v&&(v.mapping=so,v.needsUpdate=!0,s.background=v,s.environment=v,s.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",l)}const c=Ul(s.children),h=c.getCenter(new C),u=c.getSize(new C),p=Math.max(u.x,u.y,u.z)/(2*Math.tan(Math.PI*a.fov/360));a.position.set(h.x,h.y,p),a.lookAt(h);const m=new pV(a,e.domElement||document.body);m.target=h,m.update();const f=(e.domElement||document.body).getBoundingClientRect();return a.aspect=f.width/f.height,a.updateProjectionMatrix(),{scene:s,camera:a}}}function F_e(n,e,t,r="image/webp",s){return $9({context:n,width:e,height:t,mimeType:r,camera:s})}function $9(n={mimeType:"image/png",transparent:!1}){n||(n={});let{context:e,width:t,height:r,camera:s}=n;const{mimeType:o}=n;if(!e&&(e=di.Current,!e))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!s&&(s=e.mainCamera,!s))return console.error("No camera found"),null;const a=e.renderer.domElement.width,l=e.renderer.domElement.height;t||(t=a),r||(r=l);const c=window.devicePixelRatio||1;t/=c,r/=c,e.renderer.domElement.style.width=t+"px",e.renderer.domElement.style.height=r+"px";const h=e.renderer.getClearColor(new xe),u=e.renderer.getClearAlpha();try{n!=null&&n.transparent&&e.renderer.setClearColor(0,0);const p=e.renderer.domElement;e.renderer.setSize(t,r,!1),s instanceof Lt&&e.updateAspect(s,t,r);const m=n.render_events!==!1,f=new Array;m&&(Vg(e.scene,Tn,f),f.forEach(v=>v?.onBeforeRender())),e.renderNow(),m&&f.forEach(v=>v.onAfterRender());const g=p.toDataURL(o);return n.download_filename&&eW(g,n.download_filename),g}finally{e.renderer.setSize(a,l,!1),e.updateSize(),e.renderer.setClearColor(h,u)}return null}let t_=null;function eW(n,e){if(n){if(!n.startsWith("data:image")){console.error("Can not save image: Data url is not an image",n);return}t_||(t_=document.createElement("a")),t_.href=n,t_.download=e,t_.click()}}let XO=0;function tW(n){n?XO++:XO--}function U_e(){return XO>0}class iW{constructor(e){d(this,"writer"),this.writer=e}writeNode(e){}}class N_e extends iW{beforeWriteNode(e,t){At.isGizmo(e)&&(t.keep=!1)}}class z_e extends iW{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=WB(new Si(1,1,1,0)))}}const j_e={binary:!0,animations:!0};async function G_e(n){if(!n.context)throw new Error("No context provided to exportAsGLTF");n.scene||(n.scene=n.context.scene);const e={...j_e,...n},{context:t}=e,r=new zC;r.register(l=>new QQ(l)),r.register(l=>new N_e(l)),r.register(l=>new z_e(l)),rD(r,e.context);const s={binary:e.binary,animations:Q_e(t,e.scene,[])},o=new V_e;console.log("Exporting GLTF",s),o.onBeforeExport(e),tW(!0);const a=await r.parseAsync(e.scene,s).catch(l=>(console.error(l),null));if(tW(!1),o.onAfterExport(e),!a)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let l=null;if(a instanceof ArrayBuffer?l=new Blob([a],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",a),l){const c=URL.createObjectURL(l),h=document.createElement("a");h.href=c;let u=e.downloadAs;!u.endsWith(".glb")&&!u.endsWith(".gltf")&&(u+=e.binary?".glb":".gltf"),h.download=u,h.click()}}return a}const nW=Symbol("needle:weight");class V_e{constructor(){d(this,"_undo",[])}onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const r=Bg.tryGetActionsFromMixer(t);if(r)for(let s=0;s<r.length;s++){const o=r[s];o[nW]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[nW]})}t.update(0)})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function Q_e(n,e,t){n.animations.mixers.forEach(s=>{const o=Bg.tryGetActionsFromMixer(s);if(o)for(let a=0;a<o.length;a++){const l=o[a].getClip();t.push(l)}}),Array.isArray(e)||(e=[e]);for(const s of e)Bg.tryGetAnimationClipsFromObjectHierarchy(s,t);const r=new Set(t);return Array.from(r)}Object.defineProperty(Lt.prototype,"fov",{get:function(){return this._fov},set:function(n){const e=n!==this._fov;this._fov=n,e&&this.view!==void 0&&this.updateProjectionMatrix()}}),Object.defineProperty(Lt.prototype,"near",{get:function(){return this._near},set:function(n){const e=n!==this._near;this._near=n,e&&this.view!==void 0&&this.updateProjectionMatrix()}}),Object.defineProperty(Lt.prototype,"far",{get:function(){return this._far},set:function(n){const e=n!==this._far;this._far=n,e&&this.view!==void 0&&this.updateProjectionMatrix()}});const rW="needle-button",qO=st();var Gm,Vm,Qm,Co,Sl,V0,YO,sW,JO,oW,IE;class KO extends HTMLElement{constructor(){super(),kc(this,YO),kc(this,JO),kc(this,Gm,void 0),kc(this,Vm,void 0),kc(this,Qm,void 0),kc(this,Co,void 0),kc(this,Sl,void 0),kc(this,V0,void 0),kc(this,IE,e=>{qO&&console.log("Needle Button clicked"),!e.defaultPrevented&&vi(this,Co)&&vi(this,Co).click()}),this.removeEventListener("click",vi(this,IE)),this.addEventListener("click",vi(this,IE))}attributeChangedCallback(e,t,r){cL(this,YO,sW).call(this)}}Gm=new WeakMap,Vm=new WeakMap,Qm=new WeakMap,Co=new WeakMap,Sl=new WeakMap,V0=new WeakMap,YO=new WeakSet,sW=function(){var n,e;if((n=vi(this,Co))==null||n.remove(),this.getAttribute("ar")!=null)vi(this,Sl)??Tl(this,Sl,new Am),Tl(this,Co,vi(this,Sl).createARButton());else if(this.getAttribute("vr")!=null)vi(this,Sl)??Tl(this,Sl,new Am),Tl(this,Co,vi(this,Sl).createVRButton());else if(this.getAttribute("quicklook")!=null)vi(this,Sl)??Tl(this,Sl,new Am),Tl(this,Co,vi(this,Sl).createQuicklookButton());else{qO?console.warn("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."):console.debug("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute.");return}vi(this,Gm)??Tl(this,Gm,this.attachShadow({mode:"open"})),vi(this,Vm)??Tl(this,Vm,document.createElement("slot")),vi(this,Qm)??Tl(this,Qm,document.createElement("style")),vi(this,Qm).innerHTML=`
7748
7748
  button {
7749
7749
  all: initial;
7750
7750
  cursor: inherit;
@@ -7778,4 +7778,4 @@ Error:`,a),null}}updateColliderCollisionGroups(n){const e=n[no],t=n.membership;l
7778
7778
  justify-content: center;
7779
7779
  gap: .5rem;
7780
7780
  }
7781
- `),vi(this,Vm).innerHTML=vi(this,Co).innerHTML,vi(this,Vm).style.cssText="display: flex; align-items: center; justify-content: center;",vi(this,Co).innerHTML=vi(this,Vm).outerHTML,vi(this,Gm).innerHTML=vi(this,Co).outerHTML,vi(this,Gm).prepend(vi(this,Qm)),yS(KB,{element:vi(this,Gm)}),(e=vi(this,V0))==null||e.disconnect(),vi(this,V0)??Tl(this,V0,new MutationObserver(()=>cL(this,JO,oW).call(this))),vi(this,V0).observe(vi(this,Co),{attributes:!0}),qO&&console.log("Needle Button updated")},JO=new WeakSet,oW=function(){vi(this,Co)&&(vi(this,Co).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},IE=new WeakMap,d(KO,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(rW)&&window.customElements.define(rW,KO);const RE=te("debugmissingcamera");di.registerCallback(Ci.MissingCamera,n=>{var e,t,r;RE&&console.warn("Creating missing camera");const s=n.context.scene,o=new Lt;o.name="Default Fallback Camera",s.add(o);const a=new Li;a.sourceId=((t=(e=n.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",(r=n.context.domElement.getAttribute("skybox-image"))!=null&&r.length||0>0||n.context.lightmaps.tryGetSkybox(a.sourceId)?a.clearFlags=$u.Skybox:a.clearFlags=$u.SolidColor,a.backgroundColor=new Si(.5,.5,.5,1),a.fieldOfView=35,n.context.domElement.getAttribute("transparent")!=null&&(a.clearFlags=$u.Uninitialized),a.backgroundBlurriness=.2;const l=Zp(o,a,!0);o.position.x=0,o.position.y=1,o.position.z=2;const c=n.context.domElement;return c?.cameraControls!=!1&&aW(n.context,l),l}),di.registerCallback(Ci.ContextCreated,n=>{if(!n.context.mainCamera){RE&&console.log("Will not auto-fit because a default camera exists");return}const e=n.context.domElement;if(e?.cameraControls==!0){const t=$N(n.context.mainCamera);if(t?.isCameraController==!0){RE&&console.log("Will not auto-fit because a camera controller exists");return}aW(n.context)}});function aW(n,e){e=e??n.mainCameraComponent;const t=e?.gameObject;if(RE&&console.log("Creating default camera controls",e?.name),t){const r=pA(t,bi);r.sourceId=e?.sourceId??"unknown";const s=n.domElement.getAttribute("auto-rotate");r.autoRotate=s!==void 0&&(s===""||s==="true"),r.autoRotateSpeed=.5,r.autoFit=!0}else console.warn("Missing camera object, can not add orbit controls")}const PE={Context:kt,glTF:{loadFromURL:OO}};globalThis.Needle!==void 0&&console.warn("Needle Engine is already imported"),globalThis.Needle=PE;function lW(n){for(const e in n)PE[e]=n[e]}lW(rpe),lW(e_e),PE.NeedleXRSession=wt;for(const n of Object.getOwnPropertyNames(ie))switch(n){case"prototype":case"constructor":case"length":case"name":continue;default:PE[n]=ie[n];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=FZ;class H_e{constructor(e){if(this._retries=0,!Number.isInteger(e)||e<0)throw new Error("Backoff must be a positive integer");this.backoff=e}get retries(){return this._retries}get current(){return this.backoff}next(){return this._retries++,this.backoff}reset(){this._retries=0}}class W_e{constructor(e,t){if(this._retries=0,!Number.isInteger(e)||e<0)throw new Error("Base must be a positive integer or zero");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new Error("ExpMax must be a undefined, a positive integer or zero");this.base=e,this.expMax=t,this.i=0}get retries(){return this._retries}get current(){return this.base*Math.pow(2,this.i)}next(){return this._retries++,this.i=this.expMax===void 0?this.i+1:Math.min(this.i+1,this.expMax),this.current}reset(){this._retries=0,this.i=0}}class X_e{constructor(e,t,r){if(this.i=0,this._retries=0,e<0)throw new Error("Initial must be a positive number or zero");if(t<0)throw new Error("Increment must be a positive number or zero");if(r!==void 0&&r<0)throw new Error("Max must be undefined, a positive number or zero");if(r!==void 0&&r<e)throw new Error("Max must be undefined or greater than or equal to initial");this.initial=e,this.increment=t,this.max=r}get retries(){return this._retries}get current(){return this.max===void 0?this.initial+this.increment*this.i:Math.min(this.initial+this.increment*this.i,this.max)}next(){return this._retries++,this.i++,this.current}reset(){this._retries=0,this.i=0}}class q_e{constructor(){this.elements=[]}add(e){this.elements.push(e)}clear(){this.elements.length=0}forEach(e){this.elements.forEach(e)}length(){return this.elements.length}isEmpty(){return this.elements.length===0}peek(){return this.elements[0]}read(){return this.elements.shift()}}class Y_e{constructor(e){if(!Number.isInteger(e)||e<=0)throw new Error("Capacity must be a positive integer");this.elements=new Array(e+1),this.head=0,this.tail=0}add(e){this.elements[this.head]=e,this.head=(this.head+1)%this.elements.length,this.head===this.tail&&(this.tail=(this.tail+1)%this.elements.length)}clear(){this.head=0,this.tail=0}forEach(e){for(let t=this.tail;t!==this.head;t=(t+1)%this.elements.length)e(this.elements[t])}length(){return this.tail===this.head?0:this.tail<this.head?this.head-this.tail:this.elements.length-this.tail+this.head}isEmpty(){return this.head===this.tail}peek(){return this.isEmpty()?void 0:this.elements[this.tail]}read(){const e=this.peek();return e!==void 0&&(this.tail=(this.tail+1)%this.elements.length),e}}var Fi;(function(n){n.open="open",n.close="close",n.error="error",n.message="message",n.retry="retry",n.reconnect="reconnect"})(Fi||(Fi={}));class cW{constructor(e,t,r){var s,o,a,l,c,h,u,p,m,f,g,v,y,A,_;this._closedByUser=!1,this.handleOpenEvent=b=>this.handleEvent(Fi.open,b),this.handleErrorEvent=b=>this.handleEvent(Fi.error,b),this.handleCloseEvent=b=>this.handleEvent(Fi.close,b),this.handleMessageEvent=b=>this.handleEvent(Fi.message,b),this._url=e,this._protocols=t,this._options={buffer:r?.buffer,retry:{maxRetries:(s=r?.retry)===null||s===void 0?void 0:s.maxRetries,instantReconnect:(o=r?.retry)===null||o===void 0?void 0:o.instantReconnect,backoff:(a=r?.retry)===null||a===void 0?void 0:a.backoff},listeners:{open:[...(c=(l=r?.listeners)===null||l===void 0?void 0:l.open)!==null&&c!==void 0?c:[]],close:[...(u=(h=r?.listeners)===null||h===void 0?void 0:h.close)!==null&&u!==void 0?u:[]],error:[...(m=(p=r?.listeners)===null||p===void 0?void 0:p.error)!==null&&m!==void 0?m:[]],message:[...(g=(f=r?.listeners)===null||f===void 0?void 0:f.message)!==null&&g!==void 0?g:[]],retry:[...(y=(v=r?.listeners)===null||v===void 0?void 0:v.retry)!==null&&y!==void 0?y:[]],reconnect:[...(_=(A=r?.listeners)===null||A===void 0?void 0:A.reconnect)!==null&&_!==void 0?_:[]]}},this._underlyingWebsocket=this.tryConnect()}get url(){return this._url}get protocols(){return this._protocols}get buffer(){return this._options.buffer}get maxRetries(){return this._options.retry.maxRetries}get instantReconnect(){return this._options.retry.instantReconnect}get backoff(){return this._options.retry.backoff}get closedByUser(){return this._closedByUser}get lastConnection(){return this._lastConnection}get underlyingWebsocket(){return this._underlyingWebsocket}get readyState(){return this._underlyingWebsocket.readyState}get bufferedAmount(){return this._underlyingWebsocket.bufferedAmount}get extensions(){return this._underlyingWebsocket.extensions}get binaryType(){return this._underlyingWebsocket.binaryType}set binaryType(e){this._underlyingWebsocket.binaryType=e}send(e){this.closedByUser||(this._underlyingWebsocket.readyState===this._underlyingWebsocket.OPEN?this._underlyingWebsocket.send(e):this.buffer!==void 0&&this.buffer.add(e))}close(e,t){this.cancelScheduledConnectionRetry(),this._closedByUser=!0,this._underlyingWebsocket.close(e,t)}addEventListener(e,t,r){this._options.listeners[e].push({listener:t,options:r})}removeEventListener(e,t,r){const s=o=>o.listener!==t||o.options!==r;this._options.listeners[e]=this._options.listeners[e].filter(s)}tryConnect(){return this._underlyingWebsocket=new WebSocket(this.url,this.protocols),this._underlyingWebsocket.addEventListener(Fi.open,this.handleOpenEvent),this._underlyingWebsocket.addEventListener(Fi.close,this.handleCloseEvent),this._underlyingWebsocket.addEventListener(Fi.error,this.handleErrorEvent),this._underlyingWebsocket.addEventListener(Fi.message,this.handleMessageEvent),this._underlyingWebsocket}clearWebsocket(){this._underlyingWebsocket.removeEventListener(Fi.open,this.handleOpenEvent),this._underlyingWebsocket.removeEventListener(Fi.close,this.handleCloseEvent),this._underlyingWebsocket.removeEventListener(Fi.error,this.handleErrorEvent),this._underlyingWebsocket.removeEventListener(Fi.message,this.handleMessageEvent),this._underlyingWebsocket.close()}dispatchEvent(e,t){const r=this._options.listeners[e],s=[];r.forEach(({listener:o,options:a})=>{o(this,t),(a===void 0||a.once===void 0||!a.once)&&s.push({listener:o,options:a})}),this._options.listeners[e]=s}handleEvent(e,t){switch(e){case Fi.close:this.dispatchEvent(e,t),this.scheduleConnectionRetryIfNeeded();break;case Fi.open:if(this.backoff!==void 0&&this._lastConnection!==void 0){const r={retries:this.backoff.retries,lastConnection:new Date(this._lastConnection)},s=new CustomEvent(Fi.reconnect,{detail:r});this.dispatchEvent(Fi.reconnect,s),this.backoff.reset()}this._lastConnection=new Date,this.dispatchEvent(e,t),this.sendBufferedData();break;case Fi.retry:this.dispatchEvent(e,t),this.clearWebsocket(),this.tryConnect();break;default:this.dispatchEvent(e,t);break}}sendBufferedData(){if(this.buffer!==void 0)for(let e=this.buffer.read();e!==void 0;e=this.buffer.read())this.send(e)}scheduleConnectionRetryIfNeeded(){if(this.closedByUser||this.backoff===void 0)return;const e=r=>{const s=new CustomEvent(Fi.retry,{detail:r});this.handleEvent(Fi.retry,s)},t={backoff:this._options.retry.instantReconnect===!0?0:this.backoff.next(),retries:this._options.retry.instantReconnect===!0?0:this.backoff.retries,lastConnection:this._lastConnection};(this._options.retry.maxRetries===void 0||t.retries<=this._options.retry.maxRetries)&&(this.retryTimeout=globalThis.setTimeout(()=>e(t),t.backoff))}cancelScheduledConnectionRetry(){globalThis.clearTimeout(this.retryTimeout)}}class J_e{constructor(e){this._url=e}get url(){return this._url}withProtocols(e){return this._protocols=e,this}get protocols(){return this._protocols}withMaxRetries(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{maxRetries:e})}),this}get maxRetries(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.maxRetries}withInstantReconnect(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{instantReconnect:e})}),this}get instantReconnect(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.instantReconnect}withBackoff(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{backoff:e})}),this}get backoff(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.backoff}withBuffer(e){return this._options=Object.assign(Object.assign({},this._options),{buffer:e}),this}get buffer(){var e;return(e=this._options)===null||e===void 0?void 0:e.buffer}onOpen(e,t){return this.addListener(Fi.open,e,t),this}onClose(e,t){return this.addListener(Fi.close,e,t),this}onError(e,t){return this.addListener(Fi.error,e,t),this}onMessage(e,t){return this.addListener(Fi.message,e,t),this}onRetry(e,t){return this.addListener(Fi.retry,e,t),this}onReconnect(e,t){return this.addListener(Fi.reconnect,e,t),this}build(){return new cW(this._url,this._protocols,this._options)}addListener(e,t,r){var s,o,a,l,c,h,u,p,m,f,g,v,y,A,_,b,x,E,I,T,R;return this._options=Object.assign(Object.assign({},this._options),{listeners:{open:(a=(o=(s=this._options)===null||s===void 0?void 0:s.listeners)===null||o===void 0?void 0:o.open)!==null&&a!==void 0?a:[],close:(h=(c=(l=this._options)===null||l===void 0?void 0:l.listeners)===null||c===void 0?void 0:c.close)!==null&&h!==void 0?h:[],error:(m=(p=(u=this._options)===null||u===void 0?void 0:u.listeners)===null||p===void 0?void 0:p.error)!==null&&m!==void 0?m:[],message:(v=(g=(f=this._options)===null||f===void 0?void 0:f.listeners)===null||g===void 0?void 0:g.message)!==null&&v!==void 0?v:[],retry:(_=(A=(y=this._options)===null||y===void 0?void 0:y.listeners)===null||A===void 0?void 0:A.retry)!==null&&_!==void 0?_:[],reconnect:(E=(x=(b=this._options)===null||b===void 0?void 0:b.listeners)===null||x===void 0?void 0:x.reconnect)!==null&&E!==void 0?E:[],[e]:[...(R=(T=(I=this._options)===null||I===void 0?void 0:I.listeners)===null||T===void 0?void 0:T[e])!==null&&R!==void 0?R:[],{listener:t,options:r}]}}),this}}const K_e=Object.freeze(Object.defineProperty({__proto__:null,ArrayQueue:q_e,ConstantBackoff:H_e,ExponentialBackoff:W_e,LinearBackoff:X_e,RingQueue:Y_e,Websocket:cW,WebsocketBuilder:J_e,get WebsocketEvent(){return Fi}},Symbol.toStringTag,{value:"Module"})),za={node:"node",material:"material",camera:"camera",light:"light"},Hm="KHR_animation_pointer",Z_e={CUBICSPLINE:void 0,LINEAR:Rl,STEP:Yh},hW=Xt.findNode;let uW=!1;class $_e{constructor(e){this.parser=e,this.name=Hm,this.animationPointerResolver=null}setAnimationPointerResolver(e){return this.animationPointerResolver=e,this}_patchPropertyBindingFindNode(){uW||(uW=!0,Xt.findNode=function(e,t){if(t.startsWith(".materials.")){const r=t.substring(11).substring(t.indexOf(".")),s=r.indexOf("."),o=s<0?r:r.substring(0,s);let a=null;return e.traverse(l=>{a!==null||l.type!=="Mesh"&&l.type!=="SkinnedMesh"||l.material&&(l.material.uuid===o||l.material.name===o)&&(a=l.material,a!==null&&(r.endsWith(".map")?a=a.map:r.endsWith(".emissiveMap")&&(a=a.emissiveMap)))}),a}else if(t.startsWith(".nodes.")||t.startsWith(".lights.")||t.startsWith(".cameras.")){const r=t.split(".");let s;for(let o=1;o<r.length;o++){const a=r[o];if(a.length==36)s=e.getObjectByProperty("uuid",a);else if(s&&s[a]){const l=Number.parseInt(a);let c=a;l>=0&&(c=l),s=s[c]}else{const l=e.getObjectByName(a);l&&(s=l)}}if(!s){const o=hW(e,r[2]);return o||console.warn(Hm+": Property binding not found",t,e,e.name,r),o}return s}return hW(e,t)})}loadAnimationTargetFromChannel(e){const t=e.target,r=t.node!==void 0?t.node:t.id;return this.parser.getDependency("node",r)}loadAnimationTargetFromChannelWithAnimationPointer(e){this._havePatchedPropertyBindings||this._patchPropertyBindingFindNode();const t=e.target,r=t.extensions&&t.extensions[Hm]&&t.path&&t.path==="pointer";if(!r)return null;let s,o=za.node,a;if(r){const c=t.extensions[Hm];let h=c.pointer;if(!h){console.warn("Invalid path",c,t);return}if(h.startsWith("/materials/")?o=za.material:h.startsWith("/extensions/KHR_lights_punctual/lights/")?o=za.light:h.startsWith("/cameras/")&&(o=za.camera),a=this._tryResolveTargetId(h,o),a===null||isNaN(a)){console.warn("Failed resolving animation node id: "+a,h);return}switch(o){case za.material:const p=("/materials/"+a.toString()+"/").length,m=h.substring(0,p);switch(s=h.substring(p),s){case"pbrMetallicRoughness/baseColorFactor":s="color";break;case"pbrMetallicRoughness/roughnessFactor":s="roughness";break;case"pbrMetallicRoughness/metallicFactor":s="metalness";break;case"emissiveFactor":s="emissive";break;case"alphaCutoff":s="alphaTest";break;case"occlusionTexture/strength":s="aoMapIntensity";break;case"normalTexture/scale":s="normalScale";break;case"pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale":s="map/repeat";break;case"pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset":s="map/offset";break;case"emissiveTexture/extensions/KHR_texture_transform/scale":s="emissiveMap/repeat";break;case"emissiveTexture/extensions/KHR_texture_transform/offset":s="emissiveMap/offset";break;case"extensions/KHR_materials_emissive_strength/emissiveStrength":s="emissiveIntensity";break;case"extensions/KHR_materials_transmission/transmissionFactor":s="transmission";break;case"extensions/KHR_materials_ior/ior":s="ior";break;case"extensions/KHR_materials_volume/thicknessFactor":s="thickness";break;case"extensions/KHR_materials_volume/attenuationColor":s="attenuationColor";break;case"extensions/KHR_materials_volume/attenuationDistance":s="attenuationDistance";break;case"extensions/KHR_materials_iridescence/iridescenceFactor":s="iridescence";break;case"extensions/KHR_materials_iridescence/iridescenceIor":s="iridescenceIOR";break;case"extensions/KHR_materials_iridescence/iridescenceThicknessMinimum":s="iridescenceThicknessRange[0]";break;case"extensions/KHR_materials_iridescence/iridescenceThicknessMaximum":s="iridescenceThicknessRange[1]";break;case"extensions/KHR_materials_clearcoat/clearcoatFactor":s="clearcoat";break;case"extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor":s="clearcoatRoughness";break;case"extensions/KHR_materials_sheen/sheenColorFactor":s="sheenColor";break;case"extensions/KHR_materials_sheen/sheenRoughnessFactor":s="sheenRoughness";break;case"extensions/KHR_materials_specular/specularFactor":s="specularIntensity";break;case"extensions/KHR_materials_specular/specularColorFactor":s="specularColor";break}h=m+s;break;case za.node:const f=("/nodes/"+a.toString()+"/").length,g=h.substring(0,f);switch(s=h.substring(f),s){case"translation":s="position";break;case"rotation":s="quaternion";break;case"scale":s="scale";break;case"weights":s="morphTargetInfluences";break}h=g+s;break;case za.light:const v=("/extensions/KHR_lights_punctual/lights/"+a.toString()+"/").length;switch(s=h.substring(v),s){case"color":break;case"intensity":break;case"spot/innerConeAngle":s="penumbra";break;case"spot/outerConeAngle":s="angle";break;case"range":s="distance";break}h="/lights/"+a.toString()+"/"+s;break;case za.camera:const y=("/cameras/"+a.toString()+"/").length,A=h.substring(0,y);switch(s=h.substring(y),s){case"perspective/yfov":s="fov";break;case"perspective/znear":case"orthographic/znear":s="near";break;case"perspective/zfar":case"orthographic/zfar":s="far";break;case"perspective/aspect":s="aspect";break;case"orthographic/xmag":s="zoom";break;case"orthographic/ymag":s="zoom";break}h=A+s;break}const u=this.animationPointerResolver;u&&u.resolvePath&&(h=u.resolvePath(h)),t.extensions[Hm].pointer=h}if(a===null||isNaN(a)){console.warn("Failed resolving animation node id: "+a,t);return}let l;return o===za.node?l=this.parser.getDependency("node",a):o===za.material?l=this.parser.getDependency("material",a):o===za.light?l=this.parser.getDependency("light",a):o===za.camera?l=this.parser.getDependency("camera",a):console.error("Unhandled type",o),l}createAnimationTracksWithAnimationPointer(e,t,r,s,o){if(!(o.extensions&&o.extensions[Hm]&&o.path&&o.path==="pointer"))return null;let a=o.extensions[Hm].pointer;if(!a)return null;const l=[];a=a.replaceAll("/",".");const c=a.split(".");var h=e.name!==void 0&&e.name!==null?e.name:e.uuid;if(c[2]=h,c[3]==="morphTargetInfluences"&&e.type==="Group"){for(const p of e.children)p instanceof uo&&p.morphTargetInfluences&&(c[3]=p.name,c[4]="morphTargetInfluences",u(this.parser));return l}u(this.parser);function u(p){a=c.join(".");let m;switch(r.itemSize){case 1:m=Xc;break;case 2:case 3:m=kl;break;case 4:a.endsWith(".quaternion")?m=sa:m=kx;break}const f=s.interpolation!==void 0?Z_e[s.interpolation]:Rl;let g=p._getArrayFromAccessor(r);a.endsWith(".fov")&&(g=g.map(y=>y/Math.PI*180));const v=new m(a,t.array,g,f);if(f==="CUBICSPLINE"&&p._createCubicSplineTrackInterpolant(v),l.push(v),a&&r.itemSize===4&&a.startsWith(".materials.")&&a.endsWith(".color")){const y=new Float32Array(g.length/4);for(let _=0,b=g.length/4;_<b;_+=1)y[_]=g[_*4+3];const A=new m(a.replace(".color",".opacity"),t.array,y,f);f==="CUBICSPLINE"&&p._createCubicSplineTrackInterpolant(v),l.push(A)}}return l}_tryResolveTargetId(e,t){let r="";return t==="node"?r=e.substring(7):t==="material"?r=e.substring(11):t==="light"?r=e.substring(39):t==="camera"&&(r=e.substring(9)),r=r.substring(0,r.indexOf("/")),Number.parseInt(r)}loadAnimation(e){const t=this,r=this.parser.json,s=this.parser,o=r.animations[e],a=o.name?o.name:"animation_"+e,l=[],c=[],h=[],u=[],p=[];for(let m=0,f=o.channels.length;m<f;m++){const g=o.channels[m],v=o.samplers[g.sampler],y=g.target,A=o.parameters!==void 0?o.parameters[v.input]:v.input,_=o.parameters!==void 0?o.parameters[v.output]:v.output;let b=t.loadAnimationTargetFromChannelWithAnimationPointer(g);b||(b=t.loadAnimationTargetFromChannel(g)),l.push(b),c.push(s.getDependency("accessor",A)),h.push(s.getDependency("accessor",_)),u.push(v),p.push(y)}return Promise.all([Promise.all(l),Promise.all(c),Promise.all(h),Promise.all(u),Promise.all(p)]).then(function(m){const f=m[0],g=m[1],v=m[2],y=m[3],A=m[4],_=[];for(let b=0,x=f.length;b<x;b++){const E=f[b],I=g[b],T=v[b],R=y[b],D=A[b];if(E===void 0)continue;E.updateMatrix&&(E.updateMatrix(),E.matrixAutoUpdate=!0);let M=t.createAnimationTracksWithAnimationPointer(E,I,T,R,D);if(M||(M=s._createAnimationTracks(E,I,T,R,D)),M)for(let P=0;P<M.length;P++)_.push(M[P])}return new zs(a,void 0,_)})}}const exe=Object.freeze(Object.defineProperty({__proto__:null,GLTFAnimationPointerExtension:$_e},Symbol.toStringTag,{value:"Module"}));export{k_e as $physicsKey,gi as ActionBuilder,PP as ActionCollection,_a as ActionModel,E6 as Addressables,vA as AlignmentConstraint,Ng as AmbientMode,Es as Animation,im as AnimationCurve,BA as AnimationExtension,HS as AnimationTrackHandler,Bg as AnimationUtils,Wr as Animator,nd as AnimatorConditionMode,ea as AnimatorController,bk as AnimatorControllerParameterType,PA as AnimatorStateInfo,DA as Antialiasing,Qu as Application,cS as ApplicationEvents,R5 as AssetDatabase,ti as AssetReference,Pd as AudioExtension,ed as AudioListener,Mn as AudioSource,IA as AudioTrackHandler,od as Avatar,am as AvatarBlink_Simple,e0 as AvatarEyeLook_Rotation,Pk as AvatarLoader,Yr as AvatarMarker,eC as AvatarModel,NA as Avatar_Brain_LookAt,jA as Avatar_MouthShapes,Tk as Avatar_MustacheShake,sc as Avatar_POI,Wg as Axes,t0 as AxesHelper,DR as BUILD_TIME,Va as BaseUIComponent,kk as BasicIKConstraint,tC as BehaviorExtension,Ar as BehaviorModel,Be as Behaviour,lm as BloomEffect,n0 as BoxCollider,hm as BoxGizmo,ac as BoxHelperComponent,Eh as Button,yh as ButtonsFactory,L8 as CallDirection,Qg as CallInfo,Li as Camera,SA as CameraTargetReachedEvent,Jr as Canvas,hd as CanvasGroup,Ch as CapsuleCollider,o0 as ChangeMaterialOnClick,pm as ChangeTransformOnClick,gm as CharacterController,Th as CharacterControllerInput,JA as ChromaticAberration,oa as CircularBuffer,$u as ClearFlags,ec as ClipExtrapolation,Vo as Collider,J9 as Collision,LS as CollisionDetectionMode,pd as ColorAdjustments,ym as ColorBySpeedModule,sb as ColorOverLifetimeModule,Be as Component,Uy as ComponentEvents,Ny as ComponentLifecycleEvents,rV as ConnectionEvents,Y9 as ContactPoint,dc as ContactShadows,kt as Context,Hde as ContextArgs,Ci as ContextEvent,di as ContextRegistry,WS as ControlTrackHandler,bd as CustomBranding,Al as CustomShader,gS as DefaultReflectionMode,AD as Deletable,DC as DeleteBox,xl as DepthOfField,OC as DeviceFlag,bD as DocumentExtension,La as DragControls,IQ as DragMode,_d as DropListener,Em as Duplicatable,mb as EffectWrapper,uc as EmissionModule,l0 as EmphasizeOnClick,zR as EngineLoadingView,Un as EventList,BS as EventListEvent,Ta as EventSystem,UC as EventTrigger,oD as FieldWithDefault,W1 as FileReference,T6 as FileReferenceSerializer,kQ as FileSpawnModel,BQ as File_Event,ED as FixedJoint,MD as FlyControls,_0 as Fog,Hi as FrameEvent,bw as GENERATOR,ie as GameObject,At as Gizmos,yb as GltfExport,kD as GltfExportBox,Nm as GltfLoadEvent,f9 as GltfLoadEventType,fd as Gradient,um as Graphic,FS as GraphicRaycaster,ha as Graphics,S0 as GridHelper,Wk as GridLayoutGroup,Yu as GroundProjectedEnv,ku as GroupActionModel,VV as HideFlags,Yk as HideOnStart,fb as HingeJoint,Hk as HorizontalLayoutGroup,Xde as HostData,s0 as Image,Q1 as ImageReference,M6 as ImageReferenceSerializer,vd as InheritVelocityModule,D6 as Input,ql as InputEventQueue,an as InputEvents,Mm as InputField,$A as InstanceHandle,ZA as InstancingHandler,Qa as InstancingUtil,LV as InstantiateEvent,Dr as InstantiateIdProvider,Ml as InstantiateOptions,yD as Interactable,pde as JoinedRoomResponse,xue as KeyEventArgs,Ea as Keyframe,bb as LODGroup,Tm as LODModel,mde as LeftRoomResponse,wo as Light,CV as LightData,Kn as LimitVelocityOverLifetimeModule,Cne as LoadingElementOptions,FD as LogStats,Bo as LogType,Im as LookAt,nm as LookAtConstraint,Zr as MainModule,vk as MarkerType,WA as MaskableGraphic,it as Mathf,cm as MeshCollider,ib as MeshRenderer,pt as MinMaxCurve,_o as MinMaxGradient,fi as NEEDLE_progressive,Xy as NEKeyboardEvent,mh as NEPointerEvent,KO as NeedleButtonElement,di as NeedleEngine,LO as NeedleEngineHTMLElement,kO as NeedleGltfLoader,pc as NeedleMenu,T1 as NeedlePatchesKey,i5 as NeedleUSDZExporter,vB as NeedleXRController,wt as NeedleXRSession,aV as NeedleXRSync,uV as NeedleXRUtils,HC as NestedGltf,oV as NetworkConnection,oc as NetworkedStreamEvents,o_ as NetworkedStreams,E0 as Networking,UV as NewInstanceModel,Ii as NoiseModule,No as ObjectRaycaster,sA as ObjectUtils,Rm as OffsetConstraint,fw as OneEuroFilter,gR as OneEuroFilterXYZ,M0 as OpenURL,bi as OrbitControls,r0 as Outline,sV as OwnershipEvent,jB as OwnershipModel,ld as Padding,rb as ParticleBurst,aE as ParticleSubEmitter,$n as ParticleSystem,Sd as ParticleSystemBaseBehaviour,Fa as ParticleSystemRenderer,AC as ParticleSystemShapeType,ZS as PeerHandle,tV as PeerNetworking,AV as Physics,RC as PhysicsExtension,Cr as PhysicsMaterialCombine,Rb as PixelationEffect,fm as PlayAnimationOnClick,ud as PlayAudioOnClick,id as PlayableDirector,J0 as PlayerColor,Pa as PlayerState,R8 as PlayerStateEvent,Kg as PlayerSync,bV as PlayerView,_V as PlayerViewManager,q0 as PointerEventData,q1 as PointerType,Xr as PostProcessingEffect,lE as PostProcessingHandler,D0 as PostProcessingManager,c0 as PreliminaryAction,qA as PreliminaryTrigger,Yp as PrimitiveType,ni as Progress,tw as PromiseAllWithErrors,kI as PromiseErrorResult,Si as RGBAColor,e_ as RapierPhysics,sC as RawImage,ml as RaycastOptions,jk as Rect,Ts as RectTransform,u0 as ReflectionProbe,JS as RegisteredAnimationInfo,wc as RemoteSkybox,Hg as RenderTexture,l8 as RenderTextureSerializer,Tn as Renderer,SV as RendererData,eb as RendererLightmap,Oi as Rigidbody,Nn as RigidbodyConstraints,Vt as RoomEvents,Wo as RotationBySpeedModule,Ba as RotationOverLifetimeModule,mC as SceneLightSettings,ks as SceneSwitcher,Ed as ScreenCapture,Oh as ScreenSpaceAmbientOcclusion,wl as ScreenSpaceAmbientOcclusionN8,dl as SendQueue,oB as SerializationContext,mm as SetActiveOnClick,Lb as ShadowCatcher,vn as ShapeModule,Bb as SharpeningEffect,EA as SignalAsset,Yg as SignalReceiver,qg as SignalReceiverEvent,RA as SignalTrackHandler,zk as Size,to as SizeBySpeedModule,gd as SizeOverLifetimeModule,aD as SkinnedMeshRenderer,Md as SmoothFollow,wA as SpatialGrabRaycaster,Fb as SpatialHtml,zb as SpatialTrigger,Sc as SpatialTriggerReceiver,pE as SpectatorCamera,i0 as SphereCollider,yV as SphereIntersection,K9 as SphereOverlapResult,kh as Sprite,v0 as SpriteData,ka as SpriteRenderer,lb as SpriteSheet,cme as StateMachineBehaviour,D8 as StreamEndedEvent,O8 as StreamReceivedEvent,Ib as SubEmitterSystem,fE as SyncedCamera,Cc as SyncedRoom,Ku as SyncedTransform,Jk as TapGestureTrigger,IC as TeleportTarget,xO as TestRunner,L_e as TestSceneUtils,wO as TestSimulateUserData,Rs as Text,PC as TextBuilder,hb as TextExtension,$r as TextureSheetAnimationModule,Ec as TiltShiftEffect,MV as Time,dd as ToneMappingEffect,MA as TrackHandler,zo as TrackType,cn as TrailModule,Tr as TransformData,Lm as TransformGizmo,br as TriggerBuilder,Up as TriggerModel,q as TypeStore,US as UIRaycastUtils,_A as UIRootComponent,Ws as USDObject,t5 as USDWriter,Rn as USDZExporter,Ad as USDZText,BC as USDZUIExtension,hB as Upload_Result,c8 as UriSerializer,db as UsageMarker,fde as UserJoinedOrLeftRoomModel,el as VERSION,RP as VariantAction,yn as VelocityOverLifetimeModule,Qk as VerticalLayoutGroup,dr as VideoPlayer,Wu as ViewDevice,Fm as Vignette,YA as VisibilityAction,om as Voip,D0 as Volume,qe as VolumeParameter,kA as VolumeProfile,xde as WaitForFrames,mV as WaitForPromise,pV as WaitForSeconds,Nh as Watch,AE as WebARCameraBackground,io as WebARSessionRoot,Ir as WebXR,Am as WebXRButtonFactory,L0 as WebXRImageTracking,Mc as WebXRImageTrackingModel,Td as WebXRPlaneTracking,O0 as WebXRTrackedImage,Lh as XRControllerFollow,fc as XRControllerModel,Da as XRControllerMovement,Go as XRFlag,bE as XRRig,eo as XRState,rc as XRStateFlag,TO as __Ignore,O5 as __internalNotifyObjectDestroyed,$c as activeInHierarchyFieldName,GU as addAttributeChangeCallback,gl as addComponent,vge as addCustomExtensionPlugin,DQ as addFile,OQ as addFileFromUrl,a_e as addGltfLoadEventListener,Zp as addNewComponent,M1 as addPatch,IS as apply,A_e as applyHMRChanges,FV as beginListenDestroy,LQ as beginListenFileSpawn,NV as beginListenInstantiate,xB as binaryIdentifierCasts,Qde as build_scene_functions,wp as builtinComponentKeyName,UR as calculateProgress01,JU as clearBalloonMessages,JU as clearOverlayMessages,mpe as colorSerializer,p6 as compareAssociation,kS as componentSerializer,az as copyTexture,DO as createLoader,w8 as createMotion,Zs as debugNet,nA as debugOwner,Nv as deepClone,Ll as delay,NU as delayForFrames,j1 as deserializeObject,Ca as destroy,e8 as destroyComponentInstance,Qi as disposeObjectResources,Sh as disposeStream,C6 as download,dB as download_file,Kv as editorGuidKeyName,dO as effectsOrder,Nf as enableSpatialConsole,gpe as euler,_pe as eventListSerializer,G_e as exportAsGLTF,dA as findByGuid,PS as findObjectOfType,n8 as findObjectsOfType,NP as findResourceUsers,lz as fitObjectIntoVolume,Kp as foreachComponent,TS as foreachComponentEnumerator,Vie as forward,QU as generateQRCode,xS as generateSeed,Ul as getBoundingBox,$N as getCameraController,$p as getComponent,fA as getComponentInChildren,gA as getComponentInParent,mA as getComponents,Vg as getComponentsInChildren,RS as getComponentsInParent,Kj as getFormattedDate,Ao as getIconElement,YB as getIconTexture,qZ as getIp,YZ as getIpAndLocation,XZ as getIpCloudflare,Ka as getLoader,pA as getOrAddComponent,te as getParam,Wie as getParentHierarchyPath,VZ as getPath,cde as getPeerOptions,$G as getPeerjsInstance,Tle as getResourceUserCount,bp as getTempQuaternion,pi as getTempVector,Uv as getUrlParams,SR as getWorldDirection,CR as getWorldEuler,Bt as getWorldPosition,Mi as getWorldQuaternion,Wv as getWorldRotation,Vi as getWorldScale,eh as hasCommercialLicense,OR as hasIndieLicense,uk as hasPointerEventComponent,uu as hasProLicense,uB as hash,pz as hideDebugConsole,s5 as imageToCanvas,Gg as instantiate,sD as invokeAfterImportPluginHooks,R6 as invokeXRSessionEnd,I6 as invokeXRSessionStart,QV as isActiveInHierarchy,jg as isActiveSelf,jU as isAndroidDevice,oz as isAnimationAction,NZ as isDebugMode,fp as isDesktop,Jp as isDestroyed,st as isDevEnvironment,Ele as isDisposed,U_e as isExporting,kU as isHostedOnGlitch,f_e as isHotReloading,RV as isIconElement,js as isLocalNetwork,aa as isMobileDevice,gp as isMozillaXR,ew as isQuest,B5 as isResourceTrackingEnabled,Lf as isSafari,CS as isUsingInstancing,vp as isiOS,OO as loadSync,yw as logHierarchy,Fie as lookAtInverse,Hv as lookAtObject,jZ as makeId,RI as makeIdFromRandomWords,ul as makeNameSafeForUSD,HV as markAsInstancedRendered,BI as microphonePermissionsGranted,UZ as nameof,DU as nameofFactory,a8 as objectSerializer,due as offXRSessionEnd,uue as offXRSessionStart,kpe as onAfterRender,Bpe as onBeforeRender,Rpe as onClear,Ppe as onDestroy,Ipe as onInitialized,f8 as onStart,g8 as onUpdate,mB as onXRSessionEnd,X1 as onXRSessionStart,v9 as parseSync,cz as placeOnSurface,TR as postprocessFBXMaterials,Ope as prefix,OU as pushState,GZ as randomNumber,wB as registerBinaryType,bS as registerComponent,iD as registerComponentExtension,Ra as registerCustomEffectType,rD as registerExportExtensions,nD as registerExtensions,g_e as registerHotReloadType,CI as registerLoader,jV as registerPrefabProvider,$ae as registerType,zU as relativePathPrefix,VU as removeAttributeChangeCallback,rk as removeComponent,yge as removeCustomImportExtensionType,l_e as removeGltfLoadEventListener,xle as removePatch,cu as resolveUrl,UU as sanitizeString,eW as saveImage,F_e as screenshot,$9 as screenshot2,$B as sendDestroyed,w as serializable,v6 as serializeObject,Eg as serializeable,uA as setActive,qU as setAllowBalloonMessages,$Z as setAllowOverlayMessages,AR as setAutoFitEnabled,vR as setCameraController,XV as setDestroyed,ene as setDevEnvironment,UP as setDisposable,ik as setDontDestroy,TI as setOrAddParamsToUrl,zZ as setParam,Jx as setParamWithoutReload,hde as setPeerOptions,Cle as setResourceTrackingEnabled,II as setState,ER as setWorldEuler,lr as setWorldPosition,_p as setWorldPositionXYZ,ca as setWorldQuaternion,wR as setWorldQuaternionXYZW,MR as setWorldRotation,Xv as setWorldRotationXYZ,Uf as setWorldScale,IR as showBalloonError,rn as showBalloonMessage,Di as showBalloonWarning,kR as showDebugConsole,Oie as slerp,hA as syncDestroy,Ek as syncField,ek as syncInstantiate,Xie as textureToCanvas,N6 as tryCastBinary,d9 as tryDetermineFileTypeFromBinary,u9 as tryDetermineFileTypeFromURL,Df as tryFindObject,z6 as tryGetGuid,v_e as unregisterHotReloadType,PI as unwatchWrite,S6 as upload_file,ez as useForAutoFit,Hr as validate,Zx as watchWrite};
7781
+ `),vi(this,Vm).innerHTML=vi(this,Co).innerHTML,vi(this,Vm).style.cssText="display: flex; align-items: center; justify-content: center;",vi(this,Co).innerHTML=vi(this,Vm).outerHTML,vi(this,Gm).innerHTML=vi(this,Co).outerHTML,vi(this,Gm).prepend(vi(this,Qm)),yS(KB,{element:vi(this,Gm)}),(e=vi(this,V0))==null||e.disconnect(),vi(this,V0)??Tl(this,V0,new MutationObserver(()=>cL(this,JO,oW).call(this))),vi(this,V0).observe(vi(this,Co),{attributes:!0}),qO&&console.log("Needle Button updated")},JO=new WeakSet,oW=function(){vi(this,Co)&&(vi(this,Co).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},IE=new WeakMap,d(KO,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(rW)&&window.customElements.define(rW,KO);const RE=te("debugmissingcamera");di.registerCallback(Ci.MissingCamera,n=>{var e,t,r;RE&&console.warn("Creating missing camera");const s=n.context.scene,o=new Lt;o.name="Default Fallback Camera",s.add(o);const a=new Li;a.sourceId=((t=(e=n.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",(r=n.context.domElement.getAttribute("skybox-image"))!=null&&r.length||0>0||n.context.lightmaps.tryGetSkybox(a.sourceId)?a.clearFlags=$u.Skybox:a.clearFlags=$u.SolidColor,a.backgroundColor=new Si(.5,.5,.5,1),a.fieldOfView=35,n.context.domElement.getAttribute("transparent")!=null&&(a.clearFlags=$u.Uninitialized),a.backgroundBlurriness=.2;const l=Zp(o,a,!0);o.position.x=0,o.position.y=1,o.position.z=2;const c=n.context.domElement;return c?.cameraControls!=!1&&aW(n.context,l),l}),di.registerCallback(Ci.ContextCreated,n=>{if(!n.context.mainCamera){RE&&console.log("Will not auto-fit because a default camera exists");return}const e=n.context.domElement;if(e?.cameraControls==!0){const t=$N(n.context.mainCamera);if(t?.isCameraController==!0){RE&&console.log("Will not auto-fit because a camera controller exists");return}aW(n.context)}});function aW(n,e){e=e??n.mainCameraComponent;const t=e?.gameObject;if(RE&&console.log("Creating default camera controls",e?.name),t){const r=pA(t,bi);r.sourceId=e?.sourceId??"unknown";const s=n.domElement.getAttribute("auto-rotate");r.autoRotate=s!==void 0&&(s===""||s==="true"),r.autoRotateSpeed=.5,r.autoFit=!0}else console.warn("Missing camera object, can not add orbit controls")}const PE={Context:kt,glTF:{loadFromURL:OO}};globalThis.Needle!==void 0&&console.warn("Needle Engine is already imported"),globalThis.Needle=PE;function lW(n){for(const e in n)PE[e]=n[e]}lW(rpe),lW(e_e),PE.NeedleXRSession=wt;for(const n of Object.getOwnPropertyNames(ie))switch(n){case"prototype":case"constructor":case"length":case"name":continue;default:PE[n]=ie[n];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=FZ;class H_e{constructor(e){if(this._retries=0,!Number.isInteger(e)||e<0)throw new Error("Backoff must be a positive integer");this.backoff=e}get retries(){return this._retries}get current(){return this.backoff}next(){return this._retries++,this.backoff}reset(){this._retries=0}}class W_e{constructor(e,t){if(this._retries=0,!Number.isInteger(e)||e<0)throw new Error("Base must be a positive integer or zero");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new Error("ExpMax must be a undefined, a positive integer or zero");this.base=e,this.expMax=t,this.i=0}get retries(){return this._retries}get current(){return this.base*Math.pow(2,this.i)}next(){return this._retries++,this.i=this.expMax===void 0?this.i+1:Math.min(this.i+1,this.expMax),this.current}reset(){this._retries=0,this.i=0}}class X_e{constructor(e,t,r){if(this.i=0,this._retries=0,e<0)throw new Error("Initial must be a positive number or zero");if(t<0)throw new Error("Increment must be a positive number or zero");if(r!==void 0&&r<0)throw new Error("Max must be undefined, a positive number or zero");if(r!==void 0&&r<e)throw new Error("Max must be undefined or greater than or equal to initial");this.initial=e,this.increment=t,this.max=r}get retries(){return this._retries}get current(){return this.max===void 0?this.initial+this.increment*this.i:Math.min(this.initial+this.increment*this.i,this.max)}next(){return this._retries++,this.i++,this.current}reset(){this._retries=0,this.i=0}}class q_e{constructor(){this.elements=[]}add(e){this.elements.push(e)}clear(){this.elements.length=0}forEach(e){this.elements.forEach(e)}length(){return this.elements.length}isEmpty(){return this.elements.length===0}peek(){return this.elements[0]}read(){return this.elements.shift()}}class Y_e{constructor(e){if(!Number.isInteger(e)||e<=0)throw new Error("Capacity must be a positive integer");this.elements=new Array(e+1),this.head=0,this.tail=0}add(e){this.elements[this.head]=e,this.head=(this.head+1)%this.elements.length,this.head===this.tail&&(this.tail=(this.tail+1)%this.elements.length)}clear(){this.head=0,this.tail=0}forEach(e){for(let t=this.tail;t!==this.head;t=(t+1)%this.elements.length)e(this.elements[t])}length(){return this.tail===this.head?0:this.tail<this.head?this.head-this.tail:this.elements.length-this.tail+this.head}isEmpty(){return this.head===this.tail}peek(){return this.isEmpty()?void 0:this.elements[this.tail]}read(){const e=this.peek();return e!==void 0&&(this.tail=(this.tail+1)%this.elements.length),e}}var Fi;(function(n){n.open="open",n.close="close",n.error="error",n.message="message",n.retry="retry",n.reconnect="reconnect"})(Fi||(Fi={}));class cW{constructor(e,t,r){var s,o,a,l,c,h,u,p,m,f,g,v,y,A,_;this._closedByUser=!1,this.handleOpenEvent=b=>this.handleEvent(Fi.open,b),this.handleErrorEvent=b=>this.handleEvent(Fi.error,b),this.handleCloseEvent=b=>this.handleEvent(Fi.close,b),this.handleMessageEvent=b=>this.handleEvent(Fi.message,b),this._url=e,this._protocols=t,this._options={buffer:r?.buffer,retry:{maxRetries:(s=r?.retry)===null||s===void 0?void 0:s.maxRetries,instantReconnect:(o=r?.retry)===null||o===void 0?void 0:o.instantReconnect,backoff:(a=r?.retry)===null||a===void 0?void 0:a.backoff},listeners:{open:[...(c=(l=r?.listeners)===null||l===void 0?void 0:l.open)!==null&&c!==void 0?c:[]],close:[...(u=(h=r?.listeners)===null||h===void 0?void 0:h.close)!==null&&u!==void 0?u:[]],error:[...(m=(p=r?.listeners)===null||p===void 0?void 0:p.error)!==null&&m!==void 0?m:[]],message:[...(g=(f=r?.listeners)===null||f===void 0?void 0:f.message)!==null&&g!==void 0?g:[]],retry:[...(y=(v=r?.listeners)===null||v===void 0?void 0:v.retry)!==null&&y!==void 0?y:[]],reconnect:[...(_=(A=r?.listeners)===null||A===void 0?void 0:A.reconnect)!==null&&_!==void 0?_:[]]}},this._underlyingWebsocket=this.tryConnect()}get url(){return this._url}get protocols(){return this._protocols}get buffer(){return this._options.buffer}get maxRetries(){return this._options.retry.maxRetries}get instantReconnect(){return this._options.retry.instantReconnect}get backoff(){return this._options.retry.backoff}get closedByUser(){return this._closedByUser}get lastConnection(){return this._lastConnection}get underlyingWebsocket(){return this._underlyingWebsocket}get readyState(){return this._underlyingWebsocket.readyState}get bufferedAmount(){return this._underlyingWebsocket.bufferedAmount}get extensions(){return this._underlyingWebsocket.extensions}get binaryType(){return this._underlyingWebsocket.binaryType}set binaryType(e){this._underlyingWebsocket.binaryType=e}send(e){this.closedByUser||(this._underlyingWebsocket.readyState===this._underlyingWebsocket.OPEN?this._underlyingWebsocket.send(e):this.buffer!==void 0&&this.buffer.add(e))}close(e,t){this.cancelScheduledConnectionRetry(),this._closedByUser=!0,this._underlyingWebsocket.close(e,t)}addEventListener(e,t,r){this._options.listeners[e].push({listener:t,options:r})}removeEventListener(e,t,r){const s=o=>o.listener!==t||o.options!==r;this._options.listeners[e]=this._options.listeners[e].filter(s)}tryConnect(){return this._underlyingWebsocket=new WebSocket(this.url,this.protocols),this._underlyingWebsocket.addEventListener(Fi.open,this.handleOpenEvent),this._underlyingWebsocket.addEventListener(Fi.close,this.handleCloseEvent),this._underlyingWebsocket.addEventListener(Fi.error,this.handleErrorEvent),this._underlyingWebsocket.addEventListener(Fi.message,this.handleMessageEvent),this._underlyingWebsocket}clearWebsocket(){this._underlyingWebsocket.removeEventListener(Fi.open,this.handleOpenEvent),this._underlyingWebsocket.removeEventListener(Fi.close,this.handleCloseEvent),this._underlyingWebsocket.removeEventListener(Fi.error,this.handleErrorEvent),this._underlyingWebsocket.removeEventListener(Fi.message,this.handleMessageEvent),this._underlyingWebsocket.close()}dispatchEvent(e,t){const r=this._options.listeners[e],s=[];r.forEach(({listener:o,options:a})=>{o(this,t),(a===void 0||a.once===void 0||!a.once)&&s.push({listener:o,options:a})}),this._options.listeners[e]=s}handleEvent(e,t){switch(e){case Fi.close:this.dispatchEvent(e,t),this.scheduleConnectionRetryIfNeeded();break;case Fi.open:if(this.backoff!==void 0&&this._lastConnection!==void 0){const r={retries:this.backoff.retries,lastConnection:new Date(this._lastConnection)},s=new CustomEvent(Fi.reconnect,{detail:r});this.dispatchEvent(Fi.reconnect,s),this.backoff.reset()}this._lastConnection=new Date,this.dispatchEvent(e,t),this.sendBufferedData();break;case Fi.retry:this.dispatchEvent(e,t),this.clearWebsocket(),this.tryConnect();break;default:this.dispatchEvent(e,t);break}}sendBufferedData(){if(this.buffer!==void 0)for(let e=this.buffer.read();e!==void 0;e=this.buffer.read())this.send(e)}scheduleConnectionRetryIfNeeded(){if(this.closedByUser||this.backoff===void 0)return;const e=r=>{const s=new CustomEvent(Fi.retry,{detail:r});this.handleEvent(Fi.retry,s)},t={backoff:this._options.retry.instantReconnect===!0?0:this.backoff.next(),retries:this._options.retry.instantReconnect===!0?0:this.backoff.retries,lastConnection:this._lastConnection};(this._options.retry.maxRetries===void 0||t.retries<=this._options.retry.maxRetries)&&(this.retryTimeout=globalThis.setTimeout(()=>e(t),t.backoff))}cancelScheduledConnectionRetry(){globalThis.clearTimeout(this.retryTimeout)}}class J_e{constructor(e){this._url=e}get url(){return this._url}withProtocols(e){return this._protocols=e,this}get protocols(){return this._protocols}withMaxRetries(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{maxRetries:e})}),this}get maxRetries(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.maxRetries}withInstantReconnect(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{instantReconnect:e})}),this}get instantReconnect(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.instantReconnect}withBackoff(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{backoff:e})}),this}get backoff(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.backoff}withBuffer(e){return this._options=Object.assign(Object.assign({},this._options),{buffer:e}),this}get buffer(){var e;return(e=this._options)===null||e===void 0?void 0:e.buffer}onOpen(e,t){return this.addListener(Fi.open,e,t),this}onClose(e,t){return this.addListener(Fi.close,e,t),this}onError(e,t){return this.addListener(Fi.error,e,t),this}onMessage(e,t){return this.addListener(Fi.message,e,t),this}onRetry(e,t){return this.addListener(Fi.retry,e,t),this}onReconnect(e,t){return this.addListener(Fi.reconnect,e,t),this}build(){return new cW(this._url,this._protocols,this._options)}addListener(e,t,r){var s,o,a,l,c,h,u,p,m,f,g,v,y,A,_,b,x,E,I,T,R;return this._options=Object.assign(Object.assign({},this._options),{listeners:{open:(a=(o=(s=this._options)===null||s===void 0?void 0:s.listeners)===null||o===void 0?void 0:o.open)!==null&&a!==void 0?a:[],close:(h=(c=(l=this._options)===null||l===void 0?void 0:l.listeners)===null||c===void 0?void 0:c.close)!==null&&h!==void 0?h:[],error:(m=(p=(u=this._options)===null||u===void 0?void 0:u.listeners)===null||p===void 0?void 0:p.error)!==null&&m!==void 0?m:[],message:(v=(g=(f=this._options)===null||f===void 0?void 0:f.listeners)===null||g===void 0?void 0:g.message)!==null&&v!==void 0?v:[],retry:(_=(A=(y=this._options)===null||y===void 0?void 0:y.listeners)===null||A===void 0?void 0:A.retry)!==null&&_!==void 0?_:[],reconnect:(E=(x=(b=this._options)===null||b===void 0?void 0:b.listeners)===null||x===void 0?void 0:x.reconnect)!==null&&E!==void 0?E:[],[e]:[...(R=(T=(I=this._options)===null||I===void 0?void 0:I.listeners)===null||T===void 0?void 0:T[e])!==null&&R!==void 0?R:[],{listener:t,options:r}]}}),this}}const K_e=Object.freeze(Object.defineProperty({__proto__:null,ArrayQueue:q_e,ConstantBackoff:H_e,ExponentialBackoff:W_e,LinearBackoff:X_e,RingQueue:Y_e,Websocket:cW,WebsocketBuilder:J_e,get WebsocketEvent(){return Fi}},Symbol.toStringTag,{value:"Module"})),za={node:"node",material:"material",camera:"camera",light:"light"},Hm="KHR_animation_pointer",Z_e={CUBICSPLINE:void 0,LINEAR:Rl,STEP:Yh},hW=Xt.findNode;let uW=!1;class $_e{constructor(e){this.parser=e,this.name=Hm,this.animationPointerResolver=null}setAnimationPointerResolver(e){return this.animationPointerResolver=e,this}_patchPropertyBindingFindNode(){uW||(uW=!0,Xt.findNode=function(e,t){if(t.startsWith(".materials.")){const r=t.substring(11).substring(t.indexOf(".")),s=r.indexOf("."),o=s<0?r:r.substring(0,s);let a=null;return e.traverse(l=>{a!==null||l.type!=="Mesh"&&l.type!=="SkinnedMesh"||l.material&&(l.material.uuid===o||l.material.name===o)&&(a=l.material,a!==null&&(r.endsWith(".map")?a=a.map:r.endsWith(".emissiveMap")&&(a=a.emissiveMap)))}),a}else if(t.startsWith(".nodes.")||t.startsWith(".lights.")||t.startsWith(".cameras.")){const r=t.split(".");let s;for(let o=1;o<r.length;o++){const a=r[o];if(a.length==36)s=e.getObjectByProperty("uuid",a);else if(s&&s[a]){const l=Number.parseInt(a);let c=a;l>=0&&(c=l),s=s[c]}else{const l=e.getObjectByName(a);l&&(s=l)}}if(!s){const o=hW(e,r[2]);return o||console.warn(Hm+": Property binding not found",t,e,e.name,r),o}return s}return hW(e,t)})}loadAnimationTargetFromChannel(e){const t=e.target,r=t.node!==void 0?t.node:t.id;return this.parser.getDependency("node",r)}loadAnimationTargetFromChannelWithAnimationPointer(e){this._havePatchedPropertyBindings||this._patchPropertyBindingFindNode();const t=e.target,r=t.extensions&&t.extensions[Hm]&&t.path&&t.path==="pointer";if(!r)return null;let s,o=za.node,a;if(r){const c=t.extensions[Hm];let h=c.pointer;if(!h){console.warn("Invalid path",c,t);return}if(h.startsWith("/materials/")?o=za.material:h.startsWith("/extensions/KHR_lights_punctual/lights/")?o=za.light:h.startsWith("/cameras/")&&(o=za.camera),a=this._tryResolveTargetId(h,o),a===null||isNaN(a)){console.warn("Failed resolving animation node id: "+a,h);return}switch(o){case za.material:const p=("/materials/"+a.toString()+"/").length,m=h.substring(0,p);switch(s=h.substring(p),s){case"pbrMetallicRoughness/baseColorFactor":s="color";break;case"pbrMetallicRoughness/roughnessFactor":s="roughness";break;case"pbrMetallicRoughness/metallicFactor":s="metalness";break;case"emissiveFactor":s="emissive";break;case"alphaCutoff":s="alphaTest";break;case"occlusionTexture/strength":s="aoMapIntensity";break;case"normalTexture/scale":s="normalScale";break;case"pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale":s="map/repeat";break;case"pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset":s="map/offset";break;case"emissiveTexture/extensions/KHR_texture_transform/scale":s="emissiveMap/repeat";break;case"emissiveTexture/extensions/KHR_texture_transform/offset":s="emissiveMap/offset";break;case"extensions/KHR_materials_emissive_strength/emissiveStrength":s="emissiveIntensity";break;case"extensions/KHR_materials_transmission/transmissionFactor":s="transmission";break;case"extensions/KHR_materials_ior/ior":s="ior";break;case"extensions/KHR_materials_volume/thicknessFactor":s="thickness";break;case"extensions/KHR_materials_volume/attenuationColor":s="attenuationColor";break;case"extensions/KHR_materials_volume/attenuationDistance":s="attenuationDistance";break;case"extensions/KHR_materials_iridescence/iridescenceFactor":s="iridescence";break;case"extensions/KHR_materials_iridescence/iridescenceIor":s="iridescenceIOR";break;case"extensions/KHR_materials_iridescence/iridescenceThicknessMinimum":s="iridescenceThicknessRange[0]";break;case"extensions/KHR_materials_iridescence/iridescenceThicknessMaximum":s="iridescenceThicknessRange[1]";break;case"extensions/KHR_materials_clearcoat/clearcoatFactor":s="clearcoat";break;case"extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor":s="clearcoatRoughness";break;case"extensions/KHR_materials_sheen/sheenColorFactor":s="sheenColor";break;case"extensions/KHR_materials_sheen/sheenRoughnessFactor":s="sheenRoughness";break;case"extensions/KHR_materials_specular/specularFactor":s="specularIntensity";break;case"extensions/KHR_materials_specular/specularColorFactor":s="specularColor";break}h=m+s;break;case za.node:const f=("/nodes/"+a.toString()+"/").length,g=h.substring(0,f);switch(s=h.substring(f),s){case"translation":s="position";break;case"rotation":s="quaternion";break;case"scale":s="scale";break;case"weights":s="morphTargetInfluences";break}h=g+s;break;case za.light:const v=("/extensions/KHR_lights_punctual/lights/"+a.toString()+"/").length;switch(s=h.substring(v),s){case"color":break;case"intensity":break;case"spot/innerConeAngle":s="penumbra";break;case"spot/outerConeAngle":s="angle";break;case"range":s="distance";break}h="/lights/"+a.toString()+"/"+s;break;case za.camera:const y=("/cameras/"+a.toString()+"/").length,A=h.substring(0,y);switch(s=h.substring(y),s){case"perspective/yfov":s="fov";break;case"perspective/znear":case"orthographic/znear":s="near";break;case"perspective/zfar":case"orthographic/zfar":s="far";break;case"perspective/aspect":s="aspect";break;case"orthographic/xmag":s="zoom";break;case"orthographic/ymag":s="zoom";break}h=A+s;break}const u=this.animationPointerResolver;u&&u.resolvePath&&(h=u.resolvePath(h)),t.extensions[Hm].pointer=h}if(a===null||isNaN(a)){console.warn("Failed resolving animation node id: "+a,t);return}let l;return o===za.node?l=this.parser.getDependency("node",a):o===za.material?l=this.parser.getDependency("material",a):o===za.light?l=this.parser.getDependency("light",a):o===za.camera?l=this.parser.getDependency("camera",a):console.error("Unhandled type",o),l}createAnimationTracksWithAnimationPointer(e,t,r,s,o){if(!(o.extensions&&o.extensions[Hm]&&o.path&&o.path==="pointer"))return null;let a=o.extensions[Hm].pointer;if(!a)return null;const l=[];a=a.replaceAll("/",".");const c=a.split(".");var h=e.name!==void 0&&e.name!==null?e.name:e.uuid;if(c[2]=h,c[3]==="morphTargetInfluences"&&e.type==="Group"){for(const p of e.children)p instanceof uo&&p.morphTargetInfluences&&(c[3]=p.name,c[4]="morphTargetInfluences",u(this.parser));return l}u(this.parser);function u(p){a=c.join(".");let m;switch(r.itemSize){case 1:m=Xc;break;case 2:case 3:m=kl;break;case 4:a.endsWith(".quaternion")?m=sa:m=kx;break}const f=s.interpolation!==void 0?Z_e[s.interpolation]:Rl;let g=p._getArrayFromAccessor(r);a.endsWith(".fov")&&(g=g.map(y=>y/Math.PI*180));const v=new m(a,t.array,g,f);if(f==="CUBICSPLINE"&&p._createCubicSplineTrackInterpolant(v),l.push(v),a&&r.itemSize===4&&a.startsWith(".materials.")&&a.endsWith(".color")){const y=new Float32Array(g.length/4);for(let _=0,b=g.length/4;_<b;_+=1)y[_]=g[_*4+3];const A=new m(a.replace(".color",".opacity"),t.array,y,f);f==="CUBICSPLINE"&&p._createCubicSplineTrackInterpolant(v),l.push(A)}}return l}_tryResolveTargetId(e,t){let r="";return t==="node"?r=e.substring(7):t==="material"?r=e.substring(11):t==="light"?r=e.substring(39):t==="camera"&&(r=e.substring(9)),r=r.substring(0,r.indexOf("/")),Number.parseInt(r)}loadAnimation(e){const t=this,r=this.parser.json,s=this.parser,o=r.animations[e],a=o.name?o.name:"animation_"+e,l=[],c=[],h=[],u=[],p=[];for(let m=0,f=o.channels.length;m<f;m++){const g=o.channels[m],v=o.samplers[g.sampler],y=g.target,A=o.parameters!==void 0?o.parameters[v.input]:v.input,_=o.parameters!==void 0?o.parameters[v.output]:v.output;let b=t.loadAnimationTargetFromChannelWithAnimationPointer(g);b||(b=t.loadAnimationTargetFromChannel(g)),l.push(b),c.push(s.getDependency("accessor",A)),h.push(s.getDependency("accessor",_)),u.push(v),p.push(y)}return Promise.all([Promise.all(l),Promise.all(c),Promise.all(h),Promise.all(u),Promise.all(p)]).then(function(m){const f=m[0],g=m[1],v=m[2],y=m[3],A=m[4],_=[];for(let b=0,x=f.length;b<x;b++){const E=f[b],I=g[b],T=v[b],R=y[b],D=A[b];if(E===void 0)continue;E.updateMatrix&&(E.updateMatrix(),E.matrixAutoUpdate=!0);let M=t.createAnimationTracksWithAnimationPointer(E,I,T,R,D);if(M||(M=s._createAnimationTracks(E,I,T,R,D)),M)for(let P=0;P<M.length;P++)_.push(M[P])}return new zs(a,void 0,_)})}}const exe=Object.freeze(Object.defineProperty({__proto__:null,GLTFAnimationPointerExtension:$_e},Symbol.toStringTag,{value:"Module"}));export{k_e as $physicsKey,gi as ActionBuilder,PP as ActionCollection,_a as ActionModel,E6 as Addressables,vA as AlignmentConstraint,Ng as AmbientMode,Es as Animation,im as AnimationCurve,BA as AnimationExtension,HS as AnimationTrackHandler,Bg as AnimationUtils,Wr as Animator,nd as AnimatorConditionMode,ea as AnimatorController,bk as AnimatorControllerParameterType,PA as AnimatorStateInfo,DA as Antialiasing,Qu as Application,cS as ApplicationEvents,R5 as AssetDatabase,ti as AssetReference,Pd as AudioExtension,ed as AudioListener,Mn as AudioSource,IA as AudioTrackHandler,od as Avatar,am as AvatarBlink_Simple,e0 as AvatarEyeLook_Rotation,Pk as AvatarLoader,Yr as AvatarMarker,eC as AvatarModel,NA as Avatar_Brain_LookAt,jA as Avatar_MouthShapes,Tk as Avatar_MustacheShake,sc as Avatar_POI,Wg as Axes,t0 as AxesHelper,DR as BUILD_TIME,Va as BaseUIComponent,kk as BasicIKConstraint,tC as BehaviorExtension,Ar as BehaviorModel,Be as Behaviour,lm as BloomEffect,n0 as BoxCollider,hm as BoxGizmo,ac as BoxHelperComponent,Eh as Button,yh as ButtonsFactory,LV as CallDirection,Qg as CallInfo,Li as Camera,SA as CameraTargetReachedEvent,Jr as Canvas,hd as CanvasGroup,Ch as CapsuleCollider,o0 as ChangeMaterialOnClick,pm as ChangeTransformOnClick,gm as CharacterController,Th as CharacterControllerInput,JA as ChromaticAberration,oa as CircularBuffer,$u as ClearFlags,ec as ClipExtrapolation,Vo as Collider,J9 as Collision,LS as CollisionDetectionMode,pd as ColorAdjustments,ym as ColorBySpeedModule,sb as ColorOverLifetimeModule,Be as Component,Uy as ComponentEvents,Ny as ComponentLifecycleEvents,r8 as ConnectionEvents,Y9 as ContactPoint,dc as ContactShadows,kt as Context,Hde as ContextArgs,Ci as ContextEvent,di as ContextRegistry,WS as ControlTrackHandler,bd as CustomBranding,Al as CustomShader,gS as DefaultReflectionMode,AD as Deletable,DC as DeleteBox,xl as DepthOfField,OC as DeviceFlag,bD as DocumentExtension,La as DragControls,IQ as DragMode,_d as DropListener,Em as Duplicatable,mb as EffectWrapper,uc as EmissionModule,l0 as EmphasizeOnClick,zR as EngineLoadingView,Un as EventList,BS as EventListEvent,Ta as EventSystem,UC as EventTrigger,oD as FieldWithDefault,W1 as FileReference,T6 as FileReferenceSerializer,kQ as FileSpawnModel,BQ as File_Event,ED as FixedJoint,MD as FlyControls,_0 as Fog,Hi as FrameEvent,bw as GENERATOR,ie as GameObject,At as Gizmos,yb as GltfExport,kD as GltfExportBox,Nm as GltfLoadEvent,f9 as GltfLoadEventType,fd as Gradient,um as Graphic,FS as GraphicRaycaster,ha as Graphics,S0 as GridHelper,Wk as GridLayoutGroup,Yu as GroundProjectedEnv,ku as GroupActionModel,V8 as HideFlags,Yk as HideOnStart,fb as HingeJoint,Hk as HorizontalLayoutGroup,Xde as HostData,s0 as Image,Q1 as ImageReference,M6 as ImageReferenceSerializer,vd as InheritVelocityModule,D6 as Input,ql as InputEventQueue,an as InputEvents,Mm as InputField,$A as InstanceHandle,ZA as InstancingHandler,Qa as InstancingUtil,L8 as InstantiateEvent,Dr as InstantiateIdProvider,Ml as InstantiateOptions,yD as Interactable,pde as JoinedRoomResponse,xue as KeyEventArgs,Ea as Keyframe,bb as LODGroup,Tm as LODModel,mde as LeftRoomResponse,wo as Light,C8 as LightData,Kn as LimitVelocityOverLifetimeModule,Cne as LoadingElementOptions,FD as LogStats,Bo as LogType,Im as LookAt,nm as LookAtConstraint,Zr as MainModule,vk as MarkerType,WA as MaskableGraphic,it as Mathf,cm as MeshCollider,ib as MeshRenderer,pt as MinMaxCurve,_o as MinMaxGradient,fi as NEEDLE_progressive,Xy as NEKeyboardEvent,mh as NEPointerEvent,KO as NeedleButtonElement,di as NeedleEngine,LO as NeedleEngineHTMLElement,kO as NeedleGltfLoader,pc as NeedleMenu,T1 as NeedlePatchesKey,i5 as NeedleUSDZExporter,vB as NeedleXRController,wt as NeedleXRSession,a8 as NeedleXRSync,u8 as NeedleXRUtils,HC as NestedGltf,o8 as NetworkConnection,oc as NetworkedStreamEvents,o_ as NetworkedStreams,E0 as Networking,U8 as NewInstanceModel,Ii as NoiseModule,No as ObjectRaycaster,sA as ObjectUtils,Rm as OffsetConstraint,fw as OneEuroFilter,gR as OneEuroFilterXYZ,M0 as OpenURL,bi as OrbitControls,r0 as Outline,s8 as OwnershipEvent,jB as OwnershipModel,ld as Padding,rb as ParticleBurst,aE as ParticleSubEmitter,$n as ParticleSystem,Sd as ParticleSystemBaseBehaviour,Fa as ParticleSystemRenderer,AC as ParticleSystemShapeType,ZS as PeerHandle,t8 as PeerNetworking,A8 as Physics,RC as PhysicsExtension,Cr as PhysicsMaterialCombine,Rb as PixelationEffect,fm as PlayAnimationOnClick,ud as PlayAudioOnClick,id as PlayableDirector,J0 as PlayerColor,Pa as PlayerState,RV as PlayerStateEvent,Kg as PlayerSync,b8 as PlayerView,_8 as PlayerViewManager,q0 as PointerEventData,q1 as PointerType,Xr as PostProcessingEffect,lE as PostProcessingHandler,D0 as PostProcessingManager,c0 as PreliminaryAction,qA as PreliminaryTrigger,Yp as PrimitiveType,ni as Progress,tw as PromiseAllWithErrors,kI as PromiseErrorResult,Si as RGBAColor,e_ as RapierPhysics,sC as RawImage,ml as RaycastOptions,jk as Rect,Ts as RectTransform,u0 as ReflectionProbe,JS as RegisteredAnimationInfo,wc as RemoteSkybox,Hg as RenderTexture,lV as RenderTextureSerializer,Tn as Renderer,S8 as RendererData,eb as RendererLightmap,Oi as Rigidbody,Nn as RigidbodyConstraints,Vt as RoomEvents,Wo as RotationBySpeedModule,Ba as RotationOverLifetimeModule,mC as SceneLightSettings,ks as SceneSwitcher,Ed as ScreenCapture,Oh as ScreenSpaceAmbientOcclusion,wl as ScreenSpaceAmbientOcclusionN8,dl as SendQueue,oB as SerializationContext,mm as SetActiveOnClick,Lb as ShadowCatcher,vn as ShapeModule,Bb as SharpeningEffect,EA as SignalAsset,Yg as SignalReceiver,qg as SignalReceiverEvent,RA as SignalTrackHandler,zk as Size,to as SizeBySpeedModule,gd as SizeOverLifetimeModule,aD as SkinnedMeshRenderer,Md as SmoothFollow,wA as SpatialGrabRaycaster,Fb as SpatialHtml,zb as SpatialTrigger,Sc as SpatialTriggerReceiver,pE as SpectatorCamera,i0 as SphereCollider,y8 as SphereIntersection,K9 as SphereOverlapResult,kh as Sprite,v0 as SpriteData,ka as SpriteRenderer,lb as SpriteSheet,cme as StateMachineBehaviour,DV as StreamEndedEvent,OV as StreamReceivedEvent,Ib as SubEmitterSystem,fE as SyncedCamera,Cc as SyncedRoom,Ku as SyncedTransform,Jk as TapGestureTrigger,IC as TeleportTarget,xO as TestRunner,L_e as TestSceneUtils,wO as TestSimulateUserData,Rs as Text,PC as TextBuilder,hb as TextExtension,$r as TextureSheetAnimationModule,Ec as TiltShiftEffect,M8 as Time,dd as ToneMappingEffect,MA as TrackHandler,zo as TrackType,cn as TrailModule,Tr as TransformData,Lm as TransformGizmo,br as TriggerBuilder,Up as TriggerModel,q as TypeStore,US as UIRaycastUtils,_A as UIRootComponent,Ws as USDObject,t5 as USDWriter,Rn as USDZExporter,Ad as USDZText,BC as USDZUIExtension,hB as Upload_Result,cV as UriSerializer,db as UsageMarker,fde as UserJoinedOrLeftRoomModel,el as VERSION,RP as VariantAction,yn as VelocityOverLifetimeModule,Qk as VerticalLayoutGroup,dr as VideoPlayer,Wu as ViewDevice,Fm as Vignette,YA as VisibilityAction,om as Voip,D0 as Volume,qe as VolumeParameter,kA as VolumeProfile,xde as WaitForFrames,m8 as WaitForPromise,p8 as WaitForSeconds,Nh as Watch,AE as WebARCameraBackground,io as WebARSessionRoot,Ir as WebXR,Am as WebXRButtonFactory,L0 as WebXRImageTracking,Mc as WebXRImageTrackingModel,Td as WebXRPlaneTracking,O0 as WebXRTrackedImage,Lh as XRControllerFollow,fc as XRControllerModel,Da as XRControllerMovement,Go as XRFlag,bE as XRRig,eo as XRState,rc as XRStateFlag,TO as __Ignore,O5 as __internalNotifyObjectDestroyed,$c as activeInHierarchyFieldName,GU as addAttributeChangeCallback,gl as addComponent,vge as addCustomExtensionPlugin,DQ as addFile,OQ as addFileFromUrl,a_e as addGltfLoadEventListener,Zp as addNewComponent,M1 as addPatch,IS as apply,A_e as applyHMRChanges,F8 as beginListenDestroy,LQ as beginListenFileSpawn,N8 as beginListenInstantiate,xB as binaryIdentifierCasts,Qde as build_scene_functions,wp as builtinComponentKeyName,UR as calculateProgress01,JU as clearBalloonMessages,JU as clearOverlayMessages,mpe as colorSerializer,p6 as compareAssociation,kS as componentSerializer,az as copyTexture,DO as createLoader,wV as createMotion,Zs as debugNet,nA as debugOwner,Nv as deepClone,Ll as delay,NU as delayForFrames,j1 as deserializeObject,Ca as destroy,eV as destroyComponentInstance,Qi as disposeObjectResources,Sh as disposeStream,C6 as download,dB as download_file,Kv as editorGuidKeyName,dO as effectsOrder,Nf as enableSpatialConsole,gpe as euler,_pe as eventListSerializer,G_e as exportAsGLTF,dA as findByGuid,PS as findObjectOfType,nV as findObjectsOfType,NP as findResourceUsers,lz as fitObjectIntoVolume,Kp as foreachComponent,TS as foreachComponentEnumerator,Vie as forward,QU as generateQRCode,xS as generateSeed,Ul as getBoundingBox,$N as getCameraController,$p as getComponent,fA as getComponentInChildren,gA as getComponentInParent,mA as getComponents,Vg as getComponentsInChildren,RS as getComponentsInParent,Kj as getFormattedDate,Ao as getIconElement,YB as getIconTexture,qZ as getIp,YZ as getIpAndLocation,XZ as getIpCloudflare,Ka as getLoader,pA as getOrAddComponent,te as getParam,Wie as getParentHierarchyPath,VZ as getPath,cde as getPeerOptions,$G as getPeerjsInstance,Tle as getResourceUserCount,bp as getTempQuaternion,pi as getTempVector,Uv as getUrlParams,SR as getWorldDirection,CR as getWorldEuler,Bt as getWorldPosition,Mi as getWorldQuaternion,Wv as getWorldRotation,Vi as getWorldScale,eh as hasCommercialLicense,OR as hasIndieLicense,uk as hasPointerEventComponent,uu as hasProLicense,uB as hash,pz as hideDebugConsole,s5 as imageToCanvas,Gg as instantiate,sD as invokeAfterImportPluginHooks,R6 as invokeXRSessionEnd,I6 as invokeXRSessionStart,Q8 as isActiveInHierarchy,jg as isActiveSelf,jU as isAndroidDevice,oz as isAnimationAction,NZ as isDebugMode,fp as isDesktop,Jp as isDestroyed,st as isDevEnvironment,Ele as isDisposed,U_e as isExporting,kU as isHostedOnGlitch,f_e as isHotReloading,R8 as isIconElement,js as isLocalNetwork,aa as isMobileDevice,gp as isMozillaXR,ew as isQuest,B5 as isResourceTrackingEnabled,Lf as isSafari,CS as isUsingInstancing,vp as isiOS,OO as loadSync,yw as logHierarchy,Fie as lookAtInverse,Hv as lookAtObject,jZ as makeId,RI as makeIdFromRandomWords,ul as makeNameSafeForUSD,H8 as markAsInstancedRendered,BI as microphonePermissionsGranted,UZ as nameof,DU as nameofFactory,aV as objectSerializer,due as offXRSessionEnd,uue as offXRSessionStart,kpe as onAfterRender,Bpe as onBeforeRender,Rpe as onClear,Ppe as onDestroy,Ipe as onInitialized,fV as onStart,gV as onUpdate,mB as onXRSessionEnd,X1 as onXRSessionStart,v9 as parseSync,cz as placeOnSurface,TR as postprocessFBXMaterials,Ope as prefix,OU as pushState,GZ as randomNumber,wB as registerBinaryType,bS as registerComponent,iD as registerComponentExtension,Ra as registerCustomEffectType,rD as registerExportExtensions,nD as registerExtensions,g_e as registerHotReloadType,CI as registerLoader,j8 as registerPrefabProvider,$ae as registerType,zU as relativePathPrefix,VU as removeAttributeChangeCallback,rk as removeComponent,yge as removeCustomImportExtensionType,l_e as removeGltfLoadEventListener,xle as removePatch,cu as resolveUrl,UU as sanitizeString,eW as saveImage,F_e as screenshot,$9 as screenshot2,$B as sendDestroyed,w as serializable,v6 as serializeObject,Eg as serializeable,uA as setActive,qU as setAllowBalloonMessages,$Z as setAllowOverlayMessages,AR as setAutoFitEnabled,vR as setCameraController,X8 as setDestroyed,ene as setDevEnvironment,UP as setDisposable,ik as setDontDestroy,TI as setOrAddParamsToUrl,zZ as setParam,Jx as setParamWithoutReload,hde as setPeerOptions,Cle as setResourceTrackingEnabled,II as setState,ER as setWorldEuler,lr as setWorldPosition,_p as setWorldPositionXYZ,ca as setWorldQuaternion,wR as setWorldQuaternionXYZW,MR as setWorldRotation,Xv as setWorldRotationXYZ,Uf as setWorldScale,IR as showBalloonError,rn as showBalloonMessage,Di as showBalloonWarning,kR as showDebugConsole,Oie as slerp,hA as syncDestroy,Ek as syncField,ek as syncInstantiate,Xie as textureToCanvas,N6 as tryCastBinary,d9 as tryDetermineFileTypeFromBinary,u9 as tryDetermineFileTypeFromURL,Df as tryFindObject,z6 as tryGetGuid,v_e as unregisterHotReloadType,PI as unwatchWrite,S6 as upload_file,ez as useForAutoFit,Hr as validate,Zx as watchWrite};