@needle-tools/engine
Version:
Needle Engine is a web-based runtime for 3D apps. It runs on your machine for development with great integrations into editors like Unity or Blender - and can be deployed onto any device! It is flexible, extensible and networking and XR are built-in.
143 lines (131 loc) • 1.34 MB
JavaScript
import{createLoaders as ng,LODsManager as vr,NEEDLE_progressive as He,getRaycastMesh as o_,calculateMeshLODLevel as mP,getLODColor as gP,addDracoAndKTX2Loaders as fP,configureLoader as yP,setKTX2TranscoderLocation as bP,setDracoDecoderLocation as _P}from"./gltf-progressive-CVg80COO.min.js";import{Vector2 as Z,Vector3 as _,Vector4 as ye,Quaternion as U,Box3 as ei,ShadowMaterial as s_,Euler as qe,PlaneGeometry as En,WebGLRenderer as wr,PerspectiveCamera as pe,OrthographicCamera as Nd,Scene as Li,Mesh as G,Texture as Se,Uniform$1 as on,Color as oe,ShaderMaterial as Qn,MeshStandardMaterial as xt,Box3Helper as vP,GridHelper as r_,Object3D as E,Material as ve,Matrix3 as a_,Matrix4 as J,Layers as Cs,PropertyBinding as ja,AnimationClip as Vt,KeyframeTrack as wP,FileLoader as l_,BufferGeometry as Mn,TextureLoader as xr,MeshBasicMaterial as Oe,DoubleSide as Di,Group as To,CylinderGeometry as c_,SphereGeometry as og,BoxGeometry as Ba,SpriteMaterial as xP,Sprite as SP,Shape as CP,ExtrudeGeometry as PP,Ray as Ro,CubeUVReflectionMapping as sn,LinearSRGBColorSpace as Ao,ShaderChunk as ti,Sphere as Wd,DataTexture as sg,RGBAFormat as $d,EquirectangularReflectionMapping as Io,SRGBColorSpace as Lo,Clock as kP,NeutralToneMapping as Fa,AgXToneMapping as Vd,ACESFilmicToneMapping as Gd,NoToneMapping as Hd,AxesHelper as ji,MathUtils as Do,Fog as h_,DirectionalLight as rg,PointLight as ag,PCFSoftShadowMap$1 as OP,BasicNodeLibrary as EP,WebGLRenderTarget as Yn,DepthTexture as d_,NearestFilter as qd,EdgesGeometry as MP,LineSegments as lg,LineBasicMaterial as Xd,Line as Cc,BufferAttribute as ot,Raycaster as cg,ArrayCamera as TP,Plane as Ua,SkinnedMesh as Ps,InterleavedBufferAttribute as u_,Skeleton as RP,Bone as AP,WebGLCubeRenderTarget as IP,CubeCamera as LP,LoopRepeat as DP,LoopOnce as hg,AnimationMixer as dg,InterpolateLinear as jP,InterpolateDiscrete as BP,InterpolateSmooth as FP,QuaternionKeyframeTrack as Pc,BooleanKeyframeTrack as p_,VectorKeyframeTrack as kc,ColorKeyframeTrack as m_,NumberKeyframeTrack as ug,AudioContext as UP,CompressedTexture as zP,FrontSide as ks,Camera as NP,Frustum as g_,AudioListener as WP,PositionalAudio as $P,AudioLoader as pg,Audio as VP,BackSide as Qd,PMREMGenerator$1 as GP,EquirectangularRefractionMapping as mg,CubeTexture as gg,CompressedCubeTexture as f_,MeshDepthMaterial as HP,CustomBlending as qP,MaxEquation as XP,AlwaysStencilFunc as QP,GreaterEqualStencilFunc as YP,NotEqualStencilFunc as KP,GreaterStencilFunc as ZP,LessEqualStencilFunc as JP,EqualStencilFunc as ek,LessStencilFunc as tk,NeverStencilFunc as y_,InvertStencilOp as ik,DecrementWrapStencilOp as nk,IncrementWrapStencilOp as ok,DecrementStencilOp as sk,IncrementStencilOp as rk,ReplaceStencilOp as ak,ZeroStencilOp as lk,KeepStencilOp as ck,AmbientLight as hk,HemisphereLight as dk,Loader as uk,GLSL3 as pk,AlwaysDepth as mk,GreaterEqualDepth as gk,GreaterDepth as fk,LessEqualDepth as yk,LessDepth as bk,NotEqualDepth as _k,EqualDepth as vk,RawShaderMaterial as b_,BatchedMesh as __,LinearFilter as Yd,UnsignedByteType as wk,MeshPhysicalMaterial as v_,RingGeometry as xk,Line3 as Sk,AdditiveBlending as w_,BoxHelper as Ck,SpotLight as Pk,DirectionalLightHelper as kk,CameraHelper as Ok,LOD as Ek,Triangle as Mk,NormalBlending as Tk,ReinhardToneMapping as fg,LinearToneMapping as yg,EventDispatcher as bg,VideoTexture as Rk,CatmullRomCurve3 as Ak,MirroredRepeatWrapping as x_,ShaderLib as Kd,UniformsUtils as S_,MeshNormalMaterial as Ik,HalfFloatType as _g,Source as Lk}from"./three.min.js";import{GroundedSkybox as za,Font as Dk,TextGeometry as jk,FontLoader as Bk,GLTFLoader as Os,EXRLoader as vg,RGBELoader as C_,Stats as Fk,nodeFrame as P_,TransformControlsGizmo as k_,OrbitControls as Uk,PositionalAudioHelper as zk,HorizontalBlurShader as Nk,VerticalBlurShader as Wk,GLTFExporter as O_,strToU8 as E_,zipSync as $k,XRControllerModelFactory as Vk,XRHandMeshModel as Gk,Line2 as Hk,LineGeometry as qk,LineMaterial as Xk,TransformControls as Qk,InteractiveGroup as Yk,HTMLMesh as Kk,VertexNormalsHelper as Zk,OBJLoader as wg,FBXLoader as M_,mergeVertices as Jk}from"./three-examples.min.js";import{v5 as xg,ByteBuffer as eO,fetchProfile as tO,MotionController as iO,SIZE_PREFIX_LENGTH as T_,Builder as Sg,createNoise4D as nO,Matrix4 as Cg,BatchedParticleRenderer as oO,ParticleSystem as sO,RenderMode as jo,ConstantColor as rO,Vector4 as aO,ConstantValue as lO,TrailParticle as R_,WorkerBase as cO,MeshBVH as hO}from"./vendor-DqZC4Is7.min.js";import{__webpack_exports__default as Ee,__webpack_exports__Text as A_,__webpack_exports__update as dO,__webpack_exports__Block as I_,SimpleStateBehavior as uO,__webpack_exports__Inline as Pg,__webpack_exports__FontLibrary as L_,ThreeMeshUI as D_}from"./three-mesh-ui-n3JU4M2W.min.js";const j_=typeof window<"u"?window.location.search.includes("debugcontext"):!1;var ue=(o=>(o.ContextRegistered="ContextRegistered",o.ContextCreationStart="ContextCreationStart",o.ContextCreated="ContextCreated",o.ContextFirstFrameRendered="ContextFirstFrameRendered",o.ContextDestroying="ContextDestroying",o.ContextDestroyed="ContextDestroyed",o.MissingCamera="MissingCamera",o.ContextClearing="ContextClearing",o.ContextCleared="ContextCleared",o))(ue||{});class le{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(j_&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(j_&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].indexOf(t)!==-1?()=>this.unregisterCallback(e,t):(this._callbacks[e].push(t),()=>this.unregisterCallback(e,t))}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const s=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&s.push(a)}),Promise.all(s)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const kg=new Map;function Bi(o=globalThis.location?.hostname){if(kg.has(o))return kg.get(o);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(o);return kg.set(o,e),e===!0}function B_(){return window.location.hostname.includes("glitch.me")}const F_=()=>o=>o;function pO(o){return F_()(o)}function mO(){return!!w("debug")}class Fi{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let Sr=!1;const Og=new Array;typeof window<"u"&&setTimeout(()=>{if(Sr){const o={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const i=t.toString().replace(/=$|=(?=&)/g,"");for(const s of Og){const r=new URL(e);r.searchParams.append(s,""),o[s]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`\u{1F335} ?help: Debug Options for Needle Engine.
Append any of these parameters to the URL to enable specific debug options.
Example: ${i} will show an onscreen console window.`);const n=Sr===!0?"":` (containing "${Sr}")`;console.group("Available URL parameters:"+n);for(const s of Object.keys(o).sort())typeof Sr=="string"&&!s.toLowerCase().includes(Sr.toLowerCase())||(console.groupCollapsed(s),console.log("Reload with this flag enabled:"),console.log(o[s]),console.groupEnd());console.groupEnd()}},100);function Oc(){return new URLSearchParams(globalThis.location?.search)}function w(o){Sr&&!Og.includes(o)&&Og.push(o);const e=Oc();if(e.has(o)){const t=e.get(o);if(t){const i=Number(t);return isNaN(i)?t:i}else return!0}return!1}Sr=w("help");function gO(o,e){const t=Oc();t.has(o)?t.set(o,e):t.append(o,e),document.location.search=t.toString()}function Ec(o,e,t=!0){const i=Oc();i.has(o)?e===null?i.delete(o):i.set(o,e):e!==null&&i.append(o,e),t?U_(o,i):Mg(o,i)}function Eg(o,e,t){o.has(e)?o.set(e,t.toString()):o.append(e,t.toString())}function U_(o,e,t){window.history.pushState(t,o,"?"+e.toString()+window.location.hash)}function Mg(o,e,t){window.history.replaceState(t,o,"?"+e.toString()+window.location.hash)}function fO(o){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,n=0;n<o;n++)e+=t.charAt(Math.floor(Math.random()*i));return e}function yO(o,e){return Math.floor(Math.random()*(e-o+1))+o}const z_=["smol","tiny","giant","interesting","smart","bright","dull","extreme","beautiful","pretty","dark","epic","salty","silly","funny","lame","lazy","loud","lucky","mad","mean","mighty","mysterious","nasty","odd","old","powerful","quiet","rapid","scary","shiny","shy","silly","smooth","sour","spicy","stupid","sweet","tasty","terrible","ugly","unusual","vast","wet","wild","witty","wrong","zany","zealous","zippy","zombie","zorro"],N_=["cat","dog","mouse","pig","cow","horse","sheep","chicken","duck","goat","panda","tiger","lion","elephant","monkey","bird","fish","snake","frog","turtle","hamster","penguin","kangaroo","whale","dolphin","crocodile","snail","ant","bee","beetle","butterfly","dragon","eagle","fish","giraffe","lizard","panda","penguin","rabbit","snake","spider","tiger","zebra"];function W_(){const o=z_[Math.floor(Math.random()*z_.length)],e=N_[Math.floor(Math.random()*N_.length)];return o+"_"+e}function $_(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function Mc(o,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===o||e.guid==o)return e;if(i&&e.userData?.components){for(const n of e.userData.components)if(n.guid===o)return n}if(t){if(e.scenes)for(const n in e.scenes){const s=e.scenes[n],r=Mc(o,s,t,i);if(r)return r}if(e.children)for(const n in e.children){const s=e.children[n],r=Mc(o,s,t,i);if(r)return r}}}function bO(o){return!!(typeof EventTarget<"u"&&o instanceof EventTarget||o instanceof Date||o instanceof RegExp||o instanceof Map||o instanceof Set||o instanceof WeakMap||o instanceof WeakSet||o instanceof Promise||typeof ArrayBuffer<"u"&&o instanceof ArrayBuffer||ArrayBuffer.isView(o))}function Tc(o,e,t){if(o!=null&&typeof o=="object"){if(t||(t=new WeakSet),t.has(o)||(t.add(o),bO(o)))return o;let i;if(Array.isArray(o))i=[];else{i=Object.create(Object.getPrototypeOf(o));const n=Object.getOwnPropertyDescriptors(o);for(const s in n){const r=n[s];if(r.set||r.writable!==!1)try{i[s]=o[s]}catch{}}}for(const n of Object.keys(o)){const s=o[n];e&&!e(o,n,s)?i[n]=s:s?.clone!==void 0&&typeof s.clone=="function"?i[n]=s.clone():i[n]=Tc(s,e,t)}return i}return o}function Bo(o){return new Promise((e,t)=>{setTimeout(e,o)})}function Zd(o,e){if(o<=0)return Promise.resolve();if(e||(e=le.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+o;return new Promise((i,n)=>{if(!e)return n("No context");const s=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(s),1),i())};e.pre_update_callbacks.push(s)})}const Jd=w("debugresolveurl"),V_="rel:";function _O(o,e){return Kn(o,e)}function Kn(o,e){if(e===void 0)return Jd&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return Jd&&console.warn("getPath: uri is absolute, returning uri",e),e;if(o===void 0)return Jd&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(V_)&&(e=e.substring(4));const t=o.lastIndexOf("/");if(t>=0){const i=o.substring(0,t+1);for(;i.endsWith("/")&&e.startsWith("/");)e=e.substring(1);const n=i+e;return Jd&&console.log("source:",o,`changed uri
from`,e,`
to `,n,`
basePath: `+i),n}return e}function G_(o){if(o)return o=o.trim(),o=o.split("?")[0]?.split("#")[0],o}class vO{subscribeWrite(e){this.writeCallbacks.push(e)}unsubscribeWrite(e){const t=this.writeCallbacks.indexOf(e);t!==-1&&this.writeCallbacks.splice(t,1)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;const e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");const i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:n=>{e[this._wrapperProp]=n;for(const s of this.writeCallbacks)s(n,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;const e=this._object,t=this._prop;Reflect.deleteProperty(e,t);const i=e[this._wrapperProp];e[t]=i,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}}class bs{_watches=[];constructor(e,t){if(Array.isArray(t))for(const i of t)this._watches.push(new bs(e,i));else this._watches.push(new vO(e,t))}subscribeWrite(e){for(const t of this._watches)t.subscribeWrite(e)}unsubscribeWrite(e){for(const t of this._watches)t.unsubscribeWrite(e)}apply(){for(const e of this._watches)e.apply()}revoke(){for(const e of this._watches)e.revoke()}dispose(){for(const e of this._watches)e.dispose();this._watches.length=0}}const Na=Symbol("needle:watches");function eu(o,e){if(!o[Na])if(o instanceof Z)o[Na]=new bs(o,["x","y"]);else if(o instanceof _)o[Na]=new bs(o,["x","y","z"]);else if(o instanceof ye||o instanceof U)o[Na]=new bs(o,["x","y","z","w"]);else return!1;return o[Na].subscribeWrite(e),!0}function Tg(o,e){if(!o)return;const t=o[Na];t&&t.unsubscribeWrite(e)}var I;(o=>{let e;function t(){if(e!==void 0)return e;if(typeof window>"u")return e=!1;const te=window.navigator.userAgent,Ge=/Windows|MacOS|Mac OS/.test(te),bi=/Windows NT/.test(te)&&/Edg/.test(te)&&!/Win64/.test(te);return e=Ge&&!bi&&!k()}o.isDesktop=t;let i;function n(){return i!==void 0?i:typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1?i=!0:i=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent)}o.isMobileDevice=n;function s(){return a()}o.isIPad=s;let r;function a(){if(r!==void 0)return r;const te=navigator.userAgent.toLowerCase();return r=/iPad/.test(navigator.userAgent)||te.includes("macintosh")&&"ontouchend"in document}o.isiPad=a;let l;function c(){return l!==void 0?l:l=/Android/.test(navigator.userAgent)}o.isAndroidDevice=c;let d;function h(){return d!==void 0?d:d=/WebXRViewer\//i.test(navigator.userAgent)}o.isMozillaXR=h;let p;function m(){return p!==void 0?p:p=/NeedleAppClip\//i.test(navigator.userAgent)}o.isNeedleAppClip=m;let g;function f(){if(g!==void 0)return g;if(k()||a())return g=!1;const te=navigator.userAgent.toLowerCase();return navigator.userAgentData?g=navigator.userAgentData.platform==="macOS":g=te.includes("mac os x")||te.includes("macintosh")}o.isMacOS=f;let y;function b(){return y!==void 0?y:y=a()&&"xr"in navigator&&q()}o.isVisionOS=b;let v;const C=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function k(){return v!==void 0?v:v=C.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}o.isiOS=k;let O;function D(){return O!==void 0||(O=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),O}o.isSafari=D;let L;function $(){return L!==void 0?L:L=navigator.userAgent.includes("OculusBrowser")}o.isQuest=$;let W;function q(){return W!==void 0||(W=document.createElement("a").relList.supports("ar")),W}o.supportsQuickLookAR=q;async function X(){try{return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}catch(te){return console.error("Error querying `microphone` permissions.",te),!1}}o.microphonePermissionsGranted=X;let T;function V(){if(T!==void 0)return T;const te=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(te&&(T=te[1].replace("_",".")),!T){const Ge=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);Ge&&(T=Ge[1])}return T||(T=null),T}o.getiOSVersion=V;let H;function de(){if(H!==void 0)return H;const te=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return te?H=te[1].replace("_","."):H=null,H}o.getChromeVersion=de;let ae;function ge(){if(ae!==void 0)return ae;const te=navigator.userAgent.match(/Version\/(\d+\.\d+)/);return te&&D()?ae=te[1]:ae=null,ae}o.getSafariVersion=ge})(I||(I={}));function wO(){return I.isDesktop()}function xO(){return I.isMobileDevice()}function SO(){return I.isiPad()}function CO(){return I.isiPad()}function PO(){return I.isAndroidDevice()}function kO(){return I.isMozillaXR()}function OO(){return I.isMacOS()}function EO(){return I.isiOS()}function MO(){return I.isSafari()}function TO(){return I.isQuest()}async function RO(){return I.microphonePermissionsGranted()}const Es=new WeakMap;function tu(o,e,t){if(!Es.get(o)){const s=new MutationObserver(r=>{AO(o,r)});Es.set(o,{observer:s,attributeChangedListeners:new Map}),s.observe(o,{attributes:!0})}const i=Es.get(o).attributeChangedListeners;i.has(e)||i.set(e,[]);const n=i.get(e);return n.includes(t)||n.push(t),()=>{H_(o,e,t)}}function H_(o,e,t){if(!Es.get(o))return;const i=Es.get(o).attributeChangedListeners;if(!i.has(e))return;const n=i.get(e),s=n.indexOf(t);s!==-1&&(n.splice(s,1),n.length<=0&&(i.delete(e),Es.get(o)?.observer.disconnect(),Es.delete(o)))}function AO(o,e){const t=Es.get(o).attributeChangedListeners;for(const i of e)if(i.type==="attributes"){const n=i.attributeName,s=o.getAttribute(n);if(t.has(n))for(const r of t.get(n))r(s)}}class Rg{reason;constructor(e){this.reason=e}}async function Ag(o){const e=await Promise.allSettled(o).catch(n=>[new Rg(n.message)]);let t=!1;const i=e.map(n=>"value"in n?n.value:(t=!0,new Rg(n.reason)));return{anyFailed:t,results:i}}const IO=w("debugdebug");let Ig=!1;(w("noerrors")||w("nooverlaymessages"))&&(Ig=!0);const Lg="needle_engine_global_error_container";var Ui=(o=>(o[o.Log=0]="Log",o[o.Warn=1]="Warn",o[o.Error=2]="Error",o))(Ui||{});function q_(){return Y_}const Dg=new Array;function LO(o){Dg.push(o)}let jg=!1;function DO(...o){if(!jg){jg=!0;try{for(let e=0;e<Dg.length;e++)Dg[e](...o)}catch(e){console.error(e)}jg=!1}}const X_=console.error,jO=function(...o){X_.apply(console,o),UO(o),Cr(2,o,{}),FO(...o)};function Q_(o){Ig=!o,o?console.error=jO:console.error=X_}function BO(o){return Q_(o)}let Y_=0;function FO(...o){Y_+=1,DO(...o)}function UO(o){if(Array.isArray(o))for(let e=0;e<o.length;e++){const t=o[e];typeof t=="string"&&t.startsWith("THREE.PropertyBinding: Trying to update node for track:")&&(o[e]="Some animated objects couldn't be found: see console for details")}}const K_=new Set;function Cr(o,e,t={},i,n){if(Ig)return;if(t.once===!0){let a="";if(Array.isArray(e))for(let l=0;l<e.length;l++){let c=e[l];c instanceof Error&&(c=c.message),typeof c!="object"&&(l>0&&(a+=" "),a+=c)}else typeof e=="string"&&(a=e);if(K_.has(a))return;K_.add(a)}const s=le.Current;let r=s?.domElement??document.querySelector("needle-engine");if(s?.isInAR&&(r=s.arOverlayElement),!!r){if(Array.isArray(e)){let a="";for(let l=0;l<e.length;l++){let c=e[l];c instanceof Error&&(c=c.message),typeof c!="object"&&(l>0&&(a+=" "),a+=c)}e=a}!e||e.length<=0||zO(o,r,e,t)}}const Wa=new Map,Z_=.2;function zO(o,e,t,i={}){if(t==null)return;const n=$O(e);if(n.childElementCount>=20){const c=n.lastElementChild;ev(c)}t.length>400&&(t=t.substring(0,400)+"...");const s=i.key??t;if(Wa.has(s)){Wa.get(s)?.update(t,i);return}const r=VO(o,t);n.prepend(r);const a=()=>{Wa.delete(s),ev(r)};let l=setTimeout(a,Math.max(Z_,i.duration??10)*1e3);Wa.set(s,{update:(c,d)=>{c.length>400&&(c=c.substring(0,400)+"..."),r.innerHTML=c,d.duration&&(clearTimeout(l),l=setTimeout(a,Math.max(Z_,d.duration)*1e3))},removeFunction:a})}function NO(){IO&&console.log("Clearing messages");for(const o of Wa.values())o?.removeFunction.call(o);Wa.clear()}const WO=`
@import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
div[data-needle_engine_debug_overlay] {
font-family: 'Roboto Flex', sans-serif;
font-weight: 400;
font-size: 16px;
}
div[data-needle_engine_debug_overlay] strong {
font-weight: 700;
}
div[data-needle_engine_debug_overlay] a {
color: white;
text-decoration: none;
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}
div[data-needle_engine_debug_overlay] a:hover {
text-decoration: none;
border: none;
}
div[data-needle_engine_debug_overlay] .log strong {
color: rgba(200,200,200,.9);
}
div[data-needle_engine_debug_overlay] .warn strong {
color: rgba(255,255,230, 1);
}
div[data-needle_engine_debug_overlay] .error strong {
color: rgba(255,100,120, 1);
}
`;function $O(o){globalThis[Lg]||(globalThis[Lg]=new Map);const e=globalThis[Lg];if(e.has(o))return e.get(o);{const t=document.createElement("div");e.set(o,t),t.setAttribute("data-needle_engine_debug_overlay",""),t.classList.add("debug-container"),t.style.cssText=`
position: absolute;
top: 0;
right: 5px;
padding-top: env(safe-area-inset-top, 0px);
max-width: 70%;
max-height: calc(100% - 105px);
z-index: 100000;
pointer-events: scroll;
display: flex;
align-items: end;
flex-direction: column;
color: white;
overflow: auto;
word-break: break-word;
`,I.isNeedleAppClip()&&(t.style.left="5px",t.style.right="unset");const i=document.querySelector('meta[name="viewport"]');i&&!i.getAttribute("content")?.includes("viewport-fit=")&&i.setAttribute("content",i.getAttribute("content")+",viewport-fit=cover"),o.shadowRoot?o.shadowRoot.appendChild(t):o.appendChild(t);const n=document.createElement("style");return n.innerHTML=WO,t.appendChild(n),t}}const J_=Symbol("logtype"),iu=new Map;function ev(o){o.remove();const e=o[J_],t=iu.get(e)??[];t.push(o),iu.set(e,t)}function VO(o,e){if(iu.has(o)){const i=iu.get(o);if(i.length>0){const n=i.pop();return n.innerHTML=e,n}}const t=document.createElement("div");switch(t.setAttribute("data-id","__needle_engine_debug_overlay"),t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style["-webkit-backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[J_]=o,o){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}const GO=w("nodevlogs");let Bg,Fg;function M(){if(GO)return!1;if(Bg!==void 0)return Bg;if(Fg!==void 0)return Fg;let o=Bi();return o||(o=typeof window<"u"&&window.location.hostname.endsWith(".local-credentialless.webcontainer.io")),Fg=o,o}function HO(o){Bg=o}class qO{random(e,t){return Array.isArray(e)?e.length<=0?null:e[Math.floor(Math.random()*e.length)]:e!==void 0&&t!==void 0?Math.random()*(t-e)+e:Math.random()}randomVector3(e,t=0,i=1){e.x=this.random(t,i),e.y=this.random(t,i),e.z=this.random(t,i)}clamp(e,t,i){return e<t?t:e>i?i:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,i){return i=i<0?0:i,i=i>1?1:i,e+(t-e)*i}inverseLerp(e,t,i){return(i-e)/(t-e)}remap(e,t,i,n,s){return n+(s-n)*(e-t)/(i-t)}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}Rad2Deg=180/Math.PI;Deg2Rad=Math.PI/180;Epsilon=1e-5;toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}tan(e){return Math.tan(e)}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}approximately(e,t,i=Number.EPSILON){for(const n of XO){const s=e[n],r=t[n];if(s===void 0||r===void 0)break;if(Math.abs(s-r)>i)return!1}return!0}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}}const XO=["x","y","z","w"],j=new qO;class tv{y;s;alpha=0;constructor(e){this.setAlpha(e),this.y=null,this.s=null}setAlpha(e){if(e<=0||e>1)throw new Error;this.alpha=e}filter(e,t){t&&this.setAlpha(t);let i;return this.y?i=this.alpha*e+(1-this.alpha)*this.s:i=e,this.y=e,this.s=i,i}lastValue(){return this.y}reset(e){this.y=e,this.s=e}}class nu{freq;minCutOff;beta;dCutOff;x;dx;lasttime;constructor(e,t=1,i=0,n=1){if(e<=0||t<=0||n<=0)throw new Error;this.freq=e,this.minCutOff=t,this.beta=i,this.dCutOff=n,this.x=new tv(this.alpha(this.minCutOff)),this.dx=new tv(this.alpha(this.dCutOff)),this.lasttime=null}alpha(e){const t=1/this.freq;return 1/(1+1/(2*Math.PI*e)/t)}filter(e,t=null){this.lasttime&&t&&(this.freq=1/(t-this.lasttime)),this.lasttime=t;const i=this.x.lastValue(),n=i?(e-i)*this.freq:0,s=this.dx.filter(n,this.alpha(this.dCutOff)),r=this.minCutOff+this.beta*Math.abs(s);return this.x.filter(e,this.alpha(r))}reset(e){e!=null&&this.x.reset(e),this.x.alpha=this.alpha(this.minCutOff),this.dx.alpha=this.alpha(this.dCutOff),this.lasttime=null}}class Ug{x;y;z;constructor(e,t=1,i=0,n=1){this.x=new nu(e,t,i,n),this.y=new nu(e,t,i,n),this.z=new nu(e,t,i,n)}filter(e,t,i=null){t.x=this.x.filter(e.x,i),t.y=this.y.filter(e.y,i),t.z=this.z.filter(e.z,i)}reset(e){this.x.reset(e?.x),this.y.reset(e?.y),this.z.reset(e?.z)}}const ou="needle:cameraController";function iv(o){return o[ou]}function zg(o,e,t){t?o[ou]=e:o[ou]===e&&(o[ou]=null)}const Ng="needle:autofit";function nv(o){return o[Ng]===void 0?!0:o[Ng]!==!1}function su(o,e){o[Ng]=e}let Tn;const QO={x:0,y:0,width:0,height:0},YO=w("debugfocusrect");function KO(o,e,t,i,n){o instanceof Element&&(YO&&o instanceof HTMLElement&&(o.style.outline="2px dashed rgba(255, 150, 0, .8)"),o=o.getBoundingClientRect()),Tn=n.domElement.getBoundingClientRect();const s=QO;s.x=o.x,s.y=o.y,s.width=o.width,s.height=o.height,s.x-=Tn.x,s.y-=Tn.y;const r=Tn.width,a=Tn.height,l=i.view,c=e.zoom;let d=l?.offsetX||0,h=l?.offsetY||0,p=Tn.width,m=Tn.height;p/=c,m/=c,d=p*(c-1)*.5,h=m*(c-1)*.5;const g=s.x+s.width*.5,f=s.y+s.height*.5,y=Tn.width*.5,b=Tn.height*.5,v=g-y,C=f-b;d-=v/c,h-=C/c,e.offsetX!==void 0&&(d+=e.offsetX*(Tn.width*.5)),e.offsetY!==void 0&&(h-=e.offsetY*(Tn.height*.5));const k=l?.offsetX||d,O=l?.offsetY||h;d=j.lerp(k,d,t),h=j.lerp(O,h,t);const D=l?.width||r,L=l?.height||a;p=j.lerp(D,p,t),m=j.lerp(L,m,t),i.setViewOffset(r,a,d,h,p,m),i.updateProjectionMatrix(),e.damping>0&&(e.damping*=1-t,e.damping<.01&&(e.damping=0),e.damping=Math.max(0,e.damping))}function ov(o,e,t){const i=o.length(),n=e.length(),s=j.lerp(i,n,t);return o.lerp(e,t).normalize().multiplyScalar(s)}const Wg=new U,sv=new U().setFromAxisAngle(new _(0,1,0),Math.PI);function ZO(o,e){o.lookAt(e),o.quaternion.multiply(sv)}function Rc(o,e,t=!0,i=!1){if(o===e)return;Wg.copy(o.quaternion);const n=se(e),s=se(o);if(i){if(Rn(o,we(e)),t){const r=s.y,a=s.sub(hv(o));a.y=r,o.lookAt(a),o.quaternion.multiply(sv)}Number.isNaN(o.quaternion.x)&&o.quaternion.copy(Wg);return}t&&(n.y=s.y),o.lookAt(n),Number.isNaN(o.quaternion.x)&&o.quaternion.copy(Wg)}function JO(o,e,t,i=1){if(t){const n=B(0,0,0),s=e.x/window.innerWidth*2-1,r=-(e.y/window.innerHeight)*2+1;n.set(s,r,0),n.unproject(t);const a=t.worldPosition,l=o.worldPosition.distanceTo(a),c=n.sub(a);c.multiplyScalar(i*3.6*l);const d=t.worldPosition.add(c);return o.lookAt(d),d}return null}const eE=new Fi(()=>new _,100);function B(o,e,t){const i=eE.get();return i.set(0,0,0),o instanceof _?i.copy(o):Array.isArray(o)?i.set(o[0],o[1],o[2]):o instanceof DOMPointReadOnly?i.set(o.x,o.y,o.z):typeof o=="number"?(i.x=o,i.y=e!==void 0?e:i.x,i.z=t!==void 0?t:i.x):typeof o=="object"&&(i.x=o.x,i.y=o.y,i.z=o.z),i}const tE=new Fi(()=>new oe,30);function rv(o){const e=tE.get();return o?e.copy(o):e.set(0,0,0),e}const iE=new Fi(()=>new U,100);function _i(o,e,t,i){const n=iE.get();return n.identity(),o instanceof U?n.copy(o):o instanceof DOMPointReadOnly?n.set(o.x,o.y,o.z,o.w):typeof o=="number"&&e!==void 0&&t!==void 0&&i!==void 0?n.set(o,e,t,i):typeof o=="object"&&"x"in o&&"y"in o&&"z"in o&&"w"in o&&n.set(o.x,o.y,o.z,o.w),n}const $g=new Fi(()=>new _,100),av=Symbol("lastMatrixWorldUpdateKey");function se(o,e=null,t=!0){const i=e??$g.get();return o?o.parent?(t&&o.updateWorldMatrix(!0,!1),o.matrixWorldNeedsUpdate&&o[av]!==Date.now()&&(o[av]=Date.now(),o.updateMatrixWorld()),i.setFromMatrixPosition(o.matrixWorld),i):i.copy(o.position):i.set(0,0,0)}function zi(o,e){if(!o)return o;const t=$g.get();return e!==t&&t.copy(e),o.parent!==null&&o.parent.worldToLocal(t),o.position.set(t.x,t.y,t.z),o}function Pr(o,e,t,i){const n=$g.get();return n.set(e,t,i),zi(o,n),o}const ru=new Fi(()=>new U,100),kr=new U,Vg=new U;function we(o,e=null){if(!o)return ru.get().identity();const t=e??ru.get();return o.parent?(o.getWorldQuaternion(t),t):t.copy(o.quaternion)}function Rn(o,e){if(!o)return;e!==kr&&kr.copy(e);const t=kr;o?.parent?.getWorldQuaternion(Vg),Vg.invert();const i=Vg.multiply(t);o.quaternion.set(i.x,i.y,i.z,i.w)}function Gg(o,e,t,i,n){kr.set(e,t,i,n),Rn(o,kr)}const nE=new Fi(()=>new _,100),oE=new _;function Xe(o,e=null){return e||(e=nE.get()),o?o.parent?(o.getWorldScale(e),e):e.copy(o.scale):e.set(0,0,0)}function $a(o,e){if(!o)return;if(!o.parent){o.scale.copy(e);return}const t=oE;o.parent.getWorldScale(t),o.scale.copy(e),o.scale.divide(t)}const sE=new _,lv=new U;function rE(o){return we(o,lv),sE.set(0,0,1).applyQuaternion(lv)}const aE=new Fi(()=>new _,100),cv=new U;function hv(o,e){return e||(e=aE.get().set(0,0,1)),we(o,cv),e.applyQuaternion(cv)}const dv=new qe,uv=new qe,lE=new _;function Hg(o){const e=ru.get();return o.getWorldQuaternion(e),uv.setFromQuaternion(e),uv}function qg(o,e){const t=ru.get();Rn(o,t.setFromEuler(e))}function au(o){const e=Hg(o),t=lE;return t.set(e.x,e.y,e.z),t.x=j.toDegrees(t.x),t.y=j.toDegrees(t.y),t.z=j.toDegrees(t.z),t}function pv(o,e){Ac(o,e.x,e.y,e.z,!0)}function Ac(o,e,t,i,n=!0){n&&(e=j.toRadians(e),t=j.toRadians(t),i=j.toRadians(i)),dv.set(e,t,i),kr.setFromEuler(dv),Rn(o,kr)}function lu(o,e=!0){o&&(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(o):o.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}function cE(o){let e=o?.name||"";if(!o)return e;let t=o.parent;for(;t;)e=t.name+"/"+e,t=t.parent;return e}function mv(o){if(o){const e=o;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}class Xm extends Qn{static vertex=`
varying vec2 vUv;
void main(){
vUv = uv;
gl_Position = vec4(position.xy, 0., 1.0);
}`;constructor(){super({vertexShader:Xm.vertex,uniforms:{map:new on(null),flipY:new on(!0),writeDepth:new on(!1),depthTexture:new on(null)},fragmentShader:`
uniform sampler2D map;
uniform bool flipY;
uniform bool writeDepth;
uniform sampler2D depthTexture;
varying vec2 vUv;
void main(){
vec2 uv = vUv;
if (flipY) uv.y = 1.0 - uv.y;
gl_FragColor = texture2D(map, uv);
if (writeDepth) {
float depth = texture2D(depthTexture, uv).r;
gl_FragDepth = depth;
// float linearDepth = (depth - 0.99) * 100.0; // Enhance near 1.0 values
// gl_FragColor = vec4(linearDepth, linearDepth, linearDepth, 1.0);
}
}`})}reset(){this.uniforms.map.value=null,this.uniforms.flipY.value=!0,this.uniforms.writeDepth.value=!1,this.uniforms.depthTexture.value=null,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}}class fr{static _planeGeometry;static _renderer;static _perspectiveCam;static _orthographicCam;static _scene;static _blitMaterial;static _mesh;static get planeGeometry(){return this._planeGeometry??=new En(2,2,1,1)}static get renderer(){return this._renderer??=new wr({antialias:!1,alpha:!0})}static get perspectiveCam(){return this._perspectiveCam??=new pe}static get orthographicCam(){return this._orthographicCam??=new Nd}static get scene(){return this._scene??=new Li}static get blitMaterial(){return this._blitMaterial??=new Xm}static get mesh(){return this._mesh??=new G(fr.planeGeometry,fr.blitMaterial)}static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const i=t||this.blitMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;const n=i.vertexShader;i.vertexShader=Xm.vertex;const s=this.mesh;s.material=i,s.frustumCulled=!1,this.scene.children.length=0,this.scene.add(s),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const r=new Se(this.renderer.domElement);return r.name="Copy",r.needsUpdate=!0,i.vertexShader=n,r}static blit(e,t,i){const{renderer:n=this.renderer,blitMaterial:s=this.blitMaterial,flipY:r=!1,depthTexture:a=null,depthTest:l=!0,depthWrite:c=!0}=i||{};this.blitMaterial.reset(),s.uniforms.map&&(s.uniforms.map.value=e),s.uniforms.flipY&&(s.uniforms.flipY.value=r),a?(s.uniforms.writeDepth=new on(!0),s.uniforms.depthTexture.value=a):(s.uniforms.writeDepth=new on(!1),s.uniforms.depthTexture.value=null),s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const d=this.mesh;d.material=s,d.frustumCulled=!1,this.scene.children.length=0,this.scene.add(d);const h=n.getRenderTarget(),p=n.getContext();l?p.enable(p.DEPTH_TEST):p.disable(p.DEPTH_TEST),n.state.buffers.depth.setMask(c),n.setClearColor(new oe(0,0,0),0),n.setRenderTarget(t),n.clear(),n.render(this.scene,this.perspectiveCam),n.setRenderTarget(h),p.enable(p.DEPTH_TEST),n.state.buffers.depth.setMask(!0)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=gv(e));const i=e.image;if(dE(i)){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const s=n.getContext("2d");return s?(s.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}}function gv(o){return fr.copyTexture(o)}function hE(o,e=!1){return fr.textureToCanvas(o,e)}function dE(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}function uE(o){const e=o.type;return e==="Mesh"||e==="SkinnedMesh"}function Xg(o,e){e?o["needle:rendercustomshadow"]=!0:o["needle:rendercustomshadow"]=!1}function fv(o){return!!(o&&(o["needle:rendercustomshadow"]===!0||o["needle:rendercustomshadow"]==null))}function vi(o,e=void 0,t=void 0,i=void 0){const n=i||new ei;n.makeEmpty();const s=[];function r(l){let c=!0;if(l.visible&&nv(l)!==!1&&!(l.type==="TransformControlsGizmo"||l.type==="TransformControlsPlane")){if(e){if(Array.isArray(e)){if(e.includes(l))return}else if(typeof e=="function"&&e(l)===!0)return}if(l instanceof vP&&(c=!1),l instanceof r_&&(c=!1),l instanceof za&&(c=!1),l.isGizmo===!0&&(c=!1),l.material instanceof s_&&(c=!1),uE(l)||(c=!1),t&&l.layers.test(t)===!1&&(c=!1),l.isUI!==!0){if(c){const d=l.children;l.children=s;const h=l.position,p=l.scale;if(Number.isNaN(h.x)||Number.isNaN(h.y)||Number.isNaN(h.z)){console.warn(`Object "${l.name}" has NaN values in position or scale.... will ignore it`,h,p);return}l.geometry===null&&(l.geometry=void 0),n.expandByObject(l,!0),l.children=d}for(const d of l.children)r(d)}}}let a=!1;Array.isArray(o)||(o=[o]);for(const l of o)l&&(a=!0,l.updateMatrixWorld(),r(l));return a||console.warn("No objects to fit camera to..."),n}function yv(o,e,t){const i=vi([o],t?.ignore),n=new _;i.getSize(n);const s=new _;i.getCenter(s);const r=new _;e.getSize(r);const a=new _;e.getCenter(a);const l=new _;l.set(r.x/n.x,r.y/n.y,r.z/n.z);const c=Math.min(l.x,l.y,l.z),d=t?.scale!==!1;if(d&&$a(o,Xe(o).multiplyScalar(c)),t?.position!==!1){const h=new _;i.getCenter(h),h.y=i.min.y;const p=new _;e.getCenter(p),p.y=e.min.y;const m=p.clone().sub(h);d&&m.multiplyScalar(c),zi(o,se(o).add(m))}return{boundsBefore:i,scale:l}}function bv(o,e){const t=vi([o]),i=new _;t.getCenter(i),i.y=t.min.y;const n=e.clone().sub(i),s=se(o);return zi(o,s.add(n)),{offset:n,bounds:t}}function Qg(o,e,t,i){if(Array.isArray(e)){let r=!0;for(let a=0;a<e.length;a++)Qg(o,e[a],a,e)||(r=!1);return r}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const n=new xt;n["material:fbx"]=e;const s=e;return s&&(s.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(s.color),n.emissive.copyLinearToSRGB(s.emissive),n.emissiveIntensity=s.emissiveIntensity,n.opacity=s.opacity,n.displacementScale=s.displacementScale,n.transparent=s.transparent,n.bumpMap=s.bumpMap,n.aoMap=s.aoMap,n.map=s.map,n.displacementMap=s.displacementMap,n.emissiveMap=s.emissiveMap,n.normalMap=s.normalMap,n.envMap=s.envMap,n.alphaMap=s.alphaMap,n.metalness=s.reflectivity,n.vertexColors=s.vertexColors,s.shininess&&(n.roughness=1-Math.sqrt(s.shininess)/10),n.needsUpdate=!0),t===void 0?o.material=n:i[t]=n,!0}let cu=!1;function pE(){LO((...o)=>{M()&&le.Current?.isInXR&&(Va(!0),_v("error",...o))})}function Va(o){if(o){if(cu)return;cu=!0,gE()}else{if(!cu)return;cu=!1,fE()}}const Ic={log:void 0,warn:void 0,error:void 0};class mE{familyName="needle-xr";root=null;context=null;defaultFontSize=.06;constructor(){this.ensureFont()}onEnable(){this.context=le.Current||le.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){this.context?.pre_render_callbacks.splice(this.context?.pre_render_callbacks.indexOf(this.onBeforeRender),1),this.root?.removeFromParent()}targetObject=new E;userForwardViewPoint=new _;oneEuroFilter=new Ug(90,.8);_lastElementRemoveTime=0;onBeforeRender=()=>{const e=this.context?.mainCamera;if(this.context&&e instanceof pe){const t=this.getRoot();Number.isNaN(t.position.x)&&t.position.set(0,0,0),Number.isNaN(t.quaternion.x)&&t.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const i=this.context.xr?.rigScale??1,n=3.5*i,s=e.worldForward;s.y=0,s.normalize().multiplyScalar(n),this.userForwardViewPoint.copy(e.worldPosition).sub(s),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*i&&(this.targetObject.position.copy(this.userForwardViewPoint),Rc(this.targetObject,e,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,t.position,this.context.time.time);const r=this.context.time.deltaTime;if(t.quaternion.slerp(this.targetObject.quaternion,r*5),t.scale.setScalar(i),this.targetObject.removeFromParent(),this.context.scene.add(t),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const a=Date.now();for(let l=0;l<this._activeTexts.length;l++){const c=this._activeTexts[l];if(c instanceof Ee.Text&&a-c._activatedTime>2e4){c.removeFromParent(),this._textBuffer.push(c),this._activeTexts.splice(l,1);break}}}}};addLog(e,t){const i=this.getRoot(),n=this.getText();let s=16777215,r=0;switch(e){case"log":s=16777215,r=0;break;case"warn":s=16772761,r=4465152;break;case"error":s=16755370,r=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"...");const a=new Date().toISOString().split("T")[1].split(".")[0];n.textContent="["+a+"] "+t,n.visible=!0,n._activatedTime=Date.now(),i.add(n),this._activeTexts.push(n),this.context&&this.context.scene.add(i),n.set({backgroundColor:s,color:r}),Ee.update()}ensureFont(){let e=Ee.FontLibrary.getFontFamily(this.familyName);e||(e=Ee.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{Ee.update()}))}textOptions={fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025};_textBuffer=[];_activeTexts=[];getText(){const e=this.getRoot();if(this._textBuffer.length>0){const i=this._textBuffer.pop();return i.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(i),100),i}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new Ee.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let n=0;n<e.children.length;n++){const s=e.children[n];s instanceof E&&this.disableDepthTestRecursive(s,t+1)}e.renderOrder=10*t,e.layers.set(2);const i=e.material;i&&(i.depthWrite=!1,i.depthTest=!1,i.transparent=!0),t===0&&Ee.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new Ee.Block(t),this.root}}let Or=null;function gE(){Or||(Or=new mE),Or.onEnable();for(const o in Ic){Ic[o]=console[o];let e=!1;console[o]=function(){if(Ic[o]?.apply(console,arguments),!e)try{e=!0,_v(o,...arguments)}finally{e=!1}}}}function fE(){Or?.onDisable();for(const o in Ic)console[o]=Ic[o]}const Lc=new Map;function _v(o,...e){try{switch(Lc.clear(),o){case"log":Or?.addLog("log",t());break;case"warn":Or?.addLog("warn",t());break;case"error":Or?.addLog("error",t());break}}catch(s){console.error("Error in spatial console",s)}finally{Lc.clear()}function t(){let s="";for(let r=0;r<e.length;r++){const a=e[r];s+=i(a),r<e.length-1&&(s+=", ")}return s}function i(s,r=0){if(typeof s=="string")return'"'+s+'"';if(typeof s=="number"){if(s%1!==0){const a=s.toFixed(5),l=a.indexOf(".");let c=a.length-1;for(;c>l&&a[c]==="0";)c--;return a.substring(0,c+1)}return s.toString()}else if(Array.isArray(s)){let a="[";for(let l=0;l<s.length;l++){const c=s[l];a+=i(c,r+1),l<s.length-1&&(a+=", ")}return a+="]",a}else{if(s===null)return"null";if(s===void 0)return"undefined";if(typeof s=="function")return s.name+"()"}if(s instanceof Z)return`(${i(s.x)}, ${i(s.y)})`;if(s instanceof _)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)})`;if(s instanceof ye)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof U)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof ve||s instanceof Se)return s.name;if(s instanceof a_)return`[${s.elements.join(", ")}]`;if(s instanceof J)return`[${s.elements.join(", ")}]`;if(s instanceof Cs)return s.mask.toString();if(typeof s=="object"){if(Lc.has(s))return"*";let a=`{
`;a+=n(r);const l=Object.keys(s);let c="";for(let d=0;d<l.length;d++){const h=l[d],p=s[h];if(Lc.has(p)){c+="";continue}Lc.set(p,!0),c+=h+":"+i(p,r+1),d<l.length-1&&(c+=", "),c.length>=60&&(c+=`
`,c+=n(r),a+=c,c="")}return a+=c,a+=`
}`,a}return s}function n(s){let r="";for(let a=0;a<s;a++)r+=" ";return r}}function Me(o,e){Cr(e?.type??Ui.Log,o,e)}function be(o,e){Me(o,{...e,type:Ui.Warn})}function Dc(o,e){Me(o,{...e,type:Ui.Error})}let wi,Er=null,Zn=null,jc=!1,vv=null;const wv="terminal",yE=w("console");yE&&Yg();const bE=Symbol("consoleParent");function Yg(){if(wi){wi.showSwitch();return}SE()}function xv(){wi&&(wi.hide(),wi.hideSwitch())}function _E(){vv||(vv=setInterval(vE,500))}let Sv=0;function vE(){const o=q_(),e=o!==Sv;Sv=o,e&&wE()}function wE(){Yg(),Zn&&(Zn.setAttribute("error","true"),Zn.innerText="\u{1F92C}")}function xE(){Zn&&(Zn.removeAttribute("error"),Zn.innerText=wv)}function SE(o=!1){if(wi!==void 0||jc)return;jc=!0;const e=document.createElement("script");e.onload=()=>{if(!globalThis.VConsole){console.warn("\u{1F335} Debug console failed to load."),jc=!1,wi=null;return}jc=!1,_E(),wi=new VConsole({pluginOrder:["default","needle-console"]});const t=globalThis["needle:codegen_files"];if(t&&t.length>0&&wi.addPlugin(CE()),wi.addPlugin(EE()),wi.addPlugin(ME()),Er=zE(),Er&&(Er[bE]=Er.parentElement,Er.style.position="absolute",Er.style.zIndex=Number.MAX_SAFE_INTEGER.toString()),wi.setSwitchPosition(20,30),Zn=UE(),Zn){Zn.innerText=wv,Zn.addEventListener("click",xE);const i=document.createElement("style"),n=40;i.innerHTML=`
#__vconsole .vc-switch {
border: 1px solid rgba(255, 255, 255, .1);
border-radius: 50%;
width: ${n}px;
height: ${n}px;
padding: 0;
line-height: ${n}px;
font-size: ${n*.4}px;
text-align: center;
background: #ffffff5c;
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
user-select: none;
pointer-events: auto;
transition: transform .2s ease-in-out;
box-shadow: 0px 7px 0.5rem 0px rgb(0 0 0 / 6%), inset 0px 0px 1.3rem rgba(0,0,0,.05);
font-family: 'Material Symbols Outlined';
color: black;
font-size: 2.3em;
font-weight: 100;
}
#__vconsole .vc-switch:hover {
cursor: pointer;
transform: scale(1.1);
transition: transform .1s ease-in-out, background .1s linear;
background: rgba(245, 245, 245, .8);
outline: rgba(0, 0, 0, .05) 1px solid;
}
#__vconsole .vc-switch[error] {
background: rgba(255,0,0,.2);
animation: vconsole-notify 1s ease-in-out;
line-height: 35px;
}
@keyframes vconsole-notify {
from {
transform: scale(1, 1);
}
10% {
transform: scale(1.3, 1.3);
}
70% {
transform: scale(1.4, 1.4);
}
to {
transform: scale(1, 1);
}
}
#__vconsole .vc-panel {
font-family: monospace;
font-size: 11px;
}
#__vconsole .vc-plugin-box.vc-actived {
height: 100%;
}
#__vconsole .vc-mask {
overflow: hidden;
}
`,Er?.prepend(i),o===!0&&q_()<=0&&xv(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),jc=!1,wi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function CE(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),wi?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}const Kg="padding: 10px; font-family: monospace;",Cv="margin-bottom: 10px;",Mr="margin-bottom: 10px; margin-top: 15px;",PE="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",Pv="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",kE=Pv,OE=Pv+" word-break: break-all;";function Jn(o,e=!1){e&&o.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${PE}'>`;t+="<tbody>";for(const i of o){const n=typeof i.value=="boolean"?i.value?"\u2705":"\u274C":i.value;t+=`<tr><td style='${kE}'>${i.label}</td><td style='${OE}'>${n}</td></tr>`}return t+="</tbody></table>",t}function kv(){try{if(document.createElement("canvas").getContext("webgl2"))return"\u2705"}catch{}return"\u274C"}function EE(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("device-utilities","\u{1F4F1} Device Info");return o.on("renderTab",function(e){let t=`<div style='${Kg}'>`;const i=FE();t+=`<h3 style='${Cv}'>Device: ${i}</h3>`,t+=Jn([{label:"\u{1F4BB} Desktop",value:I.isDesktop()},{label:"\u{1F4F1} Mobile Device",value:I.isMobileDevice()},{label:"\u{1F34E} iOS",value:I.isiOS()},{label:"\u{1F4F1} iPad",value:I.isiPad()},{label:"\u{1F916} Android",value:I.isAndroidDevice()},{label:"\u{1F98A} Mozilla XR",value:I.isMozillaXR()},{label:"\u{1F335} Needle App Clip",value:I.isNeedleAppClip()},{label:"\u{1F34F} macOS",value:I.isMacOS()},{label:"\u{1F453} VisionOS",value:I.isVisionOS()},{label:"\u{1F9ED} Safari",value:I.isSafari()},{label:"\u{1F576}\uFE0F Meta Quest",value:I.isQuest()},{label:"\u{1F517} QuickLook AR Support",value:I.supportsQuickLookAR()}],!0);const