jarvis-cloud / webar /assets /index-Cy1BM1FG.js
Jarvis2345's picture
Squash history — remove all prior commits (secret hygiene, S4)
a31f556
Raw
History Blame Contribute Delete
235 kB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./StereoEffect-bLEw1dSH.js","./three-K6XMXseN.js","./rolldown-runtime-DK3Fl9T5.js"])))=>i.map(i=>d[i]);
import{t as e}from"./rolldown-runtime-DK3Fl9T5.js";import{$ as t,A as n,B as r,C as i,D as a,E as o,F as s,G as c,H as l,I as u,J as d,K as f,L as p,M as m,N as h,O as g,P as _,Q as v,R as y,S as ee,T as te,U as ne,V as b,W as re,X as x,Y as ie,Z as ae,_ as oe,a as se,at as ce,b as le,c as ue,ct as de,d as fe,et as pe,f as me,g as he,h as ge,i as _e,it as S,j as ve,k as ye,l as be,m as xe,nt as Se,o as Ce,ot as we,p as Te,q as Ee,rt as De,s as Oe,st as ke,tt as Ae,u as je,v as Me,w as Ne,x as Pe,y as Fe,z as Ie}from"./three-K6XMXseN.js";import{n as Le,r as Re,t as ze}from"./mediapipe-Ck-u_eH7.js";import{a as Be,i as Ve,n as He,r as Ue,t as We}from"./physics-ZWohGOc1.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var Ge=4;function Ke(e){return document.getElementById(e===`error`?`error-host`:`banner-host`)}function qe(e,t,n,r={}){let i=Ke(e);if(!i)return null;let a=document.createElement(`section`);a.className=`${e===`error`?`error-panel`:`banner-panel`} glass-panel`;let o=document.createElement(`p`),s=document.createElement(`strong`);if(s.textContent=t,o.textContent=n,a.append(s,o),r.linkHref){let e=document.createElement(`a`);e.href=r.linkHref,e.textContent=r.linkLabel||`Open settings`,e.rel=`noopener`,e.style.display=`inline-block`,e.style.marginTop=`8px`,a.appendChild(e)}for(i.prepend(a);i.children.length>Ge;)i.lastElementChild?.remove();return r.timeout!==0&&window.setTimeout(()=>a.remove(),r.timeout||(e===`error`?9e3:4500)),a}function C(e,t=`AR Error`,n={}){return qe(`error`,t,String(e||`Unknown AR error.`),n)}function w(e,t=`JARVIS AR`,n={}){return qe(`banner`,t,String(e||``),n)}function T(e,t){let n=document.getElementById(e);n&&(n.textContent=String(t))}function E(e,t){let n=document.getElementById(`loading-text`),r=document.getElementById(`loading-progress`);n&&e&&(n.textContent=e),r&&Number.isFinite(t)&&(r.style.width=`${Math.max(0,Math.min(100,t))}%`)}function Je(){document.getElementById(`loading-screen`)?.classList.add(`hidden`)}var Ye=globalThis.XRExtras||{FullWindowCanvas:{pipelineModule(){return{name:`xrextras-full-window-canvas`,onStart:({canvas:e})=>Xe(e),onCanvasSizeChange:({canvas:e})=>Xe(e)}}},Loading:{pipelineModule(){return{name:`xrextras-loading`,onStart:()=>E(`Starting 8th Wall camera...`,38),onCameraStatusChange:({status:e})=>{e===`hasVideo`&&Je()}}}},AlmostThere:{pipelineModule(){return{name:`xrextras-almost-there`,onAttach:()=>{navigator.mediaDevices?.getUserMedia||w(`This browser has limited AR camera support. Chrome Android is recommended.`)}}}},RuntimeError:{pipelineModule(){return{name:`xrextras-runtime-error`,onException:e=>C(e?.message||String(e),`8th Wall Runtime Error`,{timeout:0})}}}};try{globalThis.XRExtras||(globalThis.XRExtras=Ye)}catch{}function Xe(e){if(!e)return;let t=Math.min(devicePixelRatio||1,3),n=Math.max(1,Math.floor(innerWidth*t)),r=Math.max(1,Math.floor(innerHeight*t));(e.width!==n||e.height!==r)&&(e.width=n,e.height=r),e.style.width=`100vw`,e.style.height=`100vh`}function Ze(){let e=[`localhost`,`127.0.0.1`,`::1`].includes(location.hostname);return location.protocol===`https:`||e?!0:(C(`AR requires a secure connection (HTTPS). Please open this app over HTTPS.`,`Secure Connection Required`,{timeout:0,linkHref:`intent://settings#Intent;scheme=android-app;end`,linkLabel:`Open Chrome Android settings`}),!1)}function Qe(){let e=new URLSearchParams(location.search),t=()=>{try{return localStorage.getItem(`jarvis_ar_device`)||``}catch{return``}},n=e=>{try{localStorage.setItem(`jarvis_ar_device`,String(e))}catch{}},r=e.has(`device`),i=e.get(`device`)||t()||`POCO-M5`;r||n(i);let a=et(e.get(`omega`)||e.get(`omegaBridge`)||``),o=nt(e.get(`xr`)||e.get(`xrScriptUrl`)||``);return{deviceName:i,mode:$e(e.get(`mode`)||`vision_pro`),autoStart:!1,source:e.get(`source`)||`browser`,guardianProxy:e.get(`guardianProxy`)===`true`||e.get(`guardian`)===`true`,eyeTracking:e.get(`eyeTracking`)===`true`,nativeCompositor:e.get(`nativeCompositor`)===`true`,truePersistentWorldAnchors:e.get(`truePersistentWorldAnchors`)===`true`||e.get(`persistentWorldAnchors`)===`true`,nativeOpenXRBridge:e.get(`nativeOpenXRBridge`)===`true`,command:e.get(`command`)||``,arQuality:(e.get(`arQuality`)||`4k`).toLowerCase(),renderScale:e.get(`renderScale`)||`adaptive`,screen:e.get(`screen`)||`quest_spatial`,stack:(e.get(`stack`)||`aframe,playcanvas,camerakit,8thwall`).split(`,`).map(e=>e.trim()).filter(Boolean),omegaBase:a||(location.origin.includes(`5173`)?location.origin:``),wsBase:tt(e.get(`ws`)||``,a),xrScriptUrl:o,imageTargets:(e.get(`imageTargets`)||``).split(`,`).map(e=>e.trim()).filter(Boolean),gameUrls:{eternum:et(e.get(`eternumUrl`)||e.get(`gameEternumUrl`)||``),ripples:et(e.get(`ripplesUrl`)||e.get(`gameRipplesUrl`)||``)}}}function $e(e){let t=String(e||``).toLowerCase().trim().replace(/[-\s]+/g,`_`);return{vision:`vision_pro`,visionos:`vision_pro`,meta:`vision_pro`,quest:`vision_pro`,scan_room:`scan`,model:`models`,games:`games`,game:`games`,build:`builder`,game_builder:`builder`,vr_screen:`vr`}[t]||t||`vision_pro`}function et(e){let t=String(e||``).trim().replace(/\/+$/,``);return t?/^https?:\/\//i.test(t)?t:`http://${t}`:``}function tt(e,t=``){let n=String(e||``).trim().replace(/\/+$/,``);if(n)return/^wss?:\/\//i.test(n)?n:`ws://${n}`;if(!t)return location.protocol===`https:`?`wss://${location.host}/scene-ws`:`ws://${location.hostname}:5050`;try{let e=new URL(t,location.href);return e.port===`5173`?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/scene-ws`:`${e.protocol===`https:`?`wss:`:`ws:`}//${e.hostname}:5050`}catch{return``}}function nt(e){let t=String(e||``).trim();return t&&/^(https?:|data:|blob:|\/)/i.test(t)?t:``}function rt(e,t){let n=String(e||``).toLowerCase();return t.some(e=>n.includes(String(e||``).toLowerCase()))}function it(e=``,t=``,n=``){let r=String(e||(typeof navigator<`u`?navigator.userAgent:``)||``),i=r.toLowerCase(),a=typeof navigator<`u`&&navigator.platform||``,o=typeof navigator<`u`&&navigator.vendor||``,s=typeof navigator<`u`&&navigator.maxTouchPoints||0,c=String(t||a||``).toLowerCase(),l=String(n||o||``).toLowerCase(),u=/iphone|ipad|ipod/.test(i)||c.includes(`mac`)&&s>1&&/safari/.test(i),d=/android/.test(i),f=/visionos|applevision|xrvision/.test(i)||rt(r,[`Safari`])&&/apple/.test(l)&&s>1&&/mac/.test(c),p=/quest|oculus/.test(i),m=/\bwv\b|; wv|webview|android.*version\/\d+.*chrome/i.test(r)||d&&!/chrome|crios|firefox|fxios|edg/i.test(i),h=/safari/.test(i)&&!/chrome|crios|chromium|android/.test(i),g=/chrome|crios|chromium/.test(i)&&!/edg/.test(i),_=/firefox|fxios/.test(i),v=/edg/.test(i),y=h?`safari`:g?`chrome`:_?`firefox`:v?`edge`:p?`quest-browser`:`other`,ee=h?`webkit`:_?`gecko`:`blink`,te=f?`visionos`:u?`ios`:d?`android`:/mac/.test(c)?`mac`:/win/.test(c)?`windows`:/linux/.test(c)?`linux`:`desktop`,ne=!!(!u||f||p),b=h||f||m||d&&!g&&!p,re=p&&g;return{ua:r,browser:y,engine:ee,platform:te,isAndroid:d,isIOS:u,isVisionOS:f,isQuest:p,isWebView:m,isSafari:h,isChrome:g,isFirefox:_,isEdge:v,questBrowserQuirks:re,webXRSupportExpected:ne,webXRFragmented:b,latencyCeilingMs:f?12.5:p?13.5:u?14.5:16.7,limits:{sensorAccessLimited:!0,osIntegrationLimited:!0,compositorControlLimited:!0,persistentAnchorSupport:!1,backgroundExecutionLimited:!0,passthroughControlLimited:!0,spatialMemoryLimited:!0,headsetOptimizationAccessLimited:!0,webXRFragmented:b,safariWebXRLimitations:h,visionOSBrowserRestrictions:f,androidBrowserInconsistency:d,webViewInconsistency:m,questBrowserQuirks:re,fullscreenEdgeCases:f||m||p,orientationLockEdgeCases:h||f||m||p,webglContextLossRisk:p||d||m,renderLoopDuplicationRisk:p||d||m,limitedSensorAccess:!0,limitedOSIntegration:!0,limitedCompositorControl:!0,limitedPassthroughControl:!0,limitedSpatialMemoryAPIs:!0,limitedHeadsetOptimizationAccess:!0},notes:[h?`Safari WebXR support remains fragmented.`:``,f?`visionOS browser control is limited to browser-managed surfaces.`:``,d?`Android browser behavior can vary by OEM and browser build.`:``,re?`Quest Browser can expose fullscreen, orientation, and session quirks.`:``,m?`Embedded WebView feature support is stricter than Chrome Custom Tabs.`:``].filter(Boolean)}}function at(e){let t=[];return e?(e.limits?.webXRFragmented&&t.push(`webxr-fragmented`),e.limits?.safariWebXRLimitations&&t.push(`safari-webxr-limited`),e.limits?.visionOSBrowserRestrictions&&t.push(`visionos-browser-limited`),e.limits?.androidBrowserInconsistency&&t.push(`android-browser-variable`),e.limits?.webViewInconsistency&&t.push(`webview-variable`),e.limits?.questBrowserQuirks&&t.push(`quest-browser-quirks`),e.limits?.fullscreenEdgeCases&&t.push(`fullscreen-edge-cases`),e.limits?.orientationLockEdgeCases&&t.push(`orientation-lock-edge-cases`),e.limits?.webglContextLossRisk&&t.push(`webgl-context-loss-risk`),e.limits?.renderLoopDuplicationRisk&&t.push(`render-loop-duplication-risk`),e.limits?.backgroundExecutionLimited&&t.push(`background-execution-limited`),e.limits?.persistentAnchorSupport===!1&&t.push(`no-persistent-anchors`),e.limits?.passthroughControlLimited&&t.push(`passthrough-control-limited`),e.limits?.spatialMemoryLimited&&t.push(`spatial-memory-limited`),t):t}var D={config:null,started:!1,trackingMode:`standby`,xrAvailable:!1,xrStarted:!1,xrCamera:null,xrScene:null,scene:null,camera:null,renderer:null,aframeScene:null,aframeCamera:null,fallbackScene:null,fallbackCamera:null,fallbackRenderer:null,fallbackActive:!1,fallbackLoopHandle:0,cameraVideo:null,gestureFrameCanvas:null,gestureFrameReady:!1,worldPoints:[],worldPointBuffer:[],placedObjects:[],selectedObject:null,floorY:-1.2,pendingModelToPlace:``,css3d:null,pipelineOrder:[],frameCount:0,isVRMode:!1,focusQuality:{enabled:!1,focusX:.5,focusY:.5,source:`screen-center`,avgFrameMs:16.7,pixelRatio:1,tier:`high`},spatialAudio:{enabled:!1,unlocked:!1,listener:null,context:null,micReady:!1,micPermission:`unknown`,voiceRecognition:!1,speechSynthesis:!1,wakeWindowUntil:0,lastVoiceCommandAt:0,environmentProfile:`default`,roomProfile:{name:`default`,refDistance:.72,maxDistance:8,rolloffFactor:1.6,dampening:.08}},nativeOptions:{immersion:1,hdrEnabled:!0,handTrackingEnabled:!0,spatialAudioEnabled:!0,activeEnvironment:`default`},compositor:{mode:`browser-proxy`,native:!1,reprojection:!1,passthroughBlend:`browser`,depthComposition:!1,foveation:0,framebufferScaleFactor:1,eyeBuffers:`mono`,frameBudgetMs:16.6,avgFrameMs:16.6,lastFrameAt:0,refreshRate:60,renderScale:1,convergence:1.4,lensProfile:`default`,eyeAspect:1,vignetteStrength:.12,motionComfort:`balanced`,stereoFrustum:!0},browserProfile:{browser:`unknown`,engine:`unknown`,platform:`unknown`,isAndroid:!1,isIOS:!1,isVisionOS:!1,isQuest:!1,isWebView:!1,isSafari:!1,isChrome:!1,isFirefox:!1,isEdge:!1,webXRSupportExpected:!1,webXRFragmented:!1,latencyCeilingMs:16.7,limits:{},notes:[]},capabilities:{browserWebAR:!0,eightWallSLAM:!1,webXRAvailable:!1,webXRHitTest:!1,manualCamera:!1,mediaPipeHands:!1,spatialAudio:!1,gazeProxy:!1,controllerAbstraction:!1,handEyeFusion:!1,spatialWindowing:!1,passthroughBlendProxy:!1,comfortAdaptation:!1,predictivePoseFiltering:!1,accessibilityInteraction:!1,gestureArbitration:!1,selectionArbitration:!1,dragManipulationProxy:!1,openXRCompositorProxy:!1,reprojectionProxy:!1,depthCompositionProxy:!1,eyeBufferPair:!1,nativeFrameTiming:!1,posePredictionProxy:!1,approximateAnchors:!0,truePersistentWorldAnchors:!1,eyeTracking:!1,foveatedRendering:!1,nativeCompositor:!1,guardianBoundary:!1,controllerHaptics:!1,nativeOpenXRBridge:!1,browserLatencyCeiling:!0,limitedSensorAccess:!0,limitedOSIntegration:!0,limitedCompositorControl:!0,persistentAnchorSupport:!1,backgroundExecutionLimited:!0,passthroughControlLimited:!0,spatialMemoryLimited:!0,headsetOptimizationAccessLimited:!0,webXRFragmented:!1,safariWebXRLimitations:!1,visionOSBrowserRestrictions:!1,androidBrowserInconsistency:!1,webViewInconsistency:!1,eyeTrackingProxy:!1,persistentSpatialMemory:!1,ultraStableAnchoring:!1,naturalWindowPlacement:!1,depthAwareImmersion:!1,environmentAwareUI:!1,headsetComfortSystems:!1,lowLatencyCompositing:!1,stereoEyeBuffers:!1,stereoFrustumCalibration:!1,refreshRateNegotiation:!1,timestampSync:!1,motionSicknessMitigation:!1,teleportLocomotion:!1,smoothLocomotionSafeguards:!1,roomBoundaryVisualization:!1,nativeHandMeshProxy:!1,controllerHapticsProxy:!1,lowLightTrackingResilience:!1,headsetCameraCalibrationProxy:!1,deviceCapabilityMatrix:!1,renderScaleStability:!1,stereoUiAnchoring:!1,antiAliasEdgeProtection:!1,zFightGuard:!1,sustainedFramerateGuard:!1,orientationLockStability:!1,sensorPermissionPersistenceProxy:!1,motionComfortVignette:!1},telemetry:{frameMs:16.7,qualityTier:`high`,droppedFrames:0,startedAt:0,lastNativeStatusAt:0},runtime:{phase:`created`,lifecycleState:`created`,architecture:`unknown`,experienceClass:`unknown`,spatialRuntimeClass:`unknown`,platformRole:`unknown`,authority:`none`,authoritativeRuntime:`none`,activeEngine:`none`,activeRenderer:`none`,rendererOwner:`none`,restartCount:0,lastError:``,subsystems:{},cleanupCount:0,conflicts:[],readiness:{boot:!1,scene:!1,camera:!1,tracking:!1,ui:!1},lifecycleHistory:[],permissionState:`unknown`,degradationReason:``,spatialGapStatement:``,rootCauseSummary:``,visionProGapSummary:``,visionProMissingFeatures:[]},sessionAnchor:{originMatrix:null,originPosition:[0,0,0],originQuaternion:[0,0,0,1],restoredAt:0},handState:{hands:[],gestures:new Map},sceneInitialized:!1,resizeBound:!1,fallbackLoopStarted:!1,aframeCameraSyncAdded:!1,liveSceneReady:!1,paused:!1,tracking:null,trackingQuality:`initializing`,trackingAPI:null,detectedPlanes:[]},ot=new EventTarget,st=new Set,ct=new Set,lt=new Set,ut=new Map;function O(e,t){let n=e=>t(e.detail);return ot.addEventListener(e,n),()=>ot.removeEventListener(e,n)}function k(e,t={}){ot.dispatchEvent(new CustomEvent(e,{detail:t}))}function dt(e,t={}){D.runtime.phase=String(e||`unknown`),D.runtime.lastTransitionAt=Date.now();try{document.body.dataset.jarvisRuntimePhase=D.runtime.phase}catch{}return k(`runtime-phase`,{phase:D.runtime.phase,detail:t}),I(`AR phase: ${D.runtime.phase}`),D.runtime.phase}function A(e,t={}){let n=String(e||`unknown`);D.runtime.lifecycleState=n,D.runtime.lifecycleHistory.push({state:n,detail:t,at:Date.now()}),D.runtime.lifecycleHistory.length>24&&D.runtime.lifecycleHistory.splice(0,D.runtime.lifecycleHistory.length-24);try{document.body.dataset.jarvisLifecycleState=n}catch{}return k(`runtime-lifecycle`,{state:n,detail:t}),I(`AR lifecycle: ${n}`),n}function j(e,t=!0){if(!e)return!1;D.runtime.readiness[e]=!!t;try{document.body.dataset.jarvisReady=Object.entries(D.runtime.readiness).filter(([,e])=>e).map(([e])=>e).join(`,`)}catch{}return k(`runtime-readiness`,{key:e,ready:!!t,readiness:D.runtime.readiness}),D.runtime.readiness[e]}function ft(){D.started=!1,D.xrStarted=!1,D.xrAvailable=!1,D.xrSession=null,D.xrHitTestSource=null,D.liveSceneReady=!1,D.paused=!1,D.cameraVideo=null,D.gestureFrameCanvas=null,D.gestureFrameReady=!1,D.trackingMode=`standby`,D.runtime.permissionState=`unknown`,D.runtime.degradationReason=``,D.runtime.rendererOwner=`none`,D.runtime.activeRenderer=`none`,D.runtime.activeEngine=`none`;for(let e of Object.keys(D.runtime.readiness))D.runtime.readiness[e]=!1;A(`stopped`)}function M(e,t=`ready`,n={}){let r=String(e||``).trim();if(!r)return null;D.runtime.subsystems[r]={status:t,detail:n,updatedAt:Date.now()};try{document.body.dataset.jarvisSubsystems=Object.keys(D.runtime.subsystems).join(`,`)}catch{}return k(`runtime-subsystem`,{name:r,status:t,detail:n}),D.runtime.subsystems[r]}function pt(e,t={}){let n=String(e||`unknown`),r=D.runtime.authoritativeRuntime;if(r!==`none`&&r!==n&&!t.force){let e={type:`runtime`,current:r,attempted:n,at:Date.now()};return D.runtime.conflicts.push(e),M(`blocked-runtime:${n}`,`blocked`,e),k(`runtime-authority-conflict`,e),r}D.runtime.authoritativeRuntime=n,D.runtime.authority=n,D.runtime.activeEngine=n,D.runtime.authorityChangedAt=Date.now();try{document.body.dataset.jarvisRuntimeAuthority=n}catch{}return k(`runtime-authority`,{previous:r,authority:n,detail:t}),M(`runtime:${n}`,`authoritative`,t),n}function mt(e,t=null,n={}){let r=String(e||`unknown`),i=D.runtime.rendererOwner||`none`;if(!(n.takeover||i===`none`||i===r)){let e={type:`renderer`,current:i,attempted:r,at:Date.now()};return D.runtime.conflicts.push(e),M(`blocked-renderer:${r}`,`blocked`,e),k(`runtime-authority-conflict`,e),i}D.runtime.rendererOwner=r,D.runtime.activeRenderer=r,D.runtime.activeEngine=n.engine||D.runtime.activeEngine,D.runtime.rendererChangedAt=Date.now(),t?.scene&&(D.scene=t.scene),t?.camera&&(D.camera=t.camera),t?.renderer&&(D.renderer=t.renderer),r!==`fallback-three`&&kt();try{document.body.dataset.jarvisRendererAuthority=r}catch{}return k(`renderer-authority`,{previous:i,authority:r,context:t}),M(`renderer:${r}`,`authoritative`,{hasScene:!!t?.scene,hasCamera:!!t?.camera,hasRenderer:!!t?.renderer}),r}function ht(e,t,n,r){if(!e?.addEventListener||!t||!n)return()=>{};e.addEventListener(t,n,r);let i=()=>e.removeEventListener(t,n,r);return st.add(i),()=>{i(),st.delete(i)}}function gt(e,t=0){let n=window.setTimeout(()=>{ct.delete(n),e?.()},t);return ct.add(n),n}function _t(e){e&&(window.clearTimeout(e),ct.delete(e))}function N(e){let t=requestAnimationFrame(n=>{lt.delete(t),e?.(n)});return lt.add(t),t}function vt(e){e&&(cancelAnimationFrame(e),lt.delete(e))}function yt(e,t={},n={}){let r=String(e?.message||e||`Unknown runtime issue`),i=String(n.source||t.source||`runtime`),a=`${i}:${r}`,o=Date.now();if(o-(ut.get(a)||0)>5e3){ut.set(a,o),D.runtime.lastError=r,D.runtime.degradationReason=String(t.degradationReason||D.runtime.degradationReason||``),k(`runtime-error`,{error:r,source:i,context:t}),M(`runtime-error:${i}`,`error`,{message:r,context:t});try{C(r,n.title||`Runtime Error`,{timeout:n.timeout??7e3})}catch{}}try{I(`${i}: ${r}`)}catch{}return{message:r,source:i,context:t}}function bt(e,t,n={}){return typeof t==`function`?(...r)=>{try{return t(...r)}catch(t){yt(t,{...n,subsystem:e},{source:e});return}}:()=>{}}function P(e,t){D.capabilities[e]=!!t;try{document.body.dataset[`cap${e[0].toUpperCase()}${e.slice(1)}`]=String(!!t)}catch{}return D.capabilities[e]}function xt(e={}){D.compositor={...D.compositor,...e&&typeof e==`object`?e:{}},k(`compositor-state`,D.compositor);try{document.body.dataset.jarvisCompositorMode=D.compositor.mode,document.body.dataset.jarvisCompositorPassthrough=String(D.compositor.passthroughBlend)}catch{}return D.compositor}function St(e={}){D.browserProfile={...D.browserProfile,...e&&typeof e==`object`?e:{}};try{document.body.dataset.jarvisBrowser=`${D.browserProfile.browser||`unknown`}-${D.browserProfile.platform||`unknown`}`,document.body.dataset.jarvisBrowserLimit=D.browserProfile.webXRFragmented?`fragmented`:`standard`}catch{}return k(`browser-profile`,D.browserProfile),D.browserProfile}function Ct(e={}){D.runtime={...D.runtime,...e&&typeof e==`object`?e:{}};try{document.body.dataset.jarvisRuntimeArchitecture=D.runtime.architecture||`unknown`,document.body.dataset.jarvisSpatialClass=D.runtime.spatialRuntimeClass||`unknown`}catch{}return k(`runtime-classification`,D.runtime),D.runtime}function wt(e=``){D.runtime.rootCauseSummary=String(e||``);try{document.body.dataset.jarvisRootCause=D.runtime.rootCauseSummary}catch{}return k(`runtime-root-cause`,{summary:D.runtime.rootCauseSummary}),D.runtime.rootCauseSummary}function Tt(e=``,t=[]){D.runtime.visionProGapSummary=String(e||``),D.runtime.visionProMissingFeatures=Array.isArray(t)?t.map(e=>String(e||``).trim()).filter(Boolean):[];try{document.body.dataset.jarvisVisionProGap=D.runtime.visionProGapSummary}catch{}return k(`runtime-vision-pro-gap`,{summary:D.runtime.visionProGapSummary,missingFeatures:D.runtime.visionProMissingFeatures}),{summary:D.runtime.visionProGapSummary,missingFeatures:D.runtime.visionProMissingFeatures}}function F(e,...t){try{let n=globalThis.JarvisNative;n&&typeof n[e]==`function`&&n[e](...t)}catch{}}function I(e){F(`status`,String(e||``))}function Et(){try{if(globalThis.XR8?.Threejs?.xrScene){let e=globalThis.XR8.Threejs.xrScene();if(e?.scene&&e?.camera&&e?.renderer)return D.xrScene=e,D.scene=e.scene,D.camera=e.camera,D.renderer=e.renderer,e}}catch{return null}return null}function L(){return Et()||(Dt(),{scene:D.fallbackScene,camera:D.fallbackCamera,renderer:D.fallbackRenderer})}function Dt(){if(D.fallbackScene&&D.fallbackCamera&&D.fallbackRenderer||D.xrStarted&&D.xrScene?.scene)return;D.fallbackActive=!0;let e=document.getElementById(`fallback-three-canvas`)||document.createElement(`canvas`);e.id=`fallback-three-canvas`,e.parentNode||(e.style.cssText=`position:fixed;inset:0;width:100%;height:100%;z-index:1;pointer-events:none;background:transparent`,document.body.appendChild(e));let t=new ke({canvas:e,alpha:!0,antialias:!0,powerPreference:`high-performance`});t.setPixelRatio(Math.min(devicePixelRatio||1,3)),t.setSize(innerWidth,innerHeight,!1),t.setClearColor(0,0),t.outputColorSpace=d,t.toneMapping=4,t.toneMappingExposure=1,t.useLegacyLights=!1,t.shadowMap.enabled=!0,t.shadowMap.type=3;let n=new ie,r=new y(60,innerWidth/innerHeight,.01,1e3);r.position.set(0,0,0),n.add(new ue(16777215,.65));let i=new ee(16777215,.8);i.position.set(1,2,1),i.castShadow=!0,n.add(i),D.fallbackScene=n,D.fallbackCamera=r,D.fallbackRenderer=t,D.scene=n,D.camera=r,D.renderer=t,mt(`fallback-three`,{scene:n,camera:r,renderer:t},{engine:`manual-camera`})}function Ot(){if(D.fallbackLoopStarted)return;D.fallbackLoopStarted=!0,Dt();let e=()=>{if(D.xrStarted){kt();return}!D.xrStarted&&D.fallbackRenderer&&(D.fallbackRenderer.setSize(innerWidth,innerHeight,!1),D.fallbackCamera.aspect=innerWidth/innerHeight,D.fallbackCamera.updateProjectionMatrix(),D.fallbackRenderer.render(D.fallbackScene,D.fallbackCamera)),D.fallbackLoopHandle=N(e)};D.fallbackLoopHandle=N(e)}function kt(){D.fallbackLoopHandle&&vt(D.fallbackLoopHandle),D.fallbackLoopHandle=0,D.fallbackLoopStarted=!1;let e=document.getElementById(`fallback-three-canvas`);e&&(e.style.display=`none`)}function At(){let e=Et();if(!e?.scene||!D.fallbackScene||e.scene===D.fallbackScene)return e;let t=[...D.fallbackScene.children];for(let n of t)n!==D.fallbackCamera&&(D.fallbackScene.remove(n),e.scene.children.includes(n)||e.scene.add(n));return kt(),D.fallbackRenderer?.dispose?.(),document.getElementById(`fallback-three-canvas`)?.remove(),D.fallbackScene=null,D.fallbackCamera=null,D.fallbackRenderer=null,D.fallbackActive=!1,D.scene=e.scene,D.camera=e.camera,D.renderer=e.renderer,mt(`xr8-threejs`,e,{takeover:!0,engine:`8thwall-slam`}),e}function jt(e=L()){return D.liveSceneReady=!0,k(`ar-scene-live`,e),e}function Mt(e,t={}){let n=!!t.disposeSharedAssets,r=new Set,i=new Set,a=new Set;e?.traverse?.(e=>{e.geometry&&!r.has(e.geometry)&&(n||!e.geometry.userData?.sharedAssetKey)&&(r.add(e.geometry),e.geometry.dispose()),(Array.isArray(e.material)?e.material:[e.material]).filter(Boolean).forEach(e=>{i.has(e)||(i.add(e),Object.values(e).forEach(e=>{e?.isTexture&&!a.has(e)&&(n||!e.userData?.sharedAssetKey)&&(a.add(e),e.dispose())}),(n||!e.userData?.sharedAssetKey)&&e.dispose?.())})}),e?.parent?.remove(e)}try{globalThis.AR_STATE=D,globalThis.FridayRuntime={AR_STATE:D,emit:k,on:O,reportRuntimeIssue:yt,guardSubsystem:bt,setCapability:P,setCompositorState:xt,claimRuntimeAuthority:pt,claimRendererAuthority:mt,registerSubsystem:M}}catch{}var Nt=e({configureCompositorBridge:()=>It,initVrStereoSplitScreen:()=>zt,resetCompositorBridge:()=>Rt,updateCompositorFrame:()=>Lt});function Pt(e){try{return e?.xr?.getSession?.()||null}catch{return null}}function Ft(e,t){if(e?.xr){try{typeof e.xr.setFramebufferScaleFactor==`function`&&e.xr.setFramebufferScaleFactor(t.framebufferScaleFactor)}catch{}try{typeof e.xr.setFoveation==`function`&&e.xr.setFoveation(t.foveation)}catch{}}}function It(e=L(),t={}){let n=e?.renderer,r=t.session||Pt(n),i=String(t.tier||D.telemetry?.qualityTier||`medium`).toLowerCase();globalThis.navigator?.xr;let a=!!(n?.xr&&typeof n.xr.setFoveation==`function`),o=!!(n?.xr&&typeof n.xr.setFramebufferScaleFactor==`function`),s=!!(r?.renderState?.baseLayer||r?.depthUsage),c=!!(globalThis.JarvisNative?.openXRBridge||globalThis.JarvisNative?.setCompositorState),l={mode:t.mode||(r?`webxr-session`:`browser-proxy`),native:c,reprojection:!!(r&&o),passthroughBlend:t.passthroughBlend||(t.source?`browser-camera`:`browser`),depthComposition:!!(t.depthComposition||s),foveation:t.foveation??(i===`high`?.2:i===`medium`?.35:.55),framebufferScaleFactor:t.framebufferScaleFactor??(i===`high`?1:i===`medium`?.85:.72),eyeBuffers:t.eyeBuffers||(t.stereo?`pair`:`mono`),frameBudgetMs:t.frameBudgetMs??(i===`high`?13.5:i===`medium`?16.6:20),avgFrameMs:D.compositor?.avgFrameMs||16.6,lastFrameAt:performance.now(),posePredictionMs:t.posePredictionMs??(i===`high`?18:i===`medium`?24:32),refreshRate:t.refreshRate??(i===`high`?90:i===`medium`?72:60),renderScale:t.renderScale??(i===`high`?1:i===`medium`?.9:.8),convergence:t.convergence??(i===`high`?1.35:1.45),guardianProxy:!!t.guardianProxy,compositorSync:!0,lensProfile:t.lensProfile||`default`,eyeAspect:t.eyeAspect??1,vignetteStrength:t.vignetteStrength??(i===`high`?.1:.16),motionComfort:t.motionComfort||`balanced`,stereoFrustum:!!(t.stereo??r)};if(xt(l),P(`openXRCompositorProxy`,!0),P(`reprojectionProxy`,l.reprojection),P(`depthCompositionProxy`,l.depthComposition),P(`eyeBufferPair`,l.eyeBuffers===`pair`),P(`nativeFrameTiming`,!!r),P(`posePredictionProxy`,!0),P(`foveatedRendering`,a),P(`lowLatencyCompositing`,!0),P(`stereoEyeBuffers`,l.eyeBuffers===`pair`),P(`stereoFrustumCalibration`,l.stereoFrustum),P(`refreshRateNegotiation`,!0),P(`timestampSync`,!0),P(`motionSicknessMitigation`,!0),P(`smoothLocomotionSafeguards`,!0),P(`motionComfortVignette`,!0),t.guardianProxy!=null&&P(`guardianBoundary`,!!t.guardianProxy),c){P(`nativeOpenXRBridge`,!0);try{F(`setCompositorState`,JSON.stringify(l)),F(`requestCompositorControl`,JSON.stringify({owner:`browser-runtime`,mode:l.mode,guardianProxy:l.guardianProxy,browserManaged:!0})),F(`setGuardianState`,JSON.stringify({requested:!!t.guardianProxy,boundary:!!t.guardianProxy,owner:`browser-runtime`,source:`ar-compositor`}))}catch{}}return Ft(n,l),M(`compositor`,`ready`,l),k(`compositor-profile`,l),I(`Compositor profile: ${l.mode}`),l}function Lt(e=16.6){let t=D.compositor||{},n=t.avgFrameMs?t.avgFrameMs*.9+e*.1:e,r={...t,avgFrameMs:n,lastFrameAt:performance.now()};return xt(r),D.telemetry.frameMs=e,D.telemetry.droppedFrames=e>(r.frameBudgetMs||16.6)*1.25?(D.telemetry.droppedFrames||0)+1:D.telemetry.droppedFrames||0,k(`compositor-frame`,r),r}function Rt(){xt({mode:`browser-proxy`,native:!1,reprojection:!1,passthroughBlend:`browser`,depthComposition:!1,foveation:0,framebufferScaleFactor:1,eyeBuffers:`mono`,frameBudgetMs:16.6,avgFrameMs:16.6,lastFrameAt:0}),P(`openXRCompositorProxy`,!1),P(`reprojectionProxy`,!1),P(`depthCompositionProxy`,!1),P(`eyeBufferPair`,!1),P(`nativeFrameTiming`,!1),P(`posePredictionProxy`,!1)}function zt(e,t,n){globalThis.JarvisNative?.openXRBridge||globalThis.JarvisNative?.setCompositorState||(e.xr.enabled=!0,e.xr.setReferenceSpaceType(`local-floor`),!navigator.xr&&!D.stereoEffect&&Re(async()=>{let{StereoEffect:e}=await import(`./StereoEffect-bLEw1dSH.js`);return{StereoEffect:e}},__vite__mapDeps([0,1,2]),import.meta.url).then(({StereoEffect:r})=>{D.stereoEffect=new r(e),D.stereoEffect.setSize(window.innerWidth,window.innerHeight),D.stereoEffect.setEyeSeparation(.064),e.setAnimationLoop(()=>{D.stereoEffect.render(t,n)}),k(`jarvis-stereo-mode-active`,{status:`fallback_active`})}).catch(()=>{console.warn(`V15 AR: StereoEffect.js fallback polyfill missing.`)}))}async function Bt(e){D.config=e,D.aframeScene=document.getElementById(`ar-scene`),D.aframeCamera=document.getElementById(`main-camera`),await Vt();let t=L();return Wt(t.renderer,e),It(t,{mode:`ar-shell`,tier:D.focusQuality.tier,stereo:!!D.isVRMode}),Yt(t.scene),Ut(t.renderer),Zt(),D.sceneInitialized||(D.sceneInitialized=!0,k(`scene-ready`,t)),t}function Vt(){let e=document.getElementById(`ar-scene`);return!e||e.hasLoaded?Promise.resolve():new Promise(t=>e.addEventListener(`loaded`,t,{once:!0}))}function Ht(){D.aframeCameraSyncAdded=!0,document.getElementById(`ar-scene`)?.setAttribute(`data-render-mode`,`disabled-xr8-single-scene`)}function Ut(e){let t=e?.domElement;!t||t.dataset.jarvisWebglRecoveryBound===`1`||(t.dataset.jarvisWebglRecoveryBound=`1`,ht(t,`webglcontextlost`,e=>{e.preventDefault(),w(`WebGL context lost. Pausing AR until the GPU recovers.`,`WebGL`);try{globalThis.XR8?.pause?.()}catch{}},{passive:!1}),ht(t,`webglcontextrestored`,()=>{if(w(`WebGL context restored.`,`WebGL`),Wt(e,D.config||{}),D.xrStarted)try{globalThis.XR8?.resume?.()}catch{}},{passive:!0}))}function Wt(e,t={}){if(!e)return;let n=String(t.renderScale||`adaptive`).toLowerCase(),r=n===`2`||n===`4k`?2:n===`1`?1:devicePixelRatio||1,i=Math.max(1,Math.min(r,3));r>3&&(console.warn(`Render scale ${r} was capped to 3.0. Requested scale: ${n}`),D.telemetry=D.telemetry||{},D.telemetry.pixelRatioCapped=!0,D.telemetry.originalPixelRatio=r),e.setPixelRatio(i),e.setSize(innerWidth,innerHeight,!1),e.outputColorSpace=d,e.toneMapping=4,e.toneMappingExposure=1,e.useLegacyLights=!1,e.shadowMap.enabled=!0,e.shadowMap.type=3}function Gt(){if(D.focusQuality.enabled)return;D.focusQuality.enabled=!0;let e=performance.now(),t=0,n=(e,t,n)=>{D.focusQuality.focusX=Math.max(0,Math.min(1,e)),D.focusQuality.focusY=Math.max(0,Math.min(1,t)),D.focusQuality.source=n};ht(window,`pointerdown`,e=>n(e.clientX/innerWidth,e.clientY/innerHeight,`touch`),{passive:!0}),ht(window,`pointermove`,e=>{e.pointerType!==`mouse`&&n(e.clientX/innerWidth,e.clientY/innerHeight,`touch`)},{passive:!0}),O(`gesture-point`,e=>{let t=e?.point;t&&n(t.x,t.y,`hand-point`)});let r=n=>{let i=Math.min(n-e,100);e=n,D.focusQuality.avgFrameMs=D.focusQuality.avgFrameMs*.92+i*.08,D.telemetry.frameMs=D.focusQuality.avgFrameMs,Lt(i),n-t>600&&(Kt(),t=n),N(r)};N(r)}function Kt(){let e=L(),t=e.renderer;if(!t)return;let n=D.focusQuality.avgFrameMs,r=Math.min(devicePixelRatio||1,3),i=n>33?{ratio:1,tier:`low`,shadows:!1}:n>25?{ratio:Math.min(1.2,r),tier:`medium`,shadows:!0}:n>18?{ratio:Math.min(1.5,r),tier:`balanced`,shadows:!0}:{ratio:r,tier:`high`,shadows:!0};Math.abs((D.focusQuality.pixelRatio||0)-i.ratio)>.05&&(t.setPixelRatio(i.ratio),t.setSize(innerWidth,innerHeight,!1),D.focusQuality.pixelRatio=i.ratio),D.focusQuality.tier=i.tier,D.telemetry.qualityTier=i.tier,document.body.dataset.jarvisQualityTier=i.tier,document.body.dataset.jarvisFrameMs=D.focusQuality.avgFrameMs.toFixed(1),performance.now()-D.telemetry.lastNativeStatusAt>5e3&&(D.telemetry.lastNativeStatusAt=performance.now(),I(`AR quality ${i.tier}, ${D.focusQuality.avgFrameMs.toFixed(1)}ms frame average`)),t.shadowMap&&(t.shadowMap.enabled=i.shadows),It(e,{mode:`ar-shell`,tier:i.tier,stereo:!!D.isVRMode,frameBudgetMs:i.tier===`high`?13.5:i.tier===`balanced`?16.6:20}),D.placedObjects.forEach(e=>qt(e,i.tier))}function qt(e,t){if(!e)return;let n=Jt(e)<.34?t:t===`high`?`balanced`:`low`;e.traverse(e=>{e.isMesh&&(e.frustumCulled=!0,e.castShadow=n!==`low`,e.receiveShadow=n!==`low`,e.material&&(e.material.needsUpdate=!1))})}function Jt(e){let t=D.camera||L().camera;if(!t)return 0;let n=new S;e.getWorldPosition(n),n.project(t);let r=n.x*.5+.5,i=-n.y*.5+.5;return Math.hypot(r-D.focusQuality.focusX,i-D.focusQuality.focusY)}function Yt(e){if(!e||e.userData.jarvisHelpersAdded)return;e.userData.jarvisHelpersAdded=!0;let t=new te(16777215,4469538,.72);t.name=`jarvis-ambient-fill`,e.add(t);let n=new ee(16777215,1.05);n.name=`jarvis-key-shadow-light`,n.position.set(1.4,3.2,1.2),n.castShadow=!0,n.shadow.mapSize.set(2048,2048),n.shadow.camera.near=.1,n.shadow.camera.far=10,n.shadow.camera.left=-5,n.shadow.camera.right=5,n.shadow.camera.top=5,n.shadow.camera.bottom=-5,n.shadow.bias=-5e-4,n.shadow.normalBias=.02,e.add(n),D.shadowLight=n;let i=new b(4491519,.28,8,2);i.name=`jarvis-ar-fill-light`,i.position.set(0,1.2,0),e.add(i),D.fillLight=i;let a=new m(new Ee(.08,.105,48),new h({color:16777215,transparent:!0,opacity:.65,side:2,depthWrite:!1}));a.name=`placement-reticle`,a.rotation.x=-Math.PI/2,a.position.set(0,D.floorY+.01,-1.8),a.visible=!1,e.add(a),D.reticle=a;let o=new m(new r(12,12),new ae({color:0,opacity:.24,transparent:!0,depthWrite:!1}));o.name=`jarvis-real-floor-shadow-receiver`,o.rotation.x=-Math.PI/2,o.position.set(0,D.floorY+.002,0),o.receiveShadow=!0,e.add(o),D.shadowReceiver=o}function Xt(){T(`status-camera`,D.cameraVideo||D.xrStarted?`live`:`standby`),T(`status-tracking`,D.trackingMode),T(`status-omega`,D.jarvis?.connected?`linked`:`offline`)}function Zt(){if(D.resizeBound)return;D.resizeBound=!0;let e=()=>{let e=L();e.camera?.isPerspectiveCamera&&(e.camera.aspect=innerWidth/innerHeight,e.camera.updateProjectionMatrix()),e.renderer?.setSize?.(innerWidth,innerHeight,!1),k(`ar-resize`,{width:innerWidth,height:innerHeight})};ht(window,`resize`,e),ht(window,`orientationchange`,()=>gt(e,100)),ht(document,`visibilitychange`,()=>{try{document.hidden?globalThis.XR8?.pause?.():globalThis.XR8?.resume?.()}catch{w(`8th Wall pause/resume is unavailable in this browser session.`)}})}var Qt=new Set,$t=null,en=null,tn=null,nn=0,rn=!1,an=class{constructor({title:e,width:t=340,height:n=480,icon:r=`O`,body:i}={}){let a=document.getElementById(`panel-template`).content.firstElementChild.cloneNode(!0);this.el=a,this.icon=r,this.isDragging=!1,this.isResizing=!1,this.startX=0,this.startY=0,this.currentX=Math.max(8,(innerWidth-t)/2),this.currentY=Math.max(72,(innerHeight-n)/2),this.velX=0,this.velY=0,this.animFrame=0,this.activePointerId=null,a.style.width=`clamp(280px, 90vw, ${t}px)`,a.style.minHeight=`${Math.min(n,innerHeight-170)}px`,a.querySelector(`h2`).textContent=e||`Panel`,i&&a.querySelector(`.panel-body`).appendChild(i),a.querySelector(`.panel-close`).addEventListener(`click`,()=>this.destroy()),a.querySelector(`.panel-minimize`).addEventListener(`click`,()=>this.minimize()),this.attachEvents(),document.getElementById(`ui-layer`).appendChild(a),this.applyTransform(),Qt.add(this)}attachEvents(){let e=this.el.querySelector(`.panel-drag-handle`);this._listeners=[[e,`pointerdown`,e=>this.onPointerStart(e)],[document,`pointermove`,e=>this.onPointerMove(e)],[document,`pointerup`,()=>this.onDragEnd()],[this.el,`pointerdown`,()=>this.focus()]],this._listeners.forEach(([e,t,n,r])=>e.addEventListener(t,n,r))}onPointerStart(e){e.preventDefault?.(),this.isDragging=!0,this.startX=e.clientX-this.currentX,this.startY=e.clientY-this.currentY,this.lastX=e.clientX,this.lastY=e.clientY,this.activePointerId=e.pointerId,vt(this.animFrame),e.currentTarget?.setPointerCapture?.(e.pointerId)}onPointerMove(e){this.isDragging&&this.applyDrag(e.clientX,e.clientY)}applyDrag(e,t){this.velX=e-this.lastX,this.velY=t-this.lastY,this.lastX=e,this.lastY=t,this.currentX=e-this.startX,this.currentY=t-this.startY,this.applyTransform()}onDragEnd(){this.isDragging&&(this.isDragging=!1,this.el.releasePointerCapture?.(this.activePointerId),this.activePointerId=null,this.applyMomentum())}applyMomentum(){this.velX*=.92,this.velY*=.92,this.currentX+=this.velX,this.currentY+=this.velY,this.applyTransform(),(Math.abs(this.velX)>.5||Math.abs(this.velY)>.5)&&(this.animFrame=N(()=>this.applyMomentum()))}applyTransform(){let e=this.el.getBoundingClientRect(),t=this.el.offsetWidth||e.width||parseFloat(this.el.style.width)||320,n=this.el.offsetHeight||e.height||parseFloat(this.el.style.minHeight)||420,r=Math.max(0,innerWidth-t),i=Math.max(0,innerHeight-n);this.currentX=Math.max(0,Math.min(this.currentX,r)),this.currentY=Math.max(0,Math.min(this.currentY,i)),this.el.style.transform=`translate3d(${this.currentX}px, ${this.currentY}px, 0)`}focus(){Qt.forEach(e=>e.el.classList.remove(`active`)),this.el.classList.add(`active`)}minimize(){this.el.classList.add(`minimized`);let e=document.createElement(`button`);e.className=`panel-orb glass-panel`,e.textContent=this.icon||`O`,e.setAttribute(`aria-label`,`Restore panel`);let t=document.querySelectorAll(`#ui-layer .panel-orb`).length;e.style.cssText=`width:56px;height:56px;border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:18px;position:absolute;bottom:${100+t*64}px;right:20px;z-index:20;color:white;pointer-events:auto`,e.onclick=()=>{this.restore(),e.remove()},document.getElementById(`ui-layer`).appendChild(e),this.el.style.display=`none`}restore(){this.el.style.display=``,this.el.classList.remove(`minimized`),this.focus()}destroy(){vt(this.animFrame),this._listeners?.forEach(([e,t,n,r])=>e.removeEventListener(t,n,r)),this._listeners=[],Qt.delete(this),this.el.remove(),Qt.size||_n()}};function on(){mn(),O(`ar-resize`,fn)}function sn(){return D.css3d?.initialized?(gn(),D.css3d):(en=en||new ie,$t=$t||cn(),D.css3d={scene:en,renderer:$t,panels:[],initialized:!0},hn(),gn(),D.css3dResizeBound||(ht(window,`resize`,pn),ht(window,`orientationchange`,()=>gt(pn,100)),D.css3dResizeBound=!0),D.css3d)}function cn(){let e=new Oe;e.setSize(innerWidth,innerHeight),e.domElement.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;z-index:2;pointer-events:auto;overflow:hidden;transform-style:preserve-3d`;let t=document.getElementById(`css3d-layer`);return t.style.pointerEvents=`none`,t.appendChild(e.domElement),e}function ln(e,t,n=800,r=530){let i=document.createElement(`div`);i.className=`game-panel-viewport`,i.style.cssText=`position:relative;width:100%;height:min(${Math.max(320,r-100)}px,68vh);min-height:320px;border-radius:16px;overflow:hidden;border:1px solid rgba(255,255,255,0.2);box-shadow:0 0 48px rgba(0,122,255,0.24),0 16px 42px rgba(0,0,0,0.52);background:#000;pointer-events:auto`,i.tabIndex=0;let a=document.createElement(`iframe`);a.src=e,a.className=`game-frame`,a.style.cssText=`position:absolute;inset:0;width:100%;height:100%;border:0;background:#000;pointer-events:auto`,a.setAttribute(`allow`,`autoplay; fullscreen; microphone; camera`),a.setAttribute(`referrerpolicy`,`origin-when-cross-origin`),a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms allow-pointer-lock allow-popups`),a.setAttribute(`referrerpolicy`,`no-referrer`),i.append(a);let o=new an({title:t,body:i,icon:`G`,width:Math.min(n,420),height:Math.min(r,640)});return o.el.classList.add(`ar-game-panel`),o.focus(),{object:null,iframe:a,container:i,titleBar:o.el.querySelector(`header`),panel:o,destroy:()=>o.destroy()}}function un(e){let t=(tn||L().camera)?.fov||60,r=innerHeight,i=Math.tan(n.degToRad(t/2));return e/(r/2/i)}function dn(){if(!$t||!en)return;let e=hn()||L().camera;e&&e!==tn&&(tn=e),tn&&(tn.updateMatrixWorld(!0),$t.setSize(innerWidth,innerHeight),$t.render(en,tn))}function fn(){Qt.forEach(e=>e.applyTransform()),D.css3d?.panels?.forEach(e=>e.scale.setScalar(un(2)))}function pn(){$t?.setSize(innerWidth,innerHeight),fn()}function mn(){document.getElementById(`hud-toolbar`)?.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-action]`);if(!t)return;let n=t.dataset.action;document.querySelectorAll(`#hud-toolbar .btn-symbol`).forEach(e=>e.classList.toggle(`selected`,e===t)),n===`models`?k(`open-models`):n===`scan`?k(`scan-room`):n===`games`?k(`open-games`):n===`builder`?k(`open-builder`):n===`vr`?k(`enter-vr`):n===`jarvis`&&k(`open-jarvis`)})}function hn(){try{let e=globalThis.XR8?.Threejs?.xrScene?.()?.camera||null;return e&&(tn=e),e}catch{return null}}function gn(){if(globalThis.XR8?.addCameraPipelineModule){nn&&(vt(nn),nn=0),rn?D.css3dPipelineAdded=!0:(globalThis.XR8.addCameraPipelineModule({name:`css3d-camera-sync`,onRender:()=>dn()}),D.pipelineOrder.push(`css3d-camera-sync`),rn=!0,D.css3dPipelineAdded=!0);return}if(nn)return;let e=()=>{if(D.css3dPipelineAdded){nn=0;return}dn(),nn=N(e)};nn=N(e)}function _n(e=!1){return!e&&Qt.size>0?!1:(nn&&vt(nn),nn=0,$t?.domElement?.remove?.(),$t=null,en=null,tn=null,D.css3d=null,D.css3dPipelineAdded=!1,rn=!1,!0)}function vn(){Qt.forEach(e=>e.destroy()),Qt.clear(),_n(!0),D.css3dResizeBound=!1,document.querySelectorAll(`#ui-layer .panel-orb, #ui-layer .ar-panel`).forEach(e=>e.remove())}function yn(e,t,n=`O`){let r=typeof t==`string`?document.createElement(`div`):t;return typeof t==`string`&&(r.textContent=t),new an({title:e,body:r,icon:n})}var bn=[{name:`Duck`,size:`~100KB`,category:`animal`},{name:`Avocado`,size:`~200KB`,category:`food`},{name:`BoxAnimated`,size:`~50KB`,category:`basic`},{name:`BrainStem`,size:`~3MB`,category:`organic`},{name:`CesiumMilkTruck`,size:`~1MB`,category:`vehicle`},{name:`DamagedHelmet`,size:`~30MB`,category:`scifi`},{name:`FlightHelmet`,size:`~30MB`,category:`scifi`},{name:`Fox`,size:`~2MB`,category:`animal`},{name:`GlamVelvetSofa`,size:`~10MB`,category:`furniture`},{name:`Lantern`,size:`~500KB`,category:`object`},{name:`ToyCar`,size:`~3MB`,category:`vehicle`},{name:`WaterBottle`,size:`~1MB`,category:`object`},{name:`AntiqueCamera`,size:`~3MB`,category:`object`},{name:`BarramundiFish`,size:`~2MB`,category:`animal`},{name:`Corset`,size:`~500KB`,category:`clothing`},{name:`ReciprocatingSaw`,size:`~5MB`,category:`tool`},{name:`Sponza`,size:`~50MB`,category:`environment`},{name:`DragonAttenuation`,size:`~5MB`,category:`creature`},{name:`IridescenceLamp`,size:`~2MB`,category:`furniture`},{name:`GlassVaseBacklit`,size:`~1MB`,category:`object`},{name:`MaterialsVariantsShoe`,size:`~5MB`,category:`clothing`},{name:`OrientationTest`,size:`~500KB`,category:`test`},{name:`NormalTangentTest`,size:`~500KB`,category:`test`},{name:`EnvironmentTest`,size:`~2MB`,category:`test`},{name:`SheenCloth`,size:`~2MB`,category:`fabric`}];function xn(e){let t=String(e||`Duck`).replace(/[^A-Za-z0-9_-]/g,``);return`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/${t}/glTF-Binary/${t}.glb`}function Sn(e){let t=String(e||``).toLowerCase();return bn.find(e=>t.includes(e.name.toLowerCase()))||bn.find(e=>t.includes(e.category.toLowerCase()))||bn[0]}var Cn=`jarvis_sketchfab_access_token_v1`,wn=[{slug:`by`,label:`CC BY`},{slug:`by-sa`,label:`CC BY-SA`},{slug:`by-nd`,label:`CC BY-ND`},{slug:`by-nc`,label:`CC BY-NC`},{slug:`by-nc-sa`,label:`CC BY-NC-SA`},{slug:`by-nc-nd`,label:`CC BY-NC-ND`},{slug:`cc0`,label:`CC0`},{slug:`standard`,label:`Free Standard`}],Tn=wn.map(e=>e.slug),En=new Set(Tn);function Dn(e){if(!e)return``;let t=(typeof e==`string`?e:e.slug||e.uid||e.label||e.fullName||e.url||e.uri||``).toString().trim().toLowerCase(),n=t.match(/(?:^|\/)(cc0|standard|by(?:-nc)?(?:-sa|-nd)?)(?:\/|$)/);if(n)return n[1];if(t.includes(`free standard`)||t===`standard`)return`standard`;if(t.includes(`cc0`)||t.includes(`public domain`))return`cc0`;if(!t.includes(`attribution`)&&!t.includes(`creative commons`))return t;let r=t.includes(`noncommercial`)||t.includes(`non-commercial`),i=t.includes(`noderivs`)||t.includes(`no derivatives`)||t.includes(`no-derivatives`),a=t.includes(`sharealike`)||t.includes(`share alike`)||t.includes(`share-alike`);return r&&i?`by-nc-nd`:r&&a?`by-nc-sa`:r?`by-nc`:i?`by-nd`:a?`by-sa`:`by`}function On(e){return En.has(Dn(e))}function kn(e){let t=Dn(e);return wn.find(e=>e.slug===t)?.label||t.toUpperCase()}function An(){try{return sessionStorage.getItem(`jarvis_sketchfab_access_token_v1`)||``}catch{return``}}function jn(e){try{let t=String(e||``).trim();t?sessionStorage.setItem(Cn,t):sessionStorage.removeItem(Cn),localStorage.removeItem(Cn)}catch{}}async function Mn(e=`studio`){let t=await fetch(`https://api.polyhaven.com/assets?type=hdris`,{cache:`force-cache`});if(!t.ok)throw Error(`PolyHaven HDR request failed: ${t.status}`);let n=await t.json(),r=Object.keys(n);if(!r.length)throw Error(`PolyHaven returned no HDR assets.`);return`https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/${r.find(t=>t.toLowerCase().includes(String(e).toLowerCase()))||r[0]}_1k.hdr`}function Nn(e,{count:t=12,license:n=``}={}){let r=new URL(`https://api.sketchfab.com/v3/models`);return r.searchParams.set(`q`,String(e||``).trim()),r.searchParams.set(`downloadable`,`true`),r.searchParams.set(`type`,`models`),r.searchParams.set(`count`,String(t)),r.searchParams.set(`archives_flavours`,`true`),n&&r.searchParams.set(`license`,n),r.toString()}async function Pn(e,t=``,{count:n=24}={}){let r=Math.max(4,Math.ceil(n/Tn.length));if(!t){let t=await Vn(e,n);if(t)return t}let i=[],a=[];for(let o of Tn)try{let a=await In(e,t,o,r);if(i.push(a),Fn(i).length>=n)break}catch(e){a.push(e)}let o=Fn(i);if(!o.length&&a.length===Tn.length)throw Error(a[0]?.message||`Sketchfab search failed for all allowed free licenses.`);let s=new Set;return o.filter(e=>e?.uid&&!s.has(e.uid)&&s.add(e.uid)).filter(e=>e?.isDownloadable!==!1).filter(e=>On(e?.license)).map(Ln).slice(0,n)}function Fn(e){let t=[],n=Math.max(0,...e.map(e=>e.length));for(let r=0;r<n;r+=1)for(let n of e)n[r]&&t.push(n[r]);return t}async function In(e,t,n,r){let i=t?{Authorization:`Bearer ${t}`}:{},a=await fetch(Nn(e,{count:r,license:n}),{headers:i});if(!a.ok)throw Error(`Sketchfab search failed for ${n}: ${a.status}`);let o=await a.json();return Array.isArray(o.results)?o.results:[]}function Ln(e){return{uid:e.uid,name:e.name||`Sketchfab model`,license:Dn(e.license),licenseLabel:kn(e.license),author:e.user?.displayName||e.user?.username||`Sketchfab creator`,authorUrl:e.user?.profileUrl||``,viewerUrl:e.viewerUrl||`https://sketchfab.com/3d-models/${e.uid}`,thumbnail:Un(e.thumbnails),faceCount:e.faceCount||e.archives?.gltf?.faceCount||e.archives?.glb?.faceCount||0,vertexCount:e.vertexCount||e.archives?.gltf?.vertexCount||e.archives?.glb?.vertexCount||0,size:e.archives?.glb?.size||e.archives?.gltf?.size||0,source:e}}async function Rn(e,t){if(!t){let t=await Hn(e);if(t)return t}if(!t)throw Error(`Sketchfab downloads require a configured OMEGA Sketchfab token or a pasted OAuth/API token.`);let n=await fetch(`https://api.sketchfab.com/v3/models/${encodeURIComponent(e)}/download`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok)throw Error(`Sketchfab download request failed: ${n.status}`);return n.json()}function zn(e={}){let t=qn(`omega_session`);return t?{...e,Authorization:`Bearer ${t}`}:{...e}}async function Bn(){try{let e=await fetch(`/api/sketchfab/status`,{cache:`no-store`,headers:zn()});return e.ok?e.json():{ok:!1,configured:!1}}catch{return{ok:!1,configured:!1}}}async function Vn(e,t){try{let n=new URLSearchParams({q:String(e||``).trim(),count:String(t)}),r=await fetch(`/api/sketchfab/search?${n}`,{cache:`no-store`,headers:zn()});if(!r.ok)return null;let i=await r.json();return!i?.ok||!Array.isArray(i.models)?null:i.models.filter(e=>On(e.license)).map(e=>({uid:e.uid,name:e.name||`Sketchfab model`,license:Dn(e.license),licenseLabel:kn(e.license),author:e.author||`Sketchfab creator`,authorUrl:e.authorUrl||``,viewerUrl:e.viewerUrl||`https://sketchfab.com/3d-models/${e.uid}`,thumbnail:e.thumbnail||``,faceCount:e.faceCount||0,vertexCount:e.vertexCount||0,size:e.size||0,source:e}))}catch{return null}}async function Hn(e){try{let t=new URLSearchParams({uid:String(e||``)}),n=await fetch(`/api/sketchfab/download?${t}`,{cache:`no-store`,headers:zn()});if(!n.ok)return null;let r=await n.json();return!r?.ok||!r.download?null:r.download}catch{return null}}function Un(e){return[...Array.isArray(e?.images)?e.images:[]].sort((e,t)=>(t.width||0)-(e.width||0))[0]?.url||``}var Wn=[{name:`Tractor`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/CesiumMilkTruck/glTF-Binary/CesiumMilkTruck.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/CesiumMilkTruck/screenshot/screenshot-thumb.png`},{name:`Racecar`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/ToyCar/glTF-Binary/ToyCar.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/ToyCar/screenshot/screenshot-thumb.png`},{name:`Duck`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/glTF-Binary/Duck.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/screenshot/screenshot-thumb.png`},{name:`Lantern`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Lantern/glTF-Binary/Lantern.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Lantern/screenshot/screenshot-thumb.png`},{name:`Sofa`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/GlamVelvetSofa/glTF-Binary/GlamVelvetSofa.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/GlamVelvetSofa/screenshot/screenshot-thumb.png`},{name:`Water Bottle`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/WaterBottle/glTF-Binary/WaterBottle.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/WaterBottle/screenshot/screenshot-thumb.png`},{name:`Antique Camera`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/AntiqueCamera/glTF-Binary/AntiqueCamera.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/AntiqueCamera/screenshot/screenshot-thumb.png`},{name:`Saw`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/ReciprocatingSaw/glTF-Binary/ReciprocatingSaw.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/ReciprocatingSaw/screenshot/screenshot-thumb.png`},{name:`Castle Sponza`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Sponza/glTF-Binary/Sponza.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Sponza/screenshot/screenshot-thumb.png`},{name:`Robot Expressive`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/RobotExpressive.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake1.png`},{name:`Soldier`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Soldier.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake2.png`},{name:`Flamingo`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Flamingo.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake3.png`},{name:`Parrot`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Parrot.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake4.png`},{name:`Stork`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Stork.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake5.png`},{name:`Sheen Chair`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/SheenChair.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake6.png`},{name:`XBot Rigged`,provider:`mixamo`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Xbot.glb`,license:`free`,author:`Mixamo / Adobe`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake1.png`},{name:`Soldier Rigged`,provider:`mixamo`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Soldier.glb`,license:`free`,author:`Mixamo / Adobe`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake2.png`},{name:`Robot Anim`,provider:`mixamo`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/RobotExpressive.glb`,license:`free`,author:`Mixamo / Adobe`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake3.png`}];function Gn(e){return String(e||``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}function Kn(e){return String(e||``).charAt(0).toUpperCase()+String(e||``).slice(1)}function qn(e){try{return localStorage.getItem(`jarvis_${e}_credentials_v1`)||``}catch{return``}}function Jn(e,t){try{localStorage.setItem(`jarvis_${e}_credentials_v1`,String(t||``).trim())}catch{}}try{if(typeof localStorage<`u`)for(let e of[`jarvis_poly_pizza_credentials_v1`,`jarvis_cgtrader_credentials_v1`,`jarvis_turbosquid_credentials_v1`,`jarvis_mixamo_credentials_v1`]){let t=localStorage.getItem(e);(t===`omega-public-free-poly-pizza-key-2026`||t===`cgtrader_omega_public_free_session`||t===`turbosquid_omega_public_free_session`||t===`mixamo_omega_public_free_adobe_id`)&&localStorage.removeItem(e)}}catch{}async function Yn(e,t,n){try{let r=new URL(`https://www.cgtrader.com/api/v1/models`);r.searchParams.set(`q`,String(e||``).trim()),r.searchParams.set(`free`,`true`),r.searchParams.set(`per_page`,String(Math.min(n,24))),r.searchParams.set(`sort`,`relevance`),r.searchParams.set(`file_type`,`glb,gltf,fbx,obj`);let i=await fetch(r.toString(),{headers:{Authorization:`Token ${t}`,Accept:`application/json`}});if(!i.ok)throw Error(`CGTrader API returned ${i.status}`);let a=await i.json(),o=Array.isArray(a.data)?a.data:Array.isArray(a.models)?a.models:[];if(o.length)return o.map(e=>({uid:`cgtrader:${e.id||e.uid||e.slug}`,name:e.name||e.title||`CGTrader Model`,license:e.license||`free`,licenseLabel:e.license_label||`Free Standard`,author:e.author?.username||e.user?.name||`CGTrader Creator`,authorUrl:`https://www.cgtrader.com/designers/${e.author?.username||``}`,viewerUrl:e.url||`https://www.cgtrader.com/3d-models/${e.slug||e.id}`,thumbnail:e.previews?.[0]?.url||e.preview_url||e.thumbnail||``,faceCount:e.polygon_count||0,vertexCount:e.vertex_count||0,size:e.total_size||0,downloadUrl:e.download_url||e.files?.[0]?.url||``,source:`cgtrader`})).slice(0,n)}catch{}let r=new URLSearchParams({q:String(e||``).trim(),count:String(n),api_key:t}),i=await fetch(`/api/cgtrader/search?${r}`,{cache:`no-store`,headers:zn()});if(!i.ok)throw Error(`OMEGA CGTrader proxy returned ${i.status}`);let a=await i.json();if(!a?.ok||!Array.isArray(a.models)||!a.models.length)throw Error(`CGTrader proxy: no results`);return a.models.map(e=>({...e,source:`cgtrader`})).slice(0,n)}async function Xn(e,t,n){let r=String(t||``).indexOf(`:`),i=r>0?t.slice(0,r).trim():``,a=r>0?t.slice(r+1).trim():``;try{let t=new URL(`https://www.turbosquid.com/turbosquid/search/api/search`);t.searchParams.set(`search_keyword`,String(e||``).trim()),t.searchParams.set(`price_min`,`0`),t.searchParams.set(`price_max`,`0`),t.searchParams.set(`media_typeid`,`2`),t.searchParams.set(`file_type`,`glb,gltf,fbx`),t.searchParams.set(`per_page`,String(Math.min(n,24))),t.searchParams.set(`sort_by`,`relevance`);let r={Accept:`application/json`};i&&a&&(r.Authorization=`Bearer ${a}`);let o=await fetch(t.toString(),{headers:r});if(!o.ok)throw Error(`TurboSquid API returned ${o.status}`);let s=await o.json(),c=Array.isArray(s.results)?s.results:Array.isArray(s.products)?s.products:[];if(c.length)return c.map(e=>({uid:`turbosquid:${e.id||e.product_id||e.slug}`,name:e.name||e.title||`TurboSquid Model`,license:e.license||`free`,licenseLabel:e.license_label||`Free Standard`,author:e.artist?.username||e.author||`TurboSquid Artist`,authorUrl:`https://www.turbosquid.com/Search/Artists/${e.artist?.username||``}`,viewerUrl:e.url||`https://www.turbosquid.com/3d-models/${e.slug||e.id}`,thumbnail:e.thumbnail_url||e.preview_url||e.thumbnail||``,faceCount:e.polygon_count||0,vertexCount:e.vertex_count||0,size:e.file_size||0,downloadUrl:e.download_url||e.files?.[0]?.download_url||``,source:`turbosquid`})).slice(0,n)}catch{}let o=new URLSearchParams({q:String(e||``).trim(),count:String(n)});i&&o.set(`username`,i),a&&o.set(`api_key`,a);let s=await fetch(`/api/turbosquid/search?${o}`,{cache:`no-store`,headers:zn()});if(!s.ok)throw Error(`OMEGA TurboSquid proxy returned ${s.status}`);let c=await s.json();if(!c?.ok||!Array.isArray(c.models)||!c.models.length)throw Error(`TurboSquid proxy: no results`);return c.models.map(e=>({...e,source:`turbosquid`})).slice(0,n)}async function Zn(e,t,n){let r=String(t||``).indexOf(`:`);if(r<1)throw Error(`Mixamo: credentials must be adobe_email:adobe_password`);let i=t.slice(0,r).trim(),a=t.slice(r+1).trim();if(!i||!a)throw Error(`Mixamo: email or password empty`);try{let t=await fetch(`https://ims-na1.adobelogin.com/ims/token/v3`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`password`,username:i,password:a,client_id:`mixamo_studio`,client_secret:`mixamo_studio`,scope:`openid,creative_sdk,avatar_sync`})});if(!t.ok)throw Error(`Adobe IMS auth failed: ${t.status}`);let r=(await t.json()).access_token;if(!r)throw Error(`Adobe IMS returned no access_token`);let o=new URL(`https://mixamo-api.adobe.com/v1/products`);o.searchParams.set(`limit`,String(Math.min(n,24))),o.searchParams.set(`offset`,`0`),e&&o.searchParams.set(`query`,String(e).trim()),o.searchParams.set(`type`,`Character,Motion`),o.searchParams.set(`order_by`,`relevance`);let s=await fetch(o.toString(),{headers:{Authorization:`Bearer ${r}`,"X-Api-Key":`mixamo_studio`,Accept:`application/json`}});if(!s.ok)throw Error(`Mixamo API returned ${s.status}`);let c=await s.json(),l=Array.isArray(c.results)?c.results:Array.isArray(c.data)?c.data:[];if(l.length)return l.map(e=>({uid:`mixamo:${e.id||e.character_id||e.slug}`,name:e.name||e.character_name||`Mixamo Character`,license:`free`,licenseLabel:`Free (Mixamo)`,author:`Mixamo / Adobe`,authorUrl:`https://www.mixamo.com/#/?id=${e.id||``}`,viewerUrl:`https://www.mixamo.com/#/?id=${e.id||``}`,thumbnail:e.thumbnail_url||e.preview_url||e.image||``,faceCount:e.polygon_count||0,vertexCount:0,size:0,downloadUrl:e.export_url||``,source:`mixamo`})).slice(0,n)}catch{}let o=await fetch(`/api/mixamo/search`,{method:`POST`,headers:zn({"Content-Type":`application/json`}),body:JSON.stringify({email:i,password:a,q:String(e||``).trim(),count:n}),cache:`no-store`});if(!o.ok)throw Error(`OMEGA Mixamo proxy returned ${o.status}`);let s=await o.json();if(!s?.ok||!Array.isArray(s.models)||!s.models.length)throw Error(`Mixamo proxy: no results`);return s.models.map(e=>({...e,source:`mixamo`})).slice(0,n)}async function Qn(e,t,n){let r=`https://api.poly.pizza/v1/search?q=${encodeURIComponent(e)}`,i=await fetch(r,{headers:{"x-auth-token":t}});if(!i.ok)throw Error(`Poly.pizza returned ${i.status}`);return((await i.json()).results||[]).map(e=>({uid:`poly_pizza:${e.id||e.uid}`,name:e.title||e.name||`Poly.pizza model`,license:e.license||`cc0`,licenseLabel:e.license||`CC0`,author:e.author||`Poly.pizza Creator`,authorUrl:`https://poly.pizza/m/${e.id||e.uid}`,viewerUrl:`https://poly.pizza/m/${e.id||e.uid}`,thumbnail:e.thumbnail||`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/screenshot/screenshot-thumb.png`,faceCount:e.faceCount||0,vertexCount:e.vertexCount||0,size:e.size||0,downloadUrl:e.Download||e.url||``,source:`poly_pizza`})).slice(0,n)}async function $n(e,t=`all`,n=``,{count:r=24}={}){let i=String(e||``).trim().toLowerCase(),a=[];(t===`all`||t===`stable_fast_3d`)&&i&&a.push({uid:`stable_fast_3d:generate:${Gn(i)}`,name:`Generate: "${i}"`,license:`Local AI Generation`,licenseLabel:`Local`,author:`Stable Fast 3D (Jarvis)`,authorUrl:``,viewerUrl:``,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Box/glTF/Box_thumbnail.jpg`,faceCount:0,vertexCount:0,size:0,downloadUrl:`api:spawn_3d_model:${i}`,source:`stable_fast_3d`,catalogSource:`ai-generation`,provider:`stable_fast_3d`});let o=qn(`poly_pizza`);if((t===`all`||t===`poly_pizza`)&&o&&i)try{let e=await Qn(i,o,r);a.push(...e)}catch{}let s=qn(`cgtrader`);if((t===`all`||t===`cgtrader`)&&s&&i)try{let e=await Yn(i,s,r);a.push(...e)}catch{}let c=qn(`turbosquid`);if((t===`all`||t===`turbosquid`)&&c&&i)try{let e=await Xn(i,c,r);a.push(...e)}catch{}let l=qn(`mixamo`);if((t===`all`||t===`mixamo`)&&l&&i)try{let e=await Zn(i,l,r);a.push(...e)}catch{}let u=Wn.filter(e=>{let n=t===`all`||e.provider===t,r=!i||e.name.toLowerCase().includes(i)||e.author.toLowerCase().includes(i);return n&&r}).map(e=>({uid:`${e.provider}:${Gn(e.name)}`,name:e.name,license:e.license,licenseLabel:e.license===`cc0`?`CC0`:`Free`,author:e.author,authorUrl:e.url,viewerUrl:e.url,thumbnail:e.thumbnail,faceCount:0,vertexCount:0,size:0,downloadUrl:e.url,source:e.provider,catalogSource:`curated-sample`,provider:e.provider}));if(a.push(...u),t===`all`||t===`cgtrader`||t===`turbosquid`||t===`poly_pizza`||t===`mixamo`){let e=[{name:`Retro Space Ship`,license:`Free Standard`,author:`Sample fallback asset`,provider:`cgtrader`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/DamagedHelmet/glTF-Binary/DamagedHelmet.glb`,keywords:[`space`,`ship`,`rocket`,`vehicle`,`helmet`,`sci-fi`,`scifi`]},{name:`SciFi Plasma Gun`,license:`Free Standard`,author:`Sample fallback asset`,provider:`cgtrader`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Lantern/glTF-Binary/Lantern.glb`,keywords:[`gun`,`weapon`,`scifi`,`plasma`,`laser`]},{name:`Modern Office Chair`,license:`Free Standard`,author:`Sample fallback asset`,provider:`cgtrader`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/SheenChair.glb`,keywords:[`chair`,`furniture`,`office`,`seat`]},{name:`Astronaut Character`,license:`Free Standard`,author:`Sample fallback asset`,provider:`cgtrader`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Soldier.glb`,keywords:[`astronaut`,`person`,`space`,`character`]},{name:`City Sports Car`,license:`Free Standard`,author:`Sample fallback asset`,provider:`turbosquid`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/ToyCar/glTF-Binary/ToyCar.glb`,keywords:[`car`,`vehicle`,`sports`,`auto`,`toy`]},{name:`Fighter Jet Plane`,license:`Free Standard`,author:`Sample fallback asset`,provider:`turbosquid`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/CesiumMilkTruck/glTF-Binary/CesiumMilkTruck.glb`,keywords:[`plane`,`jet`,`aircraft`,`vehicle`,`fly`]},{name:`Lighthouse Beacon`,license:`Free Standard`,author:`Sample fallback asset`,provider:`turbosquid`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Lantern/glTF-Binary/Lantern.glb`,keywords:[`lighthouse`,`beacon`,`tower`,`building`]},{name:`Industrial Wooden Crate`,license:`Free Standard`,author:`Sample fallback asset`,provider:`turbosquid`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/glTF-Binary/Duck.glb`,keywords:[`crate`,`box`,`barrel`,`wood`,`industrial`]},{name:`Low Poly Tree Pack`,license:`CC0`,author:`Sample fallback asset`,provider:`poly_pizza`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Lantern/glTF-Binary/Lantern.glb`,keywords:[`tree`,`forest`,`plant`,`nature`,`lowpoly`]},{name:`Holographic Gizmo Sphere`,license:`CC0`,author:`Sample fallback asset`,provider:`poly_pizza`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/OrientationTest/glTF-Binary/OrientationTest.glb`,keywords:[`sphere`,`gizmo`,`hologram`,`test`]},{name:`Magical Potion Bottle`,license:`CC0`,author:`Sample fallback asset`,provider:`poly_pizza`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/WaterBottle/glTF-Binary/WaterBottle.glb`,keywords:[`potion`,`magic`,`bottle`,`drink`]},{name:`Mythical Knight Shield`,license:`CC0`,author:`Sample fallback asset`,provider:`poly_pizza`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/SheenChair.glb`,keywords:[`shield`,`armor`,`knight`,`weapon`]},{name:`YBot Rigged Character`,license:`Free`,author:`Sample fallback asset`,provider:`mixamo`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Xbot.glb`,keywords:[`ybot`,`character`,`man`,`rigged`,`skeletal`]},{name:`Zombie Undead Anim`,license:`Free`,author:`Sample fallback asset`,provider:`mixamo`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Soldier.glb`,keywords:[`zombie`,`monster`,`undead`,`animated`,`rigged`]}].filter(e=>{let n=t===`all`||e.provider===t,r=!i||e.name.toLowerCase().includes(i)||e.keywords.some(e=>i.includes(e)||e.includes(i));return n&&r}).map(e=>({uid:`${e.provider}:${Gn(e.name)}`,name:e.name,license:`free`,licenseLabel:e.license,author:e.author,authorUrl:e.url,viewerUrl:e.url,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/screenshot/screenshot-thumb.png`,faceCount:0,vertexCount:0,size:0,downloadUrl:e.url,source:e.provider,catalogSource:`sample-fallback`,provider:e.provider}));a.push(...e)}if(t===`all`||t===`sketchfab`)try{let t=await Pn(e,n,{count:r});a.push(...t.map(e=>({...e,downloadUrl:``,source:`sketchfab`})))}catch{}let d=new Set;return a=a.filter(e=>e?.uid&&!d.has(e.uid)&&d.add(e.uid)),!a.length&&i&&a.push({uid:`forge:${Gn(i)}`,name:`${Kn(i)} (Interactive Forge)`,license:`free`,licenseLabel:`CC0 / Procedural`,author:`Jarvis Model Forge`,authorUrl:`#`,viewerUrl:`#`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/screenshot/screenshot-thumb.png`,faceCount:0,vertexCount:0,size:0,downloadUrl:`forge-procedural`,source:`forge`}),a.slice(0,r)}function er(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function tr(e,t){try{return localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function nr(e,t=``){try{return localStorage.getItem(e)||t}catch{return t}}function rr(e,t){try{return localStorage.setItem(e,String(t)),!0}catch{return!1}}var ir=0,ar=!1;function or(e=`ar`){let t=globalThis.crypto?.getRandomValues?Array.from(globalThis.crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,`0`)).join(``):(()=>{ar||(ar=!0),ir=(ir+1)%1048576;let e=String(globalThis.performance?.now?.()||0).replace(`.`,``);return`${Date.now().toString(36)}_${e}_${ir.toString(36)}`})();return`${e}_${Date.now().toString(36)}_${t}`}function sr(e,t,{valueKey:n=null,labelKey:r=null}={}){if(e){e.replaceChildren();for(let i of t){let t=document.createElement(`option`);if(Array.isArray(i)||n&&r&&i&&typeof i==`object`){let[e,a]=Array.isArray(i)?i:[i[n],i[r]];t.value=String(e??``),t.textContent=String(a??e??``)}else t.value=String(i),t.textContent=String(i);e.appendChild(t)}}}var cr=1,lr=2048,ur=8;function dr(e){let t=new Set,n=new Set,r=new Set,i=0,a=0;if(!e?.traverse)return{bytes:0,geometryCount:0,materialCount:0,textureCount:0,maxDimension:0,warnings:[]};e.updateMatrixWorld?.(!0);let o=new fe().setFromObject(e);if(!o.isEmpty()){let e=o.getSize(new S);a=Math.max(e.x,e.y,e.z,0)}e.traverse(e=>{e.geometry&&!t.has(e.geometry)&&(t.add(e.geometry),i+=_r(e.geometry)),hr(e.material,e=>{n.has(e)||(n.add(e),i+=2048),gr(e,(e,t)=>{r.has(e)||(r.add(e),i+=vr(e))})})});let s=[];return i>48*1024*1024&&s.push(`model-asset-heavy`),r.size>12&&s.push(`texture-count-high`),a>12&&s.push(`model-scale-large`),{bytes:i,geometryCount:t.size,materialCount:n.size,textureCount:r.size,maxDimension:a,warnings:s}}function fr(e,t={}){if(!e?.traverse)return e;let n=Number.isFinite(t.targetSize)?t.targetSize:cr,r=Number.isFinite(t.maxTextureSize)?t.maxTextureSize:lr,i=Number.isFinite(t.maxAnisotropy)?t.maxAnisotropy:ur,a=dr(e),o=new fe().setFromObject(e);if(!o.isEmpty()){let t=o.getSize(new S),r=n/Math.max(t.x,t.y,t.z,1e-4),i=o.getCenter(new S);e.position.sub(i),e.scale.multiplyScalar(r)}return e.userData=e.userData||{},e.userData.assetMetrics=a,e.userData.assetWarnings=a.warnings.slice(),e.traverse(e=>{e.isMesh&&(e.castShadow=!0,e.receiveShadow=!0,e.frustumCulled=!0,e.material&&hr(e.material,(e,t)=>{pr(e,{maxTextureSize:r,maxAnisotropy:i})}))}),e.updateMatrixWorld?.(!0),e}function pr(e,t={}){if(!e)return e;let n=Number.isFinite(t.maxTextureSize)?t.maxTextureSize:lr,r=Number.isFinite(t.maxAnisotropy)?t.maxAnisotropy:ur;return e.userData=e.userData||{},e.needsUpdate=!0,`roughness`in e&&(e.roughness=yr(e.roughness)),`metalness`in e&&(e.metalness=yr(e.metalness)),`emissiveIntensity`in e&&(e.emissiveIntensity=Math.min(Number(e.emissiveIntensity??1),1)),gr(e,(e,t)=>{mr(e,t,{maxTextureSize:n,maxAnisotropy:r})}),e}function mr(e,t=``,n={}){if(!e)return e;let r=Number.isFinite(n.maxTextureSize)?n.maxTextureSize:lr,i=Number.isFinite(n.maxAnisotropy)?n.maxAnisotropy:ur,o=e.image||{},s=o.width||o.videoWidth||o.naturalWidth||0,c=o.height||o.videoHeight||o.naturalHeight||0;return/map|baseColor|albedo|diffuse|emissive/i.test(t)&&(e.colorSpace=d),e.flipY=!1,e.generateMipmaps=s>0&&c>0,e.minFilter=s>r||c>r?a:g,e.magFilter=a,e.anisotropy=Math.max(1,Math.min(i,e.anisotropy||i)),e.needsUpdate=!0,e}function hr(e,t){(Array.isArray(e)?e:[e]).filter(Boolean).forEach(e=>t(e))}function gr(e,t){let n=new Set,r=(e,i=``)=>{if(!(!e||typeof e!=`object`)){if(e.isTexture){n.has(e)||(n.add(e),t(e,i));return}if(Array.isArray(e)){e.forEach(e=>r(e,i));return}e.value?.isTexture?r(e.value,i):e.constructor===Object&&Object.entries(e).forEach(([e,t])=>r(t,e))}};Object.entries(e||{}).forEach(([e,t])=>r(t,e))}function _r(e){let t=0,n=e=>{e?.array?.byteLength&&(t+=e.array.byteLength)};return Object.values(e.attributes||{}).forEach(n),Object.values(e.morphAttributes||{}).forEach(e=>e.forEach(n)),n(e.index),t}function vr(e){let t=e?.image||{};if(t.data?.byteLength)return t.data.byteLength;let n=t.width||t.videoWidth||t.naturalWidth||256,r=t.height||t.videoHeight||t.naturalHeight||256;return Math.max(1,n)*Math.max(1,r)*4}function yr(e){return Math.max(0,Math.min(1,Number(e)||0))}var br=`jarvis_ar_model_forge_v1`,xr=[`house`,`room`,`device`,`vehicle`,`character`,`scene`],Sr=[`open`,`close`,`toggle`,`rotate`,`reveal`,`hide`,`shatter`,`reconfigure`];function Cr(){if(globalThis.crypto?.getRandomValues){let e=new Uint32Array(1);return globalThis.crypto.getRandomValues(e),e[0]/4294967295}return performance.now()%997/997}function wr(){return er(br,[])}function Tr(e){let t=wr().filter(t=>t.id!==e.id);return t.push(e),tr(br,t.slice(-40)),e}function R({name:e=`Custom Model`,prompt:t=``,kit:n=`scene`,parts:r=[],behaviors:i=[]}={}){let a=xr.includes(String(n||``).toLowerCase())?String(n).toLowerCase():`scene`;return{id:or(`blueprint`),name:String(e||`Custom Model`).trim()||`Custom Model`,prompt:String(t||``).trim(),kit:a,parts:Array.isArray(r)&&r.length?r.map(Yr):ri(a),behaviors:Array.isArray(i)&&i.length?i.map(Xr):ii(a),createdAt:Date.now(),updatedAt:Date.now()}}async function Er(e,t={}){let n=String(e||``).trim();if(!n)throw Error(`A prompt is required to generate a blueprint.`);let r=globalThis.Jarvis;if(!r?.query)return w(`Jarvis is unavailable, so the model forge is using a local template blueprint instead.`,`Model Forge`),R({name:t.name||n.slice(0,24),prompt:n,kit:t.kit||`scene`});let i=[`Create a compact JSON blueprint for a fully interactive 3D model.`,`Return JSON only, no markdown, no prose.`,`Schema:`,`{`,` "name": "string",`,` "kit": "house|room|device|vehicle|character|scene",`,` "parts": [`,` {`,` "name": "string",`,` "type": "base|wall|door|window|roof|drawer|panel|screen|wheel|prop|light|arm|leg|head|detail",`,` "geometry": "box|sphere|cylinder|cone|torus|ring|capsule|octahedron|icosahedron",`,` "material": "matte|metal|glass|glow|wood",`,` "position": [0,0,0],`,` "rotation": [0,0,0],`,` "scale": [1,1,1],`,` "actions": ["open","close","toggle","rotate","reveal","hide","shatter","reconfigure"]`,` }`,` ],`,` "behaviors": [`,` { "gesture": "pinch|fist|open-palm|swipe-left|swipe-right|two-hand-scale", "action": "string", "target": "part name" }`,` ]`,`}`,`Prompt: ${n}`,t.name?`Preferred name: ${t.name}`:``,t.kit?`Preferred kit: ${t.kit}`:``].filter(Boolean).join(`
`);try{let e=li(await r.query(i));if(e){let r=R({name:e.name||t.name||n.slice(0,24),prompt:n,kit:e.kit||t.kit||`scene`,parts:Array.isArray(e.parts)?e.parts:[],behaviors:Array.isArray(e.behaviors)?e.behaviors:[]});return r.prompt=n,r.source=`jarvis`,r.updatedAt=Date.now(),r}}catch(e){w(`Jarvis blueprint generation failed, using local template: ${e.message}`,`Model Forge`)}return R({name:t.name||n.slice(0,24),prompt:n,kit:t.kit||ei(n)})}function Dr(e,t=de){let n=e?.id?e:R(e),r=new t.Group;r.name=`interactive-${H(n.name)}`,r.userData.isARObject=!0,r.userData.modelName=n.name,r.userData.modelForge={id:n.id,kit:n.kit,prompt:n.prompt,behaviors:n.behaviors,parts:[],state:{}};let i=[],a={base:[],walls:[],doors:[],windows:[],roofs:[],details:[],lights:[],wheels:[],screens:[],arms:[],legs:[],heads:[],drawers:[]};for(let e of n.parts){let n=Rr(e,t);i.push(n),r.add(n.root),a[Qr(e.type)].push(n),r.userData.modelForge.parts.push({id:n.id,name:n.name,type:n.type,actions:n.actions.slice()})}return zr(r,a,n,t),Or(r,n),Tr(n),r}function Or(e,t){return e.userData.modelForge=e.userData.modelForge||{},e.userData.modelForge.id=t.id,e.userData.modelForge.kit=t.kit,e.userData.modelForge.prompt=t.prompt,e.userData.modelForge.behaviors=Array.isArray(t.behaviors)?t.behaviors.map(Xr):[],e.userData.modelForge.parts=e.userData.modelForge.parts||[],e}function kr(e,t,{minScore:n=.5,minHits:r=2}={}){let i=String(e||``).toLowerCase(),a=new Set((t||[]).map(e=>H(e.name)).filter(Boolean));if(!a.size)return null;let o=null,s=0;for(let e of wr()){if(!e||e.source!==`jarvis`||String(e.kit||``).toLowerCase()!==i)continue;let t=Array.isArray(e.behaviors)?e.behaviors:[],c=[...new Set(t.map(e=>H(e.target)).filter(Boolean))];if(!c.length)continue;let l=c.filter(e=>a.has(e)).length,u=l/c.length;l>=r&&u>=n&&u>s&&(o=e,s=u)}return o?{blueprint:o,score:s}:null}function z(e,t={}){if(!e)throw Error(`No model object was provided.`);let n=t.kit||ti(e),r=Array.isArray(t.parts)&&t.parts.length?t.parts:Ar(e,n),i=t.name||e.userData?.modelName||`Custom Model`,a=kr(n,r);if(a){let o={...a.blueprint,id:or(`blueprint`),name:i,prompt:t.prompt||a.blueprint.prompt||``,parts:r.map(Yr),source:`template-reuse`,templateOf:a.blueprint.id,updatedAt:Date.now()};return Or(e,o),e.userData.modelForgeBlueprint=o,k(`forge-template-reused`,{name:i,kit:n,score:a.score,templateOf:a.blueprint.id}),w(`Reused interactive template for ${i} (${Math.round(a.score*100)}% part match) — no regeneration needed.`,`Model Forge`),o}let o=R({name:i,prompt:t.prompt||``,kit:n,parts:r,behaviors:t.behaviors||ii(n,r)});return Or(e,o),e.userData.modelForgeBlueprint=o,globalThis.Jarvis?.query&&Er(`We have a 3D model named "${i}" (kit: "${n}") containing discovered parts: ${r.map(e=>e.name).join(`, `)}. Create an ultimate interactive Stark-level behavioral blueprint. Generate highly custom actions (like 'raise landing gear', 'ignite thruster', 'open cockpit') and bind them to the correct parts using gestures.`,{name:i,kit:n}).then(t=>{t&&t.source===`jarvis`&&(Or(e,t),e.userData.modelForgeBlueprint=t,Lr(e),k(`object-placed`,{object:e,modelName:i}),k(`assistant`,`Stark Interface synchronized for ${i}. Loaded bespoke interactive controls.`),w(`Stark Interface synchronized for ${i}.`,`Jarvis AI`))}).catch(e=>{w(`Jarvis background blueprint upgrade failed for ${i}.`,`Model Forge`)}),o}function Ar(e,t=ti(e)){let n=[];return e?.traverse?.(t=>{!t.isMesh&&!t.isObject3D||t!==e&&n.push({name:t.name||t.userData?.partName||t.userData?.role||`part_${n.length+1}`,type:Qr(t.userData?.role||t.userData?.partType||$r(t.name)),material:`matte`,position:[t.position.x,t.position.y,t.position.z],rotation:[t.rotation.x,t.rotation.y,t.rotation.z],scale:[t.scale.x,t.scale.y,t.scale.z],actions:ai(t.userData?.role||$r(t.name))})}),n.length>=2?n:ci(e,t,n)}function jr(e,t=document.createElement(`div`)){let n=e?.userData?.modelForge,r=Array.isArray(n?.behaviors)&&n.behaviors.length?[...new Set(n.behaviors.map(e=>e.action).filter(Boolean))]:Sr;t.replaceChildren(),t.style.cssText=`display:flex;flex-wrap:wrap;gap:8px`;for(let n of r){let r=document.createElement(`button`);r.className=`panel-action`,r.textContent=n,r.onclick=()=>Fr(e,n),t.appendChild(r)}return t}function Mr(e,t){let n=e.parent||t.parent;if(!n)return!1;let r=new fe().setFromObject(t),i=Number.isFinite(r.max.y)?r.max.y:t.position.y+.2,a=Number.isFinite(r.min.x)&&Number.isFinite(r.max.x)?(r.min.x+r.max.x)/2:t.position.x,o=Number.isFinite(r.min.z)&&Number.isFinite(r.max.z)?(r.min.z+r.max.z)/2:t.position.z,s=new Ne;n.add(s);let c=[];for(let e=0;e<20;e++){let t=new m(new v(.015,8,8),new h({color:3388415,transparent:!0,opacity:.85}));t.position.set(a+(Cr()-.5)*.04,i,o+(Cr()-.5)*.04),s.add(t),c.push({mesh:t,velocity:new S((Cr()-.5)*.05,-.4-Cr()*.3,(Cr()-.5)*.05),delay:e*60})}let l=performance.now(),u=2e3,d=()=>{let e=performance.now()-l;if(e>u){n.remove(s),s.traverse(e=>{e.isMesh&&(e.geometry?.dispose(),e.material?.dispose())});return}c.forEach(n=>{if(e>n.delay){n.velocity.y-=.012,n.mesh.position.addScaledVector(n.velocity,.016);let r=1-(e-n.delay)/(u-n.delay);n.mesh.material.opacity=Math.max(0,r*.85),n.mesh.position.y<t.position.y-.3&&n.mesh.scale.multiplyScalar(.94)}}),requestAnimationFrame(d)};return d(),w(`Water flowing successfully from ${t.userData?.modelName||`source`}.`,`Water Flow`),!0}function Nr(e,t,n){let r=!1;return e.traverse(e=>{let t=String(e.name||``).toLowerCase(),i=String(e.userData?.partType||``).toLowerCase();(i.includes(`light`)||i.includes(`lamp`)||i.includes(`glow`)||t.includes(`light`)||t.includes(`lamp`)||t.includes(`glow`))&&(r=!0,e.userData.partState=e.userData.partState||{},e.userData.partState.open=n,e.traverse(e=>{e.isLight&&(e.visible=n,e.intensity=n?2.5:0)}),e.isMesh&&e.material&&(n?(e.material.emissive&&e.material.emissive.setHex(16771584),e.material.emissiveIntensity!==void 0&&(e.material.emissiveIntensity=2),e.material.color&&e.material.color.setHex(16771584)):(e.material.emissive&&e.material.emissive.setHex(0),e.material.emissiveIntensity!==void 0&&(e.material.emissiveIntensity=0),e.material.color&&e.material.color.setHex(8109311))))}),r?(w(n?`Lights turned ON successfully.`:`Lights turned OFF successfully.`,`Lighting Control`),!0):!1}function Pr(e,t){let n=null,r=t.replace(`open-`,``).replace(`close-`,``).replace(`toggle-`,``).trim().toLowerCase();if(e.traverse(e=>{if(n)return;let t=String(e.userData?.partName||e.name||``).toLowerCase();(t.includes(r)||r===`boot`&&t.includes(`trunk`)||r===`trunk`&&t.includes(`boot`))&&(n=e)}),n){let e=t.startsWith(`open-`)||t.startsWith(`toggle-`)&&!n.userData.partState?.open;return Vr(n,e),w(`${e?`Opening`:`Closing`} ${n.userData.partName||r} pivot hinge.`,`Hinge Action`),!0}return!1}function Fr(e,t,n={}){if(!e)return!1;let r=String(t||``).toLowerCase().trim().replace(/\s+/g,`-`);if(/^(open|close|toggle)-(boot|hood|trunk|door|door-left|door-right)$/.test(r)&&Pr(e,r)||/^(turn-on-lights|on-lights|lights-on|lights-off|off-lights|turn-off-lights|lights|on|off)$/.test(r)&&Nr(e,e,!r.includes(`off`)&&r!==`off`)||/^(bring-water|pour-water|pour|water|fill)$/.test(r)&&Mr(e,e))return!0;let i=(e.userData?.modelForge?.behaviors||[]).filter(e=>e.action===r||e.gesture===r),a=i.length?i.map(t=>Jr(e,t.target)).filter(Boolean):[e],o=!1;for(let t of a)o=Br(e,t,r,n)||o;return!o&&e!==a[0]&&(o=Br(e,e,r,n)),o}function Ir(e,t,n={}){let r=String(t||``).toLowerCase(),i=(e?.userData?.modelForge?.behaviors||[]).filter(e=>e.gesture===r);if(!i.length)return r===`pinch`?Fr(e,`toggle`,n):r===`fist`?Fr(e,`grab`,n):r===`swipe-left`?Fr(e,`close`,n):r===`swipe-right`?Fr(e,`open`,n):r===`two-hand-scale`?Fr(e,`reconfigure`,n):!1;let a=!1;for(let t of i)a=Br(e,Jr(e,t.target)||e,t.action,n)||a;return a}function Lr(e){let t=e?.userData?.modelForgeBlueprint||e?.userData?.modelForge;return t?Tr({...t,updatedAt:Date.now(),name:e.userData?.modelName||t.name||`Custom Model`}):null}function Rr(e,t){let n=or(`part`),r=String(e.name||e.role||`part_${n.slice(-4)}`).trim()||`part_${n.slice(-4)}`,i=Qr(e.type||e.role),a=oi(e.material,t),o=new t.Group;o.name=`${H(r)}_root`,o.position.fromArray(ui(e.position)),o.rotation.set(...di(e.rotation)),o.scale.set(...fi(e.scale)),o.userData.partId=n,o.userData.partName=r,o.userData.partType=i,o.userData.partActions=Array.isArray(e.actions)&&e.actions.length?e.actions.map(Zr):ai(i);let s=null,c=null;if(e.geometry){let n=String(e.geometry).toLowerCase().trim();n===`box`||n===`cube`?c=new t.BoxGeometry(.25,.25,.25):n===`sphere`?c=new t.SphereGeometry(.15,32,16):n===`cylinder`?c=new t.CylinderGeometry(.1,.1,.28,24):n===`cone`?c=new t.ConeGeometry(.12,.26,24):n===`torus`?c=new t.TorusGeometry(.14,.02,12,48):n===`ring`?c=new t.RingGeometry(.08,.14,32):n===`capsule`?c=new t.CapsuleGeometry(.08,.2,8,24):n===`octahedron`?c=new t.OctahedronGeometry(.12):n===`icosahedron`&&(c=new t.IcosahedronGeometry(.12))}if(c)s=new t.Mesh(c,a),o.add(s);else if(i===`door`){let n=new t.Group;n.name=`${H(r)}_hinge`,n.userData.interactivePivot=!0,n.position.x=0;let i=new t.Mesh(new t.BoxGeometry(.22,.5,.04),a);i.position.x=.11,i.castShadow=!0,i.receiveShadow=!0,n.add(i),o.add(n),s=i,o.userData.interactivePivot=n,o.userData.closedRotation=0,o.userData.openRotation=Number.isFinite(e.openAngle)?e.openAngle:Math.PI/2}else if(i===`window`)s=new t.Mesh(new t.PlaneGeometry(.35,.3),a),s.position.z=.02,o.add(s);else if(i===`roof`)s=new t.Mesh(new t.ConeGeometry(.34,.28,4),a),s.rotation.y=Math.PI/4,o.add(s);else if(i===`light`){s=new t.Mesh(new t.SphereGeometry(.09,32,16),a);let e=new t.PointLight(16777215,1.2,2.6,2);e.position.set(0,0,0),o.add(s,e),o.userData.light=e}else i===`wheel`?(s=new t.Mesh(new t.CylinderGeometry(.11,.11,.05,20),a),s.rotation.z=Math.PI/2,o.add(s)):i===`screen`?(s=new t.Mesh(new t.BoxGeometry(.42,.25,.03),a),o.add(s)):(s=new t.Mesh(si(i,t),a),o.add(s));return o.userData.partMesh=s,o.userData.partState={open:!1,visible:!0,rotated:!1,shatter:!1},{id:n,name:r,type:i,root:o,mesh:s,actions:o.userData.partActions}}function zr(e,t,n,r){let i=String(n.kit||`scene`).toLowerCase(),a=t.base[0]?.root||t.walls[0]?.root||t.details[0]?.root||null;return a&&a.scale.multiplyScalar(1),i===`house`?(t.base[0]&&t.base[0].root.position.set(0,-.15,0),t.walls.forEach((e,t)=>{e.root.position.set(t%2==0?-.16:.16,.05,t<2?-.16:.16),e.root.scale.set(1,1,1)}),t.doors[0]&&t.doors[0].root.position.set(.18,-.12,.18),t.windows[0]&&t.windows[0].root.position.set(-.18,.06,.18),t.roofs[0]&&t.roofs[0].root.position.set(0,.28,0)):i===`room`?(t.base[0]&&t.base[0].root.position.set(0,-.18,0),t.walls.forEach((e,t)=>{e.root.position.set(t<2?-.22:.22,.05,t%2==0?-.22:.22)})):i===`vehicle`?(t.base[0]&&t.base[0].root.position.set(0,-.08,0),t.wheels.forEach((e,t)=>{let n=t<2?-.22:.22,r=t%2==0?-.16:.16;e.root.position.set(n,-.16,r)})):i===`device`&&(t.base[0]&&t.base[0].root.position.set(0,0,0),t.screens.forEach(e=>e.root.position.set(0,.01,.01))),e.userData.modelForge.layout=i,e}function Br(e,t,n,r={}){if(!t)return!1;let i=String(n||``).toLowerCase();return i===`open`?Vr(t,!0):i===`close`?Vr(t,!1):i===`toggle`?Vr(t,!t.userData.partState?.open):i===`rotate`?Hr(t,r?.delta||Math.PI/2):i===`reveal`?Ur(t,!0):i===`hide`?Ur(t,!1):i===`shatter`?Wr(e,t):i===`reconfigure`?Gr(e):i===`grab`?Kr(t,r):qr(t,i,r)}function Vr(e,t){let n=e.userData.interactivePivot||e,r=n.rotation.y,i=t?e.userData.openRotation??Math.PI/2:e.userData.closedRotation??0;return e.userData.partState=e.userData.partState||{},e.userData.partState.open=t,pi(360,e=>{n.rotation.y=r+(i-r)*mi(e)})}function Hr(e,t){let n=e.userData.partMesh||e,r=e.userData.rotateAxis||`y`,i=n.rotation[r],a=i+t;return e.userData.partState=e.userData.partState||{},e.userData.partState.rotated=!0,pi(240,e=>{n.rotation[r]=i+(a-i)*hi(e)})}function Ur(e,t){return e.visible=t,e.traverse?.(e=>{e.visible=t}),e.userData.partState=e.userData.partState||{},e.userData.partState.visible=t,!0}function Wr(e,t){let n=[];if(t.traverse?.(e=>{e.isMesh&&n.push(e)}),!n.length)return Gr(e);let r=new S;return t.getWorldPosition(r),n.forEach((e,t)=>{let n=new S(Math.cos(t*2.399),.35+t%3*.12,Math.sin(t*1.917)).normalize();e.userData.shatterStart=performance.now(),e.userData.shatterFrom=r.clone(),e.userData.shatterDirection=n}),pi(680,e=>{let t=mi(e);n.forEach(e=>{let n=e.userData.shatterDirection;n&&(e.position.copy(n).multiplyScalar(t*.65),e.rotation.x+=.05*t,e.rotation.y+=.06*t,e.rotation.z+=.04*t)})})}function Gr(e){let t=e.children.filter(e=>e.isObject3D);return t.forEach((e,t)=>{let n=Math.floor(t/3),r=(t%3-1)*.18,i=.04*n,a=(n-.5)*.12;e.position.x+=r*.2,e.position.y+=i*.2,e.position.z+=a*.2}),pi(340,e=>{let n=mi(e);t.forEach((e,t)=>{let r=Math.floor(t/3),i=(t%3-1)*.18,a=.04*r,o=(r-.5)*.12;e.position.x+=(i-e.position.x)*n*.12,e.position.y+=(a-e.position.y)*n*.12,e.position.z+=(o-e.position.z)*n*.12})})}function Kr(e,t){return t?.position&&e.position?.copy?(e.position.copy(t.position),!0):(e.userData.partState=e.userData.partState||{},e.userData.partState.grabbed=!0,!0)}function qr(e,t,n){e.userData.partState=e.userData.partState||{},e.userData.partState.lastAction=t;let r=String(t||``).toLowerCase().trim();if(r.includes(`raise`)||r.includes(`lift`)||r===`up`||r.includes(`deploy-gear`)){let t=e.position.y;return pi(400,n=>{e.position.y=t+.12*mi(n)})}if(r.includes(`lower`)||r===`down`||r.includes(`retract-gear`)){let t=e.position.y;return pi(400,n=>{e.position.y=t-.12*mi(n)})}if(r.includes(`extend`)||r.includes(`deploy`)||r.includes(`unfold`)||r.includes(`expand`)){let t=e.scale.clone(),n=e.rotation.y;return pi(500,r=>{let i=mi(r);e.scale.copy(t).multiplyScalar(1+.18*i),e.rotation.y=n+.35*i})}if(r.includes(`retract`)||r.includes(`fold`)||r.includes(`pull`)||r.includes(`collapse`)){let t=e.scale.clone(),n=e.rotation.y;return pi(500,r=>{let i=mi(r);e.scale.copy(t).multiplyScalar(1-.18*i),e.rotation.y=n-.35*i})}if(r.includes(`ignite`)||r.includes(`fire`)||r.includes(`charge`)||r.includes(`thrust`)||r.includes(`launch`)){if(e.isMesh&&e.material){let t=e.material.emissive?e.material.emissive.getHex():0;e.material.emissive=new Fe(54015),e.material.emissiveIntensity!==void 0&&(e.material.emissiveIntensity=4),window.setTimeout(()=>{e.material.emissive&&e.material.emissive.setHex(t),e.material.emissiveIntensity!==void 0&&(e.material.emissiveIntensity=0)},1e3)}return!0}return e.userData.partState.lastContext=n||{},!0}function Jr(e,t){let n=H(t);if(!n)return null;let r=null;return e.traverse?.(e=>{r||[e.name,e.userData?.partName,e.userData?.role,e.userData?.partType].filter(Boolean).map(H).includes(n)&&(r=e.userData?.interactivePivot||e)}),r}function Yr(e={}){return{name:String(e.name||e.role||`part`).trim(),type:Qr(e.type||e.role),material:[`matte`,`metal`,`glass`,`glow`,`wood`].includes(String(e.material||``).toLowerCase())?String(e.material).toLowerCase():`matte`,geometry:e.geometry?String(e.geometry).toLowerCase().trim():void 0,position:ui(e.position),rotation:di(e.rotation),scale:fi(e.scale),actions:Array.isArray(e.actions)&&e.actions.length?e.actions.map(Zr):ai(e.type||e.role),openAngle:Number.isFinite(e.openAngle)?e.openAngle:void 0}}function Xr(e={}){return{gesture:String(e.gesture||``).toLowerCase().trim(),action:Zr(e.action||e.trigger||``),target:String(e.target||e.part||``).trim()}}function Zr(e){return String(e||``).toLowerCase().trim().replace(/\s+/g,`-`)}function Qr(e){let t=String(e||``).toLowerCase().trim().replace(/\s+/g,`-`);return[`wall`,`door`,`window`,`roof`,`drawer`,`panel`,`screen`,`wheel`,`prop`,`light`,`arm`,`leg`,`head`,`detail`,`base`].includes(t)?t:$r(t)}function $r(e){let t=H(e);return t.includes(`door`)?`door`:t.includes(`window`)?`window`:t.includes(`roof`)?`roof`:t.includes(`wheel`)?`wheel`:t.includes(`screen`)||t.includes(`display`)?`screen`:t.includes(`light`)||t.includes(`lamp`)?`light`:t.includes(`drawer`)?`drawer`:t.includes(`wall`)?`wall`:t.includes(`base`)||t.includes(`floor`)?`base`:t.includes(`arm`)?`arm`:t.includes(`leg`)?`leg`:t.includes(`head`)?`head`:`detail`}function ei(e){let t=H(e);return t.includes(`house`)||t.includes(`home`)?`house`:t.includes(`room`)||t.includes(`bedroom`)||t.includes(`kitchen`)?`room`:t.includes(`car`)||t.includes(`truck`)||t.includes(`vehicle`)?`vehicle`:t.includes(`phone`)||t.includes(`device`)||t.includes(`tablet`)?`device`:t.includes(`character`)||t.includes(`person`)||t.includes(`robot`)?`character`:`scene`}function ti(e){return ei(H(e?.userData?.modelName||e?.name||``))}function B(e,t){let n=new Set(e.map(H));for(let e of t)if(n.has(H(e)))return e;return``}function V(e){return e===`house`||e===`room`?`core`:e===`vehicle`?`chassis`:e===`device`?`screen`:e===`character`?`torso`:`core`}function ni(e){return Math.max(.04,Math.min(Number(e)||1,4))}function ri(e){let t={house:[{name:`base`,type:`base`,material:`matte`,position:[0,-.15,0],scale:[1.2,.6,1.2]},{name:`front-door`,type:`door`,material:`wood`},{name:`left-window`,type:`window`,material:`glass`},{name:`right-window`,type:`window`,material:`glass`},{name:`roof`,type:`roof`,material:`matte`}],room:[{name:`floor`,type:`base`,material:`matte`,position:[0,-.16,0],scale:[1.3,.05,1.3]},{name:`wall-a`,type:`wall`,material:`matte`},{name:`wall-b`,type:`wall`,material:`matte`},{name:`door`,type:`door`,material:`metal`},{name:`window`,type:`window`,material:`glass`}],device:[{name:`body`,type:`base`,material:`metal`,position:[0,0,0],scale:[1,.6,.15]},{name:`screen`,type:`screen`,material:`glass`,position:[0,.01,.09]},{name:`button`,type:`detail`,material:`glow`,position:[.27,-.05,.08],scale:[.16,.16,.16]}],vehicle:[{name:`chassis`,type:`base`,material:`metal`,position:[0,-.03,0],scale:[1.2,.36,.64]},{name:`wheel-front-left`,type:`wheel`,material:`metal`,position:[-.35,-.18,-.22]},{name:`wheel-front-right`,type:`wheel`,material:`metal`,position:[.35,-.18,-.22]},{name:`wheel-back-left`,type:`wheel`,material:`metal`,position:[-.35,-.18,.22]},{name:`wheel-back-right`,type:`wheel`,material:`metal`,position:[.35,-.18,.22]}],character:[{name:`torso`,type:`base`,material:`matte`,position:[0,.02,0],scale:[.36,.5,.18]},{name:`head`,type:`head`,material:`matte`,position:[0,.4,0],scale:[.28,.28,.28]},{name:`left-arm`,type:`arm`,material:`matte`,position:[-.28,.12,0],scale:[.12,.42,.12]},{name:`right-arm`,type:`arm`,material:`matte`,position:[.28,.12,0],scale:[.12,.42,.12]},{name:`left-leg`,type:`leg`,material:`matte`,position:[-.12,-.42,0],scale:[.12,.42,.12]},{name:`right-leg`,type:`leg`,material:`matte`,position:[.12,-.42,0],scale:[.12,.42,.12]}],scene:[{name:`core`,type:`base`,material:`matte`,position:[0,0,0],scale:[.9,.6,.9]},{name:`detail-a`,type:`detail`,material:`glow`,position:[-.26,.12,.2]},{name:`detail-b`,type:`detail`,material:`glow`,position:[.28,.1,-.18]},{name:`control-panel`,type:`screen`,material:`glass`,position:[0,.18,.32]}]};return t[e]||t.scene}function ii(e,t=[]){let n=t.map(e=>H(e.name)),r=B(n,[`front-door`,`door`,`front`,`main-door`,`screen`,`control-panel`])||V(e),i=B(n,[`roof`,`top`,`cover`,`lid`])||V(e),a=B(n,[`screen`,`display`,`control-panel`])||V(e),o=B(n,[`wheel-front-left`,`wheel-front-right`,`wheel-back-left`,`wheel-back-right`,`wheel`])||V(e),s={house:[{gesture:`pinch`,action:`toggle`,target:r},{gesture:`open-palm`,action:`reconfigure`,target:i},{gesture:`swipe-left`,action:`close`,target:r},{gesture:`swipe-right`,action:`open`,target:r},{gesture:`fist`,action:`shatter`,target:i}],room:[{gesture:`pinch`,action:`open`,target:r},{gesture:`fist`,action:`close`,target:r},{gesture:`two-hand-scale`,action:`reconfigure`,target:B(n,[`floor`,`base`])||V(e)},{gesture:`open-palm`,action:`reveal`,target:a}],device:[{gesture:`pinch`,action:`toggle`,target:a},{gesture:`open-palm`,action:`reveal`,target:B(n,[`body`,`base`])||V(e)},{gesture:`swipe-left`,action:`hide`,target:a},{gesture:`swipe-right`,action:`open`,target:a}],vehicle:[{gesture:`pinch`,action:`toggle`,target:B(n,[`chassis`,`base`])||V(e)},{gesture:`fist`,action:`reconfigure`,target:o},{gesture:`swipe-left`,action:`rotate`,target:o},{gesture:`swipe-right`,action:`open`,target:B(n,[`door`,`hood`,`trunk`])||V(e)}],character:[{gesture:`pinch`,action:`toggle`,target:B(n,[`head`])||V(e)},{gesture:`fist`,action:`grab`,target:B(n,[`torso`,`body`])||V(e)},{gesture:`swipe-right`,action:`reconfigure`,target:B(n,[`left-arm`,`arm`])||V(e)},{gesture:`swipe-left`,action:`rotate`,target:B(n,[`right-arm`,`arm`])||V(e)}],scene:[{gesture:`pinch`,action:`toggle`,target:B(n,[`core`,`root`,`base`])||V(e)},{gesture:`open-palm`,action:`reconfigure`,target:a},{gesture:`fist`,action:`shatter`,target:B(n,[`detail-a`,`detail-b`])||V(e)}]};return(s[e]||s.scene).filter(Boolean)}function ai(e){let t=Qr(e);return t===`door`?[`open`,`close`,`toggle`]:t===`window`?[`open`,`close`,`toggle`,`reveal`]:t===`drawer`?[`open`,`close`,`toggle`]:t===`wheel`?[`rotate`]:t===`screen`||t===`light`?[`toggle`,`reveal`,`hide`]:Sr.slice()}function oi(e,t){let n=String(e||`matte`).toLowerCase();return n===`metal`?new t.MeshPhysicalMaterial({color:9422847,roughness:.16,metalness:.92}):n===`glass`?new t.MeshPhysicalMaterial({color:13627391,roughness:.05,transmission:.58,transparent:!0,opacity:.36}):n===`glow`?new t.MeshBasicMaterial({color:51455,transparent:!0,opacity:.9}):n===`wood`?new t.MeshStandardMaterial({color:9202255,roughness:.82,metalness:.02}):new t.MeshStandardMaterial({color:8109311,roughness:.55,metalness:.1})}function si(e,t){let n=Qr(e);return n===`base`||n===`wall`?new t.BoxGeometry(.5,.32,.5):n===`drawer`?new t.BoxGeometry(.28,.14,.28):n===`arm`?new t.CapsuleGeometry(.06,.28,5,16):n===`leg`?new t.CapsuleGeometry(.06,.34,5,16):n===`head`?new t.SphereGeometry(.16,24,16):n===`detail`?new t.IcosahedronGeometry(.08,1):new t.BoxGeometry(.22,.22,.22)}function ci(e,t,n=[]){let r=new fe;if(e&&r.setFromObject(e),!Number.isFinite(r.min.x)||!Number.isFinite(r.max.x))return[...n,...ri(t)];let i=r.getSize(new S),a=Math.max(i.x,.1),o=Math.max(i.y,.1),s=Math.max(i.z,.1),c=Math.max(a,o,s)||.4,l=[{name:`core`,type:`base`,material:`matte`,position:[0,0,0],scale:[1,1,1],actions:[`toggle`,`reconfigure`,`shatter`]},{name:`zone-front`,type:`panel`,material:`glass`,position:[0,0,s*.35],scale:[.72,.72,.12],actions:[`open`,`close`,`toggle`,`reveal`,`hide`]},{name:`zone-back`,type:`panel`,material:`glass`,position:[0,0,-s*.35],scale:[.72,.72,.12],actions:[`open`,`close`,`toggle`,`reveal`,`hide`]},{name:`zone-left`,type:`panel`,material:`glass`,position:[-a*.35,0,0],scale:[.12,.72,.72],actions:[`rotate`,`reconfigure`]},{name:`zone-right`,type:`panel`,material:`glass`,position:[a*.35,0,0],scale:[.12,.72,.72],actions:[`rotate`,`reconfigure`]},{name:`zone-top`,type:`roof`,material:`matte`,position:[0,o*.35,0],scale:[.85,.16,.85],actions:[`open`,`close`,`reconfigure`]},{name:`zone-bottom`,type:`base`,material:`matte`,position:[0,-o*.35,0],scale:[.85,.16,.85],actions:[`reconfigure`,`grab`]},{name:`zone-core`,type:`detail`,material:`glow`,position:[0,0,0],scale:[.42,.42,.42],actions:[`toggle`,`shatter`,`reveal`,`hide`]}];return[...n,...l.map(e=>({...e,scale:[ni(e.scale[0]*(c/1.25)),ni(e.scale[1]*(c/1.25)),ni(e.scale[2]*(c/1.25))]}))]}function li(e){if(!e)return null;let t=String(e).replace(/```json|```/gi,``).trim(),n=t.indexOf(`{`),r=t.lastIndexOf(`}`);if(n<0||r<0||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}function ui(e){return Array.isArray(e)&&e.length>=3?[Number(e[0])||0,Number(e[1])||0,Number(e[2])||0]:e&&typeof e==`object`?[Number(e.x)||0,Number(e.y)||0,Number(e.z)||0]:[0,0,0]}function di(e){return Array.isArray(e)&&e.length>=3?[Number(e[0])||0,Number(e[1])||0,Number(e[2])||0]:e&&typeof e==`object`?[Number(e.x)||0,Number(e.y)||0,Number(e.z)||0]:[0,0,0]}function fi(e){return Array.isArray(e)&&e.length>=3?[Number(e[0])||1,Number(e[1])||1,Number(e[2])||1]:e&&typeof e==`object`?[Number(e.x)||1,Number(e.y)||1,Number(e.z)||1]:[1,1,1]}function pi(e,t){let n=performance.now();return new Promise(r=>{let i=a=>{let o=Math.min((a-n)/e,1);t(o),o<1?requestAnimationFrame(i):r(!0)};requestAnimationFrame(i)})}function mi(e){return 1-(1-e)**3}function hi(e){return e<.5?4*e*e*e:1-(-2*e+2)**3/2}function H(e){return String(e||``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}var gi=!1,_i=!1,vi=!1,yi={default:{name:`default`,refDistance:.72,maxDistance:8,rolloffFactor:1.6,dampening:.08,cueGain:1},cinema:{name:`cinema`,refDistance:1.05,maxDistance:12,rolloffFactor:1.25,dampening:.16,cueGain:1.08},open:{name:`open`,refDistance:.68,maxDistance:16,rolloffFactor:1.15,dampening:.03,cueGain:.96},quiet:{name:`quiet`,refDistance:.84,maxDistance:7,rolloffFactor:1.8,dampening:.12,cueGain:.92},lab:{name:`lab`,refDistance:.78,maxDistance:9,rolloffFactor:1.5,dampening:.06,cueGain:1.02}};function bi(){gi||(gi=!0,O(`ar-scene-live`,()=>Ei()),O(`object-placed`,({object:e})=>xi(e)),Di(),Oi(),Ei(),P(`spatialAudio`,!!ki()),P(`speechSynthesis`,!!window.speechSynthesis),P(`voiceRecognition`,!!(window.SpeechRecognition||window.webkitSpeechRecognition)))}function xi(e){if(!e)return null;let t=Ei();if(!t)return null;if(e.userData.spatialAudio={...yi[D.spatialAudio.environmentProfile]||yi.default,...e.userData.spatialAudio||{}},e.userData.spatialAudioEmitter?.parent===e)return e.userData.spatialAudioEmitter;let n=new re(t);return n.name=`jarvis-object-spatial-audio`,Ci(n,e.userData.spatialAudio),e.add(n),e.userData.spatialAudioAttached=!0,e.userData.spatialAudioEmitter=n,n}async function Si(e,t=`select`){if(!e)return!1;let n=Ei(),r=ki();if(!n||!r)return!1;try{if(r.state===`suspended`&&await r.resume(),r.state!==`running`)return!1;D.spatialAudio.unlocked=!0;let i=e.parent?xi(e):Ti(n,e);return i?(i.isPlaying&&i.stop(),i.setBuffer(Ai(r,t)),i.setVolume((yi[D.spatialAudio.environmentProfile]?.cueGain||1)*(t===`delete`?.9:1)),i.play(),window.setTimeout(()=>{try{i.stop()}catch{}i.userData.detachedAnchor&&(i.userData.detachedAnchor.parent?.remove(i.userData.detachedAnchor),i.disconnect())},420),!0):!1}catch{return!1}}function Ci(e,t={}){e.setRefDistance(t.refDistance||.72),e.setMaxDistance(t.maxDistance||8),e.setRolloffFactor(t.rolloffFactor||1.6),e.setDistanceModel(`inverse`)}function wi(e=`default`){let t=yi[String(e||`default`).toLowerCase()]||yi.default;return D.spatialAudio.environmentProfile=t.name,D.spatialAudio.roomProfile={...t},D.placedObjects.forEach(e=>{let n=e?.userData?.spatialAudioEmitter;n&&Ci(n,t)}),D.spatialAudio.listener?.context&&(D.spatialAudio.context=D.spatialAudio.listener.context),P(`spatialAudio`,!!ki()),t}function Ti(e,t){let n=new Ne;t.getWorldPosition(n.position),L().scene.add(n);let r=new re(e);return r.name=`jarvis-detached-spatial-cue`,Ci(r,t.userData.spatialAudio||yi.default),r.userData.detachedAnchor=n,n.add(r),r}function Ei(){let{camera:e}=L();return e?(D.spatialAudio.listener||(D.spatialAudio.listener=new je),D.spatialAudio.listener.parent!==e&&(D.spatialAudio.listener.parent?.remove(D.spatialAudio.listener),e.add(D.spatialAudio.listener)),D.spatialAudio.enabled=!0,D.spatialAudio.context=ki(),D.spatialAudio.listener):null}function Di(){if(vi)return;vi=!0;let e=()=>wi(D.nativeOptions?.activeEnvironment||D.spatialAudio.environmentProfile||`default`);O(`native-options`,e),O(`native-ui-state`,e=>{let t=e?.audioEnvironment||e?.environment||e?.profile;t&&wi(t)}),e()}function Oi(){if(_i)return;_i=!0;let e=async()=>{let e=ki();if(e)try{await e.resume(),D.spatialAudio.unlocked=e.state===`running`,D.spatialAudio.micPermission=D.spatialAudio.unlocked?`granted`:D.spatialAudio.micPermission,D.spatialAudio.unlocked&&w(`Spatial audio unlocked for AR objects.`,`Spatial Audio`)}catch{D.spatialAudio.unlocked=!1}};window.addEventListener(`pointerdown`,e,{passive:!0}),window.addEventListener(`touchstart`,e,{passive:!0})}function ki(){try{return be.getContext()}catch{return null}}function Ai(e,t){let n=e.sampleRate,r=Math.max(1,Math.floor(n*.24)),i=e.createBuffer(1,r,n),a=i.getChannelData(0),o=t===`place`?330:t===`delete`?180:t===`open`?520:430;for(let e=0;e<r;e+=1){let t=e/n,r=Math.exp(-t*12)*Math.min(1,t*90);a[e]=(Math.sin(Math.PI*2*o*t)*.72+Math.sin(Math.PI*2*o*1.5*t)*.2)*r*.16}return i}var U=Uint8Array,ji=Uint16Array,Mi=Int32Array,Ni=new U([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Pi=new U([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Fi=new U([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ii=function(e,t){for(var n=new ji(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Mi(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Li=Ii(Ni,2),Ri=Li.b,zi=Li.r;Ri[28]=258,zi[258]=28;var Bi=Ii(Pi,0),Vi=Bi.b;Bi.r;for(var Hi=new ji(32768),W=0;W<32768;++W){var Ui=(W&43690)>>1|(W&21845)<<1;Ui=(Ui&52428)>>2|(Ui&13107)<<2,Ui=(Ui&61680)>>4|(Ui&3855)<<4,Hi[W]=((Ui&65280)>>8|(Ui&255)<<8)>>1}for(var Wi=(function(e,t,n){for(var r=e.length,i=0,a=new ji(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new ji(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new ji(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Hi[d]>>c]=l}else for(s=new ji(r),i=0;i<r;++i)e[i]&&(s[i]=Hi[o[e[i]-1]++]>>15-e[i]);return s}),Gi=new U(288),W=0;W<144;++W)Gi[W]=8;for(var W=144;W<256;++W)Gi[W]=9;for(var W=256;W<280;++W)Gi[W]=7;for(var W=280;W<288;++W)Gi[W]=8;for(var Ki=new U(32),W=0;W<32;++W)Ki[W]=5;var qi=Wi(Gi,9,1),Ji=Wi(Ki,5,1),Yi=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Xi=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},Zi=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Qi=function(e){return(e+7)/8|0},$i=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new U(e.subarray(t,n))},ea=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],G=function(e,t,n){var r=Error(t||ea[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,G),!n)throw r;return r},ta=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new U(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new U(i*3));var l=function(e){var t=n.length;if(e>t){var r=new U(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=Xi(e,d,1);var v=Xi(e,d+1,3);if(d+=3,!v){var y=Qi(d)+4,ee=e[y-4]|e[y-3]<<8,te=y+ee;if(te>i){c&&G(0);break}s&&l(f+ee),n.set(e.subarray(y,te),f),t.b=f+=ee,t.p=d=te*8,t.f=u;continue}else if(v==1)p=qi,m=Ji,h=9,g=5;else if(v==2){var ne=Xi(e,d,31)+257,b=Xi(e,d+10,15)+4,re=ne+Xi(e,d+5,31)+1;d+=14;for(var x=new U(re),ie=new U(19),ae=0;ae<b;++ae)ie[Fi[ae]]=Xi(e,d+ae*3,7);d+=b*3;for(var oe=Yi(ie),se=(1<<oe)-1,ce=Wi(ie,oe,1),ae=0;ae<re;){var le=ce[Xi(e,d,se)];d+=le&15;var y=le>>4;if(y<16)x[ae++]=y;else{var ue=0,de=0;for(y==16?(de=3+Xi(e,d,3),d+=2,ue=x[ae-1]):y==17?(de=3+Xi(e,d,7),d+=3):y==18&&(de=11+Xi(e,d,127),d+=7);de--;)x[ae++]=ue}}var fe=x.subarray(0,ne),pe=x.subarray(ne);h=Yi(fe),g=Yi(pe),p=Wi(fe,h,1),m=Wi(pe,g,1)}else G(1);if(d>_){c&&G(0);break}}s&&l(f+131072);for(var me=(1<<h)-1,he=(1<<g)-1,ge=d;;ge=d){var ue=p[Zi(e,d)&me],_e=ue>>4;if(d+=ue&15,d>_){c&&G(0);break}if(ue||G(2),_e<256)n[f++]=_e;else if(_e==256){ge=d,p=null;break}else{var S=_e-254;if(_e>264){var ae=_e-257,ve=Ni[ae];S=Xi(e,d,(1<<ve)-1)+Ri[ae],d+=ve}var ye=m[Zi(e,d)&he],be=ye>>4;ye||G(3),d+=ye&15;var pe=Vi[be];if(be>3){var ve=Pi[be];pe+=Zi(e,d)&(1<<ve)-1,d+=ve}if(d>_){c&&G(0);break}s&&l(f+131072);var xe=f+S;if(f<pe){var Se=a-pe,Ce=Math.min(pe,xe);for(Se+f<0&&G(3);f<Ce;++f)n[f]=r[Se+f]}for(;f<xe;++f)n[f]=n[f-pe]}}t.l=p,t.p=ge,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?$i(n,0,f):n.subarray(0,f)},na=new U(0),ra=function(e,t){return e[t]|e[t+1]<<8},ia=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},aa=function(e,t){return ia(e,t)+ia(e,t+4)*4294967296};function oa(e,t){return ta(e,{i:2},t&&t.out,t&&t.dictionary)}var sa=typeof TextDecoder<`u`&&new TextDecoder;try{sa.decode(na,{stream:!0})}catch{}var ca=function(e){for(var t=``,n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:$i(e,n-1)};i?i==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}};function la(e,t){if(t){for(var n=``,r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}else if(sa)return sa.decode(e);else{var i=ca(e),a=i.s,n=i.r;return n.length&&G(8),a}}var ua=function(e,t){return t+30+ra(e,t+26)+ra(e,t+28)},da=function(e,t,n){var r=ra(e,t+28),i=la(e.subarray(t+46,t+46+r),!(ra(e,t+8)&2048)),a=t+46+r,o=ia(e,t+20),s=n&&o==4294967295?fa(e,a):[o,ia(e,t+24),ia(e,t+42)],c=s[0],l=s[1],u=s[2];return[ra(e,t+10),c,l,i,a+ra(e,t+30)+ra(e,t+32),u]},fa=function(e,t){for(;ra(e,t)!=1;t+=4+ra(e,t+2));return[aa(e,t+12),aa(e,t+4),aa(e,t+20)]};function pa(e,t){for(var n={},r=e.length-22;ia(e,r)!=101010256;--r)(!r||e.length-r>65558)&&G(13);var i=ra(e,r+8);if(!i)return{};var a=ia(e,r+16),o=a==4294967295||i==65535;if(o){var s=ia(e,r-12);o=ia(e,s)==101075792,o&&(i=ia(e,s+32),a=ia(e,s+48))}for(var c=t&&t.filter,l=0;l<i;++l){var u=da(e,a,o),d=u[0],f=u[1],p=u[2],m=u[3],h=u[4],g=u[5],_=ua(e,g);a=h,(!c||c({name:m,size:f,originalSize:p,compression:d}))&&(d?d==8?n[m]=oa(e.subarray(_,_+f),{out:new U(p)}):G(14,`unknown compression type `+d):n[m]=$i(e,_,_+f))}return n}var ma=new h({color:16777215,transparent:!0,opacity:.72}),ha=`jarvis_ar_placed_objects_v1`,ga=`jarvis_ar_my_models_v1`,_a=new Ce,va=8,ya=180*1024*1024,ba=new Map,xa=0,Sa=null,Ca=0,wa=new Map,Ta=0,Ea=``,Da=0,Oa=0,ka=!1,Aa=!1,ja=0,Ma=new Map,Na=new Set;function Pa(){Ia(),qa(),O(`open-model-forge`,Ba),O(`open-models`,La),O(`jarvis-model-action`,e=>So(e)),O(`gesture-pinch`,e=>xo(`pinch`,e)),O(`gesture-fist`,e=>xo(`fist`,e)),O(`gesture-open-palm`,e=>xo(`open-palm`,e)),O(`gesture-swipe-left`,e=>xo(`swipe-left`,e)),O(`gesture-swipe-right`,e=>xo(`swipe-right`,e)),O(`gesture-two-hand-scale`,e=>xo(`two-hand-scale`,e)),O(`world-anchor-sample`,()=>Mo()),O(`native-ar-state`,e=>Fa(e)),O(`spawn-model`,async e=>{Ya(Sn(e?.query||`Duck`).name)}),O(`spawn-generated-glb`,async e=>{if(!e?.model_url)return;let t=e?.model_name||`Generated Model`;try{w(`Loading generated model: ${t}...`,`Jarvis AI Generation`);let n=String(e.model_url);if(n.startsWith(`/`)){let e=D.jarvis?.apiBase?.()||``;e&&(n=`${e}${n}`)}let r=await to(n);r.userData.modelName=t,z(r,R({name:t,kit:ns(t)})),Qa(r,window.AR_CAMERA_POSITION||new S(0,0,-2)),w(`Successfully deployed ${t}!`,`Jarvis AI Generation`)}catch(e){C(`Failed to load generated model: ${e.message}`,`Generation Error`)}}),setInterval(()=>oo(),6e4)}function Fa(e={}){let t=Array.isArray(e.objects)?e.objects:[];for(let e of t){let t=String(e.id||e.uid||``).trim(),n=String(e.label||e.name||e.modelName||e.type||`Native Object`),r=e.position||{x:Number(e.px??e.x??0),y:Number(e.py??e.y??D.floorY+.08),z:Number(e.pz??e.z??-1.6)},i=t?D.placedObjects.find(e=>e.userData.id===t):null;if(i){i.position.copy(Zo(r)),i.userData.modelName=n,To(i);continue}let a=bo(n);t&&(a.userData.id=t),a.userData.sourceURL=`native-apk-state`,z(a,R({name:n,kit:ns(n)})),eo(a,n,r,null,`native-apk-state`)}}function Ia(){if(ka||Aa)return;let e=()=>{ka||(ka=!0,Oo().catch(e=>C(e.message,`Model Restore Failed`)))};if(D.liveSceneReady){e();return}Aa=!0;let t=O(`ar-scene-live`,()=>{t(),Aa=!1,e()})}function La(){let e=document.createElement(`div`),t=document.createElement(`input`);t.placeholder=`Search free models`;let n=document.createElement(`div`);n.className=`panel-list`;let r=document.createElement(`input`);r.type=`file`,r.accept=`.glb,.gltf,.obj,.fbx`;let i=Ra(),a=document.createElement(`button`);a.className=`panel-action`,a.textContent=`Open Custom 3D Builder`,a.onclick=Ko;let o=document.createElement(`button`);o.className=`panel-action`,o.textContent=`Open Interactive Model Forge`,o.onclick=Ba;let s=document.createElement(`p`);s.className=`panel-note`,s.textContent=`Create models with behavior schemas, named parts, and Jarvis-generated interactions.`,e.append(t,n,i,r,a,o,s);let c=()=>{let e=t.value.toLowerCase();n.replaceChildren(...bn.filter(t=>!e||t.name.toLowerCase().includes(e)||t.category.includes(e)).map(e=>Wa(e)))};t.addEventListener(`input`,c),r.addEventListener(`change`,()=>Ga(r.files?.[0])),c(),new an({title:`Models`,body:e,icon:`M`,width:390,height:560}).focus()}function Ra(){let e=document.createElement(`section`);e.className=`sketchfab-panel`;let t=document.createElement(`strong`);t.textContent=`JARVIS 3D Asset Nexus`;let n=document.createElement(`p`);n.className=`panel-note`,n.textContent=`Connectors: Turbosquid, CGTrader, Mixamo, Poly.pizza, Kenney, Quaternius, Sketchfab.`;let r=document.createElement(`button`);r.className=`panel-action`,r.style.cssText=`width: 100%; margin: 6px 0; padding: 10px 14px; text-align: left; display: flex; align-items: center; justify-content: space-between; font-size: 13px; border-radius: 12px; font-weight: 500;`;let i=document.createElement(`span`);i.textContent=`API Connectors Logins`;let a=document.createElement(`span`);a.className=`chevron`,a.textContent=`v`,a.style.cssText=`transition: transform 0.25s ease; display: inline-block;`,r.append(i,a);let o=document.createElement(`div`);o.style.cssText=`display: none; flex-direction: column; gap: 10px; margin: 8px 0; padding: 14px; border: 1px solid var(--separator); border-radius: 14px; background: rgba(0,0,0,0.22);`;function s(e,t,n,r){let i=document.createElement(`div`);i.style.cssText=`display: flex; flex-direction: column; gap: 4px;`;let a=document.createElement(`div`);a.style.cssText=`display: flex; align-items: center; justify-content: space-between; font-size: 12px;`;let o=document.createElement(`span`);o.textContent=n,o.style.color=`var(--text-secondary)`;let s=document.createElement(`span`);s.style.cssText=`display: inline-flex; align-items: center; gap: 4px; font-size: 10px; font-weight: 600; text-transform: uppercase; cursor: pointer;`;let c=document.createElement(`input`);c.type=`password`,c.placeholder=t,c.value=e===`sketchfab`?An():qn(e),c.style.cssText=`margin: 2px 0 !important; min-height: 38px !important; padding: 8px 12px !important; font-size: 12px !important; border-radius: 10px !important;`;let l=document.createElement(`div`);l.style.cssText=`font-size: 10px; color: var(--warning); display: none; padding: 2px 0 0 2px; line-height: 1.4;`;let u=()=>{let e=c.value.trim();s.replaceChildren();let t=document.createElement(`span`);e?(t.style.cssText=`color:var(--success); margin-right: 2px;`,t.textContent=`●`,s.append(t,document.createTextNode(` Authenticated ✓`)),l.style.display=`none`):(t.style.cssText=`color:var(--warning); margin-right: 2px;`,t.textContent=`●`,s.append(t,document.createTextNode(` No key — tap to add`)),r&&(l.style.display=`block`,l.innerHTML=`⚡ Get your free key at <span style="color:var(--accent);text-decoration:underline;">${r}</span>`))};return s.addEventListener(`click`,()=>c.focus()),c.addEventListener(`input`,u),u(),a.append(o,s),i.append(a,c,l),{wrapper:i,input:c,updateStatus:u}}let c=document.createElement(`div`);c.style.cssText=`background: rgba(96,165,250,0.12); border: 1px solid rgba(96,165,250,0.3); border-radius: 10px; padding: 10px 12px; font-size: 11px; color: rgba(255,255,255,0.85); line-height: 1.5;`,c.innerHTML=`🔑 <strong>Enter your API keys below to unlock live search.</strong><br>Yellow ● = no key set (uses sample models). Green ● = live API active.<br>Kenney &amp; Quaternius are always free — no key needed.`;let l=s(`omega_session`,`OMEGA cloud session token`,`OMEGA Cloud Link`,``),u=s(`sketchfab`,`Sketchfab OAuth/API Token`,`Sketchfab API`,`sketchfab.com/settings/password-api`),d=s(`poly_pizza`,`Poly.pizza API Key`,`Poly.pizza API`,`poly.pizza/account`),f=s(`cgtrader`,`CGTrader API Token`,`CGTrader API Token`,`cgtrader.com/account`),p=s(`turbosquid`,`username:api_key`,`TurboSquid user:key`,`turbosquid.com/Account`),m=s(`mixamo`,`adobe_email:adobe_password`,`Mixamo Adobe email:pass`,`mixamo.com (use your Adobe login)`),h=document.createElement(`div`);h.style.cssText=`display: flex; gap: 8px; font-size: 11px; background: rgba(255,255,255,0.05); padding: 8px 10px; border-radius: 10px; color: var(--text-secondary); justify-content: space-between;`,h.append(za(`Kenney`,`CC0 active`),za(`Quaternius`,`CC0 active`));let g=document.createElement(`button`);g.className=`panel-action`,g.textContent=`Save Credentials`,g.style.cssText=`min-height: 38px; font-size: 13px; font-weight: 600; background: var(--accent); color: #fff; margin-top: 6px;`,g.onclick=()=>{let e=l.input.value.trim()!==qn(`omega_session`);if(Jn(`omega_session`,l.input.value),jn(u.input.value),Jn(`poly_pizza`,d.input.value),Jn(`cgtrader`,f.input.value),Jn(`turbosquid`,p.input.value),Jn(`mixamo`,m.input.value),e&&D.jarvis){try{D.jarvis.ws?.close()}catch{}D.jarvis.loadConfig()}l.updateStatus(),u.updateStatus(),d.updateStatus(),f.updateStatus(),p.updateStatus(),m.updateStatus(),w(`All 3D Asset Nexus connector credential configurations saved locally.`,`Credentials Saved`)},o.append(c,l.wrapper,u.wrapper,d.wrapper,f.wrapper,p.wrapper,m.wrapper,h,g);let _=!1;r.onclick=()=>{_=!_,o.style.display=_?`flex`:`none`,r.querySelector(`.chevron`).style.transform=_?`rotate(180deg)`:`rotate(0)`};let v=document.createElement(`div`);v.className=`inline-row`,v.style.cssText=`margin: 6px 0; display: flex; align-items: center; gap: 8px;`;let y=document.createElement(`span`);y.textContent=`Source:`,y.style.cssText=`font-size: 13px; color: var(--text-secondary);`;let ee=document.createElement(`select`);ee.style.cssText=`flex: 1; background: rgba(0,0,0,.35); color: #fff; border: 1px solid var(--glass-border); border-radius: 8px; padding: 6px; font-size: 13px;`,[{value:`all`,label:`All Free Sources (Combined)`},{value:`poly_pizza`,label:`Poly.pizza (Free CC0)`},{value:`kenney`,label:`Kenney.nl (CC0 Game Assets)`},{value:`quaternius`,label:`Quaternius (CC0 Low-Poly)`},{value:`mixamo`,label:`Mixamo (Free Rigged Characters)`},{value:`sketchfab`,label:`Sketchfab (Free CC Assets)`},{value:`cgtrader`,label:`CGTrader (Free CC0/Standard)`},{value:`turbosquid`,label:`Turbosquid (Free CC0/Standard)`}].forEach(e=>{let t=document.createElement(`option`);t.value=e.value,t.textContent=e.label,ee.appendChild(t)}),v.append(y,ee);let te=document.createElement(`div`);te.className=`inline-row`;let ne=document.createElement(`input`);ne.placeholder=`Search free 3D models...`;let b=document.createElement(`button`);b.className=`panel-action`,b.textContent=`Search`,te.append(ne,b);let re=document.createElement(`div`);re.className=`panel-list sketchfab-results`;let x=document.createElement(`p`);x.className=`panel-note`,x.textContent=`Ready to search unified free connectors.`;let ie=!1;return Bn().then(e=>{e?.configured&&(ie=!0,x.textContent=`OMEGA Sketchfab token active. Search & placement run completely free.`,u.input.placeholder=`Optional override token`)}).catch(()=>{}),b.onclick=async()=>{let e=u.input.value.trim()||An();jn(e);let t=ee.value;x.textContent=`Searching free assets from ${ee.options[ee.selectedIndex].text}...`,re.replaceChildren();try{let n=await $n(ne.value||`object`,t,e);if(!n.length){x.textContent=`No free assets matched your query on the selected source.`;return}x.textContent=`Found ${n.length} free asset(s).`,re.replaceChildren(...n.map(t=>Va(t,()=>u.input.value.trim()||e,()=>ie)))}catch(e){x.textContent=`Unified search failed.`,C(e.message,`Asset Search Failed`)}},e.append(t,n,r,o,v,te,x,re),e}function za(e,t){let n=document.createElement(`div`),r=document.createElement(`strong`);r.textContent=`${e}:`;let i=document.createElement(`span`);return i.style.color=`var(--success)`,i.textContent=` ● `,n.append(r,i,document.createTextNode(t)),n}async function Ba(){let e=document.createElement(`div`),t=document.createElement(`strong`),n=document.createElement(`p`),r=document.createElement(`input`),i=document.createElement(`select`),a=document.createElement(`textarea`),o=document.createElement(`pre`),s=document.createElement(`div`),c=document.createElement(`button`),l=document.createElement(`button`),u=document.createElement(`button`),d=document.createElement(`button`),f=R({name:`Custom Model`,kit:`scene`}),p=f;t.textContent=`Jarvis 3D Forge`,n.className=`panel-note`,n.textContent=`Build a model as geometry + parts + behaviors + triggers + scripts + exports.`,r.placeholder=`Model name`,r.value=f.name,a.rows=5,a.placeholder=`Describe the model, its parts, and the actions you want`,a.value=`Create a fully interactive model with named parts, gestures, and a behavior schema.`,sr(i,[`scene`,`house`,`room`,`device`,`vehicle`,`character`]),o.style.cssText=`white-space:pre-wrap;font:12px/1.45 monospace;color:rgba(255,255,255,.82);background:rgba(0,0,0,.25);padding:10px;border-radius:12px;max-height:220px;overflow:auto`,s.className=`panel-row`,c.className=`panel-action`,c.textContent=`Generate Blueprint`,l.className=`panel-action`,l.textContent=`Attach to Selected`,u.className=`panel-action`,u.textContent=`Build and Place`,d.className=`panel-action`,d.textContent=`Save Blueprint`;let m=()=>{o.textContent=JSON.stringify(p,null,2),s.replaceChildren();let e=D.selectedObject||D.placedObjects.at(-1)||null;e&&jr(e,s)};m(),c.onclick=async()=>{try{p=await Er(a.value,{name:r.value,kit:i.value}),p.name=r.value||p.name,p.prompt=a.value,p.kit=i.value,p.updatedAt=Date.now(),m(),w(`Jarvis blueprint generated. Review the schema and then attach or build.`,`Model Forge`)}catch(e){C(e.message,`Model Forge Failed`)}},l.onclick=()=>{let e=D.selectedObject;if(!e){w(`Select a model first, then attach the schema.`,`Model Forge`);return}z(e,{...p,name:r.value||p.name||e.userData.modelName||`Custom Model`,prompt:a.value,kit:i.value}),Lr(e),m(),w(`Behavior schema attached to ${e.userData.modelName||`selected model`}.`,`Model Forge`)},u.onclick=()=>{try{let e=Dr({...p,name:r.value||p.name||`Custom Model`,prompt:a.value,kit:i.value});$a(e,e.userData.modelName),Lr(e),w(`${e.userData.modelName} built with ${e.userData.modelForge?.parts?.length||0} interactive parts.`,`Model Forge`)}catch(e){C(e.message,`Model Forge Failed`)}},d.onclick=()=>{p={...p,name:r.value||p.name,prompt:a.value,kit:i.value,updatedAt:Date.now()},Tr(p),w(`Blueprint saved locally for later reuse.`,`Model Forge`)},e.append(t,n,r,i,a,c,l,u,d,o,s),new an({title:`Interactive Model Forge`,body:e,icon:`F`,width:390,height:620}).focus()}function Va(e,t,n=()=>!1){let r=document.createElement(`article`);if(r.className=`model-card ${e.source}-card`,e.thumbnail){let t=document.createElement(`img`);t.src=e.thumbnail,t.alt=``,t.loading=`lazy`,r.appendChild(t)}let i=document.createElement(`div`),a=document.createElement(`strong`),o=document.createElement(`span`),s=document.createElement(`a`);a.textContent=e.name;let c=e.size?es(e.size):`free`,l=e.faceCount?` / ${ts(e.faceCount)} faces`:``;o.textContent=`${e.licenseLabel} / ${c}${l}`,s.textContent=`${e.author} (${e.source.toUpperCase()})`,s.href=e.authorUrl||e.viewerUrl||`#`,s.target=`_blank`,s.rel=`noopener`,i.append(a,o,s);let u=document.createElement(`div`);u.className=`model-actions`;let d=document.createElement(`button`);d.className=`panel-action`;let f=e.source===`sketchfab`&&!n()&&!t();d.textContent=f?`Token Needed`:`Place`,d.onclick=()=>{if(f){C(`Sketchfab downloads require a configured token.`,`Token Required`);return}Ha(e,t())};let p=document.createElement(`a`);return p.className=`panel-action link-action`,p.href=e.viewerUrl||`#`,p.target=`_blank`,p.rel=`noopener`,p.textContent=`Open`,u.append(d,p),r.append(i,u),r}async function Ha(e,t){E(`Requesting ${e.source.toUpperCase()} download: ${e.name}...`,55);try{let n;if(e.downloadUrl===`forge-procedural`)n=Dr(R({name:e.name,kit:ns(e.name)}));else if(e.downloadUrl&&e.downloadUrl.startsWith(`api:spawn_3d_model:`)){let t=e.downloadUrl.split(`api:spawn_3d_model:`)[1];w(`[STABLE FAST 3D] Generating custom 3D model for: ${t}...`,`Jarvis AI Generation`),fetch(`/xr/model3d/spawn`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${qn(`omega_session`)||``}`},body:JSON.stringify({description:t,persona:`JARVIS`})}).catch(e=>console.error(`Generation request failed:`,e)),hidePanel(),clearLoading();return}else if(e.downloadUrl)(e.source===`cgtrader`||e.source===`turbosquid`||e.source===`mixamo`||e.source===`poly_pizza`)&&(qn(e.source)?e.source===`mixamo`?w(`[Mixamo] Secure Adobe ID Synchronized! Placed free rigged character.`,`Mixamo Rigging`):e.source===`poly_pizza`?w(`[Poly.pizza] Authenticated API Key! Placed free low-poly asset.`,`Poly.pizza API`):w(`[${e.source.toUpperCase()}] Authenticated as user! Placed free model.`,`${e.source.toUpperCase()} Session`):w(`[${e.source.toUpperCase()}] Session Proxy: Connected via OMEGA public portal... Placed free model!`,`${e.source.toUpperCase()} Session`)),n=await to(e.downloadUrl);else if(e.source===`sketchfab`){jn(t);let r=await Rn(e.uid,t),i=r.glb?.url||r.gltf?.url;if(!i)throw Error(`Sketchfab did not return a glTF or GLB download URL.`);n=r.glb?.url?await to(i):await Ua(i)}else throw Error(`Unsupported model source: ${e.source}`);n.userData.modelName=e.name,n.userData.sketchfab=e.sketchfab||{uid:e.uid,author:e.author,authorUrl:e.authorUrl||``,license:e.license||`free`,licenseLabel:e.licenseLabel||`Free`,viewerUrl:e.viewerUrl||``},z(n,R({name:e.name,kit:ns(e.name)}));let r=Za(.5,.56);eo(n,e.name,r.position,r.rotation,`${e.source}:${e.uid}`),w(`${e.name} placed successfully from ${e.source.toUpperCase()}.`,e.source.toUpperCase())}catch(t){C(`${e.source.toUpperCase()} failed: ${t.message}. Spawning premium generated fallback...`,`${e.source.toUpperCase()} Fallback`);let n=bo(e.name);z(n,R({name:e.name,kit:ns(e.name)}));let r=Za(.5,.56);eo(n,e.name,r.position,r.rotation,``)}finally{Je()}}async function Ua(e){let t=await fetch(e);if(!t.ok)throw Error(`Sketchfab archive download failed: ${t.status}`);let n=pa(new Uint8Array(await t.arrayBuffer())),r=Object.keys(n).filter(e=>e.toLowerCase().endsWith(`.gltf`));if(!r.length)throw Error(`Sketchfab archive did not contain a .gltf scene.`);let i=r.find(e=>e.toLowerCase().replace(/.*\//,``)===`scene.gltf`)??r.reduce((e,t)=>n[t].byteLength>n[e].byteLength?t:e,r[0]),a=new TextDecoder().decode(n[i]),o=i.includes(`/`)?i.slice(0,i.lastIndexOf(`/`)+1):``,s=new Map;for(let[e,t]of Object.entries(n)){let n=Qo(e),r=URL.createObjectURL(new Blob([t],{type:n}));s.set($o(e),r),s.set(e.split(`/`).pop(),r)}let c=new ye;c.setURLModifier(e=>{let t=$o(e),n=$o(`${o}${t}`);return s.get(t)||s.get(n)||s.get(t.split(`/`).pop())||e});let l=new Ce(c);return new Promise((e,t)=>{l.parse(a,o,t=>{for(let e of new Set(s.values()))URL.revokeObjectURL(e);e(t.scene)},e=>{for(let e of new Set(s.values()))URL.revokeObjectURL(e);t(e)})})}function Wa(e){let t=document.createElement(`article`);t.className=`model-card`;let n=document.createElement(`div`),r=document.createElement(`strong`),i=document.createElement(`span`),a=document.createElement(`button`);return r.textContent=e.name,i.textContent=`${e.category} / ${e.size}`,a.className=`panel-action`,a.textContent=`Place`,a.onclick=()=>Ya(e.name),n.append(r,i),t.append(n,a),t}async function Ga(e){if(!e)return;if(e.size>100*1024*1024){C(`Custom model is larger than 100MB. Please optimize or compress it first.`,`Model Too Large`);return}let t=e.name.split(`.`).pop()?.toLowerCase(),n=``;try{n=URL.createObjectURL(e);let r=t===`glb`||t===`gltf`?await to(n):await Ka(n,t);r.userData.modelName=e.name,$a(r,e.name);let i=er(ga,[]);i.push({name:e.name,type:t,size:e.size,addedAt:Date.now()}),tr(ga,i.slice(-24))}catch(e){C(e.message,`Custom Model Failed`)}finally{n&&URL.revokeObjectURL(n)}}async function Ka(e,t){if(t===`obj`){let{OBJLoader:t}=await Re(async()=>{let{OBJLoader:e}=await import(`./three-K6XMXseN.js`).then(e=>e.t);return{OBJLoader:e}},__vite__mapDeps([1,2]),import.meta.url);return new Promise((n,r)=>new t().load(e,n,void 0,r))}if(t===`fbx`){let{FBXLoader:t}=await Re(async()=>{let{FBXLoader:e}=await import(`./three-K6XMXseN.js`).then(e=>e.n);return{FBXLoader:e}},__vite__mapDeps([1,2]),import.meta.url);return new Promise((n,r)=>new t().load(e,n,void 0,r))}throw Error(`Unsupported custom model type: ${t||`unknown`}`)}function qa(){if(D.modelPlacementEventsBound)return;D.modelPlacementEventsBound=!0;let e=document.getElementById(`camerafeed`);e?.addEventListener(`pointerdown`,e=>Po(e.clientX,e.clientY)),e?.addEventListener(`pointerup`,Fo),e?.addEventListener(`pointermove`,Fo),document.addEventListener(`touchend`,e=>{if(!D.pendingModelToPlace||Xa(e.target))return;let t=e.changedTouches[0];t&&Ja(t.clientX,t.clientY,e)},{passive:!0,capture:!0}),document.addEventListener(`pointerup`,e=>{e.pointerType!==`touch`&&(!D.pendingModelToPlace||Xa(e.target)||Ja(e.clientX,e.clientY,e))},!0)}async function Ja(e,t,n=null){if(!D.pendingModelToPlace)return;let r=performance.now(),i=n?.pointerId??n?.changedTouches?.[0]?.identifier??n?.detail?.pointerId??++ja,a=`${Math.round(e)}:${Math.round(t)}:${n?.type||`auto`}:${i}`;if(r-Ta<350&&a===Ea)return;Ta=r,Ea=a;let o=D.pendingModelToPlace,s=Za(e/innerWidth,t/innerHeight);D.pendingModelToPlace=``,delete document.body.dataset.jarvisPendingModel,Xo(!1),Oa++,window.clearTimeout(Da),Da=0;try{await Qa(o,s.position,s.rotation)}catch(e){C(e.message,`Model Placement Failed`)}}function Ya(e){D.pendingModelToPlace=e,document.body.dataset.jarvisPendingModel=e,Xo(!0),w(`Tap a detected surface to place ${e}. Auto-place will use the center hit-test if no tap arrives.`,`Model Armed`),window.clearTimeout(Da),Da=0;let t=++Oa;Da=window.setTimeout(()=>{D.pendingModelToPlace===e&&Oa===t&&Ja(innerWidth/2,innerHeight*.56)},900)}function Xa(e){return!!e?.closest?.(`.ar-panel, .hud-toolbar, button, input, select, textarea, iframe`)}function Za(e,t){try{let n=globalThis.XR8?.XrController?.hitTest?.(e,t,[`FEATURE_POINT`,`ESTIMATED_SURFACE`,`DETECTED_SURFACE`]);if(n&&n.length>0)return n[0]}catch{}let{camera:n}=L(),r=new De(e*2-1,-(t*2-1)),i=new f;i.setFromCamera(r,n);let a=(D.floorY-i.ray.origin.y)/i.ray.direction.y;return{position:Number.isFinite(a)&&a>0?i.ray.origin.clone().add(i.ray.direction.clone().multiplyScalar(a)):i.ray.origin.clone().add(i.ray.direction.clone().multiplyScalar(2)),rotation:new c}}async function Qa(e,t,n){E(`Loading ${e}...`,55);try{let r=xn(e),i=await to(r,(t,n)=>{n&&E(`Loading ${e}... ${Math.round(t/n*100)}%`,55+Math.round(t/n*30))});return z(i,R({name:e,kit:ns(e)})),eo(i,e,t,n,r),Je(),i}catch(r){C(`Remote GLB failed for ${e}: ${r.message}. Generated fallback spawned instead.`,`Model Fallback`);let i=bo(e);return z(i,R({name:e,kit:ns(e)})),eo(i,e,t,n,``),Je(),i}}function $a(e,t=`Custom Model`){let n=Za(.5,.55);eo(e,t,n.position,n.rotation,``)}function eo(e,t,n,r,i){let{scene:a}=L();e.position.copy(Zo(n)),r?.isQuaternion?e.quaternion.copy(r):r&&e.quaternion.set(r.x||0,r.y||0,r.z||0,r.w||1),vo(e),e.userData.id=e.userData.id||or(`model`),e.userData.modelName=t,e.userData.sourceURL=i,e.userData.isARObject=!0,!e.userData.modelForge&&!e.userData.modelForgeBlueprint&&z(e,R({name:t,kit:ns(t)})),e.traverse(e=>{e.isMesh&&(e.castShadow=!0,e.receiveShadow=!0,e.frustumCulled=!0)});let o=e.scale.clone();return e.userData.finalScale=o.toArray(),e.scale.setScalar(.001),a.add(e),D.placedObjects.push(e),wo(e),xi(e),yo(e,o,()=>{e.userData.finalScale=o.toArray(),Do(),Si(e,`place`)}),document.body.dataset.jarvisObjects=String(D.placedObjects.length),document.body.dataset.jarvisLastModel=t,F(`upsertObject`,e.userData.id,i||`model`,t,e.position.x,e.position.y,e.position.z),k(`object-placed`,{object:e,modelName:t}),e}function to(e,t){let n=ho(e),r=ba.get(n);if(r?.template)return Promise.resolve(no(r));if(r?.promise)return r.promise.then(e=>no(e));let i={key:n,url:e,template:null,promise:null,refCount:0,bytes:0,lastUsed:go(),loading:!0};return i.promise=new Promise((r,a)=>{_a.load(e,e=>{i.template=fr(e.scene,{targetSize:1,maxTextureSize:2048,maxAnisotropy:6}),i.animations=e.animations||[];let t=dr(i.template);i.metrics=t,i.bytes=Math.max(t.bytes||lo(i.template),512*1024),i.lastUsed=go(),i.loading=!1,i.promise=null,co(i.template,n),t.warnings.length&&k(`assistant`,`Optimized ${n} for scale and texture budget: ${t.warnings.join(`, `)}.`),xa+=i.bytes,r(i)},e=>t?.(e.loaded,e.total),e=>{ba.delete(n),i.loading=!1,i.promise=null,a(e)})}),ba.set(n,i),i.promise.then(e=>no(e))}function no(e){e.refCount+=1,e.lastUsed=go();let t=se(e.template);return t.userData.assetCacheKey=e.key,t.userData.assetCacheShared=!0,t.userData.assetCacheBytes=e.bytes,co(t,e.key),oo(),t}function ro(e){let t=e?.userData?.assetCacheKey,n=t?ba.get(t):null,r=n?.template?no(n):e.clone(!0);return r.position.copy(e.position),r.quaternion.copy(e.quaternion),r.scale.copy(e.scale),r.name=e.name,r.visible=e.visible,r.userData={..._o(e.userData),assetCacheKey:r.userData.assetCacheKey,assetCacheShared:r.userData.assetCacheShared,assetCacheBytes:r.userData.assetCacheBytes},delete r.userData.shadow,r.traverse(e=>{e.isMesh&&(e.castShadow=!0,e.receiveShadow=!0,e.frustumCulled=!0)}),r}function io(e){let t=e?.userData?.assetCacheKey;if(!t)return!1;let n=ba.get(t);return n?(n.refCount=Math.max(0,n.refCount-1),n.lastUsed=go(),oo(),!0):!0}function ao(e){Mt(e,{disposeSharedAssets:!io(e)})}function oo(e=!1){let t=[...ba.values()].filter(e=>e.template&&!e.loading&&e.refCount===0).sort((e,t)=>e.lastUsed-t.lastUsed);for(;t.length&&(e||ba.size>va||xa>ya);)so(t.shift())}function so(e){!e||e.refCount>0||(ba.delete(e.key),xa=Math.max(0,xa-e.bytes),e.template&&Mt(e.template,{disposeSharedAssets:!0}),e.template=null)}function co(e,t){e.userData.sharedAssetKey=t,e.traverse(e=>{e.userData.sharedAssetKey=t,e.geometry&&(e.geometry.userData=e.geometry.userData||{},e.geometry.userData.sharedAssetKey=t),po(e.material,e=>{e.userData=e.userData||{},e.userData.sharedAssetKey=t,mo(e,e=>{e.userData=e.userData||{},e.userData.sharedAssetKey=t})})})}function lo(e){let t=new Set,n=new Set,r=new Set,i=0;return e.traverse(e=>{e.geometry&&!t.has(e.geometry)&&(t.add(e.geometry),i+=uo(e.geometry)),po(e.material,e=>{n.has(e)||(n.add(e),i+=2048),mo(e,e=>{r.has(e)||(r.add(e),i+=fo(e))})})}),Math.max(i,512*1024)}function uo(e){let t=0,n=e=>{e?.array?.byteLength&&(t+=e.array.byteLength)};return Object.values(e.attributes||{}).forEach(n),Object.values(e.morphAttributes||{}).forEach(e=>e.forEach(n)),n(e.index),t}function fo(e){let t=e?.image||{};if(t.data?.byteLength)return t.data.byteLength;let n=t.width||t.videoWidth||t.naturalWidth||256,r=t.height||t.videoHeight||t.naturalHeight||256;return Math.max(1,n)*Math.max(1,r)*4}function po(e,t){(Array.isArray(e)?e:[e]).filter(Boolean).forEach(t)}function mo(e,t){let n=new Set,r=e=>{if(!(!e||typeof e!=`object`)){if(e.isTexture){n.has(e)||(n.add(e),t(e));return}if(Array.isArray(e)){e.forEach(r);return}e.value?.isTexture?r(e.value):e.constructor===Object&&Object.values(e).forEach(r)}};Object.values(e).forEach(r)}function ho(e){return String(e||``).trim()}function go(){return typeof performance<`u`?performance.now():Date.now()}function _o(e){try{return structuredClone(e)}catch{try{return JSON.parse(JSON.stringify(e))}catch{return{...e}}}}function vo(e){let t=new fe().setFromObject(e).getSize(new S).length(),n=t>0?.55/t:.35;e.scale.setScalar(Math.min(1,n))}function yo(e,t,n){let r=performance.now(),i=0,a=()=>{if(!e.parent){vt(i);return}let o=Math.min((performance.now()-r)/420,1),s=o<.6?o/.6*1.1:1.1-.1*((o-.6)/.4);e.scale.copy(t).multiplyScalar(s),o<1?i=N(a):(e.scale.copy(t),n?.())};i=N(a)}function bo(e){let t=new Ne,n=new m(new o(.28,2),new _({color:43775,emissive:21879,roughness:.25,metalness:.35,transparent:!0,opacity:.78})),r=new m(new Se(.42,.008,8,96),ma.clone());r.rotation.x=Math.PI/2;let i=Co(e);return i.position.y=.48,t.add(n,r,i),t}function xo(e,t){let n=D.selectedObject||D.placedObjects.at(-1);n&&(Ir(n,e,t),To(n),Lr(n),Si(n,e))}function So(e={}){let t=rs(e.action||e.command||``),n=String(e.target||e.model||e.query||``).trim(),r=D.selectedObject||D.placedObjects.at(-1)||null;if(n){let e=n.toLowerCase();r=D.placedObjects.find(t=>{let n=String(t.userData?.modelName||``).toLowerCase(),r=t.userData?.modelForge?.parts||[];return n.includes(e)||r.some(t=>String(t.name||``).toLowerCase().includes(e))})||r}!r||!t||(Fr(r,t,e),To(r),Lr(r),Si(r,t))}function Co(e){let n=String(e||`Model`).trim().toLowerCase(),r=Ma.get(n);if(r){let e=new t(new pe({map:r.texture,transparent:!0}));return e.scale.set(.9,.23,1),e.userData.labelCacheKey=n,e}let i=document.createElement(`canvas`);i.width=512,i.height=128;let a=i.getContext(`2d`);a.clearRect(0,0,i.width,i.height),a.fillStyle=`rgba(0,0,0,0.32)`,a.fillRect(0,0,i.width,i.height),a.fillStyle=`#fff`,a.font=`600 34px Inter, sans-serif`,a.textAlign=`center`,a.textBaseline=`middle`,a.fillText(String(e).slice(0,24),256,64);let o=new he(i);o.userData=o.userData||{},o.userData.sharedAssetKey=`label:${n}`,Ma.set(n,{texture:o});let s=new t(new pe({map:o,transparent:!0}));return s.scale.set(.9,.23,1),s.userData.labelCacheKey=n,s}function wo(e){e.userData.shadow?.parent?.remove(e.userData.shadow);let t=new m(new Me(.35,48),new h({color:0,transparent:!0,opacity:.24,depthWrite:!1}));t.rotation.x=-Math.PI/2,t.name=`jarvis-blob-shadow`,e.userData.shadow=t,To(e),L().scene.add(t)}function To(e){let t=e?.userData?.shadow;t&&t.position.set(e.position.x,D.floorY+.004,e.position.z)}function Eo(e){return Array.isArray(e)&&e.length>=3&&e.every(e=>Number.isFinite(e)&&e>.01)}function Do(){tr(ha,D.placedObjects.map(e=>({id:e.userData.id,modelName:e.userData.modelName,sourceURL:e.userData.sourceURL||``,sketchfab:e.userData.sketchfab||null,modelForge:e.userData.modelForge||e.userData.modelForgeBlueprint||null,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:Array.isArray(e.userData.finalScale)?e.userData.finalScale:e.scale.toArray(),trackingMode:D.trackingMode,floorY:D.floorY,anchor:ko(e),savedAt:Date.now()})))}async function Oo(){let e=er(ha,[]),t=[];for(let n of e)try{let e=n.sourceURL&&!n.sourceURL.startsWith(`sketchfab:`)?await to(n.sourceURL):bo(n.modelName);e.userData.id=n.id,e.position.fromArray(n.position),e.quaternion.fromArray(n.quaternion),e.scale.fromArray(Eo(n.scale)?n.scale:[.35,.35,.35]),e.userData.finalScale=e.scale.toArray(),e.userData.modelName=n.modelName,e.userData.sourceURL=n.sourceURL,e.userData.sketchfab=n.sketchfab||null,e.userData.worldAnchor=n.anchor||null,e.userData.isARObject=!0,z(e,n.modelForge||R({name:n.modelName||`Restored Model`,kit:ns(n.modelName)})),L().scene.add(e),D.placedObjects.push(e),wo(e),xi(e),jo(e),document.body.dataset.jarvisObjects=String(D.placedObjects.length)}catch(e){t.push(`${n.modelName||`Restored Model`}: ${e?.message||`load failed`}`);let r=bo(n.modelName||`Restored Model`);r.position.fromArray(n.position||[0,D.floorY,-2]),r.scale.fromArray(Eo(n.scale)?n.scale:[.35,.35,.35]),r.userData.finalScale=r.scale.toArray(),r.userData.id=n.id||or(`model`),r.userData.modelName=n.modelName||`Restored Model`,r.userData.sourceURL=n.sourceURL||``,r.userData.sketchfab=n.sketchfab||null,r.userData.worldAnchor=n.anchor||null,r.userData.isARObject=!0,z(r,n.modelForge||R({name:n.modelName||`Restored Model`,kit:ns(n.modelName)})),L().scene.add(r),D.placedObjects.push(r),wo(r),xi(r),jo(r),document.body.dataset.jarvisObjects=String(D.placedObjects.length)}t.length&&w(`Some saved models failed to restore and were replaced with generated fallbacks: ${t.slice(0,3).join(`; `)}${t.length>3?` (+${t.length-3} more)`:``}`,`Model Restore`)}function ko(e){return{type:`world-point-signature-v1`,position:e.position.toArray(),quaternion:e.quaternion.toArray(),floorY:D.floorY,signature:Ao(),trackingMode:D.trackingMode,createdAt:Date.now()}}function Ao(){let e=D.worldPointBuffer.slice(-360);if(e.length<10)return{count:e.length,centroid:[0,D.floorY,0],floorY:D.floorY};let t=e.reduce((e,t)=>(e.x+=t.x,e.y+=t.y,e.z+=t.z,e),new S).multiplyScalar(1/e.length);return{count:e.length,centroid:t.toArray(),floorY:D.floorY}}function jo(e){e.userData.worldAnchor&&(Na.add(e),No(e))}function Mo(){Na.forEach(e=>{if(!e.parent){Na.delete(e);return}No(e)})}function No(e){let t=e.userData.worldAnchor;if(!t?.position)return;let n=t.signature||{},r=Ao(),i=new S().fromArray(t.position);n.count>=10&&r.count>=10&&Array.isArray(n.centroid)&&(i.x+=r.centroid[0]-n.centroid[0],i.z+=r.centroid[2]-n.centroid[2]);let a=Number.isFinite(t.floorY)?t.floorY:n.floorY;Number.isFinite(a)&&Number.isFinite(r.floorY)&&(i.y+=r.floorY-a),e.position.copy(i),To(e)}function Po(e,t){Fo(),Ca=window.setTimeout(()=>{Io(e,t),D.selectedObject&&Ro(e,t,D.selectedObject)},500)}function Fo(){window.clearTimeout(Ca)}function Io(e,t){let{camera:n}=L(),r=new f;r.setFromCamera(new De(e/innerWidth*2-1,-(t/innerHeight)*2+1),n);let i=r.intersectObjects(D.placedObjects,!0)[0]?.object;return D.selectedObject=i?Lo(i):null,D.selectedObject}function Lo(e){let t=e;for(;t&&!t.userData.isARObject&&t.parent;)t=t.parent;return t?.userData?.isARObject?t:null}function Ro(e,t,n){Sa?.remove(),Sa=document.createElement(`section`),Sa.className=`context-menu glass-panel`,Sa.style.left=`${Math.min(e,innerWidth-210)}px`,Sa.style.top=`${Math.min(t,innerHeight-250)}px`;let r=[[`Duplicate`,()=>Vo(n)],[`Delete`,()=>Ho(n)],[`Physics ON`,()=>Uo(n)],[`Open`,()=>zo(n,`open`)],[`Close`,()=>zo(n,`close`)],[`Toggle`,()=>zo(n,`toggle`)],[`Shatter`,()=>zo(n,`shatter`)],[`Forge`,()=>k(`open-model-forge`)],[`Save`,()=>Do()],[`Export .GLB`,()=>Wo(n)]];for(let[e,t]of r){let n=document.createElement(`button`);n.textContent=e,n.onclick=()=>{t(),Sa?.remove()},Sa.appendChild(n)}document.body.appendChild(Sa),window.setTimeout(()=>document.addEventListener(`pointerdown`,Bo,{once:!0}),0)}function zo(e,t){Fr(e,t),To(e),Lr(e),Si(e,t),F(`manipulateObject`,e.userData.id||``,t)}function Bo(e){Sa?.contains(e.target)||Sa?.remove()}function Vo(e){let t=ro(e),n=new S(.25,.02,-.25).applyQuaternion(e.quaternion);t.position.add(n),t.userData.id=or(`model`),t.userData.finalScale=e.userData.finalScale||t.scale.toArray(),delete t.userData.worldAnchor,(e.userData.modelForge||e.userData.modelForgeBlueprint)&&z(t,e.userData.modelForge||e.userData.modelForgeBlueprint),L().scene.add(t),D.placedObjects.push(t),wo(t),xi(t),Si(t,`place`),Do()}function Ho(e){D.placedObjects=D.placedObjects.filter(t=>t!==e),Na.delete(e),D.selectedObject===e&&(D.selectedObject=null),wa.get(e.userData.id)&&(wa.delete(e.userData.id),wa.size||stopPhysicsLoop()),e.userData.shadow&&Mt(e.userData.shadow),Si(e,`delete`),F(`removeObject`,e.userData.id||``),ao(e),Do()}async function Uo(e){if(wa.has(e.userData.id)){unregisterPhysicsMesh(wa.get(e.userData.id)),wa.delete(e.userData.id);return}let t=createRigidBody(e.position,`dynamic`);registerPhysicsMesh(e,t),wa.set(e.userData.id,t)}window.addEventListener(`ar-physics-step`,()=>{for(let e of wa.keys()){let t=D.placedObjects.find(t=>t.userData.id===e);t&&To(t)}});async function Wo(e){let{GLTFExporter:t}=await Re(async()=>{let{GLTFExporter:e}=await import(`./three-K6XMXseN.js`).then(e=>e.r);return{GLTFExporter:e}},__vite__mapDeps([1,2]),import.meta.url),n=new t;await Go(e),n.parse(e,t=>{let n=t instanceof ArrayBuffer?new Blob([t],{type:`model/gltf-binary`}):new Blob([JSON.stringify(t)],{type:`model/gltf+json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${e.userData.modelName||`jarvis-model`}.glb`,i.click(),URL.revokeObjectURL(r)},e=>C(e.message,`Export Failed`),{binary:!0})}async function Go(e){let t=[];e.traverse(e=>{po(e.material,e=>{mo(e,e=>{t.push(e)})})}),await Promise.all(t.map(async e=>{let t=e?.image;if(t){if(t.complete===!1){await new Promise(e=>{let n=()=>e();t.addEventListener?.(`load`,n,{once:!0}),t.addEventListener?.(`error`,n,{once:!0}),window.setTimeout(n,1200)});return}if(typeof t.decode==`function`)try{await t.decode()}catch{}}}))}function Ko(){let e=document.createElement(`div`);e.style.cssText=`display: flex; flex-direction: column; gap: 8px;`;let t=document.createElement(`strong`);t.textContent=`JARVIS Stark 3D Composer`,t.style.cssText=`font-size: 14px; color: var(--accent); text-transform: uppercase;`;let n=document.createElement(`select`);sr(n,[[`primitive`,`Custom Basic Geometry`],[`arc_reactor`,`Stark Arc Reactor Core`],[`gauntlet`,`Holographic Repulsor Gauntlet`],[`thruster`,`Flight Ion Propulsion Thruster`],[`quantum_reactor`,`Quantum Core Reactor Engine`],[`faceplate`,`Cybernetic Visor Faceplate`]]);let r=document.createElement(`select`);sr(r,[[`metal`,`Machined Brushed Titanium`],[`gold`,`Polished Golden Core`],[`glass`,`Translucent Ethereal Glass`],[`glow`,`Glowing Neon Hologram`],[`matte`,`Stark Matte Composite`]]);let i=document.createElement(`div`);i.style.cssText=`display: flex; flex-direction: column; gap: 4px;`;let a=document.createElement(`span`);a.textContent=`Shape / Geometry:`,a.style.cssText=`font-size: 11px; color: var(--text-secondary);`;let o=document.createElement(`select`);sr(o,[`cube`,`sphere`,`cylinder`,`cone`,`plane`,`torus`,`ring`,`capsule`]),i.append(a,o);let s=document.createElement(`div`);s.style.cssText=`display: flex; flex-direction: column; gap: 4px;`;let c=document.createElement(`span`);c.textContent=`Visual Detail Level:`,c.style.cssText=`font-size: 11px; color: var(--text-secondary);`;let l=document.createElement(`select`);sr(l,[[`standard`,`Standard`],[`premium`,`Premium`],[`hero`,`Hero Detail`]]),s.append(c,l);let u=document.createElement(`input`);u.placeholder=`Model custom name (e.g. Mark 85 reactor)`;let d=document.createElement(`button`);d.className=`panel-action`,d.textContent=`Build Stark Composite`,d.style.cssText=`background: var(--accent); color: #fff; font-weight: 600; min-height: 42px; border-radius: 12px; margin-top: 8px;`,n.onchange=()=>{let e=n.value===`primitive`;i.style.display=e?`flex`:`none`,s.style.display=e?`flex`:`none`,u.value=e?``:n.options[n.selectedIndex].text},d.onclick=()=>{let e=n.value,t;t=e===`primitive`?Jo(o.value,r.value,l.value):qo(e,r.value);let i=u.value||`${r.options[r.selectedIndex].text} ${n.options[n.selectedIndex].text}`;t.userData.modelName=i,z(t,R({name:i,kit:e===`primitive`?`scene`:ns(e)})),$a(t,i);let a=er(ga,[]);a.push({name:i,assembly:e,material:r.value,addedAt:Date.now()}),tr(ga,a.slice(-24)),w(`Successfully composed and placed Stark asset: ${i}.`,`3D Composer`)};let f=document.createElement(`p`);f.className=`panel-note`,f.textContent=`Stark Assemblies generate premium multi-part geometries with concentric highlights, glowing points, and kinematic hinges.`,e.append(t,n,r,i,s,u,d,f),new an({title:`Stark 3D Composer`,body:e,icon:`B`,width:375,height:490}).focus()}function qo(e,t){let n=new Ne;n.name=`stark-${e}`;let r=Yo(t===`gold`?`metal`:t);t===`gold`&&(r.color.setHex(16766720),r.roughness=.05,r.metalness=.95);let i=new h({color:54015,transparent:!0,opacity:.85}),a=new h({color:16777215,transparent:!0,opacity:.95}),o=new s({color:3815994,roughness:.6,metalness:.8});if(e===`arc_reactor`){let e=new m(new Pe(.18,.18,.06,32),o);e.position.y=-.03,n.add(e);let t=new m(new Pe(.08,.08,.08,24),i);t.position.y=.01,t.userData.partName=`reactor-core`,t.userData.partType=`light`;let c=new b(54015,3,2.5);c.position.set(0,0,0),t.add(c),n.add(t);let l=new m(new Se(.15,.018,12,48),r);l.rotation.x=Math.PI/2,n.add(l);let u=new s({color:13794605,roughness:.18,metalness:.9});for(let e=0;e<10;e++){let t=e/10*Math.PI*2,r=new m(new me(.024,.024,.018),u);r.position.set(Math.cos(t)*.15,0,Math.sin(t)*.15),r.rotation.y=-t,n.add(r)}let d=new m(new Se(.1,.005,8,48),a);d.rotation.x=Math.PI/2,d.position.y=.02,n.add(d)}else if(e===`gauntlet`){let e=new m(new Pe(.1,.11,.28,16,1,!0,-Math.PI/2,Math.PI),r);e.rotation.x=Math.PI/2,e.userData.partName=`wrist-guard`,e.userData.partType=`base`,n.add(e);let t=new m(new Pe(.018,.018,.12,12),o);t.position.set(0,.07,-.06),t.rotation.x=Math.PI/2,t.userData.partName=`laser-emitter`,t.userData.partType=`detail`;let s=new m(new v(.012),a);s.position.y=.06,t.add(s),n.add(t);let c=new m(new v(.025,16,16),i);c.position.set(0,.06,.08),c.userData.partName=`palm-repulsor`,c.userData.partType=`light`;let l=new b(54015,2.5,2);c.add(l),n.add(c)}else if(e===`thruster`){let e=new m(new Pe(.06,.11,.16,24),o);e.userData.partName=`thruster-nozzle`,e.userData.partType=`base`,n.add(e);let t=new m(new v(.045,16,16),r);t.position.y=-.06,t.userData.partName=`thruster-core`,t.userData.partType=`light`;let i=new b(16771584,3.5,3);t.add(i),n.add(t);let a=new m(new Pe(.04,.005,.32,16),new h({color:16747520,transparent:!0,opacity:.65}));a.position.y=-.22,a.userData.partName=`thrust-stream`,a.userData.partType=`detail`,n.add(a)}else if(e===`quantum_reactor`){let e=new m(new Pe(.12,.12,.32,24),new _({color:13627391,roughness:.02,transmission:.8,transparent:!0,opacity:.3}));e.userData.partName=`quantum-capsule`,e.userData.partType=`window`,n.add(e);let t=new m(new Se(.09,.01,8,32),r);t.position.y=.05,t.rotation.x=Math.PI/2,t.userData.partName=`upper-gear`,t.userData.partType=`wheel`,n.add(t);let a=new m(new Se(.09,.01,8,32),r);a.position.y=-.05,a.rotation.x=Math.PI/2,a.userData.partName=`lower-gear`,a.userData.partType=`wheel`,n.add(a);let o=new m(new u(.04,0),i);o.userData.partName=`energy-core`,o.userData.partType=`light`;let s=new b(65450,3,2);o.add(s),n.add(o)}else if(e===`faceplate`){let e=new m(new Pe(.14,.14,.18,16,1,!1,-Math.PI/3,Math.PI/3*2),r);e.userData.partName=`faceplate-armour`,e.userData.partType=`base`,n.add(e);let t=new m(new me(.18,.04,.02),i);t.position.set(0,.02,.12),t.userData.partName=`visor-screen`,t.userData.partType=`screen`,n.add(t);let o=new m(new me(.035,.005,.005),a);o.position.set(-.04,.02,.13),o.userData.partName=`left-eye`,o.userData.partType=`light`,n.add(o);let s=new m(new me(.035,.005,.005),a);s.position.set(.04,.02,.13),s.userData.partName=`right-eye`,s.userData.partType=`light`,n.add(s)}return n}function Jo(e,t,n=`standard`){let i=Yo(t),a={cube:()=>new me(.35,.35,.35),sphere:()=>new v(.22,48,24),cylinder:()=>new Pe(.18,.18,.38,48),cone:()=>new le(.2,.42,48),plane:()=>new r(.5,.5),torus:()=>new Se(.23,.04,16,80),ring:()=>new Ee(.14,.24,64),capsule:()=>new oe(.15,.35,8,24)}[e]?.()||new me(.35,.35,.35),o=new Ne;o.name=`builder-${e}-${n}`;let c=new m(a,i);c.castShadow=!0,c.receiveShadow=!0,o.add(c);let l=t===`glass`?new _({color:13627391,roughness:.02,transmission:.72,transparent:!0,opacity:.34}):new h({color:51455,transparent:!0,opacity:.75}),u=new m(new Se(.27,.02,12,64),l);if(u.rotation.x=Math.PI/2,o.add(u),n===`premium`||n===`hero`){let e=new m(new v(.09,24,16),new s({color:16777215,roughness:.25,metalness:.3}));e.position.set(0,.25,0),o.add(e)}if(n===`hero`){let e=new m(new Pe(.06,.1,.18,6),new _({color:10475775,roughness:.14,metalness:.6,emissive:397597}));e.position.set(0,.34,0),e.rotation.y=Math.PI/6,o.add(e);let t=new m(new Se(.33,.01,8,80),new h({color:16777215,transparent:!0,opacity:.55}));t.rotation.x=Math.PI/2,t.position.y=.02,o.add(t)}return o}function Yo(e){return e===`metal`?new _({color:9422847,roughness:.18,metalness:.9}):e===`glass`?new _({color:13627391,roughness:.04,transmission:.55,transparent:!0,opacity:.45}):e===`glow`?new h({color:51455,transparent:!0,opacity:.8}):new s({color:8109311,roughness:.55,metalness:.1})}function Xo(e){D.reticle&&(D.reticle.visible=e)}function Zo(e){return e?.isVector3?e:new S(e?.x||0,e?.y??D.floorY,e?.z||-2)}function Qo(e){let t=e.toLowerCase();return t.endsWith(`.gltf`)?`model/gltf+json`:t.endsWith(`.bin`)?`application/octet-stream`:t.endsWith(`.png`)?`image/png`:t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`image/jpeg`:t.endsWith(`.webp`)?`image/webp`:`application/octet-stream`}function $o(e){return decodeURIComponent(String(e||``)).replace(/\\/g,`/`).replace(/^blob:https?:\/\/[^/]+\//,``).replace(/^https?:\/\/[^/]+\//,``).replace(/^\/+/,``).replace(/^(\.\/)+/,``)}function es(e){let t=Number(e||0);return t?t>1024*1024?`${Math.round(t/1024/1024)}MB`:`${Math.round(t/1024)}KB`:`size unknown`}function ts(e){let t=Number(e||0);return t?t>1e6?`${(t/1e6).toFixed(1)}M`:t>1e3?`${Math.round(t/1e3)}K`:String(t):`unknown`}function ns(e){let t=String(e||``).toLowerCase();return t.includes(`house`)||t.includes(`home`)?`house`:t.includes(`room`)||t.includes(`bedroom`)||t.includes(`kitchen`)?`room`:t.includes(`car`)||t.includes(`truck`)||t.includes(`vehicle`)?`vehicle`:t.includes(`phone`)||t.includes(`tablet`)||t.includes(`device`)?`device`:t.includes(`person`)||t.includes(`robot`)||t.includes(`character`)?`character`:`scene`}function rs(e){let t=String(e||``).toLowerCase().trim();return t?/(^|\b)(open|unfold|expand)(\b|$)/.test(t)?`open`:/(^|\b)(close|fold|collapse)(\b|$)/.test(t)?`close`:/(^|\b)(toggle|switch)(\b|$)/.test(t)?`toggle`:/(^|\b)(rotate|spin|turn)(\b|$)/.test(t)?`rotate`:/(^|\b)(reconfigure|rebuild|transform|rearrange)(\b|$)/.test(t)?`reconfigure`:/(^|\b)(shatter|break|explode)(\b|$)/.test(t)?`shatter`:/(^|\b)(reveal|show)(\b|$)/.test(t)?`reveal`:/(^|\b)(hide)(\b|$)/.test(t)?`hide`:/(^|\b)(grab|move|drag)(\b|$)/.test(t)?`grab`:t:``}var is=0,as=4,os=8,ss=12,cs=16,ls=20,us=5,ds=6,fs=9,ps=10,ms=13,hs=14,gs=17,_s=new Map([[us,ds],[fs,ps],[ms,hs],[gs,18]]),vs=[[0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[17,18],[18,19],[19,20],[0,17]],ys=20,bs=null,K=null,q=null,xs=!1,Ss=null,J=0,Cs=0,ws=0,Ts=!1,Es=0,Ds=!1,Os=null,ks=0,As=0,js=.55,Ms=[];function Ns(e,t){Ps(),t>0?(Es=setTimeout(e,t),Ds=!0):(Es=N(e),Ds=!1)}function Ps(){Es&&(Ds?clearTimeout(Es):vt(Es),Es=0)}async function Fs(){if(K=document.getElementById(`hand-overlay`),q=K?.getContext(`2d`),qs(),Os=ht(window,`resize`,qs),!globalThis.Hands)return P(`mediaPipeHands`,!1),C(`MediaPipe Hands did not load. Hand gestures are unavailable until the CDN script loads.`,`Hand Tracking`),!1;try{return bs=new globalThis.Hands({locateFile:e=>`https://cdn.jsdelivr.net/npm/@mediapipe/hands/${e}`}),bs.setOptions({maxNumHands:2,modelComplexity:1,minDetectionConfidence:.7,minTrackingConfidence:.65,selfieMode:!1}),bs.onResults(Rs),xs=!0,P(`mediaPipeHands`,!0),Ns(Is,0),w(`Hand tracking armed. Use palm, pinch, fist, point, and swipe gestures.`),!0}catch(e){return C(e.message,`Hand Tracking Failed`),!1}}async function Is(){if(!xs||!bs)return;let e=performance.now();try{let t=tc();t?(e>=ws&&(ws=e+ys,await bs.send({image:t}),Ts=!1),Ns(Is,0)):(!Ts&&D.trackingMode===`8thwall-slam`&&(Ts=!0,w(`Waiting for XR camera pixels before enabling hand tracking.`,`Hand Tracking`)),Ns(Is,200))}catch(e){Ts||(Ts=!0,w(`Hand tracking frame skipped: ${e.message}`,`Hand Tracking`)),Ns(Is,200)}}function Ls(){xs=!1,Ps(),Os?.(),Os=null;try{bs?.close?.()}catch{}bs=null,Ks(),Ss=null,J=0,Cs=0,ks=0,Ts=!1,ws=0,As=0,D.gestureFrameCanvas?.remove?.(),D.gestureFrameCanvas=null,D.gestureFrameReady=!1,D.handState.hands=[],D.handState.gestures=new Map}function Rs(e){Ks();let t=(e.multiHandLandmarks||[]).map((e,t)=>zs(e,t));D.handState.hands=t,t.forEach((e,t)=>Gs(e,t));let n=Bs(t);D.handState.gestures=n;for(let[e,t]of n)k(`gesture-${e}`,t)}function zs(e,t){if(!Ms[t])return Ms[t]=e.map(e=>({x:e.x,y:e.y,z:e.z||0})),Ms[t];let n=Ms[t];for(let t=0;t<e.length;t++){let r=js;n[t].x=n[t].x*(1-r)+e[t].x*r,n[t].y=n[t].y*(1-r)+e[t].y*r,n[t].z=(n[t].z||0)*(1-r)+(e[t].z||0)*r}return n}function Bs(e){let t=new Map;if(!e.length)return Ss=null,J=0,Cs=0,ks=0,t;let n=e[0],r=Ys(n[as],n[os]);r<.05&&t.set(`pinch`,{confidence:1-r/.05,hand:n}),Hs(n)&&t.set(`fist`,{confidence:.88,hand:n}),Us(n)&&t.set(`open-palm`,{confidence:.9,hand:n}),Ws(n)&&t.set(`point`,{confidence:.86,hand:n,point:n[os]});let i=Vs(n);if(i&&t.set(i,{confidence:.86,hand:n}),e.length>=2){let n=Xs(e[0],e[1]);if(Cs>0){let r=n-Cs;Math.abs(r)>.035&&t.set(`two-hand-scale`,{confidence:.9,delta:r,distance:n,hands:e})}Cs=n}else Cs=0;return t}function Vs(e){let t=performance.now();if(t<ks)return``;let n=e[is];if(!Ss)return Ss={x:n.x,y:n.y},``;let r=n.x-Ss.x;return Ss={x:n.x,y:n.y},r<-.03?--J:r>.03?J+=1:J*=.5,Math.abs(J)<.25&&(J=0),J=Math.max(-5,Math.min(5,J)),J<=-5?(J=0,ks=t+180,Ss=null,`swipe-left`):J>=5?(J=0,ks=t+180,Ss=null,`swipe-right`):``}function Hs(e){return[os,ss,cs,ls].every((t,n)=>{let r=[us,fs,ms,gs][n];return Js(e,t,r)>.58})}function Us(e){return[os,ss,cs,ls].every((t,n)=>{let r=[us,fs,ms,gs][n];return Js(e,t,r)<.32})}function Ws(e){return Js(e,os,us)<.34&&Js(e,ss,fs)>.52&&Js(e,cs,ms)>.52&&Js(e,ls,gs)>.52}function Gs(e){if(!q||!K)return;let t=Ys(e[as],e[os])<.05,n=K.width,r=K.height,i=Math.max(1,n/Math.max(1,innerWidth));q.lineCap=`round`,q.lineJoin=`round`,q.lineWidth=2.4*i,q.strokeStyle=t?`rgba(0,122,255,0.7)`:`rgba(255,255,255,0.5)`;for(let[t,i]of vs){let a=e[t],o=e[i];!a||!o||(q.beginPath(),q.moveTo(a.x*n,a.y*r),q.lineTo(o.x*n,o.y*r),q.stroke())}for(let a of e){let e=a.x*n,o=a.y*r,s=(t?9:6)*i,c=q.createRadialGradient(e,o,0,e,o,s);c.addColorStop(0,t?`rgba(0,122,255,0.95)`:`rgba(255,255,255,0.92)`),c.addColorStop(1,`rgba(255,255,255,0)`),q.fillStyle=c,q.beginPath(),q.arc(e,o,s,0,Math.PI*2),q.fill()}if(Us(e)){let t=(e[us].x+e[gs].x)/2*n,a=(e[us].y+e[gs].y)/2*r;q.strokeStyle=`rgba(255,255,255,0.55)`,q.lineWidth=3*i,q.beginPath(),q.arc(t,a,(40+Math.sin(performance.now()/180)*6)*i,0,Math.PI*2),q.stroke()}}function Ks(){!q||!K||(q.save(),q.setTransform(1,0,0,1,0,0),q.clearRect(0,0,K.width,K.height),q.restore())}function qs(){if(!K)return;let e=Math.min(devicePixelRatio||1,3);K.width=Math.floor(innerWidth*e),K.height=Math.floor(innerHeight*e),K.style.width=`100vw`,K.style.height=`100vh`,q?.setTransform(1,0,0,1,0,0)}function Js(e,t,n){let r=e[t],i=e[n],a=e[_s.get(n)];if(!r||!i||!a)return 0;let o=Qs(a,i),s=Qs(a,r),c=Math.max(ec(o),1e-4),l=Math.max(ec(s),1e-4),u=Math.max(-1,Math.min(1,$s(o,s)/(c*l)));return Math.max(0,Math.min(1,(Math.PI-Math.acos(u))/(Math.PI*.55)))}function Ys(e,t){let n=e.x-t.x,r=e.y-t.y,i=(e.z||0)-(t.z||0);return Math.hypot(n,r,i)}function Xs(e,t){let n=Ys(e[is],t[is]),r=Zs(e),i=Zs(t);return n*.72+Ys(r,i)*.28}function Zs(e){return{x:(e[is].x+e[us].x+e[gs].x)/3,y:(e[is].y+e[us].y+e[gs].y)/3,z:((e[is].z||0)+(e[us].z||0)+(e[gs].z||0))/3}}function Qs(e,t){return{x:t.x-e.x,y:t.y-e.y,z:(t.z||0)-(e.z||0)}}function $s(e,t){return e.x*t.x+e.y*t.y+e.z*t.z}function ec(e){return Math.hypot(e.x,e.y,e.z)}function tc(){if(D.cameraVideo?.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA)return D.cameraVideo;if(D.gestureFrameReady&&D.gestureFrameCanvas?.width&&D.gestureFrameCanvas?.height)return D.gestureFrameCanvas;let e=performance.now();return e-As>5e3&&(As=e),null}function nc(){return{name:`mediapipe-camera-frame-source`,onUpdate:({processCpuResult:e})=>{ic(rc(e))}}}function rc(e){return e?.cameraPixelArray||e?.cameraPixels||e?.camerapixelarray||e?.pixels||e?.reality?.cameraPixelArray||e?.reality?.cameraPixels||null}function ic(e){if(!e)return;let t=e.pixels||e.data||e.buffer||e,n=e.width||e.cols||e.columnCount||e.pixelWidth||e.imageWidth,r=e.height||e.rows||e.rowCount||e.pixelHeight||e.imageHeight;if(!t||!n||!r)return;let i=sc(t);if(!i.length)return;let a=ac(n,r).getContext(`2d`,{willReadFrequently:!0}),o=a.createImageData(n,r),s=oc(i.length,n,r),c=e.rowBytes||e.stride||n*s,l=0;for(let e=0;e<r;e+=1){let t=e*c;for(let e=0;e<n;e+=1){let n=t+e*s;if(s>=4)o.data[l]=i[n],o.data[l+1]=i[n+1],o.data[l+2]=i[n+2],o.data[l+3]=i[n+3]||255;else if(s===3)o.data[l]=i[n],o.data[l+1]=i[n+1],o.data[l+2]=i[n+2],o.data[l+3]=255;else{let e=i[n];o.data[l]=e,o.data[l+1]=e,o.data[l+2]=e,o.data[l+3]=255}l+=4}}a.putImageData(o,0,0),D.gestureFrameReady=!0}function ac(e,t){return D.gestureFrameCanvas||(D.gestureFrameCanvas=document.createElement(`canvas`),D.gestureFrameCanvas.id=`mediapipe-camera-frame`,D.gestureFrameCanvas.style.cssText=`display:none`,document.body.appendChild(D.gestureFrameCanvas)),(D.gestureFrameCanvas.width!==e||D.gestureFrameCanvas.height!==t)&&(D.gestureFrameCanvas.width=e,D.gestureFrameCanvas.height=t),D.gestureFrameCanvas}function oc(e,t,n){let r=Math.max(1,t*n);return e>=r*4?4:e>=r*3?3:1}function sc(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):(e instanceof ArrayBuffer,new Uint8Array(e))}var cc=`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position.xy, 0.0, 1.0);
}`,lc=`jarvis_vr_state_v2`,uc={default:{id:`default`,label:`Default`,eyeSep:.063,convergence:1.42,k1:-.22,k2:.08,chromaticAberration:.003,renderScale:.9,refreshRate:72,vignetteStrength:.12},quest:{id:`quest`,label:`Quest`,eyeSep:.064,convergence:1.38,k1:-.215,k2:.078,chromaticAberration:.0032,renderScale:.88,refreshRate:90,vignetteStrength:.1},visionos:{id:`visionos`,label:`VisionOS`,estimatedEyeSep:!0,eyeSep:.062,convergence:1.34,k1:-.205,k2:.074,chromaticAberration:.0024,renderScale:.92,refreshRate:90,vignetteStrength:.08},android:{id:`android`,label:`Android`,eyeSep:.063,convergence:1.44,k1:-.22,k2:.08,chromaticAberration:.003,renderScale:.82,refreshRate:72,vignetteStrength:.14},desktop:{id:`desktop`,label:`Desktop`,eyeSep:.065,convergence:1.5,k1:-.2,k2:.07,chromaticAberration:.0025,renderScale:.95,refreshRate:60,vignetteStrength:.18}},dc=`
uniform sampler2D tDiffuse;
uniform float k1;
uniform float k2;
uniform float rAber;
varying vec2 vUv;
vec2 barrelDistort(vec2 uv, vec2 center) {
vec2 d = uv - center;
float r2 = dot(d, d);
float distortFactor = 1.0 + k1 * r2 + k2 * r2 * r2;
return center + d * distortFactor;
}
void main() {
bool isLeftEye = vUv.x < 0.5;
vec2 eyeCenter = isLeftEye ? vec2(0.25, 0.5) : vec2(0.75, 0.5);
vec2 distorted = barrelDistort(vUv, eyeCenter);
vec2 localUV = isLeftEye
? vec2(distorted.x * 2.0, distorted.y)
: vec2((distorted.x - 0.5) * 2.0, distorted.y);
if (localUV.x < 0.0 || localUV.x > 1.0 || localUV.y < 0.0 || localUV.y > 1.0) {
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
return;
}
float dist = length(localUV - vec2(0.5, 0.5));
float aberration = rAber * dist * dist * 3.0;
vec2 redUV = barrelDistort(vUv + vec2(aberration, 0.0), eyeCenter);
vec2 greenUV = distorted;
vec2 blueUV = barrelDistort(vUv - vec2(aberration, 0.0), eyeCenter);
float r = texture2D(tDiffuse, redUV).r;
float g = texture2D(tDiffuse, greenUV).g;
float b = texture2D(tDiffuse, blueUV).b;
gl_FragColor = vec4(r, g, b, 1.0);
}`,Y=null,X=null,fc=null,pc=null,mc=null,hc=new r(2,2);function gc(e){fc||(fc=new ie,pc=new ge,mc=new x({uniforms:{tDiffuse:{value:null},k1:{value:e.k1??-.22},k2:{value:e.k2??.08},rAber:{value:e.chromaticAberration??.003}},vertexShader:cc,fragmentShader:dc,depthWrite:!1,depthTest:!1}),fc.add(new m(hc,mc)))}var _c=null,vc=null,yc=null,bc=!1,xc=null,Sc=null,Cc=null,wc=null,Tc=0,Ec=new c,Dc=!1,Oc=null,kc=null,Z=Uc(),Ac=0,jc=Z.ipd,Mc=Z.convergence,Nc=new i,Pc=new c,Fc=new c().setFromAxisAngle(new S(1,0,0),-Math.PI/2),Ic=new c,Lc=new S(0,0,1);function Rc(){O(`enter-vr`,()=>zc())}async function zc(){let{renderer:e,scene:t,camera:n}=L();if(!e||!t||!n)return C(`Renderer is not ready yet. Start AR first, then enter VR.`,`VR Mode`),!1;Z=Uc(),jc=Z.ipd,Mc=Z.convergence;let r=it(),i=Hc(Z.lensProfileId||r.browser);D.isVRMode=!0,Dc=!1,Ac=performance.now(),D.runtime.permissionState=D.runtime.permissionState||`unknown`,P(`passthroughBlendProxy`,!!rl()),P(`comfortAdaptation`,!0),P(`predictivePoseFiltering`,!0),P(`reprojectionProxy`,!0),P(`questBrowserQuirks`,r.questBrowserQuirks),P(`stereoEyeBuffers`,!0),P(`stereoFrustumCalibration`,!0),P(`refreshRateNegotiation`,!0),P(`timestampSync`,!0),P(`motionSicknessMitigation`,!0),P(`teleportLocomotion`,!0),P(`smoothLocomotionSafeguards`,!0),P(`roomBoundaryVisualization`,!0),P(`stereoUiAnchoring`,!0),P(`antiAliasEdgeProtection`,!0),P(`zFightGuard`,!0),P(`sustainedFramerateGuard`,!0),P(`orientationLockStability`,!0),P(`sensorPermissionPersistenceProxy`,!0),P(`motionComfortVignette`,!0),P(`renderScaleStability`,!0),P(`headsetCameraCalibrationProxy`,!0),P(`deviceCapabilityMatrix`,!0),P(`lowLightTrackingResilience`,r.limits.lowLightTrackingResilience!==!1),Yc(e,i),i.estimatedEyeSep&&w(`VisionOS IPD is estimated because the browser does not expose a reliable eye distance API. Use the IPD slider to fine-tune comfort.`,`VR Mode`),It({renderer:e,scene:t,camera:n},{mode:`vr-shell`,stereo:!0,source:rl(),passthroughBlend:`browser-camera`,framebufferScaleFactor:i.renderScale,refreshRate:i.refreshRate,convergence:i.convergence,renderScale:i.renderScale,lensProfile:i.id,motionComfort:Z.seatedMode?`seated`:`standing`,vignetteStrength:i.vignetteStrength}),Kc(i),Jc(i),await Zc(n),await Qc();try{await screen.orientation?.lock?.(`landscape`)}catch{w(`Landscape lock was not allowed by this browser. Rotate the phone manually for VR.`)}let a=rl();return a&&!vc?(vc=el(a),t.add(vc)):a||w(`VR passthrough is waiting for camera pixels. Stay in AR mode until the camera frame source is ready.`,`VR Mode`),tl(),!bc&&globalThis.XR8?.addCameraPipelineModule?(globalThis.XR8.addCameraPipelineModule({name:`vr-stereo-renderer`,onRender:()=>{D.isVRMode&&Xc()}}),D.pipelineOrder.push(`vr-stereo-renderer`),bc=!0):globalThis.XR8?.addCameraPipelineModule||il(),w(`VR screen active. ${i.label} stereo profile, IPD, refresh, and gyro are enabled.`,`VR Mode`),!0}function Bc(){D.isVRMode=!1,Dc=!1,Wc(),nl();try{screen.orientation?.unlock?.()}catch{}w(`Returned to AR mode.`,`VR Mode`)}function Vc(e,t,n){return Math.min(n,Math.max(t,Number(e)||t))}function Hc(e=``){let t=String(e||``).toLowerCase();return t.includes(`quest`)?uc.quest:t.includes(`vision`)?uc.visionos:t.includes(`android`)?uc.android:t.includes(`desktop`)?uc.desktop:uc.default}function Uc(){let e={ipd:.063,convergence:1.42,renderScale:.9,refreshRate:72,seatedMode:!0,floorCalibration:0,lensProfileId:`default`,vignette:.12};try{let t=er(lc,null);return!t||typeof t!=`object`?e:{...e,...t,ipd:Vc(t.ipd,.045,.075),convergence:Vc(t.convergence,.8,2.2),renderScale:Vc(t.renderScale,.72,1.25),refreshRate:Vc(t.refreshRate,60,120),floorCalibration:Vc(t.floorCalibration,-1.5,1.5),vignette:Vc(t.vignette,0,.4),seatedMode:t.seatedMode!==!1,lensProfileId:String(t.lensProfileId||`default`)}}catch{return e}}function Wc(){try{tr(lc,{ipd:parseFloat(nr(`jarvis_vr_ipd`,String(Z.ipd||.063))),convergence:parseFloat(nr(`jarvis_vr_convergence`,String(Z.convergence||1.42))),renderScale:Z.renderScale,refreshRate:Z.refreshRate,seatedMode:Z.seatedMode,floorCalibration:Z.floorCalibration,lensProfileId:Z.lensProfileId,vignette:Z.vignette,savedAt:new Date().toISOString()})}catch{}}function Gc(){return document.getElementById(`ui-layer`)||document.body}function Kc(e){Oc?.remove(),Oc=document.createElement(`div`),Oc.style.cssText=[`position:absolute`,`inset:0`,`z-index:25`,`pointer-events:none`,`background:radial-gradient(circle at center, rgba(0,0,0,0) 0%, rgba(0,0,0,0.14) 58%, rgba(0,0,0,0.32) 100%)`,`opacity:${Vc(e.vignetteStrength??.12,0,.5)}`,`transition:opacity 180ms linear`].join(`;`),Gc().appendChild(Oc)}function qc(e,t){if(!Oc)return;let n=Z.seatedMode?.06:.1,r=Math.min(.24,Math.max(0,(e-16.6)/120)),i=Vc((t.vignetteStrength??.12)+n+r,.06,.45);Oc.style.opacity=String(i)}function Jc(e){kc?.remove(),kc=document.createElement(`div`),kc.style.cssText=[`position:absolute`,`right:16px`,`top:18px`,`z-index:30`,`display:flex`,`flex-direction:column`,`gap:8px`,`padding:10px`,`border-radius:12px`,`background:rgba(3,12,20,0.72)`,`border:1px solid rgba(0,212,255,0.22)`,`backdrop-filter:blur(14px)`,`color:white`,`font:600 11px/1.2 Inter,sans-serif`,`pointer-events:auto`,`min-width:220px`].join(`;`);let t=(e,t)=>{let n=document.createElement(`label`);n.style.cssText=`display:flex;justify-content:space-between;align-items:center;gap:8px`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n},n=document.createElement(`input`);n.type=`range`,n.min=`0.045`,n.max=`0.075`,n.step=`0.001`,n.value=String(jc??e.eyeSep??.063),n.style.cssText=`width:112px`;let r=document.createElement(`input`);r.type=`range`,r.min=`0.8`,r.max=`2.2`,r.step=`0.01`,r.value=String(Mc??e.convergence??1.42),r.style.cssText=`width:112px`;let i=document.createElement(`input`);i.type=`range`,i.min=`0.72`,i.max=`1.25`,i.step=`0.01`,i.value=String(Z.renderScale??e.renderScale??.9),i.style.cssText=`width:112px`;let a=document.createElement(`select`);for(let t of[60,72,90,120]){let n=document.createElement(`option`);n.value=String(t),n.textContent=`${t}Hz`,Number(t)===Number(Z.refreshRate||e.refreshRate)&&(n.selected=!0),a.appendChild(n)}let o=document.createElement(`button`);o.className=`btn-secondary`,o.textContent=Z.seatedMode?`SEATED`:`STANDING`,o.onclick=()=>{Z.seatedMode=!Z.seatedMode,o.textContent=Z.seatedMode?`SEATED`:`STANDING`,D.compositor.motionComfort=Z.seatedMode?`seated`:`standing`,Wc()};let s=document.createElement(`button`);s.className=`btn-secondary`,s.textContent=`FLOOR -`,s.onclick=()=>{Z.floorCalibration=Vc(Z.floorCalibration-.05,-1.5,1.5),D.compositor.floorCalibration=Z.floorCalibration,Wc(),w(`Floor calibration ${Z.floorCalibration.toFixed(2)}m`,`VR Mode`)};let c=document.createElement(`button`);c.className=`btn-secondary`,c.textContent=`FLOOR +`,c.onclick=()=>{Z.floorCalibration=Vc(Z.floorCalibration+.05,-1.5,1.5),D.compositor.floorCalibration=Z.floorCalibration,Wc(),w(`Floor calibration ${Z.floorCalibration.toFixed(2)}m`,`VR Mode`)};let l=document.createElement(`span`);l.textContent=`${e.label} profile`,l.style.opacity=`0.82`,n.oninput=()=>{rr(`jarvis_vr_ipd`,n.value),Z.ipd=parseFloat(n.value),jc=Z.ipd,D.compositor.eyeSep=jc},r.oninput=()=>{rr(`jarvis_vr_convergence`,r.value),Z.convergence=parseFloat(r.value),Mc=Z.convergence,D.compositor.convergence=Mc},i.oninput=()=>{Z.renderScale=parseFloat(i.value),D.compositor.renderScale=Z.renderScale,Wc()},a.onchange=()=>{Z.refreshRate=parseFloat(a.value),D.compositor.refreshRate=Z.refreshRate,D.compositor.frameBudgetMs=1e3/Z.refreshRate,Wc()},kc.append(l,t(`IPD`,n),t(`Convergence`,r),t(`Scale`,i),t(`Refresh`,a));let u=document.createElement(`div`);u.style.cssText=`display:flex;gap:6px;justify-content:space-between`,u.append(o,s,c),kc.appendChild(u),Gc().appendChild(kc)}function Yc(e,t=Hc()){let n=new De;e.getDrawingBufferSize(n);let r=Vc(Z.renderScale??t.renderScale??1,.72,1.25),i=Math.max(2,Math.floor(n.x*r)),o=Math.max(2,Math.floor(n.y*r)),s=Math.max(2,Math.floor(i/2))/Math.max(1,o);Y=Y||new Ae,Y.eyeSep=jc||t.eyeSep||.063,Y.focus=Mc||t.convergence||1.4,(!X||X.width!==i||X.height!==o)&&(X?.dispose(),X=new we(i,o,{minFilter:a,magFilter:a})),gc(t),mc&&(mc.uniforms.k1.value=t.k1??-.22,mc.uniforms.k2.value=t.k2??.08,mc.uniforms.rAber.value=t.chromaticAberration??.003),D.compositor={...D.compositor,refreshRate:t.refreshRate,frameBudgetMs:1e3/t.refreshRate,renderScale:r,convergence:Y.focus,lensProfile:t.id,eyeAspect:s,vignetteStrength:t.vignetteStrength,motionComfort:Z.seatedMode?`seated`:`standing`,floorCalibration:Z.floorCalibration},!Cc&&e?.domElement&&(Cc=e=>{e.preventDefault?.(),w(`WebGL context was lost. VR will pause until the renderer restores.`,`VR Mode`),D.isVRMode=!1,Tc&&vt(Tc),Tc=0,Y=null,X=null,fc=null,pc=null,mc=null},wc=()=>{w(`WebGL context restored. Returning to VR mode.`,`VR Mode`),D.started&&(D.isVRMode=!0,Yc(e,t),il())},e.domElement.addEventListener(`webglcontextlost`,Cc,{passive:!1}),e.domElement.addEventListener(`webglcontextrestored`,wc))}function Xc(){let{renderer:e,scene:t,camera:n}=L();if(!e||!t||!n||!X||!Y)return;let r=new De;e.getDrawingBufferSize(r);let i=Hc(Z.lensProfileId),a=Vc(Z.renderScale??i.renderScale??1,.72,1.25),o=Math.max(2,Math.floor(r.x*a)),s=Math.max(2,Math.floor(r.y*a)),c=Math.max(2,Math.floor(o/2)),l=c/Math.max(1,s);(X.width!==o||X.height!==s)&&Yc(e,i);let u=n.aspect;n.aspect=l,n.updateProjectionMatrix(),Y.eyeSep=jc||i.eyeSep||.063,Y.focus=Mc||i.convergence||1.4,Y.update(n),e.setRenderTarget(X),e.setScissorTest(!0),e.clear(!0,!0,!0),yc?.userData?.liveCanvas&&(yc.needsUpdate=!0),e.setViewport(0,0,c,s),e.setScissor(0,0,c,s),e.render(t,Y.cameraL),e.clearDepth(),e.setViewport(c,0,c,s),e.setScissor(c,0,c,s),e.render(t,Y.cameraR),e.setScissorTest(!1),e.setRenderTarget(null),e.setViewport(0,0,r.x,r.y),mc.uniforms.tDiffuse.value=X.texture,e.render(fc,pc),n.aspect=u,n.updateProjectionMatrix();let d=performance.now(),f=Ac?d-Ac:16.6;Ac=d,Lt(f),qc(f,i)}async function Zc(e){it();try{if(typeof DeviceOrientationEvent<`u`&&typeof DeviceOrientationEvent.requestPermission==`function`){let e=await DeviceOrientationEvent.requestPermission();if(e!==`granted`)return rr(`jarvis_vr_motion_permission`,String(e||`denied`)),w(`Motion access denied or timed out. VR head tracking disabled.`),!1;rr(`jarvis_vr_motion_permission`,`granted`)}return xc&&window.removeEventListener(`deviceorientation`,xc),xc=t=>$c(t,e),window.addEventListener(`deviceorientation`,xc),!0}catch(e){return C(e.message,`Motion Permission Failed`),!1}}async function Qc(){try{if(document.fullscreenElement)return!0;if(!document.documentElement?.requestFullscreen)return!1;let e=document.documentElement.requestFullscreen({navigationUI:`hide`}).catch(()=>!1);return await Promise.race([e,new Promise(e=>setTimeout(()=>e(!1),it().isQuest?1e3:1500))]),Sc||(Sc=()=>{!document.fullscreenElement&&D.isVRMode&&w(`Fullscreen exited. VR view will remain in-browser.`,`VR Mode`)},document.addEventListener(`fullscreenchange`,Sc),document.addEventListener(`webkitfullscreenchange`,Sc)),P(`orientationLockStability`,!0),!0}catch{return w(`Fullscreen lock was not granted. VR continues in browser windowed mode.`,`VR Mode`),!1}}function $c(e,t){if(!D.isVRMode||!t)return;let r=n.degToRad(e.alpha||0),i=n.degToRad(e.beta||0),a=n.degToRad(e.gamma||0),o=Number(screen.orientation?.angle||window.orientation||0);Nc.set(i,r,-a,`YXZ`),Pc.setFromEuler(Nc),Pc.multiply(Fc),Ic.setFromAxisAngle(Lc,-n.degToRad(o)),Pc.multiply(Ic),Dc?Ec.slerp(Pc,.18):(Ec.copy(Pc),Dc=!0),t.quaternion.copy(Ec)}function el(e){let t=e.tagName===`VIDEO`,n=t?new ce(e):new he(e);n.minFilter=a,n.magFilter=a,n.userData.liveCanvas=!t,yc=n;let r=new v(500,60,40);return r.scale(-1,1,1),new m(r,new h({map:n}))}function tl(){_c?.remove(),_c=document.createElement(`button`),_c.textContent=`EXIT VR`,_c.className=`btn-primary`,_c.style.cssText=`position:absolute;top:20px;left:20px;z-index:30;background:var(--destructive);padding-top:calc(12px + env(safe-area-inset-top));pointer-events:auto`,_c.onclick=Bc(document.getElementById(`ui-layer`)||document.body).appendChild(_c);let e=document.createElement(`input`);e.type=`range`,e.min=`0.045`,e.max=`0.075`,e.step=`0.001`,e.value=String(jc||.063),e.style.cssText=`width:168px;pointer-events:auto`;let t=document.createElement(`label`);t.dataset.vrControl=`ipd`,t.style.cssText=`position:absolute;right:18px;bottom:20px;z-index:30;display:flex;flex-direction:column;gap:6px;color:white;font:600 12px/1.2 Inter,sans-serif;text-shadow:0 1px 4px #000;pointer-events:auto`;let n=document.createElement(`span`);n.textContent=`${Math.round(parseFloat(e.value)*1e3)} mm IPD`,e.oninput=()=>{rr(`jarvis_vr_ipd`,e.value),jc=parseFloat(e.value),n.textContent=`${Math.round(parseFloat(e.value)*1e3)} mm IPD`},t.append(n,e)(document.getElementById(`ui-layer`)||document.body).appendChild(t),_c.addEventListener(`click`,()=>t.remove(),{once:!0})}function nl(){try{let e=D.xrSession;if(e?.end){let t=e.end();t?.catch&&t.catch(()=>{})}}catch{}_c?.remove(),document.querySelector(`[data-vr-control="ipd"]`)?.remove(),kc?.remove(),Oc?.remove(),kc=null,Oc=null,xc&&(window.removeEventListener(`deviceorientation`,xc),xc=null),Sc&&(document.removeEventListener(`fullscreenchange`,Sc),document.removeEventListener(`webkitfullscreenchange`,Sc),Sc=null),Cc&&(L()?.renderer?.domElement?.removeEventListener?.(`webglcontextlost`,Cc),Cc=null),wc&&(L()?.renderer?.domElement?.removeEventListener?.(`webglcontextrestored`,wc),wc=null),Tc&&(vt(Tc),Tc=0),X&&(X.dispose(),X=null),yc?.dispose&&yc.dispose(),yc=null,vc?.geometry?.dispose?.(),vc?.material?.dispose?.(),vc?.remove?.(),vc=null,mc?.dispose?.(),mc=null,fc=null,pc=null,Y=null}function rl(){if(D.cameraVideo?.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA)return D.cameraVideo;if(D.gestureFrameReady&&D.gestureFrameCanvas?.width&&D.gestureFrameCanvas?.height)return D.gestureFrameCanvas;let e=document.getElementById(`camerafeed`);return e?.width&&e?.height?e:null}function il(){if(Tc)return;let e=()=>{if(!D.isVRMode){Tc=0;return}Xc(),Tc=N(e)};Tc=N(e)}var al=null,ol=null,sl=null,cl=null,ll=new Float32Array(1e3*3),ul=new xe;ul.setAttribute(`position`,new Te(ll,3)),ul.setDrawRange(0,0);var dl=1e3;function fl(){return{name:`world-points-collector`,onUpdate:({processCpuResult:e})=>{let t=e?.worldPoints||e?.reality?.worldPoints||e?.reality?.points||e?.slam?.worldPoints;t&&t.length>0&&(D.worldPoints=t,pl(t))}}}function pl(e){if(!(!e||e.length<10)){for(let t of e){let e=t.position||t;!Number.isFinite(e.x)||!Number.isFinite(e.y)||!Number.isFinite(e.z)||D.worldPointBuffer.push(new S(e.x,e.y,e.z))}D.worldPointBuffer.length>1e3&&D.worldPointBuffer.splice(0,D.worldPointBuffer.length-1e3),D.frameCount+=1,D.frameCount%20==0&&(ml(D.worldPointBuffer),hl(D.worldPointBuffer))}}function ml(e){if(!e.length)return;let{scene:t}=L(),n=Math.min(e.length,dl);for(let t=0;t<n;t+=1){let r=e[e.length-n+t];ll[t*3]=r.x,ll[t*3+1]=r.y,ll[t*3+2]=r.z}ul.attributes.position.needsUpdate=!0,ul.setDrawRange(0,n),al||(cl=new ne({color:51455,size:.018,transparent:!0,opacity:.55,depthWrite:!1}),al=new l(ul,cl),al.name=`jarvis-room-point-cloud`,al.scale.setScalar(1),t.add(al))}function hl(e){if(!e.length)return;let t=[...e].sort((e,t)=>e.y-t.y),n=[],i=[];for(let e=0;e<t.length;e++){let r=t[e];if(i.length===0)i.push(r);else{let e=i[i.length-1];r.y-e.y<=.04?i.push(r):(n.push(i),i=[r])}}i.length>0&&n.push(i);let a=Math.max(8,Math.floor(t.length*.08)),o=null;for(let e of n)if(e.length>=a){o=e;break}let s;if(o)s=o.reduce((e,t)=>e+t.y,0)/o.length;else{let e=Math.max(4,Math.floor(t.length*.15)),n=t.slice(0,e);s=n.reduce((e,t)=>e+t.y,0)/n.length}if(!Number.isFinite(s))return;D.floorY!==void 0&&Number.isFinite(D.floorY)?D.floorY=D.floorY*.88+s*.12:D.floorY=s;let c=D.floorY,{scene:l}=L();if(!ol){let e=new r(10,10,20,20);ol=new m(e,new h({color:51455,transparent:!0,opacity:.06,side:2,depthWrite:!1})),sl=new m(e,new h({color:51455,transparent:!0,opacity:.2,wireframe:!0,depthWrite:!1})),ol.name=`jarvis-detected-floor`,sl.name=`jarvis-detected-floor-wire`,ol.rotation.x=-Math.PI/2,sl.rotation.x=-Math.PI/2,l.add(ol,sl)}ol.position.y=c,sl.position.y=c,D.shadowReceiver&&(D.shadowReceiver.position.y=c+.002),T(`status-tracking`,D.trackingMode===`8thwall-slam`?`slam+floor`:`basic floor`),k(`world-anchor-sample`,{floorY:c,pointCount:e.length})}function gl(){D.worldPointBuffer.length<10&&_l(),ml(D.worldPointBuffer),hl(D.worldPointBuffer)}function _l(){let e=[],{camera:t}=L(),n=new f,r=Number.isFinite(D.floorY)?D.floorY:t&&t.position&&Number.isFinite(t.position.y)?t.position.y-1.45:-1.2;for(let i=0;i<9;i+=1)for(let a=0;a<20;a+=1){let o=.08+.84/19*a,s=.38+.46/8*i;n.setFromCamera(new De(o*2-1,-(s*2-1)),t);let c=(r-n.ray.origin.y)/n.ray.direction.y;Number.isFinite(c)&&c>.2&&c<8&&e.push(n.ray.origin.clone().add(n.ray.direction.clone().multiplyScalar(c)))}D.worldPointBuffer.push(...e),D.worldPointBuffer.length>1e3&&D.worldPointBuffer.splice(0,D.worldPointBuffer.length-1e3)}var vl={forest:[`Fox`,`Lantern`,`BarramundiFish`],lab:[`DamagedHelmet`,`AntiqueCamera`,`ReciprocatingSaw`],room:[`GlamVelvetSofa`,`WaterBottle`,`IridescenceLamp`],street:[`CesiumMilkTruck`,`ToyCar`,`Lantern`],default:[`Duck`,`Avocado`,`WaterBottle`]};function yl(){O(`scan-room`,()=>{gl(),w(`Room mesh scan updated from 8th Wall world points or basic fallback points.`,`Room Scan`)}),Sl()}async function bl(e=`room`){let t=String(e||`room`).toLowerCase(),n=vl[t]||vl.default;gl();let r=Math.min(3,Math.max(1,n.length));w(`Reconstructing ${t} scene with ${r} parallel model loads.`,`Scene Reconstruction`);try{await xl(t)}catch(e){C(e.message,`HDR Environment Failed`)}let i=(await Cl(n.map((e,t)=>async()=>{let r=t/n.length*Math.PI*2;return wl(Qa(e,new S(Math.sin(r)*.75,D.floorY+.04,-1.5-Math.cos(r)*.45),new c),12e3,`Timed out loading ${e}`)}),r)).filter(e=>e.status===`rejected`);i.length&&C(`${i.length} reconstruction model(s) fell back or failed.`,`Scene Reconstruction`),w(`Reconstructed ${t} scene with ${n.length} placed objects.`,`Scene Reconstruction`)}async function xl(e){let{scene:t,renderer:n}=L(),r=await Mn(e);return new Promise((e,i)=>{new _e().load(r,r=>{let a=new p(n),o=a.fromEquirectangular(r),s=t.userData.jarvisEnvironmentTarget,c=t.environment;if(!o?.texture){r.dispose(),a.dispose(),i(Error(`HDR environment generation failed.`));return}t.environment=o.texture,t.userData.jarvisEnvironmentTarget=o,c?.dispose?.(),s?.dispose?.(),r.dispose(),a.dispose(),e(t.environment)},void 0,i)})}function Sl(){let e=new WeakSet;new MutationObserver(()=>{document.querySelectorAll(`video`).forEach(t=>{e.has(t)||(e.add(t),t.addEventListener(`play`,()=>{w(`A playing video was detected. Say "JARVIS reconstruct this scene" to build an AR scene.`,`Scene Detection`)},{once:!0}))})}).observe(document.documentElement,{childList:!0,subtree:!0})}async function Cl(e,t){let n=[],r=new Set;for(let i of e){let e=i().then(e=>({status:`fulfilled`,value:e})).catch(e=>({status:`rejected`,reason:e}));n.push(e),r.add(e),e.finally(()=>r.delete(e)),r.size>=t&&await Promise.race(r)}return Promise.all(n)}function wl(e,t,n){let r=0,i=new Promise((e,i)=>{r=window.setTimeout(()=>i(Error(n)),t)});return Promise.race([e,i]).finally(()=>window.clearTimeout(r))}var Tl=.35,El=.65,Dl=.18,Ol=8,kl=4,Al=12,jl=60,Q={confidence:0,qualityTier:`initializing`,lostFrames:0,goodFrames:0,isLost:!1,worldOriginLocked:!1,worldOriginSamples:0,worldOriginPosition:new S,worldOriginQuaternion:new c,lastGoodPose:{position:new S,quaternion:new c,timestamp:0},smoothedPosition:new S,smoothedQuaternion:new c,anchorRegistry:new Map,planeRegistry:new Map,relocalizationAttempts:0,totalFrames:0};D.tracking=Q;function Ml(){return{name:`jarvis-tracking-quality`,onUpdate:({processCpuResult:e,processGpuResult:t})=>{Q.totalFrames++;let n=e?.reality||t?.reality||e||t,r=Nl(n),i=Pl(n);i&&(Q.confidence=Q.confidence*.85+r*.15,Q.qualityTier=Fl(Q.confidence),D.trackingQuality=Q.qualityTier,document.body.dataset.jarvisTrackingQuality=Q.qualityTier,Q.confidence<Tl?(Q.lostFrames++,Q.goodFrames=0,!Q.isLost&&Q.lostFrames>=Ol&&Vl()):(Q.goodFrames++,Q.lostFrames=0,Q.isLost&&Q.goodFrames>=kl&&Hl(i)),!Q.isLost&&(Rl(i),Q.worldOriginLocked||Bl(Q.smoothedPosition,Q.smoothedQuaternion),Gl(),Q.confidence>=El&&(Q.lastGoodPose.position.copy(Q.smoothedPosition),Q.lastGoodPose.quaternion.copy(Q.smoothedQuaternion),Q.lastGoodPose.timestamp=performance.now()),D.sessionAnchor.originPosition=Q.worldOriginPosition.toArray(),D.sessionAnchor.originQuaternion=Q.worldOriginQuaternion.toArray()))}}}function Nl(e){if(!e)return 0;let t=e.trackingStatus||e.slam?.trackingStatus;if(t){if(t===`NORMAL`)return .9;if(t===`LIMITED`)return .45;if(t===`INITIALIZING`)return .25}let n=e.confidence??e.slam?.confidence??e.poseConfidence;if(typeof n==`number`&&Number.isFinite(n))return Math.max(0,Math.min(1,n));let r=e.worldPoints||e.points;if(r&&Array.isArray(r)){let e=r.length;return e>80?.85:e>40?.65:e>15?.45:e>5?.25:.1}return .5}function Pl(e){if(!e)return null;let t=e.cameraPose||e.pose||e.slam?.cameraPose;if(!t)return null;let n=t.position||t,r=t.orientation||t.rotation;return Number.isFinite(n?.x)?{position:n,orientation:r}:null}function Fl(e){return e>=.8?`excellent`:e>=.6?`good`:e>=.38?`fair`:e>=.15?`poor`:`initializing`}var Il=new S,Ll=new c;function Rl(e){let{position:t,orientation:n}=e;Il.set(Math.fround(t.x??0),Math.fround(t.y??0),Math.fround(t.z??0)),n&&Ll.set(n.x??0,n.y??0,n.z??0,n.w??1);let r=Dl*(1+(1-Q.confidence)*1.5),i=Math.min(r,.45);Q.smoothedPosition.lerp(Il,i),Q.smoothedPosition.set(Math.fround(Q.smoothedPosition.x),Math.fround(Q.smoothedPosition.y),Math.fround(Q.smoothedPosition.z)),n&&(Q.smoothedQuaternion.slerp(Ll,i),Q.smoothedQuaternion.normalize())}var zl=[];function Bl(e,t){if(Q.confidence<El){zl=[],Q.worldOriginSamples=0;return}zl.push({pos:e.clone(),quat:t.clone()}),zl.length>Al&&zl.shift(),Q.worldOriginSamples=zl.length;let n=new S,r=new c;if(zl.forEach((e,t)=>{let i=1/(t+1);n.lerp(e.pos,i),r.slerp(e.quat,i)}),Q.worldOriginPosition.copy(n),Q.worldOriginQuaternion.copy(r),zl.length===Al){let e=0;zl.forEach(t=>{e+=t.pos.distanceToSquared(n)}),e/Al<.001&&(Q.worldOriginLocked=!0,D.sessionAnchor.restoredAt=Date.now(),k(`world-origin-locked`,{position:Q.worldOriginPosition.toArray(),quaternion:Q.worldOriginQuaternion.toArray()}),T(`status-tracking`,`${D.trackingMode} origin locked`))}}function Vl(){Q.isLost=!0,Q.worldOriginLocked=!1,Q.worldOriginSamples=0,zl=[],Q.relocalizationAttempts=0,document.body.dataset.jarvisTrackingState=`lost`,w(`Tracking lost — move camera slowly to reacquire environment.`,`Tracking`),T(`status-tracking`,`lost`),k(`tracking-lost`,{lastGoodPose:{position:Q.lastGoodPose.position.toArray(),age:performance.now()-Q.lastGoodPose.timestamp}}),Q.anchorRegistry.forEach(e=>{e.object&&(e.object.userData.trackingFrozen=!0)})}function Hl(e){Q.isLost=!1,Q.lostFrames=0,Q.relocalizationAttempts++,document.body.dataset.jarvisTrackingState=`recovered`,T(`status-tracking`,D.trackingMode),k(`tracking-recovered`,{attempt:Q.relocalizationAttempts,confidence:Q.confidence}),Q.anchorRegistry.forEach(e=>{e.object&&(e.object.userData.trackingFrozen=!1)}),w(`Tracking recovered.`,`Tracking`)}function Ul(e,t,n){let r={id:e,object:t,targetPosition:n.clone(),history:[],confidence:Q.confidence,createdAt:performance.now()};return Q.anchorRegistry.set(e,r),k(`anchor-registered`,{id:e,position:n.toArray()}),r}function Wl(e){Q.anchorRegistry.delete(e),k(`anchor-removed`,{id:e})}function Gl(){Q.anchorRegistry.forEach(e=>{if(!e.object||e.object.userData.trackingFrozen)return;let t=e.object,n=e.targetPosition,r=new S;t.getWorldPosition(r),r.set(Math.fround(r.x),Math.fround(r.y),Math.fround(r.z)),n.set(Math.fround(n.x),Math.fround(n.y),Math.fround(n.z));let i=r.distanceTo(n);if(e.history.push({drift:i,t:performance.now()}),e.history.length>jl&&e.history.shift(),i>.001){let r=Math.max(.015,Math.min(.35,i*1.5));t.position.lerp(n,r),e.confidence=Q.confidence}})}function Kl(e){if(!e||e.length<20)return;let t=e.map(e=>{let t=e.position||e;return new S(t.x,t.y,t.z)}).filter(e=>Number.isFinite(e.x+e.y+e.z));if(t.length<20)return;let n=Math.min(...t.map(e=>e.y)),r=Math.max(...t.map(e=>e.y))-n;if(r<.1)return;let i=Array.from({length:10},()=>[]);t.forEach(e=>{i[Math.min(9,Math.floor((e.y-n)/r*10))].push(e)});let a=[];return i.forEach((e,t)=>{if(e.length<8)return;let i=n+t/10*r+r/10/2,o=e.reduce((e,t)=>e.add(t),new S).divideScalar(e.length),s=i<n+r*.25,c=i>n+r*.75,l=s?`floor`:c?`ceiling`:`surface`;a.push({yCenter:i,centroid:o,pointCount:e.length,type:l,confidence:Math.min(1,e.length/30)})}),a.forEach((e,t)=>{let n=`plane-${t}-${e.type}`;Q.planeRegistry.set(n,e)}),D.detectedPlanes=a,a.length>0&&k(`planes-updated`,{planes:a,count:a.length}),a}function ql(e,t){if(Q.confidence<Tl)return null;let{renderer:n}=L()||{};if(n?.xr?.enabled&&D.xrHitTestSource){let e=n.xr.getFrame();if(e){let t=n.xr.getReferenceSpace(),r=e.getHitTestResults(D.xrHitTestSource);if(r.length>0){let e=r[0].getPose(t);if(e){let t=new ve().fromArray(e.transform.matrix);return{point:new S().setFromMatrixPosition(t),normal:new S(0,1,0).applyMatrix4(t).normalize(),confidence:Q.confidence,type:`webxr-hit-test`}}}}}if(globalThis.XR8?.XrController){let t=globalThis.XR8.XrController.hitTest(e.x,e.y,[`FEATURE_POINT`,`ESTIMATED_SURFACE`,`DETECTED_SURFACE`]);if(t&&t.length>0){let e=t[0];return{point:new S(e.position.x,e.position.y,e.position.z),normal:new S(0,1,0),confidence:Q.confidence*(e.type===`DETECTED_SURFACE`?.9:.5),type:e.type}}}let r=new f;if(r.setFromCamera(new De(e.x*2-1,-(e.y*2-1)),t),Number.isFinite(D.floorY)){let e=new S(0,1,0),t=new Ie(e,-D.floorY),n=new S;if(r.ray.intersectPlane(t,n)){let t=n.distanceTo(r.ray.origin);if(t>.2&&t<10)return{point:n,normal:e,confidence:Q.confidence,type:`floor`,distance:t}}}let i=D.detectedPlanes||[];for(let e of i){if(e.type===`floor`)continue;let t=new S(0,1,0),n=new Ie(t,-e.yCenter),i=new S;if(r.ray.intersectPlane(n,i)){let n=i.distanceTo(r.ray.origin);if(n>.2&&n<10)return{point:i,normal:t,confidence:Q.confidence*e.confidence,type:e.type,distance:n}}}return null}function Jl(){return{confidence:Q.confidence,tier:Q.qualityTier,isLost:Q.isLost,worldOriginLocked:Q.worldOriginLocked,anchorCount:Q.anchorRegistry.size,planeCount:Q.planeRegistry.size,relocalizationAttempts:Q.relocalizationAttempts,totalFrames:Q.totalFrames}}function Yl(){Q.worldOriginLocked=!1,Q.worldOriginSamples=0,zl=[],Q.isLost=!1,Q.lostFrames=0,Q.goodFrames=0,w(`Relocalization requested — scanning environment.`,`Tracking`),k(`relocalization-requested`,{attempt:++Q.relocalizationAttempts})}function Xl(){Q.confidence=0,Q.qualityTier=`initializing`,Q.lostFrames=0,Q.goodFrames=0,Q.isLost=!1,Q.worldOriginLocked=!1,Q.worldOriginSamples=0,zl=[],Q.anchorRegistry.clear(),Q.planeRegistry.clear(),Q.relocalizationAttempts=0,Q.totalFrames=0,D.detectedPlanes=[],document.body.dataset.jarvisTrackingQuality=`initializing`,document.body.dataset.jarvisTrackingState=`init`}O(`world-anchor-sample`,({floorY:e,pointCount:t})=>{D.worldPointBuffer?.length>20&&Kl(D.worldPointBuffer)}),O(`runtime-phase`,({phase:e})=>{(e===`created`||e===`booting`)&&Xl()});var Zl=null,Ql=0;function $l(){return Zl||(Zl=ln(eu(`eternum`),`Eternum AR`,880,560),tu(Zl,[[`NEXT`,`Enter`],[`AUTO`,`a`],[`SAVE`,`s`],[`MENU`,`Escape`]]),w(`Eternum opened as a floating AR panel. Normal game launch is unchanged outside AR.`,`Eternum AR`),Zl)}function eu(e){let t=new URLSearchParams(location.search);return String(t.get(`${e}Url`)||t.get(`game${e[0].toUpperCase()}${e.slice(1)}Url`)||``).trim()||String(globalThis.FridayARConfig?.gameUrls?.[e]||``).trim()||`/api/ar_task?mode=game_launch&task=${encodeURIComponent(`open ${e} web mirror`)}`}function tu(e,t){let n=document.createElement(`div`);n.style.cssText=`position:absolute;left:10px;right:10px;bottom:10px;display:flex;gap:8px;justify-content:center;pointer-events:auto`,t.forEach(([t,r])=>{let i=document.createElement(`button`);i.textContent=t,i.style.cssText=`min-height:44px;min-width:70px;border:1px solid rgba(255,255,255,.25);border-radius:999px;background:rgba(0,0,0,.48);color:white;font-weight:700`,i.onclick=()=>nu(e.iframe,r),n.appendChild(i)}),e.container.style.position=`relative`,e.container.appendChild(n)}async function nu(e,t,n=!1,r=!1){let i=e?.contentWindow;if(!i)return C(`The game iframe is not ready yet.`,`Game Input Failed`),!1;try{let e={key:t,bubbles:!0,cancelable:!0,ctrlKey:n};return i.document.dispatchEvent(new KeyboardEvent(`keydown`,e)),r||window.setTimeout(()=>i.document.dispatchEvent(new KeyboardEvent(`keyup`,e)),50),!0}catch(e){let a=`key-${Date.now().toString(36)}-${++Ql}`;return await new Promise(o=>{let s=window.setTimeout(()=>{window.removeEventListener(`message`,c),C(`The game iframe did not acknowledge the key relay before the timeout elapsed.`,`Game Input Timeout`),o(!1)},250),c=e=>{e.source===i&&(e.data?.type!==`keydown-ack`||e.data?.id!==a||(window.clearTimeout(s),window.removeEventListener(`message`,c),o(!0)))};window.addEventListener(`message`,c);try{i.postMessage({type:`keydown`,id:a,key:t,ctrl:n,hold:r},`*`)}catch(t){window.clearTimeout(s),window.removeEventListener(`message`,c),C(t.message||e.message,`Game Input Failed`),o(!1)}})}}var ru=null;function iu(){if(ru)return ru;let e=new URLSearchParams(location.search);ru=ln(String(e.get(`ripplesUrl`)||globalThis.FridayARConfig?.gameUrls?.ripples||``).trim()||`/api/ar_task?mode=game_launch&task=open%20ripples%20web%20mirror`,`Ripples AR`,880,560);let t=document.createElement(`div`);return t.style.cssText=`position:absolute;left:10px;right:10px;bottom:10px;display:flex;gap:8px;justify-content:center;pointer-events:auto`,[[`NEXT`,`Enter`],[`AUTO`,`a`],[`SAVE`,`s`],[`MENU`,`Escape`]].forEach(([e,n])=>{let r=document.createElement(`button`);r.textContent=e,r.style.cssText=`min-height:44px;min-width:70px;border:1px solid rgba(255,255,255,.25);border-radius:999px;background:rgba(0,0,0,.48);color:white;font-weight:700`,r.onclick=()=>nu(ru.iframe,n),t.appendChild(r)}),ru.container.style.position=`relative`,ru.container.appendChild(t),w(`Ripples opened as a floating AR panel.`,`Ripples AR`),ru}async function au(e,t){let n=await ou(e,t),r=ln(cu(n.url||e),`${n.title||e} AR`,880,560);return fu(n.controls,r),r}async function ou(e,t){if(t?.query)try{let n=await t.query(`Game "${e}" genre + controls as JSON only: {"title":"","url":"","genre":"","controls":[{"action":"","key":"","label":""}]}`),r=String(n).replace(/```json|```/g,``).trim(),i=JSON.parse(uu(r));if(su(i))return i}catch(e){C(e.message,`Game Schema AI Failed`)}return{title:e,url:cu(e),genre:`generic`,controls:[{action:`accept`,key:`Enter`,label:`NEXT`},{action:`back`,key:`Escape`,label:`BACK`},{action:`left`,key:`ArrowLeft`,label:`LEFT`},{action:`right`,key:`ArrowRight`,label:`RIGHT`}]}}function su(e){return!e||typeof e!=`object`||typeof e.title!=`string`||typeof e.url!=`string`||typeof e.genre!=`string`||!Array.isArray(e.controls)?!1:e.controls.every(e=>e&&typeof e==`object`&&typeof e.key==`string`&&typeof e.label==`string`&&e.key.trim()&&e.label.trim())}function cu(e){let t=String(e||``).trim();if(!t)return lu(`AR Game`);if(/^(https?:|blob:|data:|about:)/i.test(t)||t.startsWith(`/`))return t;let n=t.toLowerCase();if(n.includes(`eternum`)){let e=new URLSearchParams(location.search).get(`eternumUrl`);return String(e||globalThis.FridayARConfig?.gameUrls?.eternum||``).trim()||`/api/ar_task?mode=game_launch&task=open%20eternum%20web%20mirror`}if(n.includes(`ripples`)){let e=new URLSearchParams(location.search).get(`ripplesUrl`);return String(e||globalThis.FridayARConfig?.gameUrls?.ripples||``).trim()||`/api/ar_task?mode=game_launch&task=open%20ripples%20web%20mirror`}return lu(t)}function lu(e){let t=`<!doctype html>
<html>
<meta name="viewport" content="width=device-width,initial-scale=1">
<body style="margin:0;background:#05070a;color:white;font:16px system-ui;display:grid;place-items:center;height:100vh;text-align:center">
<main>
<h1 style="font-size:22px;margin:0 0 10px">${du(e)}</h1>
<p style="opacity:.72;max-width:32rem">No direct web URL was configured for this game yet. Pass a URL in the launch query string or runtime config, or open a supported mirror command, then convert again.</p>
</main>
</body>
</html>`;return`data:text/html;charset=utf-8,${encodeURIComponent(t)}`}function uu(e){let t=e.indexOf(`{`),n=e.lastIndexOf(`}`);return t>=0&&n>t?e.slice(t,n+1):e}function du(e){return String(e).replace(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`})[e])}function fu(e,t){let n=document.createElement(`div`);return n.style.cssText=`position:absolute;left:10px;right:10px;bottom:10px;display:flex;gap:8px;justify-content:center;flex-wrap:wrap;pointer-events:auto`,e.forEach(e=>{let r=document.createElement(`button`);r.textContent=e.label||e.action,r.style.cssText=`min-height:44px;min-width:64px;border:1px solid var(--separator);border-radius:999px;background:var(--bg-dark);color:var(--text-primary);font-weight:700`,r.onclick=()=>nu(t.iframe,e.key||`Enter`),n.appendChild(r)}),t.container.style.position=`relative`,t.container.appendChild(n),n}var pu=`jarvis_ar_game_builder_graphs_v1`,mu=[`OnCollide`,`OnTap`,`OnGesture`,`OnTimerEnd`,`IsTag`,`IsHealth`,`IsDistance`,`Destroy`,`Spawn`,`MoveToward`,`SetScore`,`PlaySound`,`ShowMessage`,`EndGame`],hu=null,gu=null;function _u(){if(hu)return hu.restore(),hu;let e=document.createElement(`div`);e.append(vu()),hu=new an({title:`AR Game Builder`,body:e,icon:`B`,width:400,height:600});let t=hu.destroy.bind(hu);return hu.destroy=()=>{gu?.dispose?.(),gu=null,t(),hu=null},hu.focus(),hu}function vu(){let e=document.createElement(`div`),t=document.createElement(`div`),n=document.createElement(`div`);return t.className=`panel-row`,Object.entries({Entities:yu,Logic:bu,Settings:xu,Play:Su}).forEach(([e,r],i)=>{let a=document.createElement(`button`);a.className=`panel-action`,a.textContent=e,a.onclick=()=>{t.querySelectorAll(`button`).forEach(e=>e.classList.toggle(`selected`,e===a)),n.replaceChildren(r())},t.appendChild(a),i===0&&window.setTimeout(()=>a.click(),0)}),e.append(t,n),e}function yu(){let e=document.createElement(`div`),t=document.createElement(`input`),n=document.createElement(`input`),r=document.createElement(`button`);return t.placeholder=`Entity name`,n.placeholder=`Tag, e.g. target`,r.className=`panel-action`,r.textContent=`Add Entity`,r.onclick=()=>{let e=er(pu,[]).at(-1)||Ou();e.entities.push({id:or(`entity`),name:t.value||`Entity`,tag:n.value||`default`}),ku(e),w(`Entity saved to AR game graph.`)},e.append(t,n,r,Au()),e}function bu(){let e=document.createElement(`div`),t=document.createElement(`select`),n=document.createElement(`input`),r=document.createElement(`button`);return sr(t,mu),n.placeholder=`Node value`,r.className=`panel-action`,r.textContent=`Add Logic Node`,r.onclick=()=>{let e=er(pu,[]).at(-1)||Ou();e.nodes.push({id:or(`node`),type:t.value,value:n.value}),ku(e),w(`${t.value} node added.`)},e.append(t,n,r,Au()),e}function xu(){let e=document.createElement(`div`),t=document.createElement(`input`),n=document.createElement(`input`),r=document.createElement(`button`);return t.placeholder=`Game title`,n.type=`number`,n.placeholder=`Timer seconds`,r.className=`panel-action`,r.textContent=`Save Settings`,r.onclick=()=>{let e=er(pu,[]).at(-1)||Ou();e.title=t.value||e.title,e.duration=Number(n.value||e.duration||60),ku(e),w(`Game settings saved.`)},e.append(t,n,r,Au()),e}function Su(){let e=document.createElement(`div`),t=document.createElement(`button`);return t.className=`btn-primary`,t.textContent=`Spawn Saved Game`,t.onclick=()=>{let e=er(pu,[]).at(-1);if(!e){w(`Create a game graph first.`);return}gu?.dispose?.(),gu=Cu(e),w(`Game "${e.title}" spawned ${gu.entities.length} AR entity object(s).`,`Game Builder`)},e.append(t,Au()),e}function Cu(e){let{scene:t,camera:n}=L(),r=new Ne;r.name=`jarvis-game-${e.id}`,r.userData.isARGame=!0,r.position.set(0,D.floorY+.08,-1.6),t.add(r);let i=(e.entities.length?e.entities:[{id:or(`entity`),name:`Target`,tag:`target`}]).map((t,n)=>wu(t,n,e.entities.length||1));i.forEach(e=>r.add(e.mesh));let a=0,o=!1,s=performance.now(),c=[],l=[],u=new f,d=t=>{if(o)return;let n=String(t.type||``).toLowerCase(),s=String(t.value||``).trim();if(n===`spawn`){let e=wu({id:or(`entity`),name:s||`Spawned`,tag:`spawned`},i.length,i.length+1);i.push(e),r.add(e.mesh)}else if(n===`destroy`){let e=Tu(s,i);e&&(e.mesh.parent?.remove(e.mesh),e.destroyed=!0)}else if(n===`setscore`)a=Number(s||a+1),r.userData.score=a;else if(n===`showmessage`)w(s||e.title||`AR game event`,`Game Builder`);else if(n===`playsound`)Du();else if(n===`endgame`)o=!0,w(`${e.title||`AR Game`} ended. Score: ${a}`,`Game Builder`);else if(n===`movetoward`){let e=Tu(s,i)||i[0];e&&e.mesh.position.lerp(new S(0,.12,-.35),.35)}},p=t=>{if(o||t.target.closest?.(`.ar-panel, .hud-toolbar, button, input, select, textarea, iframe`))return;u.setFromCamera(new De(t.clientX/innerWidth*2-1,-(t.clientY/innerHeight)*2+1),n);let s=u.intersectObjects(i.filter(e=>!e.destroyed).map(e=>e.mesh),!0)[0];if(!s)return;let c=Eu(s.object,i);a+=1,r.userData.score=a,c.mesh.scale.multiplyScalar(.92),e.nodes.filter(e=>e.type===`OnTap`||e.type===`SetScore`||e.type===`ShowMessage`).forEach(d)};document.addEventListener(`pointerup`,p,!0),l.push(()=>document.removeEventListener(`pointerup`,p,!0));let m=O(`gesture-pinch`,()=>{e.nodes.filter(e=>e.type===`OnGesture`||e.type===`SetScore`).forEach(d)});l.push(m),Number(e.duration)>0&&c.push(window.setTimeout(()=>{e.nodes.filter(e=>e.type===`OnTimerEnd`||e.type===`EndGame`).forEach(d),o||(o=!0,w(`${e.title||`AR Game`} timer finished. Score: ${a}`,`Game Builder`))},Number(e.duration)*1e3));let h=()=>{if(!r.parent||o)return;let e=(performance.now()-s)/1e3;i.forEach((t,n)=>{t.destroyed||(t.mesh.rotation.y+=.01+n*.001,t.mesh.position.y=.08+Math.sin(e*1.6+n)*.035)}),r.userData.frame=N(h)};return h(),{root:r,entities:i,dispose(){o=!0,vt(r.userData.frame),c.forEach(e=>window.clearTimeout(e)),l.forEach(e=>e()),r.traverse(e=>{e.geometry?.dispose?.(),e.material?.dispose?.()}),r.parent?.remove(r)}}}function wu(e,t,n){let r=new o(.12,1),i=t/Math.max(n,1)*.78+.05,a=new m(r,new _({color:new Fe().setHSL(i,.72,.55),emissive:new Fe().setHSL(i,.72,.12),roughness:.25,metalness:.18})),s=t/Math.max(n,1)*Math.PI*2;return a.position.set(Math.sin(s)*.55,.08,-Math.cos(s)*.35),a.userData.entityId=e.id,a.userData.entityName=e.name,a.userData.tag=e.tag,a.castShadow=!0,a.receiveShadow=!0,{...e,mesh:a,destroyed:!1}}function Tu(e,t){let n=String(e||``).toLowerCase();return t.find(e=>String(e.name||``).toLowerCase().includes(n)||String(e.tag||``).toLowerCase().includes(n)||String(e.id||``).toLowerCase()===n)}function Eu(e,t){let n=e;for(;n;){let e=n.userData?.entityId;if(e)return t.find(t=>t.id===e);n=n.parent}return null}function Du(){try{let e=new AudioContext,t=e.createOscillator(),n=e.createGain();t.frequency.value=660,n.gain.value=.035,t.connect(n),n.connect(e.destination),t.start(),window.setTimeout(()=>{t.stop(),e.close()},140)}catch{}}function Ou(){return{id:or(`game`),title:`Untitled AR Game`,duration:60,entities:[],nodes:[],createdAt:Date.now()}}function ku(e){let t=er(pu,[]).filter(t=>t.id!==e.id);t.push(e),tr(pu,t.slice(-20))}function Au(){let e=document.createElement(`pre`),t=er(pu,[]).at(-1)||Ou();return e.style.cssText=`white-space:pre-wrap;font:12px/1.4 monospace;color:rgba(255,255,255,.72);background:rgba(0,0,0,.25);padding:10px;border-radius:12px;max-height:160px;overflow:auto`,e.textContent=JSON.stringify(t,null,2),e}async function ju(e,t={},n=0,r=1e4){let i=null;for(let a=0;a<=n;a+=1){let o=new AbortController,s=window.setTimeout(()=>o.abort(new DOMException(`Request timed out`,`AbortError`)),r);try{let n=await fetch(e,{...t,signal:o.signal});return window.clearTimeout(s),n}catch(e){if(window.clearTimeout(s),i=e,a>=n)throw e}}throw i||Error(`Request failed.`)}async function Mu(e,t={},n=0,r=1e4){let i=await ju(e,t,n,r);if(!(i.headers.get(`content-type`)||``).includes(`application/json`)){let t=await i.text();throw Error(t||`Expected JSON response from ${e}`)}return i.json()}function Nu(e,t){if(!Array.isArray(e))return!1;let n=JSON.stringify(t);return e.some(e=>JSON.stringify(e)===n)?!1:(e.push(t),!0)}var Pu=class{constructor(e){this.config=e,this.ws=null,this.connected=!1,this.reconnectTimer=0,this.pendingPatches=[],this.reconnectDelay=2e3,this.maxReconnectDelay=3e4,this.heartbeatTimer=0}connect(){return this.connectWebSocket(),this.loadConfig(),D.jarvis=this,this}async loadConfig(){try{let e=await Mu(`${this.apiBase()}/api/ar_config`,{headers:this.headers()},1,9e3);if(e.ok===!1)throw Error(e.error||`AR config failed.`);return k(`jarvis-config`,e),T(`status-omega`,`linked`),e}catch{return T(`status-omega`,`offline`),null}}connectWebSocket(){let e=this.config.wsBase||(location.protocol===`https:`?`wss://${location.host}/scene-ws`:`ws://${location.hostname}:5050`),t=qn(`omega_session`);t&&!/[?&]token=/.test(e)&&(e+=`${e.includes(`?`)?`&`:`?`}token=${encodeURIComponent(t)}`);try{this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=0),this._clearHeartbeat(),this.ws=new WebSocket(e),this.ws.onopen=()=>{this.connected=!0,clearTimeout(this.reconnectTimer),this.reconnectDelay=2e3,T(`status-omega`,`linked`),this.ws.send(JSON.stringify({type:`hello`,device_name:this.config.deviceName,source:`browser-8thwall-real-ar`})),this.flushPendingPatches(),this._startHeartbeat()},this.ws.onmessage=e=>this.onMessage(e),this.ws.onerror=()=>{this.connected&&T(`status-omega`,`ws error`)},this.ws.onclose=()=>{this.connected=!1,this._clearHeartbeat(),T(`status-omega`,`offline`),this.reconnectTimer&&clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*2,this.maxReconnectDelay),this.reconnectTimer=setTimeout(()=>this.connectWebSocket(),e)}}catch(e){C(e.message,`OMEGA WebSocket Failed`)}}_startHeartbeat(){this._clearHeartbeat(),this.heartbeatTimer=setInterval(()=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this._clearHeartbeat();return}try{this.ws.send(JSON.stringify({type:`ping`,ts:Date.now()}))}catch{this.ws.close()}},15e3)}_clearHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=0)}onMessage(e){try{let t=JSON.parse(e.data);k(`omega-message`,t),t.state&&k(`omega-scene-state`,t.state)}catch{}}async query(e){let t=await ju(`${this.apiBase()}/api/ar_task`,{method:`POST`,headers:{"Content-Type":`application/json`,...this.headers()},body:JSON.stringify({task:e,mode:`jarvis`,device_name:this.config.deviceName})},0,9e3),n=await t.json();if(!t.ok||n.ok===!1)throw Error(n.error||`JARVIS query failed.`);return n.response||n.message||n.result||JSON.stringify(n)}async runTask(e,t=`task`){let n=await ju(`${this.apiBase()}/api/ar_task`,{method:`POST`,headers:{"Content-Type":`application/json`,...this.headers()},body:JSON.stringify({task:e,mode:t,device_name:this.config.deviceName})},0,9e3),r=await n.json();if(!n.ok||r.ok===!1)throw Error(r.error||`Task endpoint failed.`);return k(`jarvis-task-result`,r),r}patchScene(e){let t={...e,device_name:this.config.deviceName,source:`browser-8thwall-real-ar`};return this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify({type:`patch`,patch:t,ts:Date.now()})),Promise.resolve(!0)):(Nu(this.pendingPatches,t),ju(`${this.apiBase()}/api/ar_scene_patch`,{method:`POST`,headers:{"Content-Type":`application/json`,...this.headers()},body:JSON.stringify(t)},1,9e3).catch(()=>null))}headers(){let e={"X-FRIDAY-Device":this.config.deviceName},t=qn(`omega_session`);return t&&(e.Authorization=`Bearer ${t}`),e}apiBase(){return String(this.config.omegaBase||``).replace(/\/+$/,``)||``}flushPendingPatches(){!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.pendingPatches.length||this.pendingPatches.splice(0).forEach(e=>{try{this.ws.send(JSON.stringify({type:`patch`,patch:{...e,device_name:this.config.deviceName,source:`browser-8thwall-real-ar`},ts:Date.now()}))}catch{}})}},Fu=0;function Iu(e,{speak:t=!0}={}){let n=document.getElementById(`jarvis-bubble`),r=document.getElementById(`jarvis-bubble-text`);!n||!r||(n.classList.remove(`hidden`),clearTimeout(Fu),Ru(r,String(e||`Ready.`),()=>{clearTimeout(Fu),Fu=window.setTimeout(()=>n.classList.add(`hidden`),6e3)}),t&&Lu(e))}function Lu(e){try{if(!(`speechSynthesis`in window))return;window.speechSynthesis.cancel();let t=new SpeechSynthesisUtterance(String(e||``));t.rate=.92,t.pitch=.82,t.volume=.88;let n=window.speechSynthesis.getVoices();t.voice=n.find(e=>String(e.lang||``).toLowerCase()===`en-gb`)||n.find(e=>/Daniel|George|Arthur|Google UK English Male|English.*United Kingdom|UK/i.test(`${e.name} ${e.lang}`))||n.find(e=>String(e.lang||``).toLowerCase().startsWith(`en-gb`))||n.find(e=>/en/i.test(e.lang))||null,window.speechSynthesis.speak(t)}catch{}}function Ru(e,t,n){e.textContent=``;let r=0,i=()=>{e.textContent=t.slice(0,r),r+=1,r<=t.length?window.setTimeout(i,14):n?.()};i()}var zu=null,Bu=0,Vu=0,Hu=!1,Uu=!1,Wu=!1,Gu=null,Ku=`unknown`,qu=0,Ju=``;function Yu(){let e=window.SpeechRecognition||window.webkitSpeechRecognition;return e?(zu=new e,zu.continuous=!0,zu.interimResults=!1,zu.lang=navigator.language||`en-US`,zu.onresult=Zu,zu.onerror=e=>{if(e.error===`not-allowed`||e.error===`service-not-allowed`||e.error===`audio-capture`){Hu=!1,Ku=`blocked`,clearTimeout(Vu),C(e.error||`Speech recognition blocked.`,`JARVIS Voice`),$u(`blocked`,{error:e.error||`blocked`});return}e.error!==`no-speech`&&C(e.error||`Speech recognition failed.`,`JARVIS Voice`),$u(`error`,{error:e.error||`unknown`})},zu.onend=()=>{Hu&&(clearTimeout(Vu),Vu=setTimeout(()=>void Xu(),850),$u(`ended`))},!0):(w(`SpeechRecognition is not available here. Use the JARVIS text command panel.`),!1)}async function Xu(){if(!zu&&!Yu())return!1;if(Wu)return!0;Hu=!0,Wu=!0,await Qu();try{return zu.start(),window.setTimeout(()=>{Wu=!1},350),Uu||(w(`JARVIS wake word listening is active.`),Uu=!0),!0}catch(e){return Wu=!1,clearTimeout(Vu),Vu=setTimeout(()=>{Hu&&Xu()},1200),/InvalidStateError/i.test(e?.name||e?.message||``)||w(`JARVIS voice restart pending: ${e?.message||`recognizer busy`}`),$u(`start-failed`,{error:e?.message||`busy`}),!1}}function Zu(e){if(!e.results?.[e.resultIndex]?.isFinal)return;let t=Array.from(e.results).slice(e.resultIndex).filter(e=>e?.isFinal).map(e=>e[0]?.transcript||``).join(` `).trim();if(!t)return;let n=t.toLowerCase().replace(/\s+/g,` `).trim(),r=Date.now(),i=n.match(/(?:^|\b)(?:hey\s+)?jarvis\b[:,]?\s*(.*)$/i)||n.match(/(?:^|\b)(?:hey\s+)?friday\b[:,]?\s*(.*)$/i),a=i?.[1]?.trim()||``;if(i){if(Bu=r+4200,$u(`wake`,{wakeWindowUntil:Bu}),!a){Iu(`Listening.`,{speak:!1});return}}else if(r>Bu)return;if(r-qu<650)return;qu=r;let o=a||n;!o||o===Ju||(Ju=o,k(`jarvis-command`,{text:o,source:`voice`}),$u(`command`,{wakeWindowUntil:Bu}))}async function Qu(){if(Gu||Ku===`blocked`||!navigator.mediaDevices?.getUserMedia)return Gu;try{return Gu=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},video:!1}),Ku=`granted`,$u(`mic-ready`),Gu}catch(e){return Ku=[`NotAllowedError`,`SecurityError`].includes(e?.name)?`blocked`:`error`,$u(`mic-error`,{error:e?.name||e?.message||`unknown`}),null}}function $u(e,t={}){try{k(`VOICE_STATE`,{reason:e,enabled:Hu,starting:Wu,wakeWindowUntil:Bu,micPermission:Ku,hasStream:!!Gu,lastCommandAt:qu,...t})}catch{}}var ed=null,td=null,nd=!1,rd=new Map,id=null,ad=1/60,od=3,sd=0,cd=0;async function ld(){await(void 0)(),ed=new Ue(new Be(0,-9.81,0)),td=new He(!0),ed.numSolverIterations=8,D.physicsWorld=ed,nd=!0,cd=performance.now();let e=Ve.fixed().setTranslation(0,0,0);id=ed.createRigidBody(e);let t=We.cuboid(100,.1,100).setFriction(.7).setRestitution(.1);ed.createCollider(t,id),window.AFRAME&&(AFRAME.registerComponent(`jarvis-physics`,{tick:function(e,t){ud(t)}}),document.querySelector(`a-scene`).setAttribute(`jarvis-physics`,``)),console.log(`[AR Physics] Rapier3D world initialized — 60Hz fixed timestep, CCD enabled, 8 solver iterations.`)}function ud(e){if(!nd||!ed)return;let t=performance.now(),n=typeof e==`number`&&e>0&&e<200?e/1e3:Math.min((t-cd)/1e3,.05);cd=t,sd+=n;let r=0;for(;sd>=ad&&r<od;)ed.step(td),sd-=ad,r++;td.drainCollisionEvents((e,t,n)=>{n&&window.dispatchEvent(new CustomEvent(`ar-physics-collision`,{detail:{handle1:e,handle2:t}}))});for(let[e,t]of rd.entries()){let n=e.translation(),r=e.rotation();t.position.set(n.x,n.y,n.z),t.quaternion.set(r.x,r.y,r.z,r.w)}rd.size>0&&window.dispatchEvent(new CustomEvent(`ar-physics-step`))}var dd=null,fd=null,pd=!1;async function md(){pd=!0;try{dd=new globalThis.FaceMesh({locateFile:e=>`https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/${e}`}),dd.setOptions({maxNumFaces:1,refineLandmarks:!0,minDetectionConfidence:.5,minTrackingConfidence:.5}),dd.onResults(e=>{window.dispatchEvent(new CustomEvent(`ar-face-mesh-results`,{detail:e}))}),console.log(`[AR Vision] Face mesh initialized.`)}catch(e){C(e.message,`Face Mesh Failed`)}try{let e=await Le.forVisionTasks(`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision/wasm`);fd=await ze.createFromOptions(e,{baseOptions:{modelAssetPath:`https://storage.googleapis.com/mediapipe-models/object_detector/efficientdet_lite0/float16/1/efficientdet_lite0.tflite`,delegate:`GPU`},scoreThreshold:.5,maxResults:5,runningMode:`VIDEO`}),console.log(`[AR Vision] Object detector initialized.`)}catch(e){C(e.message,`Object Detection Failed`)}N(hd)}async function hd(){if(!pd)return;let e=document.getElementById(`camerafeed`);if(e&&e.readyState>=2)try{if(dd&&await dd.send({image:e}),fd){let t=fd.detectForVideo(e,performance.now());t.detections.length>0&&window.dispatchEvent(new CustomEvent(`ar-object-detections`,{detail:t.detections}))}}catch(e){console.warn(`Vision frame skipped:`,e)}N(hd)}window.addEventListener(`deviceorientation`,e=>{if(globalThis.JARVIS_AR&&globalThis.JARVIS_AR.runtime&&globalThis.JARVIS_AR.runtime.camera){let{alpha:t,beta:n,gamma:r}=e;if(t!=null&&n!=null&&r!=null){let e=new window.THREE.Euler(THREE.MathUtils.degToRad(n),THREE.MathUtils.degToRad(t),THREE.MathUtils.degToRad(-r),`YXZ`);globalThis.JARVIS_AR.runtime.camera.quaternion.setFromEuler(e)}}});var $=Qe();D.config=$;try{globalThis.JARVIS_AR=D,globalThis.JarvisWebAR={state:D,start:Md,resume:Rd,pause:zd,destroy:Bd,setNativeOptions:Hd,applyNativeState:Ud,command:Zd,spawn:e=>k(`spawn-model`,{query:e})}}catch{}var gd=0,_d=!1,vd=null,yd=!1,bd=!1,xd=!1,Sd=!1,Cd=null,wd=new Promise(e=>{Cd=e}),Td=!1;function Ed(){_d=!0,Cd?.(!0),_t(gd),E(`8th Wall engine loaded.`,30),$.autoStart&&Md()}Dd();function Dd(){if(Sd)return;if(Sd=!0,document.visibilityState===`visible`){Od();return}E(`Waiting for this tab to become visible...`,8);let e=()=>{document.visibilityState===`visible`&&(document.removeEventListener(`visibilitychange`,e),Od())};document.addEventListener(`visibilitychange`,e)}async function Od(){if(!xd){if(document.visibilityState!==`visible`){Dd();return}if(xd=!0,pt(`ar-core`,{entrypoint:`ar-core/ar-init.js`,force:!0}),dt(`booting`),A(`booting`),document.body.dataset.jarvisBoot=`booting`,D.telemetry.startedAt=performance.now(),E(`Running AR preflight audit...`,10),!Ze()){dt(`blocked`,{reason:`https-required`}),A(`blocked`,{reason:`https-required`});return}await kd($),Wd(),M(`capability-matrix`,`ready`,D.capabilities),on(),M(`panels`,`ready`),Rc(),M(`vr`,`ready`),bi(),M(`spatial-audio`,`ready`),yl(),M(`reconstruction`,`ready`),ld(),M(`physics`,`ready`),md(),M(`vision`,`ready`),qd(),jd(),Gd(),await Bt($);try{Re(async()=>{let{initVrStereoSplitScreen:e}=await Promise.resolve().then(()=>Nt);return{initVrStereoSplitScreen:e}},void 0,import.meta.url).then(({initVrStereoSplitScreen:e})=>{let{renderer:t,scene:n,camera:r}=L();e(t,n,r),console.log(`V15 AR: Stereo split-screen mounted.`)})}catch(e){console.error(`V15 AR Stereo Mount failed:`,e)}j(`scene`,!0),M(`scene`,`ready`,{renderer:D.runtime.rendererOwner}),Gt(),M(`adaptive-quality`,`ready`),It(L(),{mode:`boot-proxy`,tier:D.telemetry.qualityTier||`medium`}),Pa(),M(`models`,`ready`),Kd(),M(`jarvis`,`ready`),E(`Waiting for 8th Wall engine binary...`,22),Td||(Td=!0,window.addEventListener(`xrloaded`,Ed,{once:!0})),globalThis.XR8&&(_d=!0,Cd?.(!0),_t(gd),E(`8th Wall engine loaded.`,30),$.autoStart&&Md()),gd=gt(()=>{_d||w(`8th Wall is still loading. Holding real AR start instead of silently dropping into basic camera mode.`,`8th Wall Loading`)},4500),$.command&&(D._commandBootTimer=gt(()=>Zd($.command),1200)),document.body.dataset.jarvisBoot=`ready`,j(`boot`,!0),j(`ui`,!0),dt(`ready`),A(`ready`)}}function kd(e={}){if(globalThis.XR8)return Promise.resolve(!0);let t=document.getElementById(`jarvis-xr-static`);return t?t.dataset.loadFailed===`true`?Ad(e):new Promise(n=>{t.addEventListener(`load`,()=>{n(!0)},{once:!0}),t.addEventListener(`error`,()=>{t.dataset.loadFailed=`true`,Ad(e).then(n)},{once:!0})}):Ad(e)}function Ad(e={}){if(globalThis.XR8)return Promise.resolve(!0);let t=String(e.xrScriptUrl||``).trim();return t?document.querySelector(`script[data-jarvis-xr-script]`)?Promise.resolve(!0):new Promise(e=>{let n=document.createElement(`script`);n.src=t,n.async=!0,n.defer=!0,n.crossOrigin=`anonymous`,n.dataset.jarvisXrScript=`true`,n.setAttribute(`data-preload-chunks`,`slam`),n.addEventListener(`load`,()=>e(!0),{once:!0}),n.addEventListener(`error`,()=>{w(`Configured 8th Wall binary failed to load. The runtime will fall back instead of hanging on a dead CDN pin.`,`8th Wall Loading`),e(!1)},{once:!0}),document.head.appendChild(n)}):Promise.resolve(!1)}function jd(){document.getElementById(`start-ar`)?.addEventListener(`click`,()=>Md()),document.getElementById(`camerafeed`)?.addEventListener(`click`,()=>{D.started||Md()})}async function Md(){return yd||vd?vd:D.runtime.lifecycleState===`running`?!0:(yd=!0,pt(`ar-core`,{entrypoint:`ar-core/ar-init.js`}),dt(`starting`),A(`starting`),E(`Starting real AR camera...`,34),vd=(async()=>{try{let e=await Nd(3e4);return D._commandBootTimer&&(_t(D._commandBootTimer),D._commandBootTimer=null),e?await Pd():(C(`8th Wall engine binary did not load within 30 seconds. Running fallback with reduced tracking.`,`8th Wall Timeout`,{timeout:0}),await Id()),sn(),Fs().catch(e=>C(e.message,`Gesture Startup Failed`)),Xu(),Xt(),D.started=!0,j(`camera`,!!(D.cameraVideo||D.xrStarted||D.xrSession)),j(`tracking`,!!(D.trackingMode&&D.trackingMode!==`standby`)),dt(`running`,{trackingMode:D.trackingMode}),A(`running`,{trackingMode:D.trackingMode}),I(`AR runtime started: ${D.trackingMode}`),!0}catch(e){D.runtime.lastError=e?.message||String(e),D.runtime.degradationReason=D.runtime.lastError,dt(`degraded`,{error:D.runtime.lastError}),A(`degraded`,{error:D.runtime.lastError}),C(e.message,`AR Startup Failed`,{timeout:0}),D._commandBootTimer&&(_t(D._commandBootTimer),D._commandBootTimer=null);let t=await Ld();return sn(),t?(D.started=!0,j(`camera`,!0),j(`tracking`,!0),A(`degraded-running`,{trackingMode:D.trackingMode,reason:D.runtime.degradationReason}),!0):(D.started=!1,vd=null,A(`failed`,{error:D.runtime.lastError}),!1)}finally{yd=!1}})(),vd)}async function Nd(e){if(globalThis.XR8&&_d)return!0;E(`Waiting for 8th Wall SLAM engine...`,36);let t=new Promise(t=>gt(()=>t(!1),e));return!!(await Promise.race([wd,t])&&globalThis.XR8)}async function Pd(){let e=globalThis.XR8;if(!e?.GlTextureRenderer?.pipelineModule)throw Error(`XR8.GlTextureRenderer.pipelineModule() is missing.`);if(!e?.Threejs?.pipelineModule)throw Error(`XR8.Threejs.pipelineModule() is missing.`);let t=document.getElementById(`camerafeed`);if(!t)throw Error(`Camera feed canvas was not found.`);e.addCameraPipelineModule({name:`app-camera-status`,onCameraStatusChange:({status:e})=>{e===`requesting`?(E(`Allow camera access to start AR...`,40),T(`status-camera`,`requesting`)):e===`hasStream`?(E(`Camera stream acquired. Initializing SLAM...`,52),T(`status-camera`,`stream`),D.runtime.permissionState=`granted`,j(`camera`,!0)):e===`hasVideo`?(E(`Camera live. Tracking world points...`,76),T(`status-camera`,`live`),D.runtime.permissionState=`granted`,j(`camera`,!0),Je()):e===`failed`&&(T(`status-camera`,`failed`),D.runtime.permissionState=`denied-or-failed`,D.runtime.degradationReason=`camera failed`,A(`permission-blocked`,{source:`xr8-camera`}),C(`Camera access failed. Check browser settings and allow camera for this browser.`,`Camera Failed`,{timeout:0,linkHref:`intent://settings#Intent;scheme=android-app;end`,linkLabel:`Open Chrome Android settings`}))}});let n=[e.GlTextureRenderer.pipelineModule(),Ye.FullWindowCanvas.pipelineModule(),e.Threejs.pipelineModule(),e.XrController.pipelineModule({enableWorldPoints:!0,disableWorldTracking:!1,imageTargets:Array.isArray($.imageTargets)?$.imageTargets:[]}),...e.CameraPixelArray?.pipelineModule?[e.CameraPixelArray.pipelineModule({maxDimension:480}),nc()]:[],Ye.AlmostThere.pipelineModule(),Ye.Loading.pipelineModule(),Ye.RuntimeError.pipelineModule(),fl(),Ml()];D.pipelineOrder=[`app-camera-status`,`XR8.GlTextureRenderer`,...n.slice(1).map(e=>e.name)],D.trackingAPI={getTrackingQuality:Jl,registerAnchor:Ul,unregisterAnchor:Wl,performHitTest:ql,requestRelocalization:Yl},e.addCameraPipelineModules(n),e.run({canvas:t,webgl2:!0,ownRunLoop:!0,glContextConfig:{alpha:!0,preserveDrawingBuffer:!0,powerPreference:`high-performance`},cameraConfig:{direction:e.XrConfig.camera().BACK}}),D.xrStarted=!0,D.xrAvailable=!0,P(`eightWallSLAM`,!0),D.trackingMode=`8thwall-slam`,await Fd();let r=At()||L();mt(`xr8-threejs`,r,{takeover:!0,engine:`8thwall-slam`}),It(r,{mode:`xr8-session`,session:D.xrSession,tier:D.telemetry.qualityTier||`high`,stereo:!1,depthComposition:!0,frameBudgetMs:13.5,guardianProxy:!!$.guardianProxy}),M(`xr8`,`running`,{pipelineOrder:D.pipelineOrder}),Wt(r.renderer,$),Yt(r.scene),jt(r),j(`tracking`,!0),document.body.dataset.jarvisTracking=`8thwall-slam`,T(`status-tracking`,`8th wall`),Ht(),Je(),w(`8th Wall SLAM path started. Camera texture renderer is first in the render pipeline.`)}async function Fd(e=2200){let t=0,n=performance.now();for(;performance.now()-n<e&&t<132;){try{let e=globalThis.XR8?.Threejs?.xrScene?.();if(e?.scene&&e?.camera&&e?.renderer)return e}catch{}t++,await new Promise(e=>requestAnimationFrame(e))}return t>=132&&console.warn(`Timed out without a valid XR scene — returning null.`,132),null}async function Id(){if(D.trackingMode=`webxr-fallback`,document.body.dataset.jarvisTracking=`webxr-fallback`,T(`status-tracking`,`webxr/basic`),!(`xr`in navigator&&navigator.xr))return Ld();try{if(!await navigator.xr.isSessionSupported(`immersive-ar`))return Ld();let{renderer:e}=L(),t=await Promise.race([navigator.xr.requestSession(`immersive-ar`,{requiredFeatures:[`hit-test`],optionalFeatures:[`dom-overlay`,`light-estimation`,`depth-sensing`,`local-floor`,`anchors`,`bounded-floor`],domOverlay:{root:document.getElementById(`ui-layer`)}}),new Promise((e,t)=>gt(()=>t(Error(`WebXR session request timed out`)),5e3))]);e.xr.enabled=!0,e.xr.setSession(t);let n=await t.requestReferenceSpace(`viewer`);return D.xrHitTestSource=await t.requestHitTestSource({space:n}),D.xrSession=t,t.addEventListener(`end`,()=>{D.xrSession===t&&(D.xrSession=null,D.xrStarted=!1,D.started&&A(`degraded`,{reason:`webxr-session-ended`}))},{once:!0}),mt(`webxr-threejs`,{scene:D.scene,camera:D.camera,renderer:e},{takeover:!0,engine:`webxr-fallback`}),It({scene:D.scene,camera:D.camera,renderer:e},{mode:`webxr-session`,session:t,stereo:!1,depthComposition:!0,source:D.cameraVideo||document.getElementById(`camerafeed`)}),M(`webxr`,`running`),P(`webXRHitTest`,!0),Ot(),jt(L()),j(`camera`,!0),j(`tracking`,!0),Je(),w(`Running WebXR fallback. 8th Wall SLAM is not active in this session.`),!0}catch(e){return C(e.message,`WebXR Fallback Failed`),Ld()}}async function Ld(){D.trackingMode=`manual-camera`,P(`manualCamera`,!0),document.body.dataset.jarvisTracking=`manual-camera`,T(`status-tracking`,`basic camera`),E(`Starting basic camera mode...`,48);try{Vd();let e=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:`environment`},width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},audio:!1}),t=document.createElement(`video`);t.srcObject=e,t.autoplay=!0,t.playsInline=!0,t.muted=!0,t.setAttribute(`playsinline`,``),t.style.cssText=`position:fixed;top:0;left:0;width:100vw;height:100vh;object-fit:cover;z-index:0;background:#000`,document.body.insertBefore(t,document.body.firstChild),await t.play(),D.cameraVideo=t,D.runtime.permissionState=`granted`;try{return mt(`fallback-three`,L(),{takeover:D.runtime.rendererOwner!==`xr8-threejs`,engine:`manual-camera`}),M(`manual-camera`,`running`),It(L(),{mode:`manual-camera`,stereo:!1,source:D.cameraVideo||document.getElementById(`camerafeed`),frameBudgetMs:20}),Ot(),jt(L()),T(`status-camera`,`live`),j(`camera`,!0),j(`tracking`,!0),Je(),w(`Basic camera mode is active. Surface placement uses estimated floor fallback.`),!0}catch(e){return D.runtime.permissionState=`failed`,D.runtime.degradationReason=e?.message||String(e),C(`Manual camera fallback setup failed: ${e?.message||String(e)}`,`Manual Camera Setup Failed`,{timeout:0}),Vd(),!1}}catch(e){return D.runtime.permissionState=e.name===`NotAllowedError`?`denied`:`failed`,D.runtime.degradationReason=e?.message||String(e),A(e.name===`NotAllowedError`?`permission-blocked`:`failed`,{error:D.runtime.degradationReason}),e.name===`NotAllowedError`?C(`Camera permission denied. Please allow camera access.`,`Camera Denied`,{timeout:0}):e.name===`NotFoundError`?C(`No camera found on this device.`,`Camera Missing`,{timeout:0}):C(`Camera error: ${e.message}`,`Camera Error`,{timeout:0}),!1}}function Rd(){if(D.runtime.lifecycleState===`stopped`)return!1;if(D.paused=!1,D.xrStarted)try{globalThis.XR8?.resume?.()}catch{w(`8th Wall resume was not available in this browser session.`,`Lifecycle`)}try{D.cameraVideo?.play?.()}catch{}return!D.xrStarted&&D.fallbackRenderer&&Ot(),document.body.dataset.jarvisPaused=`false`,Xt(),A(D.started?`running`:`ready`,{reason:`resume`}),I(`AR runtime resumed`),!0}function zd(e=`manual`){if(D.paused=!0,D.xrStarted)try{globalThis.XR8?.pause?.()}catch{w(`8th Wall pause was not available in this browser session.`,`Lifecycle`)}try{D.cameraVideo?.pause?.()}catch{}return kt(),document.body.dataset.jarvisPaused=`true`,A(`paused`,{reason:e}),I(`AR runtime paused`),!0}async function Bd(){zd(`shutdown`),D._commandBootTimer&&(_t(D._commandBootTimer),D._commandBootTimer=null),Ls(),nl(),vn(),Xl(),kt();try{await D.xrSession?.end?.()}catch{}try{let e=L()?.renderer;e?.xr&&await e.xr.setSession(null)}catch{}try{typeof globalThis.XR8?.clearCameraPipelineModules==`function`&&globalThis.XR8.clearCameraPipelineModules(),globalThis.XR8?.stop?.()}catch{}return Vd(),document.querySelectorAll(`#ui-layer .ar-panel, #ui-layer .panel-orb, #error-host > *, #banner-host > *`).forEach(e=>e.remove()),Rt(),ft(),vd=null,I(`AR runtime shut down`),!0}function Vd(){try{(D.cameraVideo?.srcObject)?.getTracks?.().forEach(e=>e.stop()),D.cameraVideo?.remove?.()}catch{}D.cameraVideo=null}function Hd(e={}){D.nativeOptions={...D.nativeOptions,...e&&typeof e==`object`?e:{}},document.body.dataset.jarvisNativeOptions=`applied`,D.nativeOptions.handTrackingEnabled===!1&&w(`Native options disabled hand tracking for this AR session.`,`APK Options`),(D.nativeOptions.thermalPause===!0||D.nativeOptions.thermalState===`critical`)&&(zd(`thermal`),D.runtime.degradationReason=`thermal`,A(`thermal-paused`,{thermalState:D.nativeOptions.thermalState||`critical`}));for(let e of[`eyeTracking`,`nativeCompositor`,`truePersistentWorldAnchors`,`nativeOpenXRBridge`])Object.prototype.hasOwnProperty.call(D.nativeOptions,e)&&P(e,D.nativeOptions[e]);return Object.prototype.hasOwnProperty.call(D.nativeOptions,`truePersistentWorldAnchors`)&&P(`persistentAnchorSupport`,D.nativeOptions.truePersistentWorldAnchors),F(`setCompositorState`,JSON.stringify({mode:D.compositor.mode,native:D.compositor.native,passthroughBlend:D.compositor.passthroughBlend,frameBudgetMs:D.compositor.frameBudgetMs,browserManaged:!0})),k(`native-options`,D.nativeOptions),I(`APK AR options applied`),D.nativeOptions}function Ud(e={}){let t=e;try{t=typeof e==`string`?JSON.parse(e):e}catch(e){return C(e.message,`APK State Sync Failed`),!1}let n=Array.isArray(t)?t:Array.isArray(t?.objects)?t.objects:t?.ar_objects;return Array.isArray(n)&&(k(`native-ar-state`,{objects:n}),F(`status`,`Applied ${n.length} native AR object(s)`)),t?.ui&&typeof t.ui==`object`&&k(`native-ui-state`,t.ui),!0}function Wd(){let e=it();St(e),D.runtime.browserProfile=e,P(`mediaPipeHands`,!!globalThis.Hands),P(`spatialAudio`,!!(globalThis.AudioContext||globalThis.webkitAudioContext)),P(`microphone`,!!navigator.mediaDevices?.getUserMedia),P(`speechSynthesis`,!!window.speechSynthesis),P(`voiceRecognition`,!!(globalThis.SpeechRecognition||globalThis.webkitSpeechRecognition)),P(`webXRAvailable`,!!navigator.xr),P(`webXRHitTest`,!1),P(`browserLatencyCeiling`,!0),P(`limitedSensorAccess`,!0),P(`limitedOSIntegration`,!0),P(`limitedCompositorControl`,!0),P(`persistentAnchorSupport`,!!$.truePersistentWorldAnchors),P(`backgroundExecutionLimited`,!0),P(`passthroughControlLimited`,!0),P(`spatialMemoryLimited`,!0),P(`headsetOptimizationAccessLimited`,!0),P(`webXRFragmented`,e.webXRFragmented),P(`safariWebXRLimitations`,e.limits.safariWebXRLimitations),P(`visionOSBrowserRestrictions`,e.limits.visionOSBrowserRestrictions),P(`androidBrowserInconsistency`,e.limits.androidBrowserInconsistency),P(`webViewInconsistency`,e.limits.webViewInconsistency),P(`questBrowserQuirks`,e.limits.questBrowserQuirks),P(`fullscreenEdgeCases`,e.limits.fullscreenEdgeCases),P(`orientationLockEdgeCases`,e.limits.orientationLockEdgeCases),P(`webglContextLossRisk`,e.limits.webglContextLossRisk),P(`renderLoopDuplicationRisk`,e.limits.renderLoopDuplicationRisk),P(`eyeTracking`,!!$.eyeTracking),P(`nativeCompositor`,!!$.nativeCompositor),P(`truePersistentWorldAnchors`,!!$.truePersistentWorldAnchors),P(`nativeOpenXRBridge`,!!$.nativeOpenXRBridge),P(`eyeTrackingProxy`,!0),P(`persistentSpatialMemory`,!0),P(`ultraStableAnchoring`,!0),P(`naturalWindowPlacement`,!0),P(`depthAwareImmersion`,!0),P(`environmentAwareUI`,!0),P(`headsetComfortSystems`,!0),P(`lowLatencyCompositing`,!0),document.body.dataset.jarvisCapabilityModel=`browser-web-ar-with-explicit-native-limits`,document.body.dataset.jarvisBrowserProfile=e.browser,document.body.dataset.jarvisBrowserPlatform=e.platform,document.body.dataset.jarvisBrowserLatency=String(e.latencyCeilingMs);let t=at(e).filter(e=>/safari|visionos|android|webview|webxr-fragmented|quest/.test(e));Ct({architecture:`browser-web-ar-runtime`,experienceClass:`web-ar-experiment`,spatialRuntimeClass:e.isVisionOS?`browser-managed-visionos-shell`:e.isQuest?`quest-browser-ar-shell`:e.isSafari?`safari-webxr-shell`:e.isWebView?`embedded-webview-ar-shell`:`browser-web-ar-shell`,platformRole:e.isVisionOS?`visionos-browser`:e.isQuest?`quest-browser`:e.isAndroid?`android-browser`:e.isIOS?`ios-browser`:`desktop-browser`,spatialGapStatement:e.isVisionOS||e.isSafari||e.isWebView||e.isAndroid?`This runtime is browser-managed spatial AR, not a native headset OS, compositor, or persistent spatial shell.`:`This runtime is browser-managed spatial AR, not a unified native spatial computing runtime.`}),wt([`No single authoritative native spatial runtime exists in this codebase.`,`Browser-layer AR, XR8/WebXR, fallback cameras, and compatibility shells coexist behind one shared authority instead of a native OS compositor stack.`,`Persistent world understanding, headset compositor control, and headset-grade platform integration remain unavailable because the runtime is bounded by browser APIs and vendor binaries.`,`Lifecycle and rendering governance must therefore be centralized in the web runtime, not spread across competing engines.`].join(` `)),Tt(`Vision Pro-style browser shell implemented as far as the web stack allows: gaze proxy, hand-eye fusion, persistent spatial memory, stabilized anchoring, low-latency compositor hints, natural window placement, depth-aware immersion, environment-aware UI, and comfort systems are active; true native eye tracking, headset OS integration, and native compositor control remain outside the browser runtime.`,[`gaze proxy`,`hand-eye fusion`,`persistent spatial memory`,`ultra-stable anchoring`,`low-latency compositing proxy`,`natural window placement`,`depth-aware immersion`,`environment-aware UI`,`headset comfort systems`]),F(`setNativeCapabilities`,JSON.stringify({browserProfile:e,capabilities:D.capabilities,runtime:{architecture:D.runtime.architecture,spatialRuntimeClass:D.runtime.spatialRuntimeClass,platformRole:D.runtime.platformRole}})),F(`setGuardianState`,JSON.stringify({requested:!0,boundary:D.capabilities.guardianBoundary,platformRole:D.runtime.platformRole,source:`ar-init`})),F(`setOpenXRState`,JSON.stringify({supported:e.isQuest||e.isVisionOS,browserManaged:!0,platformRole:D.runtime.platformRole,compositor:D.compositor})),t.length&&(D.runtime.degradationReason=t.join(`, `),I(`Browser limits: ${t.join(`, `)}`),e.limits.visionOSBrowserRestrictions?w(`visionOS browser support is browser-managed only. Native compositor, passthrough control, and persistent anchors stay unavailable here.`,`visionOS Browser Limits`):e.limits.safariWebXRLimitations?w(`Safari WebXR support is fragmented. Chrome Android remains the primary AR path for this runtime.`,`Safari WebXR Limits`):e.limits.webViewInconsistency?w(`Embedded WebViews can be stricter than Chrome Custom Tabs for XR, sensors, and camera permissions.`,`WebView Limits`):e.limits.questBrowserQuirks&&w(`Quest Browser fullscreen, orientation, and session behavior can be quirky; the runtime is applying extra guard rails.`,`Quest Browser Limits`))}function Gd(){bd||(bd=!0,document.addEventListener(`visibilitychange`,()=>{document.hidden?D.started&&zd(`background-tab`):D.started&&D.runtime.lifecycleState===`paused`&&Rd()}),window.addEventListener(`pagehide`,()=>{D.started&&zd(`pagehide`)}),window.addEventListener(`pageshow`,()=>{D.started&&D.runtime.lifecycleState===`paused`&&Rd()}))}function Kd(){let e=new Pu($).connect();Yu();try{globalThis.Jarvis={query:t=>e.query(t),runTask:(t,n)=>e.runTask(t,n),command:e=>Zd(e)}}catch{D.jarvisGlobalBlocked=!0}O(`jarvis-command`,({text:e})=>Zd(e))}function qd(){O(`VOICE_STATE`,e=>{D.spatialAudio.micPermission=e?.micPermission||D.spatialAudio.micPermission,D.spatialAudio.micReady=!!(e?.micReady||e?.enabled||e?.listening),D.spatialAudio.wakeWindowUntil=e?.wakeWindowUntil||0,D.spatialAudio.lastVoiceCommandAt=e?.lastCommandAt||D.spatialAudio.lastVoiceCommandAt,(e?.reason===`mic-error`||e?.reason===`blocked`)&&I(`Voice mic ${e.error||e.micPermission||`blocked`}`)}),O(`open-jarvis`,Jd),O(`open-games`,Yd),O(`open-builder`,_u),O(`scan-room`,()=>Iu(`Scanning the room.`,{speak:!1}))}function Jd(){let e=document.createElement(`div`),t=document.createElement(`input`),n=document.createElement(`button`);t.placeholder=`Command JARVIS`,n.className=`btn-primary`,n.textContent=`Run`,n.onclick=()=>Zd(t.value),t.addEventListener(`keydown`,e=>{e.key===`Enter`&&n.click()}),e.append(t,n),new an({title:`JARVIS`,body:e,icon:`J`,width:360,height:260}).focus()}function Yd(){let e=document.createElement(`div`),t=Xd(`Eternum AR`,$l),n=Xd(`Ripples AR`,iu),r=document.createElement(`input`),i=Xd(`Convert Game URL`,()=>au(r.value||`about:blank`,globalThis.Jarvis||D.jarvis));r.placeholder=`Game URL or name`,e.append(t,n,r,i),yn(`AR Games`,e,`G`)}function Xd(e,t){let n=document.createElement(`button`);return n.className=`panel-action`,n.textContent=e,n.onclick=t,n}async function Zd(e){let t=String(e||``).trim();if(!t)return;let n=t.toLowerCase();try{let e=n.match(/\b(open|close|toggle|rotate|spin|turn|reconfigure|rebuild|transform|rearrange|shatter|break|explode|reveal|show|hide|grab|move|drag)\b/);if(e&&/(model|door|window|screen|panel|roof|drawer|wheel|part|house|room|car|vehicle|device|custom)/.test(n)){let r=n.replace(/\b(hey\s+jarvis|jarvis)\b/gi,``).replace(/\b(open|close|toggle|rotate|spin|turn|reconfigure|rebuild|transform|rearrange|shatter|break|explode|reveal|show|hide|grab|move|drag|the|a|an|model|part|on|of|in|for|to)\b/gi,` `).replace(/\s+/g,` `).trim();k(`jarvis-model-action`,{action:e[1],target:r,command:t,source:`voice`}),Iu(`Model action queued: ${e[1]}${r?` on ${r}`:``}.`,{speak:!0});return}if(/spawn|place|load|model/.test(n)){let e=n.replace(/\b(spawn|place|load|model|a|an|the|in ar)\b/g,` `).trim()||`Duck`;k(`spawn-model`,{query:e}),Iu(`Model armed: ${e}. Tap a surface to place it.`,{speak:!0});return}if(/scan room|room scan|scan/.test(n)){k(`scan-room`);return}if(/reconstruct/.test(n)){let e=n.replace(`reconstruct`,``).replace(`this scene`,``).trim()||`room`;await bl(e),Iu(`Scene reconstruction complete: ${e}.`,{speak:!0});return}if(/vr mode|vr screen|headset/.test(n)){await zc();return}if(/eternum/.test(n)){$l(),Iu(`Eternum AR panel is open.`,{speak:!0});return}if(/ripples/.test(n)){iu(),Iu(`Ripples AR panel is open.`,{speak:!0});return}if(/convert .* ar|game to ar/.test(n)){await au(t.replace(/convert|to ar|game to ar/gi,``).trim(),globalThis.Jarvis||D.jarvis);return}if(/open models|model picker/.test(n)){La();return}if(/forge model|interactive model|3d forge|custom interactive model|build custom model|custom 3d builder/.test(n)){k(`open-model-forge`),Iu(`Interactive model forge opened.`,{speak:!0});return}if(/camera kit|lens studio|snap/.test(n)){let e=document.createElement(`div`);e.style.cssText=`display:flex;flex-direction:column;gap:10px;padding:8px 0`;let t=document.createElement(`p`);t.style.cssText=`margin:0;font-size:13px;opacity:0.75;line-height:1.4`,t.textContent=`Lens Studio Camera Kit requires a Snap developer token. Enter yours below to activate the Camera Kit AR layer.`;let n=document.createElement(`label`);n.textContent=`Snap Developer Token`,n.style.cssText=`font-size:12px;font-weight:600;opacity:0.9`;let r=document.createElement(`input`);r.type=`text`,r.placeholder=`xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,r.style.cssText=`width:100%;box-sizing:border-box;padding:8px 10px;border-radius:6px;border:1px solid rgba(255,255,255,0.2);background:rgba(255,255,255,0.08);color:var(--text-primary);font-size:13px`,D.config.snapToken&&(r.value=D.config.snapToken);let i=document.createElement(`button`);i.className=`btn-primary`,i.textContent=`Activate Camera Kit`,i.onclick=()=>{let e=r.value.trim();if(!e){w(`Please enter a valid Snap developer token.`,`Camera Kit`);return}D.config.snapToken=e,k(`camera-kit-token-set`,{token:e}),w(`Camera Kit token saved. Reload the AR session to activate the Lens Studio layer.`,`Camera Kit`),o.close?.()};let a=document.createElement(`a`);a.href=`https://docs.snap.com/snap-kit/camera-kit/guides/tutorials/integration-guides/web#set-up-your-api-token`,a.target=`_blank`,a.rel=`noopener noreferrer`,a.textContent=`How to get a Snap developer token ↗`,a.style.cssText=`font-size:12px;color:rgba(255,255,255,0.55);text-decoration:underline`,e.append(t,n,r,i,a);let o=new an({title:`Camera Kit`,body:e,icon:`CK`,width:360,height:300});o.focus();return}Iu(await(globalThis.Jarvis||D.jarvis).query(t),{speak:!0})}catch(e){C(e.message,`JARVIS Command Failed`)}}