@liveroom-tech/react-immersive 6.1.2 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/{SequencesTab-JTIVIZJD.mjs → SequencesTab-ODR5IGDX.mjs} +1 -1
  2. package/dist/binding-builder.css +1 -1
  3. package/dist/binding-builder.d.mts +3 -3
  4. package/dist/binding-builder.d.ts +3 -3
  5. package/dist/binding-builder.js +75 -34
  6. package/dist/binding-builder.mjs +1 -1
  7. package/dist/chunk-2CUPPOBW.mjs +3 -0
  8. package/dist/chunk-3MIILDHB.mjs +83 -0
  9. package/dist/chunk-3XZKDTB2.mjs +1 -0
  10. package/dist/chunk-7MN2TMY6.mjs +47 -0
  11. package/dist/{chunk-W7M2YD65.mjs → chunk-EWNN4BBR.mjs} +1 -1
  12. package/dist/{chunk-5XII5XCD.mjs → chunk-GXY3VML4.mjs} +1 -1
  13. package/dist/chunk-IOLT2VXU.mjs +1 -0
  14. package/dist/chunk-X4WRTDO6.mjs +50 -0
  15. package/dist/hosted.css +1 -1
  16. package/dist/hosted.d.mts +4 -4
  17. package/dist/hosted.d.ts +4 -4
  18. package/dist/hosted.js +73 -32
  19. package/dist/hosted.mjs +1 -1
  20. package/dist/index.css +1 -1
  21. package/dist/index.d.mts +4 -4
  22. package/dist/index.d.ts +4 -4
  23. package/dist/index.js +72 -31
  24. package/dist/index.mjs +1 -1
  25. package/dist/{modelFileResolver-pPzMl63D.d.mts → modelFileResolver-ChKYsF21.d.mts} +33 -1
  26. package/dist/{modelFileResolver-pPzMl63D.d.ts → modelFileResolver-ChKYsF21.d.ts} +33 -1
  27. package/dist/{modelViewerProps-07WgBVqm.d.ts → modelViewerProps-Ch6pIZIE.d.ts} +30 -31
  28. package/dist/{modelViewerProps-CGgtm4Zb.d.mts → modelViewerProps-HazR2IE_.d.mts} +30 -31
  29. package/dist/{publicProps-BylAVwPu.d.mts → publicProps-Cmh9JtzJ.d.ts} +2 -1
  30. package/dist/{publicProps-CEt3hxQU.d.ts → publicProps-TMARX628.d.mts} +2 -1
  31. package/dist/simple-model-viewer.css +1 -1
  32. package/dist/simple-model-viewer.d.mts +15 -2
  33. package/dist/simple-model-viewer.d.ts +15 -2
  34. package/dist/simple-model-viewer.js +5 -5
  35. package/dist/simple-model-viewer.mjs +1 -1
  36. package/dist/utils.d.mts +4 -4
  37. package/dist/utils.d.ts +4 -4
  38. package/dist/utils.js +50 -9
  39. package/dist/utils.mjs +1 -1
  40. package/package.json +7 -4
  41. package/dist/chunk-35UERL2D.mjs +0 -83
  42. package/dist/chunk-DS5XNP7A.mjs +0 -47
  43. package/dist/chunk-M4LVNNVP.mjs +0 -1
  44. package/dist/chunk-Q4QPI5GG.mjs +0 -9
  45. package/dist/chunk-WJIICFV4.mjs +0 -3
  46. package/dist/chunk-XBVAZFXW.mjs +0 -1
package/dist/utils.js CHANGED
@@ -1,9 +1,50 @@
1
- "use strict";var yo=Object.create;var Le=Object.defineProperty;var So=Object.getOwnPropertyDescriptor;var xo=Object.getOwnPropertyNames;var wo=Object.getPrototypeOf,Mo=Object.prototype.hasOwnProperty;var Ao=(e,t)=>{for(var o in t)Le(e,o,{get:t[o],enumerable:!0})},Bt=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of xo(t))!Mo.call(e,r)&&r!==o&&Le(e,r,{get:()=>t[r],enumerable:!(n=So(t,r))||n.enumerable});return e};var Et=(e,t,o)=>(o=e!=null?yo(wo(e)):{},Bt(t||!e||!e.__esModule?Le(o,"default",{value:e,enumerable:!0}):o,e)),vo=e=>Bt(Le({},"__esModule",{value:!0}),e);var Ar={};Ao(Ar,{ACTION_CATALOG:()=>Re,DEFAULT_MODEL_VIEWER_LABELS:()=>At,DEFAULT_SCENE_CONFIG:()=>pe,DEFAULT_SECTION_CONFIG:()=>Zt,MATERIAL_BLENDING_MODES:()=>Yt,MATERIAL_SIDES:()=>Xt,MAX_VIEWER_STATE_BYTES:()=>ae,MEASUREMENT_UNITS:()=>gt,SEQUENCE_EASINGS:()=>ut,SEQUENCE_OBJECT_PROPERTIES:()=>dt,applyIsolation:()=>$t,applyProductOptions:()=>Cn,applyStyleRules:()=>Ft,buildBindingsFromNodes:()=>Wt,calibrateMeasurements:()=>ln,chooseMaterialVariant:()=>_e,collectObjectHierarchy:()=>En,colorScaleValue:()=>nt,compareViewerConfigurations:()=>bo,copyBindingStyle:()=>Vn,createARHandoffUrl:()=>uo,createDefaultBinding:()=>st,decodeProductSelections:()=>Sn,defaultProductSelections:()=>ve,defineObjectBindings:()=>Vt,encodeProductSelections:()=>wt,evaluateProductConfiguration:()=>ne,exportConfiguredUSDZ:()=>oo,findCatalogAction:()=>Ht,formatProductPrice:()=>hn,generateProductSkus:()=>xn,groundAsset:()=>tn,inferType:()=>it,inspectAsset:()=>Ln,isolatedBindingKeys:()=>ot,material:()=>Lt,measurementResult:()=>yt,measurementScale:()=>ht,measurementValue:()=>Ge,measurementsToCsv:()=>un,parseAssetTransform:()=>Ae,parseMeasurements:()=>ye,parseProductConfiguration:()=>vn,parseProductDefinition:()=>xt,parseSceneProduct:()=>We,parseSectionConfig:()=>Ie,parseSelectionSets:()=>He,parseSequences:()=>Me,parseViewerState:()=>Ce,pasteBindingStyle:()=>Dn,patchBindings:()=>Ue,patchSceneConfig:()=>Ut,prepareViewerState:()=>Xe,productCheckoutUrl:()=>yn,productDefinitionWarnings:()=>wn,productOptionStates:()=>Mn,productPriceFromDefinition:()=>bn,readARHandoffUrl:()=>mo,resolveProductSelections:()=>Ke,sampleSequenceTrack:()=>$e,sceneLight:()=>_t,sectionSnapshot:()=>Jt,selectBindingKeys:()=>Y,selectBindings:()=>Nt,serializeMeasurements:()=>dn,serializeProductConfiguration:()=>An,serializeViewerState:()=>Bn,snapAssetToGrid:()=>en,upsertSequenceKeyframe:()=>Qt});module.exports=vo(Ar);function Vt(e){return e}function et(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function je(e,t){if(!et(t))return t;let o=et(e)?{...e}:{};for(let n of Object.keys(t)){let r=t[n];o[n]=et(r)?je(o[n],r):r}return o}function Dt(e,t){if(e[t])return t;let o=Object.entries(e).find(([,r])=>r.id===t)?.[0];return o||(Object.entries(e).find(([,r])=>r.modelObjectId===t)?.[0]??null)}function Co(e){return typeof e=="object"&&!Array.isArray(e)}function Oo(e,t){return"group"in t?e.group===t.group:"tag"in t?e.tags?.includes(t.tag)??!1:(e.type??"other")===t.type}function Y(e,t){if(Co(t))return Object.entries(e).filter(([,r])=>Oo(r,t)).map(([r])=>r);let n=(typeof t=="string"?[t]:t).map(r=>Dt(e,r)).filter(r=>r!==null);return[...new Set(n)]}function Nt(e,t){return Y(e,t).map(o=>e[o]).filter(o=>o!==void 0)}function ko(e){return Array.isArray(e)&&e.length>0&&typeof e[0]!="string"}function Ue(e,t,o){let n=ko(t)?t:[{ids:t,patch:o??{}}],r=e;for(let i of n)for(let s of Y(r,i.ids)){let a=r[s];if(!a)continue;let c=je(a,i.patch);r===e&&(r={...e}),r[s]=c}return r}function Lt(e){return{style:{material:e}}}function Ut(e,t){return je(e,t)}var jo={type:"point",color:"#ffffff",intensity:1,position:[0,0,0],distance:0,decay:2,attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0};function _t(e){return{...jo,...e}}var To="#ff3b30",Ro=Object.freeze({}),zt=e=>e;function Io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Po(e,t){let o=e.metadata;for(let n of t.split(".")){if(!Io(o))return;o=o[n]}return o}function Bo(e,t){if("metric"in t){let o=e.metrics?.[t.metric];return!(typeof o!="number"||!Number.isFinite(o)||t.above!==void 0&&!(o>t.above)||t.below!==void 0&&!(o<t.below))}if("status"in t){let o=e.status??"normal";return Array.isArray(t.status)?t.status.includes(o):t.status===o}return Po(e,t.metadata)===t.equals}function Eo(e){let t=e.trim().replace(/^#/,""),o=t.length===3?t.split("").map(n=>n+n).join(""):t;return/^[0-9a-f]{6}$/i.test(o)?[0,2,4].map(n=>parseInt(o.slice(n,n+2),16)):null}var tt=e=>`#${e.map(t=>Math.round(t).toString(16).padStart(2,"0")).join("")}`;function nt(e,t){let o=e.map(([c,l])=>({at:c,rgb:Eo(l)})).filter(c=>Number.isFinite(c.at)&&c.rgb!==null).sort((c,l)=>c.at-l.at);if(o.length===0||!Number.isFinite(t))return null;if(t<=o[0].at)return tt(o[0].rgb);let n=o[o.length-1];if(t>=n.at)return tt(n.rgb);let r=o.findIndex(c=>c.at>=t),i=o[r-1],s=o[r],a=s.at===i.at?1:(t-i.at)/(s.at-i.at);return tt(i.rgb.map((c,l)=>c+(s.rgb[l]-c)*a))}function Ft(e,t){if(!t?.length)return{bindings:e,pulses:Ro,sourceOf:zt};let o=new Map,n={};for(let s of t){let a=s.target?Y(e,s.target):Object.keys(e),c=s.when?Array.isArray(s.when)?s.when:[s.when]:[];for(let l of a){let d=e[l];if(!c.every(f=>Bo(d,f)))continue;let u={...s.material};if(s.colorScale){let f=d.metrics?.[s.colorScale.metric],p=typeof f=="number"?nt(s.colorScale.stops,f):null;p&&(u={...u,[s.colorScale.channel??"baseColor"]:p})}if(s.pulse){let f=s.pulse===!0?{}:s.pulse;n[l]={color:f.color??To,speed:f.speed!==void 0&&f.speed>0?f.speed:1};let p=u.emissiveIntensity??o.get(l)?.emissiveIntensity??d.style?.material?.emissiveIntensity;p!==void 0&&p>0||(u.emissiveIntensity=1)}Object.keys(u).length>0&&o.set(l,{...o.get(l),...u})}}if(o.size===0)return{bindings:e,pulses:n,sourceOf:zt};let r={...e},i=new WeakMap;for(let[s,a]of o){let c=e[s],l={...c,style:{...c.style,material:{...c.style?.material,...a}}};r[s]=l,i.set(l,c)}return{bindings:r,pulses:n,sourceOf:s=>i.get(s)??s}}function _e(e,t,o){let n=o.find(i=>i.variants.some(s=>s.name===t)),r=new Set(n?.variants.map(i=>i.name)??[t]);return[...e.filter(i=>!r.has(i)),t]}var Vo=.12,qt=new Set;function ot(e,t){return t?new Set(Y(e,t.target)):qt}function $t(e,t){let o=ot(e.bindings,t);if(!t||o.size===0)return{...e,setAside:qt};let n=Math.min(Math.max(t.ghostOpacity??Vo,0),1),r={...e.bindings},i=new WeakMap,s=new Set;for(let[a,c]of Object.entries(e.bindings)){if(o.has(a))continue;s.add(a);let l=t.mode==="hide"?{...c,visible:!1}:{...c,style:{...c.style,material:{...c.style?.material,opacity:Math.min(c.style?.material?.opacity??1,n)}}};r[a]=l,i.set(l,e.sourceOf(c))}return{bindings:r,pulses:e.pulses,sourceOf:a=>i.get(a)??e.sourceOf(a),setAside:s}}var Do=require("three"),rt=Symbol("react-immersive.model-node-id");function No(e,t){Object.defineProperty(e,rt,{value:t,configurable:!0})}function ze(e){let t=new Map;e.traverse(c=>{if(!c.name)return;let l=t.get(c.name);l?l.push(c):t.set(c.name,[c])});let o=Object.create(null),n=new WeakMap,r=new Map,i=new Set(Array.from(t,([c,l])=>l.length===1?c:null).filter(c=>c!==null)),s=new Set,a=(c,l)=>{No(c,l),o[l]=c,n.set(c,l),s.add(l)};for(let[c,l]of t)l.length===1&&a(l[0],c);for(let[c,l]of t){if(l.length<2)continue;let d=[];l.forEach((u,f)=>{let p=`${c} [${f+1}]`,O=p,T=2;for(;i.has(O)||s.has(O);)O=`${p}.${T++}`;a(u,O),d.push(O)}),r.set(c,d)}return{nodesById:o,idByNode:n,duplicateNames:r}}function Te(e){return e[rt]??e.name??null}function Gt(e,t){let o=null,n=[];return e.traverse(r=>{r[rt]===t&&(o=r),r.name===t&&n.push(r)}),o??(n.length===1?n[0]:null)}var Re=Object.freeze([{id:"change-color",label:"Change Color",handling:"viewer",description:"Opens a color picker docked under the action and commits the result to style.material.baseColor."},{id:"change-material",label:"Change Material",handling:"viewer",description:"Opens the material picker so the viewer can swap the object's texture."},{id:"add-text",label:"Add Text",handling:"viewer",description:"Opens a text box docked under the action; the viewer's user types, clicks the object to place it, and can resize, turn, move, or remove it. Saved to the binding's decals."},{id:"add-image",label:"Add Image",handling:"viewer",description:"Lets the viewer's user choose an image, click the object to place it, and resize, turn, move, or remove it. Saved to the binding's decals."},{id:"toggle-visibility",label:"Toggle Visibility",handling:"viewer",description:"Flips the binding's visible flag."},{id:"toggle-light",label:"Toggle Light",handling:"viewer",description:"Turns the scene lights attached to this object on or off, or the object's own glow when none is attached."},{id:"change-light-color",label:"Change Light Color",handling:"viewer",description:"Opens a color picker docked under the action for the scene lights attached to this object, or the object's own glow."},{id:"set-brightness",label:"Set Brightness",handling:"viewer",description:"Opens a brightness slider docked under the action for the scene lights attached to this object, or the object's own glow."}]);function Ht(e){return Re.find(t=>t.id===e)}var Fr=Re.filter(e=>e.handling==="viewer").map(e=>e.id),qr=new Set(["","New Action",...Re.map(e=>e.label)]);var me=require("three");function Fe(e){return Number.isFinite(e)&&e>0?e:1}function Kt(e){return e?.loopMode??"repeat"}function Lo(e){return e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").replace(/[^a-zA-Z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").toLowerCase()}function Uo(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function it(e){let t=e.toLowerCase();return t.includes("light")?"light":t.includes("wheel")||t.includes("rim")||t.includes("tire")?"wheel":t.includes("glass")||t.includes("window")||t.includes("windshield")||t.includes("sunroof")?"glass":t.includes("seat")||t.includes("dashboard")||t.includes("console")||t.includes("doorpanel")?"interior":t.includes("floor")?"floor":t.includes("wall")?"wall":t.includes("door")?"door":t.includes("chair")||t.includes("table")||t.includes("sofa")||t.includes("bed")?"furniture":"other"}function _o(e,t=!0){return e==="light"||e.endsWith("light")?[{id:"toggle-light",label:"Toggle Light",type:"command"},{id:"change-light-color",label:"Change Light Color",type:"command"},{id:"set-brightness",label:"Set Brightness",type:"command"}]:[{id:"change-color",label:"Change Color",type:"command"},...t?[{id:"change-material",label:"Change Material",type:"command"}]:[],{id:"toggle-visibility",label:"Toggle Visibility",type:"command"}]}function st(e,t=!0){let o=it(e);return{id:Lo(e),modelObjectId:e,type:o,label:Uo(e),status:"normal",selectable:!0,hoverable:!0,visible:!0,style:{},actions:_o(o,t),metrics:{},metadata:{}}}function Wt(e,t){return Object.fromEntries(e.map(o=>[o,st(o,!t?.has(o))]))}var Xt=["front","back","double"],Yt=["normal","additive"];var Zt={enabled:!1,axis:"y",position:.5,flip:!1},zo={clips:[],autoplayClip:null},Fo={autofocus:{enabled:!1,focusDistance:5,focusRange:5,focalLength:.02,bokehScale:6,target:[0,0,0],mouse:!0,debug:0,manual:!1,smoothTime:.25},toneMapping:{enabled:!1,mode:"aces",exposure:1,resolution:256,whitePoint:4,middleGrey:.6,minLuminance:.01,averageLuminance:1,adaptationRate:1},brightnessContrast:{enabled:!1,brightness:0,contrast:0},hueSaturation:{enabled:!1,hue:0,saturation:0},colorAverage:{enabled:!1},dotScreen:{enabled:!1,angle:Math.PI/2,scale:1},glitch:{enabled:!1,mode:"sporadic",delay:[1.5,3.5],duration:[.6,1],strength:[.3,1],chromaticAberrationOffset:[0,0],columns:.05,ratio:.85},ssao:{enabled:!1,samples:30,rings:4,intensity:8,radius:.25,bias:.025,luminanceInfluence:.6,fade:.01,minRadiusScale:.33,worldDistanceThreshold:20,worldDistanceFalloff:5,worldProximityThreshold:6,worldProximityFalloff:3},bloom:{enabled:!1,intensity:.3,luminanceThreshold:.9,luminanceSmoothing:.2,mipmapBlur:!0,radius:0,levels:8},godRays:{enabled:!1,sunPosition:[5,10,5],samples:60,density:.96,decay:.9,weight:.4,exposure:.6,clampMax:1,blur:!0,kernelSize:"small"},grid:{enabled:!1,scale:1,lineWidth:0},noise:{enabled:!1,opacity:1,premultiply:!1},depthOfField:{enabled:!1,focusDistance:5,focusRange:5,focalLength:.02,bokehScale:6},chromaticAberration:{enabled:!1,offsetX:.002,offsetY:.002,radialModulation:!1,modulationOffset:.15},lensflare:{enabled:!1,lensPosition:[-25,6,-60],smoothTime:.07,glareSize:.2,flareSize:.01,flareSpeed:.01,flareShape:.01,animated:!0,anamorphic:!1,colorGain:"#141414",haloScale:.5,secondaryGhosts:!0,aditionalStreaks:!0,ghostScale:0,opacity:1,starBurst:!1},vignette:{enabled:!1,offset:.3,darkness:.3,eskil:!1},smaa:{enabled:!1},sepia:{enabled:!1,intensity:0},scanline:{enabled:!1,density:1.25},pixelation:{enabled:!1,granularity:5},outline:{enabled:!1,selectionLayer:10,edgeStrength:2.5,pulseSpeed:0,visibleEdgeColor:"#ffffff",hiddenEdgeColor:"#22090a",kernelSize:"large",blur:!1,xRay:!0},selectiveBloom:{enabled:!1,selectionLayer:10,intensity:1,luminanceThreshold:.9,luminanceSmoothing:.025,kernelSize:"large",mipmapBlur:!0,inverted:!1,ignoreBackground:!1},ramp:{enabled:!1,rampType:"linear",rampStart:[.5,.5],rampEnd:[1,1],startColor:"#000000",endColor:"#ffffff",opacity:.5,rampBias:.5,rampGain:.5,rampMask:!1,rampInvert:!1}},pe={model:{rotation:[0,0,0],showAdvancedRotation:!1,renderer:"pbr",shading:"lit",autoRotate:!1,autoRotateSpeed:1},camera:{fieldOfView:50,showAdvancedSettings:!1},lighting:{ambient:{intensity:.25,color:"#ffffff"},lights:[{id:"light-hemi",type:"hemisphere",color:"#ffffff",intensity:.3,position:[0,1,0],attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0},{id:"light-key",type:"directional",color:"#ffffff",intensity:2.5,position:[6,12,6],attachedToCamera:!1,castShadow:!0,shadowBias:-5e-4,visible:!0},{id:"light-fill",type:"directional",color:"#ffffff",intensity:0,position:[-6,8,-6],attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0}]},shadows:{enabled:!0,mapSize:2048,bias:-5e-4,normalBias:.02,radius:3},environment:{source:"preset",preset:"apartment",customEnvironmentUrl:"",intensity:.25,rotation:0,shadowLight:{enabled:!1,intensity:2.5,bias:-5e-4}},wireframe:{enabled:!1,color:"#000000",opacity:1},background:{enabled:!1,type:"color",color:"#1c1c1d",imageUrl:""},groundShadows:{enabled:!1,mode:"shadowCatcher",intensity:.7,borderFade:1,height:0,size:10},postProcessing:Fo,animations:zo,annotations:[]};function Ie(e){let t=d=>{throw new Error(`Invalid section: ${d}`)},o=d=>d&&typeof d=="object"&&!Array.isArray(d)?d:t("expected an object"),n=d=>typeof d=="string"&&d.trim().length>0&&d.length<=200?d:t("expected a nonempty name or id (up to 200 characters)"),r=d=>typeof d=="number"&&Number.isFinite(d)&&d>=0&&d<=1?d:t("position must be between 0 and 1"),i=d=>!Array.isArray(d)||d.length!==3||!d.every(u=>typeof u=="number"&&Number.isFinite(u))||Math.hypot(...d)<1e-8?t("normal must be a finite, nonzero vector"):[...d],s=d=>{let u=o(d);return!["x","y","z"].includes(u.axis)||typeof u.enabled!="boolean"||typeof u.flip!="boolean"?t("invalid plane"):{enabled:u.enabled,axis:u.axis,position:r(u.position),flip:u.flip,...u.normal!==void 0?{normal:i(u.normal)}:{}}},a=d=>{let u=o(d),f=s(u);if(u.mode!==void 0){if(!["plane","planes","box"].includes(u.mode))return t("invalid mode");f.mode=u.mode}if(u.planes!==void 0){if(!Array.isArray(u.planes)||u.planes.length>6)return t("at most six planes are supported");let p=new Set;f.planes=u.planes.map(O=>{let T=o(O),x=n(T.id);return p.has(x)?t("duplicate plane id"):(p.add(x),{...s(T),id:x,name:n(T.name)})})}if(u.activePlaneId!==void 0&&(f.activePlaneId=n(u.activePlaneId)),u.invertBox!==void 0){if(typeof u.invertBox!="boolean")return t("invalid box inversion");f.invertBox=u.invertBox}if(u.box!==void 0){let p=o(u.box),O=w=>!Array.isArray(w)||w.length!==3?t("invalid box bounds"):w.map(r),T=O(p.min),x=O(p.max);if(T.some((w,A)=>w>=x[A]))return t("box minimum must be below its maximum on every axis");f.box={min:T,max:x}}return f},c=o(e),l=a(c);if(c.presets!==void 0){if(!Array.isArray(c.presets)||c.presets.length>32)return t("at most 32 presets are supported");let d=new Set;l.presets=c.presets.map(u=>{let f=o(u),p=n(f.id);return d.has(p)?t("duplicate preset id"):(d.add(p),{id:p,name:n(f.name),settings:a(f.settings)})})}return l}function Jt(e){let{presets:t,...o}=Ie(e);return o}var lt=require("three"),dt=["position","rotation","scale","visible","baseColor","emissive","opacity","roughness","metalness","emissiveIntensity"],ut=["linear","ease-in","ease-out","ease-in-out","step"],qo=new Set(["position","rotation","scale"]),$o=new Set(["baseColor","emissive"]),ge=e=>typeof e=="string"&&e.length>0&&e.length<=256,he=e=>typeof e=="number"&&Number.isFinite(e),at=e=>Array.isArray(e)&&e.length===3&&e.every(he);function Pe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function be(e){throw new Error(`Invalid sequences: ${e}`)}function Go(e){return e.kind==="object"?JSON.stringify([e.kind,e.objectId,e.property]):e.kind==="clip"?JSON.stringify([e.kind,e.clip]):"camera"}function Ho(e,t){if(t.kind==="camera")return Pe(e)&&at(e.position)&&at(e.target)&&(e.fov===null||he(e.fov)&&e.fov>0&&e.fov<180)&&he(e.zoom)&&e.zoom>0;if(t.kind==="clip")return he(e)&&e>=0;let o=t.property;return qo.has(o)?at(e)&&(o!=="scale"||e.every(n=>n!==0)):$o.has(o)?typeof e=="string"&&/^#[\da-f]{6}$/i.test(e):o==="visible"?typeof e=="boolean":he(e)&&e>=0&&(o==="emissiveIntensity"||e<=1)}function Me(e){(!Array.isArray(e)||e.length>64)&&be("expected up to 64 sequences.");let t=new Set,o=0;return e.map(n=>{(!Pe(n)||!ge(n.id)||t.has(n.id)||!(typeof n.name=="string"&&ge(n.name.trim()))||!he(n.duration)||n.duration<.1||n.duration>3600||typeof n.loop!="boolean"||typeof n.autoPlay!="boolean"||!Array.isArray(n.tracks)||n.tracks.length>128)&&be("each sequence needs a unique id, name, 0.1\u20133600 second duration, loop/autoplay flags and up to 128 tracks."),t.add(n.id);let r=new Set,i=new Set,s=n.tracks.map(a=>{(!Pe(a)||!ge(a.id)||r.has(a.id)||!(typeof a.name=="string"&&ge(a.name.trim()))||!Pe(a.target)||!Array.isArray(a.keyframes)||a.keyframes.length>2048||a.muted!==void 0&&typeof a.muted!="boolean")&&be("invalid or duplicate track."),r.add(a.id);let c;a.target.kind==="camera"?c={kind:"camera"}:a.target.kind==="clip"&&ge(a.target.clip)?c={kind:"clip",clip:a.target.clip}:a.target.kind==="object"&&ge(a.target.objectId)&&dt.includes(a.target.property)?c={kind:"object",objectId:a.target.objectId,property:a.target.property}:be("unknown track target or property.");let l=Go(c);i.has(l)&&be("only one track may own each target property in a sequence."),i.add(l);let d=new Set,u=new Set,f=a.keyframes.map(p=>{++o>2e4&&be("too many keyframes."),(!Pe(p)||!ge(p.id)||d.has(p.id)||!he(p.time)||p.time<0||p.time>n.duration||u.has(p.time)||p.easing!==void 0&&!ut.includes(p.easing)||!Ho(p.value,c))&&be("keyframes need unique ids/times, valid values and times inside the sequence."),d.add(p.id),u.add(p.time);let O=p.value,T=c.kind==="camera"?{position:[...O.position],target:[...O.target],fov:O.fov,zoom:O.zoom}:Array.isArray(p.value)?[...p.value]:p.value;return{id:p.id,time:p.time,value:T,...p.easing?{easing:p.easing}:{}}}).sort((p,O)=>p.time-O.time);return{id:a.id,name:a.name.trim(),target:c,keyframes:f,...a.muted!==void 0?{muted:a.muted}:{}}});return{id:n.id,name:n.name.trim(),duration:n.duration,loop:n.loop,autoPlay:n.autoPlay,tracks:s}})}function Ko(e,t="ease-in-out"){let o=Math.max(0,Math.min(1,e));return t==="step"?0:t==="ease-in"?o*o:t==="ease-out"?1-(1-o)**2:t==="ease-in-out"?o*o*(3-2*o):o}var qe=(e,t,o)=>e+(t-e)*o,ct=(e,t,o)=>e.map((n,r)=>qe(n,t[r],o));function $e(e,t){if(e.muted||!e.keyframes.length||!Number.isFinite(t))return null;let o=e.keyframes;if(t<o[0].time)return null;let n=o[0],r;for(let c of o)if(c.time<=t)n=c;else{r=c;break}if(!r||typeof n.value=="boolean")return structuredClone(n.value);let i=Ko((t-n.time)/(r.time-n.time),n.easing);if(typeof n.value=="number"&&typeof r.value=="number")return qe(n.value,r.value,i);if(typeof n.value=="string"&&typeof r.value=="string")return`#${new lt.Color(n.value).lerp(new lt.Color(r.value),i).getHexString()}`;if(Array.isArray(n.value)&&Array.isArray(r.value))return ct(n.value,r.value,i);let s=n.value,a=r.value;return{position:ct(s.position,a.position,i),target:ct(s.target,a.target,i),fov:s.fov!==null&&a.fov!==null?qe(s.fov,a.fov,i):s.fov,zoom:qe(s.zoom,a.zoom,i)}}function Qt(e,t){return{...e,keyframes:[...e.keyframes.filter(o=>o.id!==t.id&&Math.abs(o.time-t.time)>1e-6),t].sort((o,n)=>o.time-n.time)}}var Z=require("three");function mt(e){return e.id??e.url}function Ae(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected an asset transform object.");let t={};for(let o of["position","rotation","scale"]){let n=e[o];if(n!==void 0){if(!Array.isArray(n)||n.length!==3||!n.every(r=>typeof r=="number"&&Number.isFinite(r))||o==="scale"&&n.some(r=>r===0))throw new Error(`Invalid asset ${o}: expected three finite ${o==="scale"?"nonzero ":""}numbers.`);t[o]=[...n]}}return t}function en(e,t){if(!Number.isFinite(t)||t<=0)throw new Error("Grid size must be positive.");let o=Ae(e),[n,r,i]=o.position??[0,0,0];return{...o,position:[Math.round(n/t)*t,r,Math.round(i/t)*t]}}function tn(e,t){let o=Ae(e),n=o.position??[0,0,0],r=new Z.Matrix4().compose(new Z.Vector3(...n),new Z.Quaternion().setFromEuler(new Z.Euler(...o.rotation??[0,0,0])),new Z.Vector3(...o.scale??[1,1,1])),i=new Z.Box3(new Z.Vector3(...t.min),new Z.Vector3(...t.max)).applyMatrix4(r);if(!Number.isFinite(i.min.y))throw new Error("Cannot place an asset with empty bounds.");return{...o,position:[n[0],n[1]-i.min.y,n[2]]}}var ie=require("three"),Wo=new Map,pt={color:"#93c5fd",intensity:.07},ii=new ie.Color(pt.color).multiplyScalar(pt.intensity),si=new ie.Color(pt.color);var Xo=new Map;function nn(e){return Xo.get(e)}function on(e){for(let t of Wo.values())if(t.texture.source===e.source&&(!t.loaded||t.failed))return!0;return!1}var H=require("three");function rn(e){if(e.length!==3)return null;let t=new H.Vector3(...e[0]).sub(new H.Vector3(...e[1])),o=new H.Vector3(...e[2]).sub(new H.Vector3(...e[1]));return t.lengthSq()===0||o.lengthSq()===0?null:Math.acos(Math.max(-1,Math.min(1,t.normalize().dot(o.normalize()))))*180/Math.PI}function sn(e,t){if(!e.normal)return null;let o=new H.Vector3(...e.normal);if(o.lengthSq()===0)return null;o.normalize();let n=new H.Vector3(...t),r=n.clone().sub(new H.Vector3(...e.position)).dot(o);return{distance:Math.abs(r),projection:n.addScaledVector(o,-r).toArray()}}function an(e){if(e.length<3)return{error:"Pick at least three points to finish the area."};let t=new H.Vector3(...e[0]),o=e.map(x=>new H.Vector3(...x).sub(t)),n=Math.max(...o.map(x=>x.length()));if(n===0)return{error:"Area points must be distinct."};let r=new H.Vector3;for(let x=1;x<o.length-1;x+=1){let w=o[x].clone().cross(o[x+1]);w.lengthSq()>r.lengthSq()&&r.copy(w)}if(r.length()<=n*n*1e-10)return{error:"Area points must not lie on one straight line."};r.normalize();let i=Math.max(n*1e-5,Number.EPSILON*Math.max(...e.flat().map(Math.abs))*32);if(o.some(x=>Math.abs(x.dot(r))>i))return{error:"Area points must lie on one plane."};let s=o.find(x=>x.length()>n*1e-10).clone().normalize(),a=r.clone().cross(s).normalize(),c=o.map(x=>new H.Vector2(x.dot(s),x.dot(a))),l=(x,w,A)=>(w.x-x.x)*(A.y-x.y)-(w.y-x.y)*(A.x-x.x),d=n*n*1e-10,u=(x,w,A)=>Math.abs(l(x,w,A))<=d&&A.x>=Math.min(x.x,w.x)-n*1e-10&&A.x<=Math.max(x.x,w.x)+n*1e-10&&A.y>=Math.min(x.y,w.y)-n*1e-10&&A.y<=Math.max(x.y,w.y)+n*1e-10;for(let x=0;x<c.length;x+=1){let w=c[x],A=c[(x+1)%c.length];if(w.distanceTo(A)<=n*1e-10)return{error:"Area points must be distinct."};for(let g=x+1;g<c.length;g+=1){if(g===x+1||x===0&&g===c.length-1)continue;let y=c[g],v=c[(g+1)%c.length],B=l(w,A,y),k=l(w,A,v),I=l(y,v,w),b=l(y,v,A);if(B*k<0&&I*b<0||u(w,A,y)||u(w,A,v)||u(y,v,w)||u(y,v,A))return{error:"Area edges must not cross or touch each other."}}}let f=0,p=0,O=0;for(let x=0;x<c.length;x+=1){let w=c[x],A=c[(x+1)%c.length],g=w.x*A.y-A.x*w.y;f+=g,p+=(w.x+A.x)*g,O+=(w.y+A.y)*g}if(Math.abs(f)<=d)return{error:"The polygon has no measurable area."};let T=t.clone().addScaledVector(s,p/(3*f)).addScaledVector(a,O/(3*f));return{area:Math.abs(f)/2,center:T.toArray(),triangles:H.ShapeUtils.triangulateShape(c,[])}}function cn(e,t){if(e.length<2)return 0;let o=0;for(let n=1;n<e.length;n+=1)o+=new H.Vector3(...e[n]).distanceTo(new H.Vector3(...e[n-1]));return t&&(o+=new H.Vector3(...e[e.length-1]).distanceTo(new H.Vector3(...e[0]))),o}var gt=["m","cm","mm","in","ft"],ft={m:1,cm:.01,mm:.001,in:.0254,ft:.3048},Yo=["distance","angle","area","pointToPlane","wrap","wrapHorizontal"];function bt(e){return gt.includes(e)}function ht(e={},t="m"){let o=e.displayUnit??t,n=e.metersPerUnit??ft[e.sourceUnit??"m"];if(!Number.isFinite(n)||n<=0)throw new Error("Measurement scale must be a positive finite number.");return{displayUnit:o,metersPerUnit:n,factor:bt(o)?n/ft[o]:1}}function ln(e,t,o,n={}){if(!bt(o)||!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)throw new Error("Calibration needs two distinct points and a positive known distance.");let r=t*ft[o]/e;if(!Number.isFinite(r)||r<=0)throw new Error("Calibration scale is outside the supported range.");return{...n,metersPerUnit:r}}function Ge(e,t){let o=t.map(n=>n.position);if(e==="angle"){let n=rn(o);return n===null?null:{value:n,dimension:0}}if(e==="area"){let n=an(o);return"error"in n?null:{value:n.area,dimension:2}}if(e==="pointToPlane"){let n=t.length===2?sn(t[0],t[1].position):null;return n?{value:n.distance,dimension:1}:null}return t.length<(e==="distance"?2:3)?null:{value:cn(o,e!=="distance"),dimension:1}}function yt(e,t={},o="m",n=e.points,r=e.approximate?"approximate":"ready"){let i=Ge(e.tool,n),{factor:s,displayUnit:a}=ht(t,o),c=r==="ready"||r==="approximate",l=c&&i?i.value*s**i.dimension:null;return{id:e.id,status:c?i&&l!==null&&Number.isFinite(l)?r:"invalid":r,rawValue:c&&i&&Number.isFinite(i.value)?i.value:null,value:l!==null&&Number.isFinite(l)?l:null,unit:e.tool==="angle"?"\xB0":e.tool==="area"?`${a}\xB2`:a}}function ye(e){function t(){throw new Error("Invalid measurements: expected settings and valid named measurements with finite points.")}let o=a=>!!a&&typeof a=="object"&&!Array.isArray(a),n=a=>Array.isArray(a)&&a.length===3&&a.every(c=>typeof c=="number"&&Number.isFinite(c));typeof e=="string"&&(e.length>5*1024*1024&&t(),e=JSON.parse(e)),(!o(e)||e.version!==void 0&&e.version!==1||!o(e.settings)||!Array.isArray(e.items)||e.items.length>256)&&t();let r={};for(let a of["sourceUnit","displayUnit"])e.settings[a]!==void 0&&(bt(e.settings[a])||t(),r[a]=e.settings[a]);e.settings.metersPerUnit!==void 0&&((typeof e.settings.metersPerUnit!="number"||!Number.isFinite(e.settings.metersPerUnit)||e.settings.metersPerUnit<=0)&&t(),r.metersPerUnit=e.settings.metersPerUnit);let i=new Set,s=e.items.map(a=>{(!o(a)||typeof a.id!="string"||!a.id||i.has(a.id)||typeof a.name!="string"||!a.name.trim()||typeof a.modelId!="string"||!a.modelId||!Yo.includes(a.tool)||!Array.isArray(a.points)||a.points.length>8192||typeof a.createdAt!="string"||!Number.isFinite(Date.parse(a.createdAt)))&&t(),i.add(a.id),a.tilesetUrl!==void 0&&a.tilesetUrl!==null&&typeof a.tilesetUrl!="string"&&t(),(a.visible!==void 0&&typeof a.visible!="boolean"||a.approximate!==void 0&&typeof a.approximate!="boolean")&&t();let c=new Set,l=a.points.map(u=>{if((!o(u)||typeof u.id!="number"||!Number.isFinite(u.id)||!n(u.position))&&t(),c.has(u.id)&&t(),c.add(u.id),u.normal!==void 0&&!n(u.normal)&&t(),u.faceVertices!==void 0&&(!Array.isArray(u.faceVertices)||u.faceVertices.length!==3||!u.faceVertices.every(n))&&t(),u.snapped!==void 0&&!["vertex","edge"].includes(u.snapped)&&t(),u.anchor!==void 0){let p=u.anchor;(!o(p)||typeof p.nodeId!="string"||!p.nodeId||!n(p.localPosition)||typeof p.geometrySignature!="string"||typeof p.poseSignature!="string")&&t(),p.localNormal!==void 0&&!n(p.localNormal)&&t(),p.localFaceVertices!==void 0&&(!Array.isArray(p.localFaceVertices)||p.localFaceVertices.length!==3||!p.localFaceVertices.every(n))&&t(),p.instanceId!==void 0&&(!Number.isInteger(p.instanceId)||p.instanceId<0)&&t()}let f=u.anchor;return{id:u.id,position:[...u.position],...u.normal?{normal:[...u.normal]}:{},...u.faceVertices?{faceVertices:u.faceVertices.map(p=>[...p])}:{},...u.snapped?{snapped:u.snapped}:{},...f?{anchor:{nodeId:f.nodeId,localPosition:[...f.localPosition],geometrySignature:f.geometrySignature,poseSignature:f.poseSignature,...f.localNormal?{localNormal:[...f.localNormal]}:{},...f.localFaceVertices?{localFaceVertices:f.localFaceVertices.map(p=>[...p])}:{},...f.instanceId!==void 0?{instanceId:f.instanceId}:{}}}:{}}}),d={id:a.id,name:a.name,modelId:a.modelId,tool:a.tool,points:l,createdAt:a.createdAt,...a.tilesetUrl!==void 0?{tilesetUrl:a.tilesetUrl}:{},...a.visible!==void 0?{visible:a.visible}:{},...a.approximate!==void 0?{approximate:a.approximate}:{}};return Ge(d.tool,l)||t(),d});return{settings:r,items:s}}function dn(e){return JSON.stringify({version:1,...ye(e)},null,2)}function un(e,t,o="m"){let n=ye(e),r=new Map(t?.map(s=>[s.id,s])),i=s=>{let a=String(s??"");return/^[=+@-]/.test(a)&&(a=`'${a}`),`"${a.replace(/"/g,'""')}"`};return[["id","name","modelId","type","status","value","unit","createdAt"],...n.items.map(s=>{let a=r.get(s.id)??yt(s,n.settings,o);return[s.id,s.name,s.modelId,s.tool,a.status,a.value,a.unit,s.createdAt]})].map(s=>s.map(i).join(",")).join(`\r
2
- `)}function He(e){if(!Array.isArray(e)||e.length>128)throw new Error("Invalid selections: expected up to 128 named selection sets.");let t=new Set;return e.map(o=>{if(!o||typeof o!="object"||typeof o.id!="string"||!o.id||t.has(o.id)||typeof o.name!="string"||!o.name.trim()||o.name.length>200||!Array.isArray(o.objectIds)||o.objectIds.length>1e5||o.objectIds.some(n=>typeof n!="string"||!n))throw new Error("Invalid selections: each set needs a unique id, a name, and model object ids.");return t.add(o.id),{id:o.id,name:o.name.trim(),objectIds:[...new Set(o.objectIds)]}})}var pn=new Set(["__proto__","constructor","prototype"]),St=(e,t)=>e<t?-1:e>t?1:0;function L(e){throw new Error(`Invalid product: ${e}`)}var W=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Be=e=>typeof e=="string"&&e.length>0&&e.length<=200&&!pn.has(e),se=e=>typeof e=="string"&&e.trim().length>0&&e.length<=500;function fn(e){let t=0;function o(n,r){return(++t>1e5||r>32)&&L("definition is too complex."),n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)?n:Array.isArray(n)?n.map(i=>o(i,r+1)):(W(n)||L("expected JSON data."),Object.fromEntries(Object.entries(n).filter(([,i])=>i!==void 0).map(([i,s])=>(pn.has(i)&&L("reserved property name."),[i,o(s,r+1)]))))}return o(e,0)}function Zo(e){if(typeof e!="string"||e.length>2048)return!1;try{return["http:","https:"].includes(new URL(e.replace(/\{[a-zA-Z]+\}/g,"x")).protocol)}catch{return!1}}function xt(e){let t=fn(typeof e=="string"?JSON.parse(e):e);(!W(t)||!Be(t.id)||!se(t.label)||!Be(t.revision)||!Array.isArray(t.groups)||!t.groups.length||t.groups.length>64)&&L("id, label, revision, and 1\u201364 option groups are required.");let o=new Map;for(let r of t.groups){(!W(r)||!Be(r.id)||o.has(r.id)||!se(r.label)||r.required!==void 0&&typeof r.required!="boolean"||!Array.isArray(r.options)||!r.options.length||r.options.length>128)&&L("groups need unique ids, labels, and 1\u2013128 options.");let i=new Set;o.set(r.id,i);for(let s of r.options)if((!W(s)||!Be(s.id)||i.has(s.id)||!se(s.label)||s.sku!==void 0&&!se(s.sku))&&L("options need unique ids and labels."),i.add(s.id),s.description!==void 0&&!se(s.description)&&L("an option description must be text."),s.swatch!==void 0&&!(typeof s.swatch=="string"&&/^#[0-9a-f]{3,8}$/i.test(s.swatch))&&L("a swatch must be a hex color."),s.priceDeltaMinor!==void 0&&!Number.isSafeInteger(s.priceDeltaMinor)&&L("a price change must be a whole number of minor units."),s.variants!==void 0&&(!Array.isArray(s.variants)||s.variants.some(a=>!se(a)))&&L("variant names must be strings."),s.appearance!==void 0){(!Array.isArray(s.appearance)||s.appearance.length>128)&&L("invalid appearance edits.");for(let a of s.appearance){W(a)||L("invalid appearance edit.");let c=a.target;typeof c=="string"&&c||Array.isArray(c)&&c.every(l=>typeof l=="string"&&!!l)||W(c)&&Object.keys(c).length===1&&["group","tag","type"].some(l=>typeof c[l]=="string")||L("appearance needs an object id, id list, or selector."),a.visible!==void 0&&typeof a.visible!="boolean"&&L("visibility must be boolean."),a.material!==void 0&&!W(a.material)&&L("material must be an object.");for(let l of Object.values(a.material??{}))typeof l=="string"||typeof l=="number"||typeof l=="boolean"||l===null||W(l)&&typeof l.path=="string"&&(l.offset===void 0||Array.isArray(l.offset)&&l.offset.length===2&&l.offset.every(d=>typeof d=="number"))||L("invalid material field.")}}r.defaultOptionId!==void 0&&!i.has(r.defaultOptionId)&&L("a default must name an option in its group."),r.display!==void 0&&!["list","chips","swatches"].includes(r.display)&&L("a group's display must be list, chips or swatches.")}t.pricing!==void 0&&!(W(t.pricing)&&/^[A-Z]{3}$/.test(t.pricing.currency)&&Number.isSafeInteger(t.pricing.basePriceMinor)&&t.pricing.basePriceMinor>=0)&&L("pricing needs a 3-letter currency and a base price of zero or more."),t.checkout!==void 0&&(!W(t.checkout)||t.checkout.label!==void 0&&!se(t.checkout.label)||!Zo(t.checkout.urlTemplate))&&L("a checkout link needs an http or https URL.");let n=r=>W(r)&&typeof r.groupId=="string"&&typeof r.optionId=="string"&&!!o.get(r.groupId)?.has(r.optionId);if(t.rules!==void 0){(!Array.isArray(t.rules)||t.rules.length>2048)&&L("invalid rules.");let r=new Set;for(let i of t.rules){(!W(i)||!Be(i.id)||r.has(i.id)||!n(i.when)||i.message!==void 0&&!se(i.message))&&L("rules need unique ids and valid option references."),r.add(i.id),["requires","excludes"].some(s=>Array.isArray(i[s])&&i[s].length>0)||L("a rule needs a requires or excludes constraint.");for(let s of["requires","excludes"])i[s]!==void 0&&(!Array.isArray(i[s])||i[s].length>128||!i[s].every(n))&&L("rule references must name existing options.")}}if(t.skus!==void 0){(!Array.isArray(t.skus)||t.skus.length>4096)&&L("invalid SKU table.");let r=new Set;for(let i of t.skus){(!W(i)||!se(i.sku)||!W(i.selections)||Object.keys(i.selections).length!==o.size)&&L("SKU mappings need one selection per group.");for(let[a,c]of Object.entries(i.selections))(!o.has(a)||c!==null&&!o.get(a).has(c))&&L("SKU mapping references an unknown option.");let s=JSON.stringify(Object.entries(i.selections).sort(([a],[c])=>St(a,c)));r.has(s)&&L("a combination can map to only one SKU."),r.add(s)}}return{id:t.id,label:t.label,revision:t.revision,groups:t.groups.map(r=>({id:r.id,label:r.label,...r.required!==void 0?{required:r.required}:{},...r.defaultOptionId!==void 0?{defaultOptionId:r.defaultOptionId}:{},...r.display!==void 0?{display:r.display}:{},options:r.options.map(i=>({id:i.id,label:i.label,...i.sku!==void 0?{sku:i.sku}:{},...i.description!==void 0?{description:i.description}:{},...i.swatch!==void 0?{swatch:i.swatch}:{},...i.priceDeltaMinor!==void 0?{priceDeltaMinor:i.priceDeltaMinor}:{},...i.variants!==void 0?{variants:i.variants}:{},...i.appearance!==void 0?{appearance:i.appearance.map(s=>({target:s.target,...s.material!==void 0?{material:s.material}:{},...s.visible!==void 0?{visible:s.visible}:{}}))}:{}}))})),...t.rules!==void 0?{rules:t.rules.map(r=>({id:r.id,when:r.when,...r.requires?{requires:r.requires}:{},...r.excludes?{excludes:r.excludes}:{},...r.message?{message:r.message}:{}}))}:{},...t.skus!==void 0?{skus:t.skus.map(r=>({sku:r.sku,selections:r.selections}))}:{},...t.pricing!==void 0?{pricing:{currency:t.pricing.currency,basePriceMinor:t.pricing.basePriceMinor}}:{},...t.checkout!==void 0?{checkout:{urlTemplate:t.checkout.urlTemplate,...t.checkout.label!==void 0?{label:t.checkout.label}:{}}}:{}}}function ve(e){return Object.fromEntries(e.groups.map(t=>[t.id,t.defaultOptionId??null]))}function Jo(e,t){let o=[];for(let n of e.groups){if(t[n.id]===null)continue;let r=n.options.find(i=>i.id===t[n.id])?.sku;if(!r)return null;o.push(r)}return o.length?o.join("-"):null}function ne(e,t=ve(e),o=1){if(!Number.isSafeInteger(o)||o<1||o>9999)throw new Error("Quantity must be an integer from 1 to 9999.");if(!W(t)||Object.values(t).some(d=>d!==null&&typeof d!="string"))throw new Error("Product selections must map group ids to option ids or null.");let n=[],r=[...e.groups].sort((d,u)=>St(d.id,u.id)),i=Object.fromEntries(r.map(d=>[d.id,!Object.prototype.hasOwnProperty.call(t,d.id)||t[d.id]===void 0?d.defaultOptionId??null:t[d.id]]));for(let d of Object.keys(t).sort())e.groups.some(u=>u.id===d)||n.push({code:"unknown-group",groupIds:[d],message:`Unknown option group: ${d}.`});let s=[];for(let d of r){let u=i[d.id],f=d.options.find(p=>p.id===u);u!==null&&!f?n.push({code:"unknown-option",groupIds:[d.id],message:`Unknown choice for ${d.label}: ${u}.`}):d.required&&u===null&&n.push({code:"required",groupIds:[d.id],message:`Choose ${d.label}.`}),f&&s.push({groupId:d.id,optionId:f.id,label:f.label,...f.sku?{sku:f.sku}:{}})}let a=d=>e.groups.find(u=>u.id===d.groupId)?.options.find(u=>u.id===d.optionId)?.label??d.optionId;for(let d of[...e.rules??[]].sort((u,f)=>St(u.id,f.id)))if(i[d.when.groupId]===d.when.optionId){for(let u of d.requires??[])i[u.groupId]!==u.optionId&&n.push({code:"requires",ruleId:d.id,groupIds:[...new Set([d.when.groupId,u.groupId])],message:d.message??`${a(d.when)} requires ${a(u)}.`});for(let u of d.excludes??[])i[u.groupId]===u.optionId&&n.push({code:"excludes",ruleId:d.id,groupIds:[...new Set([d.when.groupId,u.groupId])],message:d.message??`${a(d.when)} cannot be combined with ${a(u)}.`})}let c=e.skus?.length?e.skus.find(d=>r.every(u=>d.selections[u.id]===i[u.id]))?.sku??null:Jo(e,i);e.skus?.length&&!c&&!n.length&&n.push({code:"sku",groupIds:r.map(d=>d.id),message:"This combination has no product SKU."});let l=JSON.stringify({productId:e.id,revision:e.revision,quantity:o,selections:i});return{version:1,productId:e.id,revision:e.revision,key:l,quantity:o,selections:i,sku:c,items:s,valid:!n.length,issues:n}}var gn=new Set(["requires","excludes"]);function Ke(e,t,o,n,r=1){let i={...ne(e,t,r).selections,[o]:n},s=new Set([JSON.stringify(i)]),a=[i];for(let c=0;c<a.length&&c<2e3;c++){let l=a[c],d=ne(e,l,r).issues.filter(u=>gn.has(u.code));if(!d.length)return l;for(let u of new Set(d.flatMap(f=>f.groupIds))){if(u===o)continue;let f=e.groups.find(p=>p.id===u);if(f)for(let p of[...f.options.map(O=>O.id),...f.required?[]:[null]]){let O={...l,[u]:p},T=JSON.stringify(O);s.has(T)||(s.add(T),a.push(O))}}}return null}function Qo(e,t,o,n,r){let i=Ke(e,t,o,n,r);return i?Object.entries(i).filter(([s,a])=>s!==o&&a!==t[s]&&a!==null).map(([s,a])=>({groupId:s,optionId:a})):null}function bn(e,t){if(!e.pricing)return null;let o=e.pricing.basePriceMinor;for(let n of t.items)o+=e.groups.find(r=>r.id===n.groupId)?.options.find(r=>r.id===n.optionId)?.priceDeltaMinor??0;return{amountMinor:Math.max(0,o)*t.quantity,currency:e.pricing.currency}}function hn(e,t,o=!1){try{let n=new Intl.NumberFormat(void 0,{style:"currency",currency:t,...o?{signDisplay:"exceptZero"}:{}});return n.format(e/10**(n.resolvedOptions().maximumFractionDigits??2))}catch{return`${e} ${t}`}}function yn(e,t){let o=e.checkout?.urlTemplate;if(!o||!t.valid||o.includes("{sku}")&&!t.sku)return null;let n={sku:t.sku??"",quantity:String(t.quantity),productId:e.id,revision:e.revision,selections:wt(t.selections)};return o.replace(/\{([a-zA-Z]+)\}/g,(r,i)=>Object.prototype.hasOwnProperty.call(n,i)?encodeURIComponent(n[i]):r)}function wt(e){return Object.entries(e).filter(([,t])=>t!==null).map(([t,o])=>`${encodeURIComponent(t)}:${encodeURIComponent(o)}`).join(",")}function Sn(e,t){let o={...ve(t)};for(let n of e.split(",")){let[r,i]=n.split(":");if(!r||!i)continue;let s,a;try{s=decodeURIComponent(r),a=decodeURIComponent(i)}catch{continue}t.groups.find(c=>c.id===s)?.options.some(c=>c.id===a)&&(o[s]=a)}return o}var mn=4096;function xn(e,t="-"){let o=[{}];for(let i of e.groups){let s=[...i.options.map(a=>a.id),...i.required?[]:[null]];if(o.length*s.length>mn*8)throw new Error("This product has too many combinations to list. Use a pricing service to resolve SKUs instead.");o=o.flatMap(a=>s.map(c=>({...a,[i.id]:c})))}let n={...e,skus:void 0},r=[];for(let i of o){if(ne(n,i).issues.length)continue;let s=e.groups.flatMap(a=>{let c=i[a.id];return c===null?[]:[a.options.find(l=>l.id===c)?.sku??null]});if(!(!s.length||s.includes(null))&&(r.push({sku:s.join(t),selections:i}),r.length>mn))throw new Error("This product has too many combinations to list. Use a pricing service to resolve SKUs instead.")}return r}function wn(e,t={},o){let n=[],r=ve(e),i=ne({...e,skus:void 0},r).issues.filter(a=>gn.has(a.code));for(let a of i)n.push({code:"invalid-default",message:`The default choices conflict: ${a.message}`});e.checkout?.urlTemplate.includes("{sku}")&&!e.skus?.length&&e.groups.some(a=>a.options.some(c=>!c.sku))&&n.push({code:"missing-sku",message:"The buy link uses {sku}, but it won't appear until every option has an SKU."});let s=Object.keys(t).length>0;for(let a of e.groups)for(let c of a.options){let l=`${a.label} \u203A ${c.label}`,d={groupId:a.id,optionId:c.id};if(s)for(let f of c.appearance??[])Y(t,f.target).length||n.push({code:"no-objects",message:`${l} changes objects that aren't in this model.`,...d});if(o)for(let f of c.variants??[])o.includes(f)||n.push({code:"missing-variant",message:`${l} uses a material variant this model doesn't have: ${f}.`,...d});let u={...r,[a.id]:c.id};Ke(e,u,a.id,c.id)||n.push({code:"unreachable",message:`The rules leave no way to choose ${l}.`,...d})}return n}function Mn(e,t,o,n=1){return t=ne(e,t,n).selections,e.groups.flatMap(r=>r.options.map(i=>{let a=ne(e,{...t,[r.id]:i.id},n).issues.filter(d=>d.groupIds.includes(r.id)&&d.code!=="sku").map(d=>d.message),c=o?.options?.find(d=>d.groupId===r.id&&d.optionId===i.id);c?.available===!1&&a.push(c.reason??"Currently unavailable.");let l=a.length&&c?.available!==!1?Qo(e,t,r.id,i.id,n):null;return{groupId:r.id,optionId:i.id,selected:t[r.id]===i.id,available:!a.length,...l?{fix:l}:{},reasons:[...new Set(a)]}}))}function We(e){W(e)||L("expected a product definition and selections.");let t=xt(e.definition),o=ne(t,e.selections??ve(t));return o.issues.some(n=>n.code==="unknown-group"||n.code==="unknown-option")&&L("selections reference unknown options."),{definition:t,selections:o.selections}}function An(e){return JSON.stringify({version:1,productId:e.productId,revision:e.revision,quantity:e.quantity,selections:e.selections})}function vn(e,t){let o=fn(typeof e=="string"?JSON.parse(e):e);if(!W(o)||o.version!==1||o.productId!==t.id||o.revision!==t.revision)throw new Error("This configuration belongs to a different product or revision.");if(!W(o.selections)||!Number.isSafeInteger(o.quantity))throw new Error("Invalid product configuration selections or quantity.");let n=ne(t,o.selections,o.quantity);if(n.issues.some(r=>r.code==="unknown-group"||r.code==="unknown-option"))throw new Error("This configuration references unknown product options.");return n}function Cn(e,t,o=[],n=[]){let r=e,i=[...o];if(!t)return{objectBindings:r,activeVariants:i};for(let s of t.definition.groups){let a=s.options.find(c=>c.id===(t.selections[s.id]===void 0?s.defaultOptionId:t.selections[s.id]));if(a){for(let c of a.appearance??[])r=Ue(r,c.target,{...c.material!==void 0?{style:{material:c.material}}:{},...c.visible!==void 0?{visible:c.visible}:{}});if(a.variants?.length){let c=new Set(s.options.flatMap(l=>l.variants??[]));i=i.filter(l=>!c.has(l));for(let l of a.variants)i=_e(i,l,n)}}}return{objectBindings:r,activeVariants:i}}var ae=5*1024*1024,er=["activeModelId","modelUrl","modelFormat","tilesetUrl","models","mergeModels","sceneConfig","isolation","multiSelectedKeys","activeAnnotation","annotationCategories","backgroundColor","shadows","cinematic","cameraControllerType","objectTransformSpace","arScaleMode","usdzUrl","measurements","measurementSettings","measurementUnit","measurementModelId"];function C(e,t){throw new Error(`Invalid viewer state at ${e}: ${t}`)}function K(e,t){(!e||typeof e!="object"||Array.isArray(e))&&C(t,"expected an object.")}function Ee(e,t){(!Array.isArray(e)||!e.every(o=>typeof o=="string"))&&C(t,"expected strings.")}function ee(e,t,o){(!Array.isArray(e)||e.length!==t||!e.every(n=>typeof n=="number"&&Number.isFinite(n)))&&C(o,`expected ${t} finite numbers.`)}function tr(e){let t=new Set,o=0;function n(r,i,s){if((++o>2e5||s>64)&&C(i,"configuration is too complex."),r===null||typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return r;(typeof r!="object"||!r)&&C(i,"expected JSON data (finite numbers, no functions)."),t.has(r)&&C(i,"cyclic data."),!Array.isArray(r)&&Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null&&C(i,"expected plain JSON data."),t.add(r);let a=Array.isArray(r)?[]:{};for(let[c,l]of Object.entries(r))["__proto__","constructor","prototype"].includes(c)&&C(`${i}.${c}`,"reserved property."),l!==void 0?a[c]=n(l,`${i}.${c}`,s+1):Array.isArray(r)&&C(i,"undefined array entry.");return t.delete(r),a}return n(e,"state",0)}function te(e,t,o,n,r=!1,i){let s=e[t];if(s==null||s==="")return;typeof s!="string"&&C(o,"expected a URL.");let a=r?nn(s)??s:s;if(a.trim().startsWith("blob:")){if(r&&i){i.set(s,{source:a,path:o});return}C(o,r?"this image is temporary. Use getStateAsync() for JSON or createShareUrl() to include it.":"upload this model/environment asset to a durable URL before saving or sharing.")}if(a!==s&&(s=a,e[t]=a),r&&/^data:image\//i.test(s))return;let c;try{c=new URL(s,n??"https://relative.invalid/")}catch{C(o,"invalid asset URL.")}["http:","https:"].includes(c.protocol)||C(o,"use an HTTP(S) asset URL."),n&&(e[t]=c.href)}function nr(e,t){K(e,t),ee(e.position,3,`${t}.position`),ee(e.target,3,`${t}.target`),(typeof e.zoom!="number"||e.zoom<=0)&&C(t,"zoom must be positive."),e.fov!==null&&(typeof e.fov!="number"||e.fov<=0||e.fov>=180)&&C(t,"fov must be null or between 0 and 180.");for(let o of["azimuthAngle","polarAngle"])e[o]!==void 0&&typeof e[o]!="number"&&C(t,`${o} must be a number.`)}function jn(e,t,o,n){K(e,t),(typeof e.id!="number"||typeof e.title!="string"||typeof e.description!="string")&&C(t,"expected an annotation id, title and description.");for(let r of["worldPosition","localPosition"])ee(e[r],3,`${t}.${r}`);e.images!==void 0&&(Array.isArray(e.images)||C(t,"images must be an array."),e.images.forEach(r=>{K(r,t),te(r,"src",t,o,!0,n)})),e.links!==void 0&&(Array.isArray(e.links)||C(t,"links must be an array."),e.links.forEach(r=>{K(r,t),te(r,"href",t,o,!1,n)}))}function Tn(e,t){K(e,t),e.waypoints!==void 0&&(Array.isArray(e.waypoints)||C(t,"expected waypoints."),e.waypoints.forEach(o=>{K(o,t),ee(o.position,3,t),ee(o.target,3,t)}));for(let o of["enabled","loop","autoPlay"])e[o]!==void 0&&typeof e[o]!="boolean"&&C(t,`${o} must be boolean.`);e.duration!==void 0&&(typeof e.duration!="number"||e.duration<=0)&&C(t,"duration must be positive.")}function Mt(e,t,o){if(t!==null)if(Array.isArray(t))Array.isArray(e)||C(o,"expected an array."),t.length&&e.forEach(n=>Mt(n,t[0],o));else if(typeof t=="object"){K(e,o);for(let[n,r]of Object.entries(t))Mt(e[n],r,`${o}.${n}`)}else typeof e!=typeof t&&C(o,`expected ${typeof t}.`)}function On(e,t,o,n){if(Mt(e,pe,t),e.measurements!==void 0&&(e.measurements=ye(e.measurements)),e.sequences!==void 0&&(e.sequences=Me(e.sequences)),e.selectionSets!==void 0&&(e.selectionSets=He(e.selectionSets)),e.product!==void 0&&(e.product=We(e.product),e.product.definition.groups.forEach(r=>r.options.forEach(i=>i.appearance?.forEach(s=>{for(let[a,c]of Object.entries(s.material??{}))c&&typeof c=="object"&&!Array.isArray(c)&&"path"in c&&te(c,"path",`${t}.product.material.${a}.path`,o,!0,n)})))),ee(e.model.rotation,3,`${t}.model.rotation`),e.lighting.lights.forEach(r=>ee(r.position,3,`${t}.lighting.lights`)),e.annotations.forEach(r=>jn(r,`${t}.annotations`,o,n)),e.animations.autoplayClip!==null&&typeof e.animations.autoplayClip!="string"&&C(t,"invalid autoplay clip."),e.animations.clips.forEach(r=>{K(r,t),(typeof r.sourceName!="string"||typeof r.displayName!="string"||typeof r.hidden!="boolean"||typeof r.speed!="number"||!["repeat","once","ping-pong"].includes(r.loopMode))&&C(t,"invalid animation clip settings.")}),e.cinematic!==void 0&&Tn(e.cinematic,`${t}.cinematic`),e.styleRules!==void 0&&!Array.isArray(e.styleRules)&&C(t,"styleRules must be an array."),te(e.environment,"customEnvironmentUrl",`${t}.environment`,o,!1,n),te(e.background,"imageUrl",`${t}.background`,o,!0,n),e.model.activeVariants!==void 0&&Ee(e.model.activeVariants,t),e.section!==void 0)try{e.section=Ie(e.section)}catch(r){C(`${t}.section`,r.message)}}function Rn(e,t,o,n){K(e,t);for(let[r,i]of Object.entries(e)){let s=`${t}.${r}`;K(i,s),(typeof i.id!="string"||typeof i.modelObjectId!="string")&&C(s,"expected binding id and modelObjectId.");for(let a of["label","group","type","status"])i[a]!==void 0&&typeof i[a]!="string"&&C(s,`${a} must be a string.`);i.tags!==void 0&&Ee(i.tags,s),i.metadata!==void 0&&K(i.metadata,`${s}.metadata`),i.metrics!==void 0&&(K(i.metrics,s),Object.values(i.metrics).some(a=>typeof a!="number")&&C(s,"metrics must be numbers.")),i.actions!==void 0&&(Array.isArray(i.actions)||C(s,"actions must be an array."),i.actions.forEach(a=>{K(a,s),(typeof a.id!="string"||typeof a.label!="string"||a.type!=="command"||a.effects!==void 0&&!Array.isArray(a.effects))&&C(s,"invalid action.")}));for(let a of["visible","removed","selectable","hoverable"])i[a]!==void 0&&typeof i[a]!="boolean"&&C(s,`${a} must be boolean.`);if(i.transform!==void 0){K(i.transform,s);for(let a of["position","rotation","scale","shear"])i.transform[a]!==void 0&&ee(i.transform[a],3,`${s}.transform.${a}`);i.transform.pivot!==void 0&&(K(i.transform.pivot,s),ee(i.transform.pivot.point,3,s),ee(i.transform.pivot.offset,3,s))}if(i.style!==void 0&&(K(i.style,s),i.style.material!==void 0)){K(i.style.material,s);for(let[a,c]of Object.entries(i.style.material))c&&typeof c=="object"&&!Array.isArray(c)&&"path"in c&&te(c,"path",`${s}.style.material.${a}.path`,o,!0,n)}i.decals!==void 0&&(Array.isArray(i.decals)||C(s,"decals must be an array."),i.decals.forEach(a=>{K(a,s),(typeof a.id!="string"||typeof a.size!="number"||a.size<=0)&&C(s,"invalid decal."),ee(a.position,3,s),ee(a.normal,3,s),te(a,"image",s,o,!0,n)}))}}function kn(e,t,o,n){Array.isArray(e)||C(t,"expected merge sources."),e.forEach(r=>{K(r,t),(typeof r.url!="string"||!r.url||typeof r.namePrefix!="string")&&C(t,"expected source URL and prefix."),te(r,"url",t,o,!1,n)})}function or(e,t,o){K(e,"configuration");let n=Object.fromEntries(er.filter(r=>e[r]!==void 0).map(r=>[r,e[r]]));(typeof n.modelUrl!="string"||!n.modelUrl)&&C("configuration.modelUrl","expected the active model URL.");for(let r of["modelUrl","tilesetUrl","usdzUrl"])te(n,r,`configuration.${r}`,t,!1,o);if(n.sceneConfig!==void 0&&On(n.sceneConfig,"configuration.sceneConfig",t,o),n.mergeModels!==void 0&&kn(n.mergeModels,"configuration.mergeModels",t,o),n.models!==void 0){(!Array.isArray(n.models)||n.models.length===0)&&C("configuration.models","expected model entries.");let r=new Set,i=new Set;n.models.forEach(s=>{K(s,"model"),(typeof s.url!="string"||!s.url)&&C("model.url","expected a URL."),te(s,"url","model.url",t,!1,o),s.id!==void 0&&(typeof s.id!="string"||!s.id.trim())&&C("model.id","expected a nonempty instance ID.");let a=mt({id:s.id,url:s.url});i.has(a)&&C("configuration.models","instance identities must be unique; assign IDs when reusing a URL."),i.add(a),s.transform!==void 0&&(s.transform=Ae(s.transform)),s.visible!==void 0&&typeof s.visible!="boolean"&&C("model.visible","expected boolean."),r.add(s.url),Rn(s.objectBindings,"model.objectBindings",t,o),s.sceneConfig!==void 0&&On(s.sceneConfig,"model.sceneConfig",t,o),s.mergeModels!==void 0&&kn(s.mergeModels,"model.mergeModels",t,o)}),n.activeModelId!==void 0&&(typeof n.activeModelId!="string"||!i.has(n.activeModelId))&&C("configuration.activeModelId","active instance is not in models."),n.activeModelId!==void 0&&n.models.find(s=>mt(s)===n.activeModelId)?.url!==n.modelUrl&&C("configuration.modelUrl","source does not match the active instance."),r.has(n.modelUrl)||C("configuration.modelUrl","active model is not in models.")}if(n.multiSelectedKeys!==void 0&&Ee(n.multiSelectedKeys,"configuration.multiSelectedKeys"),n.annotationCategories!==void 0&&n.annotationCategories!==null&&Ee(n.annotationCategories,"configuration.annotationCategories"),n.activeAnnotation!==void 0&&n.activeAnnotation!==null&&jn(n.activeAnnotation,"configuration.activeAnnotation",t,o),n.measurements!==void 0||n.measurementSettings!==void 0){let r=ye({items:n.measurements??[],settings:n.measurementSettings??{}});n.measurements!==void 0&&(n.measurements=r.items),n.measurementSettings!==void 0&&(n.measurementSettings=r.settings)}n.measurementModelId!==void 0&&typeof n.measurementModelId!="string"&&C("configuration.measurementModelId","expected a stable id."),n.measurementUnit!==void 0&&typeof n.measurementUnit!="string"&&C("configuration.measurementUnit","expected a unit label.");for(let r of["backgroundColor"])n[r]!==void 0&&typeof n[r]!="string"&&C(r,"expected a string.");n.shadows!==void 0&&typeof n.shadows!="boolean"&&C("shadows","expected boolean.");for(let[r,i]of Object.entries({modelFormat:["glb","gltf","obj","fbx","usdz","stl","ply"],cameraControllerType:["orbit","pointerLock"],objectTransformSpace:["world","local"],arScaleMode:["normalized","real-world"]}))n[r]!==void 0&&!i.includes(n[r])&&C(r,"unsupported value.");if(n.cinematic!==void 0&&Tn(n.cinematic,"cinematic"),n.isolation!==void 0&&n.isolation!==null){let{target:r,mode:i,ghostOpacity:s}=n.isolation;typeof r=="string"||Array.isArray(r)&&r.every(a=>typeof a=="string")||r&&typeof r=="object"&&["group","tag","type"].some(a=>typeof r[a]=="string")||C("configuration.isolation","invalid target."),i!==void 0&&!["ghost","hide"].includes(i)&&C("configuration.isolation","invalid mode."),s!==void 0&&(typeof s!="number"||s<0||s>1)&&C("configuration.isolation","opacity must be between 0 and 1.")}return n}function In(e,t,o,n){if(!(!e||typeof e!="object"))for(let[r,i]of Object.entries(e))r!=="metadata"&&(typeof i=="string"&&["url","modelUrl","tilesetUrl","usdzUrl","path","image","src","href","imageUrl","customEnvironmentUrl"].includes(r)?te(e,r,`${t}.${r}`,o,["path","image","src","imageUrl"].includes(r),n):In(i,`${t}.${r}`,o,n))}function Pn(e,t,o){typeof e=="string"&&(new TextEncoder().encode(e).length>ae&&C("state","exceeds the 5 MiB limit."),e=JSON.parse(e));let n=tr(e);K(n,"state"),new TextEncoder().encode(JSON.stringify(n)).length>ae&&C("state","exceeds the 5 MiB limit."),n.version!==void 0&&n.version!==1&&C("version","unsupported version."),n.version===void 0&&(n.objectBindings!==void 0||n.configuration!==void 0)&&C("version","full configurations require version 1.");let r={};return n.version!==void 0&&(r.version=1),n.camera!==void 0&&(nr(n.camera,"camera"),r.camera=n.camera),n.hidden!==void 0&&(Ee(n.hidden,"hidden"),r.hidden=n.hidden),n.selected!==void 0&&(n.selected!==null&&typeof n.selected!="string"&&C("selected","expected an object id or null."),r.selected=n.selected),n.objectBindings!==void 0&&(Rn(n.objectBindings,"objectBindings",t,o),r.objectBindings=n.objectBindings),n.configuration!==void 0&&(r.configuration=or(n.configuration,t,o)),In(r,"state",t,o),new TextEncoder().encode(JSON.stringify(r)).length>ae&&C("state","exceeds the 5 MiB limit."),r}function Bn(e,t){return JSON.stringify(Ce(e,t))}function Ce(e,t){return Pn(e,t)}async function Xe(e,t){let o=new Map,n=Pn(e,t,o),r=new Map,i=new Map;for(let[a,{source:c,path:l}]of o){let d=r.get(c);d||(d=(async()=>{let u;try{u=await fetch(c)}catch{C(l,"this temporary image is no longer available. Reload or reselect it before saving.")}u.ok||C(l,"could not read the temporary image. Reload or reselect it before saving.");let f=await u.blob();f.size>ae*3/4&&C(l,"embedded image exceeds the 5 MiB configuration limit. Use a hosted image URL.");let p=new Uint8Array(await f.arrayBuffer()),O=f.type.split(";")[0].toLowerCase(),T=O.startsWith("image/")?O:rr(p);T||C(l,"temporary asset is not a supported image. Use a hosted asset URL.");let x="";for(let w=0;w<p.length;w+=32768)x+=String.fromCharCode(...p.subarray(w,w+32768));return`data:${T};base64,${btoa(x)}`})(),r.set(c,d)),i.set(a,await d)}function s(a){if(!(!a||typeof a!="object"))for(let[c,l]of Object.entries(a))c!=="metadata"&&(["path","image","src","imageUrl"].includes(c)&&typeof l=="string"&&i.has(l)?a[c]=i.get(l):s(l))}return s(n),Ce(n,t)}function rr(e){let t=(o,n)=>String.fromCharCode(...e.subarray(o,n));if(e[0]===137&&t(1,4)==="PNG")return"image/png";if(e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(t(0,3)==="GIF")return"image/gif";if(t(0,4)==="RIFF"&&t(8,12)==="WEBP")return"image/webp";if(t(4,8)==="ftyp"&&["avif","avis"].includes(t(8,12)))return"image/avif";if(/<svg[\s>]/i.test(new TextDecoder().decode(e.subarray(0,1024))))return"image/svg+xml"}var At={verifyingLicense:"Verifying License",checkingYourLicenseKey:"Checking your license key...",invalidLicense:"Invalid License",licenseHasBeenRevokedOrHasExpired:"License has been revoked or has expired",failedToLoadPleaseContactTheSiteAdministrator:"Failed to load. Please contact the site administrator.",contextRestoringTitle:"Reloading viewer\u2026",contextLostTitle:"3D view interrupted",contextRestoringMessage:"Rebuilding the 3D view. Please wait\u2026",contextLostMessage:"The graphics connection was interrupted. The viewer will rebuild when it returns, or you can reload it now.",reloadViewer:"Reload viewer",texturePositioningHint:"Drag to move \xB7 Scroll to zoom \xB7 Click elsewhere to finish",texturePositioningStartHint:"Double-click to move or zoom",dismiss:"Dismiss",missingUVsAreShownInMagenta:"Missing UVs are shown in magenta.",viewThisModelInARWithAppleQuickLook:"View this model in AR with Apple Quick Look",sequencePlayer:"Sequence player",sequenceSelect:"Sequence",sequencePlay:"Play sequence",sequencePause:"Pause sequence",sequenceStop:"Stop and restore scene",sequencePlayhead:"Sequence playhead",sequenceTime:"Sequence time",sequenceIssues:"Unavailable sequence targets",arConfiguredButton:"AR handoff",arConfiguredTitle:"Take this configuration to AR",arConfiguredDescription:"Your current materials, visible models and placements are included.",arSnapshotStale:"Updating AR to include your latest changes\u2026",arPreparing:"Preparing your scene\u2026",arStart:"Start AR",arStarting:"Starting AR\u2026",arCheckingSupport:"Checking AR support\u2026",arUnavailable:"AR is unavailable in this browser. Open this link in an AR-capable browser on your phone.",arStartFailed:"Could not start AR. Check camera permissions and try again.",arAnimations:"AR animations",arAnimationSelect:"Animation",arAnimationClips:"Model clips",arAnimationSequences:"Sequences",arAnimationPlay:"Play animation",arAnimationPause:"Pause animation",arRefresh:"Refresh AR",arRetry:"Try again",arExportDetails:"Export details",arPrepare:"Prepare AR",arPrepareAgain:"Prepare again",arDownloadUSDZ:"Download USDZ for iPhone/iPad",arScanConfigured:"Scan to open this configuration on your phone.",arOpenConfiguredLink:"Open configuration link",viewInAR:"View in AR",openThisExperienceOnAPhoneForAR:"Open this experience on a phone for AR",openOnPhone:"Open on phone",viewThisModelInYourSpace:"View this model in your space",viewThisModelInVR:"View this model in VR",closePhoneHandoff:"Close phone handoff",arScanCode:"Scan the code and choose AR.",qrCodeToOpenThisModelOnAPhone:"QR code to open this model on a phone",disableUVChecker:"Disable UV checker",enableUVChecker:"Enable UV checker",explodedView:"Exploded view",explodeAmount:"Explode amount",removeSectionCut:"Remove section cut",sectionCut:"Section cut",sectionAxis:"Section axis",sectionPosition:"Section position",keepTheOtherSide:"Keep the other side",pauseCinematic:"Pause cinematic",playCinematic:"Play cinematic",stopCinematicAndResetCamera:"Stop cinematic and reset camera",cancel:"Cancel",annotationCategories:"Annotation categories",annotations:"Annotations",all:"All",uncategorized:"Uncategorized",decalDragHint:"Drag the decal on the object. Release to save; Escape to cancel.",showAll:"Show all",materialVariants:"Material variants",startGuidedTour:"Start guided tour",guidedTour:"Guided Tour",previousAnnotation:"Previous annotation",previous:"Prev",stopGuidedTour:"Stop guided tour",nextAnnotation:"Next annotation",next:"Next",exitFullscreen:"Exit fullscreen",enterFullscreen:"Enter fullscreen",resetCameraView:"Reset camera view",orbitControl:"Orbit Control",pointLock:"Pointer lock",cameraController:"Camera controller",cameraControllerSettings:"Camera controller settings",downloadGLB:"Download GLB",downloadGLBDescription:"All visible models, material edits and animations in one file. No annotations or separate editor model slots. Duplicate mesh names may change on reimport.",downloadCombinedGLB:"Download as one GLB",downloadSeparateGLBs:"Download separate GLBs",downloadSeparateGLBsDescription:"One GLB file per model",downloadPNG:"Download PNG",downloadUVLayout:"Download UV Layout",videoFormat:"Video format",auto:"Auto",recordTurntableVideo:"Record turntable video",recordCinematicVideo:"Record cinematic video",videoUnsupported:"Video recording is not supported in this browser.",downloadOptions:"Download options",exporting:"Exporting\u2026",download:"Download",annotationTitlePlaceholder:"Title *",description:"Description",ok:"OK",arRelocate:"Relocate",tapToPlace:"Tap to place",closeAnnotation:"Close annotation",learnMore:"Learn more",stopMeasuring:"Stop measuring",startMeasuring:"Start measuring",toggleBoundingDimensions:"Toggle bounding dimensions",measurementTool:"Measurement tool",distance:"Distance",angle:"Angle",area:"Area",pointToPlane:"Point to plane",wrap:"Circumference (Edge)",wrapHorizontal:"Circumference (Horizontal)",measurementSnapping:"Measurement snapping",noSnapping:"No snapping",snapAuto:"Snap: auto",snapVertex:"Snap: vertex",snapEdge:"Snap: edge",undoMeasurementPoint:"Undo measurement point",clearMeasurements:"Clear measurements",finishArea:"Finish area",savedMeasurements:"Saved measurements ({count})",noSavedMeasurements:"No saved measurements yet. Pick points in the preview, then save a measurement here.",measurementFiles:"Import / export",measurementSourceUnit:"Model units",measurementDisplayUnit:"Display units",measurementName:"Name",measurementNamePlaceholder:"e.g. Door width",saveMeasurement:"Save",knownMeasurementDistance:"Known length",calibrationUnit:"Calibration unit",calibrateMeasurement:"Calibrate",measurementCalibrationHint:"Pick two distance points, enter their known length, then calibrate.",measurementCalibratedScale:"Calibrated: 1 model unit = {scale} m",resetMeasurementCalibration:"Reset calibration",showSavedMeasurement:"Show {name}",renameSavedMeasurement:"Rename {name}",deleteSavedMeasurement:"Delete {name}",exportMeasurementJson:"Export JSON",exportMeasurementCsv:"Export CSV",importMeasurementJson:"Import JSON",measurementReady:"Ready",measurementApproximate:"Approximate LOD",measurementModelChanged:"Different model",measurementObjectMissing:"Object unavailable",measurementGeometryChanged:"Geometry changed \u2014 measure again",measurementPoseChanged:"Pose changed \u2014 measure again",measurementObjectHidden:"Object hidden",measurementInvalid:"Invalid measurement",measurementWaiting:"Waiting for model",openSceneObjectsPanel:"Open scene objects panel",sceneObjects:"Scene Objects",searchNodesLabels:"Search nodes, labels",closeSceneObjectsPanel:"Close scene objects panel",objectNavigator:"Objects in the 3D view",compareBefore:"Before",compareAfter:"After",compareDivider:"Comparison divider",viewIn3D:"View in 3D",objectNavigatorHint:"Arrow keys browse \xB7 Enter selects \xB7 Esc clears",selectionCleared:"Selection cleared",cameraKeyboardHelp:"3D view. Arrow keys orbit, Shift with Up or Down zooms, and W, A, S, D, Space and C move the camera.",isolate:"Isolate",hide:"Hide",show:"Show",closePanel:"Close panel",actions:"Actions",openPanel:"Open panel",close:"Close",position:"Position",decalNudgeHint:"Click to fine-tune \xB7 Hold to move",decalNudgeControls:"Move decal in small steps",text:"Text",yourText:"Your text",textToAdd:"Text to add",textColour:"Text color",addText:"Add text",image:"Image",chooseImage:"Choose image",imageToAdd:"Image to add",added:"Added",colour:"Color",size:"Size",turn:"Turn",rotation:"Rotation",dragTheDecalAcrossTheObjectsSurface:"Drag the decal across the object's surface",move:"Move",remove:"Remove",noneAddedYet:"None added yet",done:"Done",moveForward:"Move forward",moveLeft:"Move left",moveRight:"Move right",moveBackward:"Move backward",productOptions:"Options",productOptionsFor:"{product} options",productReset:"Reset",productOptional:"optional",productNone:"None",productAlsoChanges:"Also changes: {changes}",productUnavailable:"Currently unavailable.",productQuantity:"Quantity",productCheckingPrice:"Checking price and availability\u2026",productTotal:"Total",productAddToCart:"Add to cart",productAddingToCart:"Adding\u2026",productRequestQuote:"Request quote",productRequestingQuote:"Requesting\u2026",productRefresh:"Refresh",productBuy:"Buy now",productCopyLink:"Copy link",productLinkCopied:"Link copied",productShowOptions:"Show options",productHideOptions:"Hide options",productIssues:"Configuration issues",productRequestDone:"Request completed.",productSaved:"Saved: {id}",sceneSettings:"Scene Settings",background:"Background",backgroundColor:"Background Color",showEnvironmentAsBackground:"Show as background",backgroundBlur:"Background Blur",environmentPreset:"Preset",environmentIntensity:"Intensity",toneMapping:"Tone Mapping",toneMappingAces:"ACES Filmic",toneMappingAgx:"AgX",toneMappingNeutral:"Neutral",toneMappingNone:"None",ground:"Ground",groundShadow:"Ground Shadow",groundShadowOpacity:"Shadow Opacity",floorGrid:"Floor Grid",display:"Display",wireframe:"Wireframe",autoRotateSpeed:"Rotation Speed",fieldOfView:"Field of View",modelInfo:"Model",modelInfoObjects:"Objects",modelInfoTriangles:"Triangles",modelInfoMaterials:"Materials",resetSettings:"Reset Settings",environment:"Environment",autoRotate:"Auto Rotate",lighting:"Lighting",exposure:"Exposure",ambientLightIntensity:"Ambient Light Intensity",ambientLightColor:"Ambient Light Color",directLightIntensity:"Direct Light Intensity",directLightColor:"Direct Light Color",searchObjects:"Search objects",uploadedModel:"Uploaded model",clear:"Clear",chooseModel:"Choose model",loadingModel:"Loading model...",releaseToLoadYourModel:"Release to load your model",arFindSurface:"Move your device over a flat surface",arReleaseToPlace:"Release to place",arGestureHint:"Pinch to resize \xB7 Twist to rotate",angleFirstArmHint:"Pick the first arm",angleVertexHint:"Pick the angle's vertex",angleSecondArmHint:"Pick the second arm",angleNewHint:"Pick a point to start a new angle",areaNewHint:"Pick a point to start a new area",areaCornersHint:"Pick polygon corners in order, then Finish area",pointToPlaneFaceHint:"Pick the reference face",pointToPlanePointHint:"Pick a point to measure its perpendicular distance",pointToPlaneNewHint:"Pick a face to start a new measurement",distanceHint:"Pick points on the model to measure distances",wrapHint:"Click a point on the surface to measure its circumference, following the surface (best for limbs)",wrapHorizontalHint:"Click a point to measure a level circumference around it (best for the torso/waist)",visibleEntries:"{count} visible entries",objectCount:"{count} objects",annotationMarker:"Annotation {id}: {title}",recordingVideo:"Recording video \xB7 {progress}%",isolatedObjects:"Isolated: {count} objects",largeModelWarning:"Very large model ({millions}M triangles) \u2014 it may render and move slowly on this device, and click/hover selection on the model is disabled. Use the objects panel to select parts.",preparingLargeModel:"Preparing large model ({millions}M triangles) \u2014 the first display can take a while on this device...",enterAR:"Enter AR",enterVR:"Enter VR",decalImage:"Image {index}",decalText:"Text {index}",decalAdded:"{count} added",up:"up",down:"down",left:"left",right:"right",moveDecal:"Move decal {direction}",moveDecalOnSurface:"Move {direction} on the visible surface",showAllObject:"Show all {name}",isolateObject:"Isolate {name}",isolatedObject:"Isolated: {name}",hideObject:"Hide {name}",showObject:"Show {name}",objectSelected:"{name} selected",objectNavigatorPosition:"{position} of {count}",compareDividerValue:"{before} {percent}%, {after} {rest}%",bindingMismatchOne:"1 object binding doesn't match this model",bindingMismatchMany:"{count} object bindings don't match this model",simpleLargeModelWarning:"Very large model detected ({millions}M triangles) \u2014 it may render and move slowly on this device, and click/hover selection on the model is disabled. Use the scene objects panel to select parts.",dropModelHint:"Drag and drop {formats} here",loadErrorTitle:"This model couldn't be loaded",loadErrorNotFound:"Nothing was found at this address ({status}). Check that modelUrl points to the file.",loadErrorDenied:"The server refused access to the file ({status}). Check that the file is public, or that a signed URL hasn't expired.",loadErrorStatus:"The server responded with {status} when the file was requested.",loadErrorNetwork:"The download was blocked or failed. Check that the URL is correct and, if the file is on another domain, that its server allows cross-origin requests (CORS) from this site.",loadErrorHtml:"The server sent back a web page instead of a model. There's probably no file at this path: many servers answer a missing file with their index.html.",loadErrorInvalidFile:"The file couldn't be read as {format}. Check that it's a valid {format} file.",loadErrorInvalidExplicitFormat:"The file couldn't be read as {format}. Check that it's a valid {format} file and that modelFormat matches it.",loadErrorMissingFormat:"The file couldn't be read as {format}. The URL has no file extension, so set modelFormat to the file's format.",loadErrorPointCloud:"This PLY file is a point cloud: it has points but no faces, and the viewer shows meshes. Turn it into a mesh first, for example with MeshLab or Blender.",measurementReferenceFaceRequired:"Pick a triangle face to define the reference plane.",measurementTooManyPoints:"Finish or clear this measurement before adding more points.",measurementAngleDistinct:"Pick a point away from the angle's vertex.",areaMinimumPoints:"Pick at least three points to finish the area.",areaDistinctPoints:"Area points must be distinct.",areaStraightLine:"Area points must not lie on one straight line.",areaNotPlanar:"Area points must lie on one plane.",areaEdgesCross:"Area edges must not cross or touch each other.",areaZero:"The polygon has no measurable area.",decalSurfaceMissing:"Could not find a surface on this object for the decal.",decalDirectionMissing:"No visible surface in that direction. Try another arrow or rotate the view.",fullscreenExitFailed:"Could not exit fullscreen. Press Escape to exit.",fullscreenEnterFailed:"Could not enter fullscreen. Check your browser or iframe fullscreen permissions and try again.",uvCoordinatesMissing:"This model does not contain UV coordinates.",uvExportFailed:"Could not create the UV layout archive.",videoExportFailed:"Could not export the video.",videoNotReady:"Viewer not ready for video export.",videoExitXR:"Exit the XR session before recording a video.",videoAlreadyRecording:"A video export is already in progress.",videoPathRequired:"Enable a cinematic camera path before recording it.",videoDurationInvalid:"Video duration must be greater than 0 and at most 300 seconds.",videoFrameRateInvalid:"Video frame rate must be between 1 and 60.",videoBitrateInvalid:"Video bitrate must be a positive number.",videoContextLost:"Video export stopped because the WebGL context was lost.",videoTimedOut:"Video export timed out. Keep the viewer tab visible while recording.",videoEncodingFailed:"The browser could not encode the video.",videoEmpty:"The browser produced an empty video.",videoDidNotStart:"Video recording did not start.",videoWebMUnsupported:"Video recording as WEBM is not supported in this browser.",videoMP4Unsupported:"Video recording as MP4 is not supported in this browser.",videoGIFUnsupported:"Video recording as GIF is not supported in this browser.",videoGifWidthInvalid:"GIF width must be a whole number of pixels from 16 to 4096.",environmentApartment:"apartment",environmentCity:"city",environmentDawn:"dawn",environmentForest:"forest",environmentLobby:"lobby",environmentNight:"night",environmentPark:"park",environmentStudio:"studio",environmentSunset:"sunset",environmentWarehouse:"warehouse",color:"Color",material:"Material",texturePreview:"texture preview",noTextureApplied:"No texture applied",noTextureCoordinates:"This part has no texture coordinates, so an image can't be placed on it.",replaceImage:"Replace image",uploadImage:"Upload image",removeTexture:"Remove texture",texturePosition:"Texture position",offsetX:"Offset X",offsetY:"Offset Y",confirmTexturePosition:"Confirm this texture position and exit positioning mode",donePositioning:"Done positioning",textureOffsetHint:"Double-click the object in the preview to drag its texture directly (scroll to zoom), or edit its offset numerically.",actionToggleLight:"Toggle Light",actionChangeLightColor:"Change Light Color",actionSetBrightness:"Set Brightness",actionChangeColor:"Change Color",actionChangeMaterial:"Change Material",actionToggleVisibility:"Toggle Visibility"};var Ci=new Map(Object.entries(At).map(([e,t])=>[t,e]));function En(e){ze(e);let t=[],o=[{node:e,path:"0",parentId:null}];for(;o.length;){let{node:r,path:i,parentId:s}=o.pop(),a=`node:${i}`,c=r.isMesh&&r.name?Te(r):null;t.push({id:a,parentId:s,name:r.name||r.type||"Group",...c?{objectId:c}:{}});for(let l=r.children.length-1;l>=0;l--)o.push({node:r.children[l],path:`${i}/${l}`,parentId:a})}let n=new Set;for(let r=t.length-1;r>=0;r--){let i=t[r];(i.objectId||n.has(i.id))&&(n.add(i.id),i.parentId&&n.add(i.parentId))}return t.filter(r=>n.has(r.id))}function Vn(e){return structuredClone(e.style??{})}function Dn(e,t,o){let n=Y(e,t).filter(i=>!e[i].removed);if(!n.length)return e;let r={...e};for(let i of n)r[i]={...e[i],style:structuredClone(o)};return r}var Se=require("three"),ir=new Set(["KHR_binary_glTF","KHR_draco_mesh_compression","KHR_lights_punctual","KHR_materials_clearcoat","KHR_materials_dispersion","KHR_materials_ior","KHR_materials_sheen","KHR_materials_specular","KHR_materials_transmission","KHR_materials_iridescence","KHR_materials_anisotropy","KHR_materials_unlit","KHR_materials_volume","KHR_texture_basisu","KHR_texture_transform","KHR_mesh_quantization","KHR_materials_emissive_strength","KHR_materials_variants","EXT_materials_bump","EXT_texture_webp","EXT_texture_avif","EXT_meshopt_compression","EXT_mesh_gpu_instancing"]),sr=new WeakMap;function ar(e){let t=sr.get(e);return t?structuredClone(t):void 0}function Nn(e){if(/^(blob|data):/i.test(e))return"Local resource";let t=e.split(/[?#]/,1)[0].replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).slice(0,300)||"Resource"}function cr(e){return/^(blob|data):/i.test(e)?"Local resource":e.split(/[?#]/,1)[0].replace(/\\/g,"/").replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i,"").replace(/^\/+/,"").slice(0,500)||"Resource"}function lr(e){let t=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0?o:null;return{...e.format?{format:e.format}:{},...e.name?{name:Nn(e.name)}:{},sourceBytes:t(e.sourceBytes),loadDurationMs:t(e.loadDurationMs),extensionsUsed:[...new Set(e.extensionsUsed??[])].sort(),extensionsRequired:[...new Set(e.extensionsRequired??[])].sort(),failedResources:[...new Set((e.failedResources??[]).map(cr))].slice(0,50)}}function dr(e){let t=new Set(e.extensionsRequired);return[...new Set([...e.extensionsUsed??[],...t])].sort().map(o=>({name:o,required:t.has(o),recognized:ir.has(o)}))}function ur(e,t){let o=e.image,n=l=>typeof l=="number"&&Number.isSafeInteger(l)&&l>0?l:null,r=n(o?.naturalWidth??o?.width),i=n(o?.naturalHeight??o?.height),s=!!e.isCompressedTexture,a=e.mipmaps.reduce((l,d)=>l+(d.data?.byteLength??0),0),c=r&&i?Math.ceil(r*i*4*(e.generateMipmaps?4/3:1)):null;return{name:e.name?Nn(e.name):t,width:r,height:i,compressed:s,estimatedBytes:s?a||null:c!==null&&Number.isSafeInteger(c)?c:null}}function Ln(e,t={}){let o=lr({...ar(e),...t.source}),n=[],r=new Set,i=new Map,s=new Set,a=new Map,c=new Map,l=new Set,d=new Map,u=0,f=0,p=0,O=0,T=0,x=(b,m)=>{let h=d.get(b)??{count:0,names:[]};h.count++,h.names.length<20&&h.names.push(m||"Unnamed object"),d.set(b,h)},w=b=>{let m=b?.array??b?.data?.array;m?.buffer&&!l.has(m.buffer)&&(l.add(m.buffer),T+=m.buffer.byteLength)};e.traverse(b=>{let m=b;if(!m.isMesh||!m.geometry)return;u++,f+=m.isInstancedMesh?Number.isSafeInteger(m.count)?Math.max(0,m.count??0):0:1;let h=m.geometry,S=h.getAttribute("position"),j=h.getAttribute("uv"),P=m.material?Array.isArray(m.material)?m.material:[m.material]:[];if(!i.has(h)){let R=!!S&&(!Number.isSafeInteger(S.count)||S.count<0);for(let E=0;!R&&S&&E<S.count;E++)if(!Number.isFinite(S.getX(E))||!Number.isFinite(S.getY(E))||!Number.isFinite(S.getZ(E))){R=!0;break}i.set(h,R)}if(i.get(h)&&x("invalid-positions",b.name),S?.count||x("empty-geometry",b.name),j||x("missing-uv",b.name),h.getAttribute("normal")||x("missing-normals",b.name),h.boundingBox&&[...h.boundingBox.min.toArray(),...h.boundingBox.max.toArray()].some(R=>!Number.isFinite(R))&&x("invalid-bounds",b.name),!r.has(h)){r.add(h),p+=Number.isSafeInteger(S?.count)?Math.max(0,S?.count??0):0;let R=h.index?.count??S?.count??0;O+=Number.isSafeInteger(R)?Math.floor(Math.max(0,R)/3):0,Object.values(h.attributes).forEach(w),Object.values(h.morphAttributes).flat().forEach(w),w(h.index)}let q=!1;for(let R of P){s.add(R);let E=a.get(R);if(!E){E=Object.values(R).filter(M=>!!M&&M.isTexture===!0),a.set(R,E);for(let M of E)c.has(M)||c.set(M,`Texture ${c.size+1}`)}for(let M of E){let D=M.channel??0;h.getAttribute(D===0?"uv":`uv${D}`)||(q=!0)}}q&&x("textured-missing-uv",b.name)});let A=(b,m,h,S,j)=>{let P=d.get(b);P&&n.push({code:b,severity:m,title:h,detail:S,suggestion:j,count:P.count,objects:P.names})};A("empty-geometry","error","Empty mesh geometry","Some meshes have no position data.","Remove empty meshes or export their geometry again."),A("invalid-positions","error","Invalid vertex coordinates","Some vertices contain non-finite coordinates.","Repair NaN or infinite vertex positions in the source application, then re-export."),A("invalid-bounds","error","Invalid geometry bounds","Some cached bounds contain non-finite values.","Repair invalid coordinates in the source application and re-export."),A("textured-missing-uv","warning","Textures have no matching UV coordinates","A texture references a UV channel that its mesh does not contain.","Unwrap the affected meshes and export the UV channel used by each texture."),A("missing-uv","info","Meshes without UVs","Solid colors can work without UVs; image textures and surface decals need them.","Add a UV map before applying image textures or decals."),A("missing-normals","info","Meshes without normals","Some loaded meshes lack vertex normals; generated shading may differ from the source.","Export vertex normals to preserve hard edges and smooth surfaces."),u||n.push({code:"no-meshes",severity:"warning",title:"No mesh geometry found",detail:"This scene contains no loaded meshes.",suggestion:"Check that meshes were included in the export. Streamed scenes may still be loading."});let g=[...c].map(([b,m])=>ur(b,m)),y=g.filter(b=>(b.width??0)>4096||(b.height??0)>4096);y.length&&n.push({code:"large-textures",severity:"warning",title:"Large texture dimensions",detail:"Some textures exceed 4096 pixels on one side.",suggestion:"Resize textures for the visible detail needed; use KTX2/Basis where appropriate.",count:y.length,objects:y.slice(0,20).map(b=>b.name)}),O>1e6&&n.push({code:"high-triangle-count",severity:"warning",title:"High geometry count",detail:"The loaded geometry contains more than one million unique triangles.",suggestion:"Simplify hidden detail, create lower-detail exports, or use streamed assets for large scenes."}),s.size>100&&n.push({code:"many-materials",severity:"warning",title:"Many material definitions",detail:"More than 100 materials can increase rendering work.",suggestion:"Reuse materials and atlas compatible textures; inspect runtime draw calls to confirm the cost."});let v=dr(o);for(let b of v.filter(m=>!m.recognized))n.push({code:"unrecognized-extension",severity:b.required?"error":"warning",title:`${b.required?"Required":"Optional"} extension not recognized`,detail:b.name,suggestion:"Export with extensions supported by the bundled loader, or verify the asset's fallback appearance."});o.failedResources?.length&&n.push({code:"failed-resources",severity:"error",title:"Some resources failed to load",detail:"The model may be missing textures or other referenced resources.",suggestion:"Include sidecar files in the ZIP, correct their paths, and check HTTP access and CORS.",count:o.failedResources.length,objects:o.failedResources.slice(0,20)});let B=null,k=[...i.values()].some(Boolean)?new Se.Box3:new Se.Box3().setFromObject(e);!k.isEmpty()&&[...k.min.toArray(),...k.max.toArray(),...k.getSize(new Se.Vector3).toArray()].every(Number.isFinite)&&(B={min:k.min.toArray(),max:k.max.toArray(),center:k.getCenter(new Se.Vector3).toArray(),size:k.getSize(new Se.Vector3).toArray()}),t.scope==="resident-tiles"&&n.unshift({code:"partial-stream",severity:"info",title:"Loaded tiles only",detail:"Geometry and texture counts cover the current resident tiles, not the entire source asset.",suggestion:"Use the live cache/detail statistics to inspect streaming pressure. Rescan after moving the camera."});let I=b=>b.code==="partial-stream"?-1:b.severity==="error"?0:b.severity==="warning"?1:2;return n.sort((b,m)=>I(b)-I(m)),{version:1,status:"ready",scope:t.scope??"asset",source:o,units:o.format==="glb"||o.format==="gltf"?"meters (glTF convention)":"unknown",bounds:B,statistics:{meshes:u,instances:f,geometries:r.size,materials:s.size,textures:c.size,vertices:p,triangles:O,geometryBytes:T,estimatedTextureBytes:g.reduce((b,m)=>b+(m.estimatedBytes??0),0),unknownTextureSizes:g.filter(b=>b.estimatedBytes===null).length,meshesWithoutUvs:d.get("missing-uv")?.count??0,meshesWithoutNormals:d.get("missing-normals")?.count??0},textures:g,extensions:v,issues:n}}var mr=new WeakMap;function Un(e){e.traverse(t=>{let o=mr.get(t);if(o)throw new Error(o)})}var z=require("three");var Ye=require("three");function Ve(e){return e.isSkinnedMesh===!0}function _n(e){let t=[];return e.traverse(o=>{Ve(o)&&t.push(o)}),t}var Oe="reactImmersiveSkinFreeze";function zn(e){return!!e.userData[Oe]}function Fn(e,t,o=[t]){let n=e.userData,r=new Ye.Matrix4().copy(t).invert(),i=n[Oe];if(i){i.frozenInverse.copy(r),i.restWorldTransforms=o.map(c=>c.clone()),e.bindMatrixInverse.copy(r);return}let s={frozenInverse:r,restWorldTransforms:o.map(c=>c.clone()),previousOnBeforeRender:e.onBeforeRender,previousUpdateMatrixWorld:Object.prototype.hasOwnProperty.call(e,"updateMatrixWorld")?e.updateMatrixWorld:void 0};e.bindMatrixInverse.copy(r);let a=e.updateMatrixWorld;e.updateMatrixWorld=function(c){a.call(this,c),e.bindMatrixInverse.copy(s.frozenInverse)},e.onBeforeRender=function(c,l,d,u,f,p){s.previousOnBeforeRender.call(this,c,l,d,u,f,p),e.bindMatrixInverse.copy(s.frozenInverse)},n[Oe]=s}function vt(e){return e.userData[Oe]?.frozenInverse??null}function qn(e){let t=e.userData,o=t[Oe];o&&(e.onBeforeRender=o.previousOnBeforeRender,o.previousUpdateMatrixWorld?e.updateMatrixWorld=o.previousUpdateMatrixWorld:delete e.updateMatrixWorld,delete t[Oe],e.updateMatrixWorld(!0))}function $n(e){let t=e,o=vt(e);o&&t.bindMatrixInverse.copy(o),t.skeleton?.update?.();let n=t.geometry.clone(),r=n.getAttribute("position");if(r){let i=new Ye.Vector3;for(let s=0;s<r.count;s++)t.getVertexPosition(s,i),r.setXYZ(s,i.x,i.y,i.z);r.needsUpdate=!0}return n.deleteAttribute("skinIndex"),n.deleteAttribute("skinWeight"),n.morphAttributes={},n.morphTargetsRelative=!1,n.computeVertexNormals(),n.computeBoundingBox(),n.computeBoundingSphere(),n}var le=require("three"),eo=require("three/examples/jsm/utils/SkeletonUtils.js"),de=require("fflate");var ce=require("three");function Gn(e){let t=e._loopCount;return e.loop===ce.LoopPingPong&&(t&1)===1}function pr(e){return Gn(e)?e.getClip().duration-e.time:e.time}function Hn({root:e,clips:t,getClipConfig:o,onChange:n}){let r=new ce.AnimationMixer(e),i=new Map;for(let{clip:m,sourceName:h}of t)i.set(h,r.clipAction(m));let s=new Map,a=new Set,c=new Map,l=1,d=m=>typeof m=="string",u=m=>d(m)?s.has(m)?[m]:[]:[...s.keys()],f=(m,h)=>{let S=Kt(o(h));S==="once"?m.setLoop(ce.LoopOnce,1):S==="ping-pong"?m.setLoop(ce.LoopPingPong,1/0):m.setLoop(ce.LoopRepeat,1/0),m.clampWhenFinished=S==="once"},p=m=>{m.action.setEffectiveTimeScale(m.reverse?-m.speed:m.speed)},O=m=>{let h=s.get(m);h&&(h.action.stop(),s.delete(m))},T=(m,h={})=>{let S=i.get(m);if(!S||o(m)?.hidden)return;let j=Number.isFinite(h.fade)&&h.fade>0?h.fade:0,P=h.reverse??!1;if(!h.alongside)for(let[M,D]of[...s])M!==m&&(j>0?(s.delete(M),D.action.fadeOut(j),a.add(D.action)):O(M));a.delete(S)&&S.stop();let q=S.getClip().duration,R=s.get(m),E=()=>{S.reset(),P&&(S.time=q),S.play()};if(!R)E(),j>0&&S.fadeIn(j);else{let M=P?S.time<=0:S.time>=q;R.finished&&M&&E(),S.paused=!1,S.enabled=!0,s.delete(m)}f(S,m),R={action:S,speed:o(m)?.speed??c.get(m)??l,reverse:P,finished:!1},R.speed=Fe(R.speed),p(R),s.set(m,R),n()},x=m=>{for(let h of u(m))s.get(h).action.paused=!0;n()},w=m=>{for(let h of u(m))O(h);if(!d(m)){for(let h of a)h.stop();a.clear()}n()},A=(m,h)=>{let S=Fe(m);d(h)?c.set(h,S):l=S;for(let j of u(h)){let P=s.get(j);c.set(j,S),P.speed=S,p(P)}n()},g=(m,h)=>{for(let S of u(h)){let j=s.get(S),P=j.action.getClip().duration,q=Math.min(Math.max(m,0),P);j.action.time=Gn(j.action)?P-q:q,j.finished&&(j.finished=!1,j.action.paused=!0)}r.update(0),n()},y=()=>{for(let[m,h]of[...s]){let S=o(m);if(S?.hidden){O(m);continue}f(h.action,m),S?.speed!==void 0&&(h.speed=Fe(S.speed),p(h))}n()},v=m=>{for(let h of s.values())h.action===m.action&&(h.finished=!0);n()};return r.addEventListener("finished",v),{play:T,pause:x,stop:w,setSpeed:A,seek:g,getState:()=>{let m=[...s].map(([S,j])=>({clip:S,status:j.finished?"finished":j.action.paused?"paused":"playing",time:pr(j.action),duration:j.action.getClip().duration,speed:j.speed,reverse:j.reverse})),h=m[m.length-1];return{currentClip:h?.clip??null,isPlaying:m.some(S=>S.status==="playing"),speed:h?.speed??l,time:h?.time??0,duration:h?.duration??0,active:m}},applyClipConfigs:y,isRunning:()=>{if(a.size>0)return!0;for(let{action:m}of s.values())if(!m.paused&&m.enabled)return!0;return!1},update:m=>{r.update(m);for(let h of a)(!h.enabled||h.getEffectiveWeight()<=0)&&(h.stop(),a.delete(h))},dispose:()=>{r.removeEventListener("finished",v),r.stopAllAction(),r.uncacheRoot(e),s.clear(),a.clear()}}}var Tt=require("three");var Ot=require("react"),Ct=require("three");function Kn(e){return[e.x,e.y,e.z]}function Wn(e,t){let o=new Ct.Vector3,n=new Ct.Vector3;return t.getPosition(o),t.getTarget(n),{position:Kn(o),target:Kn(n),fov:"fov"in e&&typeof e.fov=="number"?e.fov:null,zoom:"zoom"in e&&typeof e.zoom=="number"?e.zoom:1,azimuthAngle:t.azimuthAngle,polarAngle:t.polarAngle}}var oe=require("three");function fr(e){return new oe.Matrix4().set(1,e[0],e[1],0,0,1,e[2],0,0,0,1,0,0,0,0,1)}function kt(e,t){e.matrixAutoUpdate=!t,e.updateMatrix(),t&&(e.matrix.makeRotationFromQuaternion(e.quaternion).multiply(fr(t)).scale(e.scale).setPosition(e.position),e.matrixWorldNeedsUpdate=!0)}function Xn(e,t,o){let n=new oe.Vector3().setFromMatrixColumn(e,0),r=new oe.Vector3().setFromMatrixColumn(e,1),i=new oe.Vector3().setFromMatrixColumn(e,2),s=(O,T)=>{let x=O*(T<0?-1:1);return Math.abs(x-T)<1e-10?T:x},a=s(n.length(),t.x);if(Math.abs(a)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};n.divideScalar(a);let c=n.dot(r);r.addScaledVector(n,-c);let l=s(r.length(),t.y);if(Math.abs(l)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};r.divideScalar(l);let d=n.dot(i);i.addScaledVector(n,-d);let u=r.dot(i);i.addScaledVector(r,-u);let f=s(i.length(),t.z);if(Math.abs(f)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};i.divideScalar(f);let p=[c/l,d/f,u/f].map(O=>Math.abs(O)<1e-10?0:O);return{rotation:new oe.Quaternion().setFromRotationMatrix(new oe.Matrix4().makeBasis(n,r,i)).normalize(),scale:new oe.Vector3(a,l,f),shear:p.some(Boolean)?p:void 0}}var jt=e=>e==="baseColor"?"color":e;function Yn(e){let t=new Set;return e.traverse(o=>{let n=o;if(n.isMesh)for(let r of Array.isArray(n.material)?n.material:[n.material])r&&t.add(r)}),[...t]}function Zn({root:e,controls:t,animations:o,invalidate:n,cameraEnabled:r=()=>!0}){let i=new Map,s=new Map,a=new Map,c=new Set,l=new Map,d=null,u="",f=g=>e()?Gt(e(),g):null,p=g=>{if(g.kind==="camera"){let I=t();if(!I)return null;let b=Wn(I.camera,I);return{position:b.position,target:b.target,fov:b.fov,zoom:b.zoom}}if(g.kind==="clip"){let I=o();return I?.clips.includes(g.clip)?I.getState?.().active.find(b=>b.clip===g.clip)?.time??0:null}let y=f(g.objectId);if(!y)return null;let v=g.property;if(v==="position"||v==="rotation"||v==="scale")return[y[v].x,y[v].y,y[v].z];if(v==="visible")return y.visible;let B=Yn(y).find(I=>I[jt(v)]!==void 0),k=B?B[jt(v)]:void 0;return k?.isColor?`#${k.getHexString()}`:typeof k=="number"?k:null},O=g=>{if(!r())return;let y=t();y&&(y.stop(),y.setLookAt(...g.position,...g.target,!1),g.fov!==null&&"fov"in y.camera&&(y.camera.fov=g.fov,y.camera.updateProjectionMatrix()),y.zoomTo(g.zoom,!1),y.update(0))},T=g=>{if(i.has(g))return;g.updateWorldMatrix(!0,!0);let y=g.matrixAutoUpdate?void 0:Xn(g.matrix,g.scale,g.quaternion).shear;i.set(g,{position:g.position.toArray(),rotation:[g.rotation.x,g.rotation.y,g.rotation.z],scale:g.scale.toArray(),matrix:g.matrix.clone(),auto:g.matrixAutoUpdate,shear:y});for(let v of _n(g))zn(v)||(Fn(v,v.matrixWorld),c.add(v))},x=(g,y)=>{let v=o();v?.stop(g),y&&v&&(v.play(g,{alongside:!0,reverse:y.reverse}),v.setSpeed(y.speed,g),v.seek?.(y.time,g),y.status!=="playing"&&v.pause(g))};return{capture:p,restore:()=>{for(let[g,y]of l)x(g,y);l.clear();for(let[g,y]of i)g.position.fromArray(y.position),g.rotation.set(...y.rotation),g.scale.fromArray(y.scale),g.matrix.copy(y.matrix),g.matrixAutoUpdate=y.auto,g.matrixWorldNeedsUpdate=!0;i.clear(),s.forEach((g,y)=>y.visible=g),s.clear(),a.forEach((g,y)=>{g.forEach((v,B)=>{v instanceof Tt.Color?y[B].copy(v):y[B]=v}),y.needsUpdate=!0}),a.clear(),c.forEach(qn),c.clear(),d&&O(d),d=null,u="",e()?.updateWorldMatrix(!0,!0),n()},inspect:g=>g.tracks.filter(y=>!y.muted&&y.keyframes.length&&(y.target.kind!=="camera"||r())&&p(y.target)===null).map(y=>`Unavailable target: ${y.name}.`),invalidate:n,apply:({sequence:g,time:y,playing:v})=>{let B=g.tracks.filter(b=>b.target.kind!=="camera"||r()).map(b=>({track:b,value:$e(b,y)})).filter(b=>b.value!==null);for(let[b,m]of l)B.some(({track:h})=>h.target.kind==="clip"&&h.target.clip===b)||(x(b,m),l.delete(b));for(let{track:b}of B)if(b.target.kind==="object"&&["position","rotation","scale"].includes(b.target.property)){let m=f(b.target.objectId);m&&T(m)}let k=new Map([...a.keys()].map(b=>[b,b.transparent]));s.forEach((b,m)=>m.visible=b),i.forEach((b,m)=>{m.position.fromArray(b.position),m.rotation.set(...b.rotation),m.scale.fromArray(b.scale),kt(m,b.shear)}),a.forEach((b,m)=>b.forEach((h,S)=>{h instanceof Tt.Color?m[S].copy(h):m[S]=h}));let I=o();for(let{track:b,value:m}of B){if(b.target.kind!=="clip"||!I?.seek||!I.clips.includes(b.target.clip))continue;let h=b.target.clip;l.has(h)||(l.set(h,I.getState?.().active.find(S=>S.clip===h)),I.play(h,{alongside:!0}),I.pause(h)),I.seek(m,h)}for(let{track:b,value:m}of B){let h=b.target;if(h.kind==="clip")continue;if(h.kind==="camera"){d||(d=p(h));let P=JSON.stringify(m);(v||P!==u)&&(O(m),u=P);continue}let S=f(h.objectId);if(!S)continue;let j=h.property;if(j==="visible")s.has(S)||s.set(S,S.visible),S.visible=m;else if(j==="position"||j==="rotation"||j==="scale")j==="rotation"?S.rotation.set(...m):S[j].fromArray(m),kt(S,i.get(S)?.shear);else for(let P of Yn(S)){let q=jt(j),R=P[q];if(R===void 0)continue;let E=a.get(P);if(E||(E=new Map,a.set(P,E)),k.has(P)||k.set(P,P.transparent),E.has(q)||E.set(q,R?.isColor?R.clone():R),R?.isColor?R.set(m):P[q]=m,j==="opacity"){E.has("transparent")||E.set("transparent",P.transparent);let M=m<1||E.get("transparent")===!0;P.transparent=M}}}d&&!B.some(({track:b})=>b.target.kind==="camera")&&(O(d),u=""),k.forEach((b,m)=>{b!==m.transparent&&(m.needsUpdate=!0)}),e()?.updateWorldMatrix(!0,!0)}}}function Jn(e){let t=new Map;return e.map((o,n)=>{let i=o.name.trim()||`Animation ${n+1}`,s=t.get(i)??0;return t.set(i,s+1),{clip:o,sourceName:s===0?i:`${i} (${s+1})`,duration:o.duration}})}var ke=30,gr=12e4,Qn=new Set(["position","quaternion","rotation","scale"]);function br(e){let t=Me(e.sceneConfig?.sequences??[]).find(l=>l.autoPlay),o=e.sceneConfig?.animations.autoplayClip,n=Jn(e.scene.animations),r=n.find(l=>l.sourceName===o),i=e.sceneConfig?.animations.clips.find(l=>l.sourceName===o),s=i?.speed??1,a=Number.isFinite(s)&&s>0?s:1,c=r&&!i?.hidden?r.duration*(i?.loopMode==="ping-pong"?2:1)/a:0;return{sequence:t,autoplay:o,clips:n,duration:Math.max(c,t?.duration??0)}}function to(e,t,o){let n=new Set,r=new Map,i=0,s=0,a=e.map(br),c=Math.max(0,...a.map(l=>l.duration));for(let[l,d]of e.entries()){o?.throwIfAborted();let{sequence:u,autoplay:f}=a[l];if(!u&&!f)continue;let p=(0,eo.clone)(d.scene),O=[],T=[];d.scene.traverse(M=>O.push(M)),p.traverse(M=>T.push(M));let x=new Map;O.forEach((M,D)=>{T[D].uuid=M.uuid,x.set(M,T[D])});let w=ze(p),A=new le.Group;A.matrixAutoUpdate=!1,A.matrix.copy(d.scene.parent?.matrixWorld??new le.Matrix4),A.add(p);let g=new Set(u?.tracks.filter(M=>!M.muted&&M.target.kind==="clip").map(M=>M.target.kind==="clip"?M.target.clip:"")??[]);f&&g.add(f);let y=a[l].clips.map(M=>{if(!g.has(M.sourceName))return M;let D=M.clip.tracks.filter($=>{let _=le.PropertyBinding.parseTrackName($.name),J=le.PropertyBinding.findNode(p,_.nodeName),G=!!J&&Qn.has(_.propertyName)&&J?.type!=="Bone"&&!_.objectName;return G||n.add("Quick Look exports object motion. Skeletal, morph and other clip tracks keep their captured pose."),G});return{...M,clip:new le.AnimationClip(M.clip.name,M.duration,D)}}),v=M=>d.sceneConfig?.animations.clips.find(D=>D.sourceName===M),B=Hn({root:p,clips:y,getClipConfig:v,onChange(){}}),k={...B,clips:y.map(M=>M.sourceName)},I=Zn({root:()=>p,controls:()=>null,animations:()=>k,invalidate(){},cameraEnabled:()=>!1}),b=u?.tracks.filter(M=>{if(M.target.kind==="object"&&w.nodesById[M.target.objectId]?.type==="Bone")return M.muted||n.add("Quick Look keeps skeletal deformation at its captured pose."),!1;let D=M.target.kind==="clip"||M.target.kind==="object"&&Qn.has(M.target.property);return!D&&!M.muted&&n.add("Quick Look exports sequence object motion. Camera, visibility and appearance tracks stay in WebXR."),D}),m=u?{...u,tracks:b??[]}:void 0;m&&I.inspect(m).forEach(M=>n.add(M));let h=y.some(M=>g.has(M.sourceName)&&M.clip.tracks.length&&!v(M.sourceName)?.hidden),S=b?.some(M=>!M.muted&&M.keyframes.length&&M.target.kind==="object");if(!h&&!S){B.dispose();continue}let j=c,P=t.filter(M=>M.sourceIndex===l),q=Math.ceil(j*ke);if(s+=(q+1)*P.length,!Number.isFinite(j)||s>gr)throw B.dispose(),new Error("This animation is too large for browser USDZ conversion. Use arHandoff.createUSDZ for this model.");let R=Object.entries(d.objectBindings??{}).flatMap(([M,D])=>{if(!D.transform)return[];let $=w.nodesById[D.modelObjectId??M];return $?[{node:$,matrix:$.matrix.clone(),position:$.position.clone(),quaternion:$.quaternion.clone(),scale:$.scale.clone()}]:[]}),E=P.map(M=>({target:M,node:x.get(M.source),inverse:M.bakedMatrix.clone().invert(),frames:[]}));try{f&&B.play(f);let M=0;for(let D=0;D<=q;D++){o?.throwIfAborted();let $=Math.min(D/ke,j);B.update($-M),M=$;for(let _ of R)_.node.position.copy(_.position),_.node.quaternion.copy(_.quaternion),_.node.scale.copy(_.scale),_.node.matrix.copy(_.matrix);if(m){let _=m.loop&&$>m.duration?$%m.duration:Math.min($,m.duration);I.apply({sequence:m,time:_,playing:!1})}A.updateMatrixWorld(!0);for(let _ of E){let J=_.node.matrixWorld.clone().multiply(_.target.instanceMatrix).multiply(_.inverse);if(!J.elements.every(Number.isFinite)||J.determinant()<=0)throw new Error("Quick Look animation cannot preserve a reflected or zero-scale transform. Use arHandoff.createUSDZ.");_.frames.push({time:$*ke,matrix:J.toArray()})}}for(let D of E){let $=D.frames[0]?.matrix;$&&D.frames.some(_=>_.matrix.some((J,G)=>Math.abs(J-$[G])>1e-8))&&(r.set(D.target.exported.name,D.frames),i=Math.max(i,j))}}finally{I.restore(),B.dispose()}}return{samples:r,duration:i,warnings:[...n]}}function no(e,t){if(!t.samples.size)return e;let o=(0,de.unzipSync)(e),n=(0,de.strFromU8)(o["model.usda"]);n=n.replace(" metersPerUnit = 1",` startTimeCode = 0
3
- endTimeCode = ${t.duration*ke}
4
- timeCodesPerSecond = ${ke}
5
- framesPerSecond = ${ke}
6
- metersPerUnit = 1`);for(let[s,a]of t.samples){let c=new RegExp(`(def Xform "${s}"[\\s\\S]*?\\n[\\t ]*)matrix4d xformOp:transform = [^\\n]+`);if(!c.test(n))throw new Error("The USDZ exporter produced an unsupported animation layout.");let l=a.map(d=>{let u=[0,4,8,12].map(f=>`(${d.matrix.slice(f,f+4).join(", ")})`);return`${d.time}: (${u.join(", ")})`}).join(`,
7
- `);n=n.replace(c,(d,u)=>`${u}matrix4d xformOp:transform.timeSamples = {
8
- ${l}
9
- }`)}o["model.usda"]=(0,de.strToU8)(n);let r={},i=0;for(let[s,a]of Object.entries(o)){i+=34+(0,de.strToU8)(s).length;let c=i&63;r[s]=c===4?a:[a,{extra:{12345:new Uint8Array(64-c)}}],i=a.length}return(0,de.zipSync)(r,{level:0})}function hr(e,t={}){t.signal?.throwIfAborted();let o=new z.Group,n=new z.Group;o.add(n);let r=new Set,i=[],s=[],a=[],c=new Map,l=[],d=0,u=0,f=()=>{i.forEach(p=>p.dispose()),s.forEach(p=>p.dispose()),a.forEach(p=>p.dispose())};try{for(let[w,{scene:A,objectBindings:g={},materialOverrides:y={}}]of e.entries()){Un(A),A.updateWorldMatrix(!0,!0);let v=new Map(Object.entries(g).map(([B,k])=>[k.modelObjectId??B,B]));A.traverse(B=>{let k=B;if(!k.isMesh||!k.geometry)return;for(let j=B;j;j=j.parent){let P=Te(j)??j.name??j.uuid;if(!j.visible||g[v.get(P)??P]?.visible===!1||g[v.get(P)??P]?.removed)return}let I=Te(k)??k.name??k.uuid,b=y[v.get(I)??I]??k.material;if(!b)throw new Error(`Material for ${I} is not ready. Wait for the model to finish loading.`);let m=Array.isArray(b)?b:[b],h=k.isInstancedMesh?k.count:1;if(k.userData.riDecal&&Ve(k)&&k.parent){let j=vt(k.parent);j&&k.bindMatrixInverse.copy(j)}let S=Ve(k)?$n(k):k.geometry.clone();try{if(!Ve(k)&&k.morphTargetInfluences?.some(q=>q!==0)){let q=S.getAttribute("position"),R=new z.Vector3;for(let E=0;E<q.count;E++)k.getVertexPosition(E,R),q.setXYZ(E,R.x,R.y,R.z);S.morphAttributes={},S.computeVertexNormals()}if(!S.getAttribute("position"))throw new Error(`Mesh ${I} has no positions.`);let j=S.index?.count??S.getAttribute("position").count,P=Array.isArray(b)?S.groups:[{start:0,count:j,materialIndex:0}];if(!P.length)throw new Error(`Mesh ${I} has multiple materials without geometry groups.`);for(let q=0;q<h;q++){let R=k.matrixWorld.clone(),E=new z.Matrix4;k.isInstancedMesh&&(k.getMatrixAt(q,E),R.multiply(E));for(let M of P){let D=m[M.materialIndex??0];if(!D)throw new Error(`A material group on ${I} is missing its material.`);if(!D.visible)continue;let $=D;if(!$.isMeshStandardMaterial||$.wireframe||$.vertexColors)throw new Error(`AR snapshot cannot preserve ${D.type}${$.wireframe?" wireframe":$.vertexColors?" vertex colors":""} on ${I}. Use a PBR material or provide arHandoff.createUSDZ.`);let _=Math.max(M.start,S.drawRange.start),J=Math.min(j,M.start+M.count,S.drawRange.start+S.drawRange.count);if(J<=_)continue;if(_%3||(J-_)%3)throw new Error(`Mesh ${I} has an incomplete triangle range.`);let G=new z.BufferGeometry;i.push(G);let re=Array.from({length:J-_},(V,U)=>S.index?S.index.getX(_+U):_+U);if(R.determinant()<0)for(let V=0;V<re.length;V+=3)[re[V+1],re[V+2]]=[re[V+2],re[V+1]];for(let[V,U]of Object.entries(S.attributes)){let N=new Float32Array(re.length*U.itemSize);for(let F=0;F<re.length;F++)for(let Q=0;Q<U.itemSize;Q++)N[F*U.itemSize+Q]=U.getComponent(re[F],Q);G.setAttribute(V,new z.BufferAttribute(N,U.itemSize))}G.setIndex(re.map((V,U)=>U)),G.applyMatrix4(R);let Ne=G.getAttribute("position");for(let V=0;V<Ne.count;V++)if(![Ne.getX(V),Ne.getY(V),Ne.getZ(V)].every(Number.isFinite))throw new Error(`Mesh ${I} contains invalid coordinates.`);G.getAttribute("normal")||G.computeVertexNormals();let X=$.clone();s.push(X);let Pt=$.userData.reactImmersiveConfiguredEmissive;if(Pt?.isColor&&X.emissive.copy(Pt),X.side===z.DoubleSide){let V=G.toNonIndexed();i.push(V);let U=V.getAttribute("position").count,N=new z.BufferGeometry;i.push(N);for(let[F,Q]of Object.entries(V.attributes)){let Qe=new Float32Array(U*Q.itemSize*2);for(let fe=0;fe<U;fe++)for(let we=0;we<Q.itemSize;we++){Qe[fe*Q.itemSize+we]=Q.getComponent(fe,we);let ho=Math.floor(fe/3)*3+(2-fe%3);Qe[(U+fe)*Q.itemSize+we]=Q.getComponent(ho,we)*(F==="normal"?-1:1)}N.setAttribute(F,new z.BufferAttribute(Qe,Q.itemSize))}X.side=z.FrontSide,G.copy(N)}else if(X.side!==z.FrontSide){let V=G.getIndex();for(let N=0;N<V.count;N+=3){let F=V.getX(N+1);V.setX(N+1,V.getX(N+2)),V.setX(N+2,F)}let U=G.getAttribute("normal");for(let N=0;N<U.count;N++)U.setXYZ(N,-U.getX(N),-U.getY(N),-U.getZ(N));X.side=z.FrontSide}if(k.isInstancedMesh&&k.instanceColor){let V=new z.Color;k.getColorAt(q,V),X.color.multiply(V)}for(let[V,U]of Object.entries(X)){if(!U?.isTexture)continue;let N=U;if(on(N)||!N.image||N.image.complete===!1)throw new Error(`Texture on ${I} is not ready. Wait for image loading or replace failed textures before preparing AR.`);let F=c.get(N);if(F||(F=N.clone(),c.set(N,F),a.push(F)),X[V]=F,!G.getAttribute(F.channel?`uv${F.channel}`:"uv"))throw new Error(`Texture on ${I} needs UV coordinates missing from this geometry.`)}if(k.userData.riDecal){G.computeBoundingBox();let V=Math.max(1e-6,G.boundingBox.getSize(new z.Vector3).length()*1e-4),U=G.getAttribute("position"),N=G.getAttribute("normal");for(let F=0;F<U.count;F++)U.setXYZ(F,U.getX(F)+N.getX(F)*V,U.getY(F)+N.getY(F)*V,U.getZ(F)+N.getZ(F)*V)}let Je=new z.Mesh(G,X);Je.name=`AR_${d++}`,n.add(Je),l.push({sourceIndex:w,source:k,exported:Je,bakedMatrix:R.clone(),instanceMatrix:E}),u+=(G.index?.count??G.getAttribute("position").count)/3,(X.clearcoat||X.transmission||X.iridescence||X.anisotropy)&&r.add("Advanced PBR effects may look different in Quick Look.")}}}finally{S.dispose()}})}if(!d||!u)throw new Error("There is no visible model geometry to send to AR.");let p=new z.Box3().setFromObject(n),O=p.getSize(new z.Vector3),T=p.getCenter(new z.Vector3),x=t.scaleMode==="real-world"?1:1/Math.max(O.x,O.y,O.z,1e-9);return n.position.set(-T.x*x,-p.min.y*x,-T.z*x),n.scale.setScalar(x),o.updateMatrixWorld(!0),r.add("Viewer lighting, background, post-processing, annotations and measurement overlays stay in the web viewer."),{root:o,meshCount:d,triangleCount:u,scale:x,warnings:[...r],textures:a,motionMeshes:l,dispose:f}}catch(p){throw f(),p}}async function oo(e,t={}){let o=t.maxTextureSize??2048;if(!Number.isInteger(o)||o<256||o>4096)throw new Error("AR maxTextureSize must be an integer from 256 to 4096.");let n=hr(e,t),r=[];try{let i=to(e,n.motionMeshes,t.signal),{USDZExporter:s}=await import("three/examples/jsm/exporters/USDZExporter.js");t.signal?.throwIfAborted();for(let l of n.textures){if(!l.isCompressedTexture)continue;let{decompress:d}=await import("three/examples/jsm/utils/WebGLTextureUtils.js"),u=d(l,o);r.push(u),n.root.traverse(f=>{let p=f.material;if(p)for(let O of Object.keys(p))p[O]===l&&(p[O]=u)})}let a=await new s().parseAsync(n.root,{onlyVisible:!0,quickLookCompatible:!0,maxTextureSize:o});t.signal?.throwIfAborted();let c=no(a,i);return{blob:new Blob([new Uint8Array(c)],{type:"model/vnd.usdz+zip"}),meshCount:n.meshCount,triangleCount:n.triangleCount,scale:n.scale,warnings:[...n.warnings,...i.warnings]}}catch(i){if(t.signal?.aborted)throw i;let s=i instanceof Error&&i.name==="SecurityError"?" Textures must allow cross-origin canvas access.":"";throw new Error(`Could not prepare the configured USDZ: ${i instanceof Error?i.message:"export failed"}${s}`)}finally{n.dispose(),r.forEach(i=>i.dispose())}}var ue=require("fflate");var Rt="ri-ar",It="ri-ar-id",ro=4096,yr=2200,Sr=(0,ue.strToU8)(JSON.stringify(pe)).byteLength;function io(e){return e==="localhost"||e.endsWith(".localhost")||/^127\./.test(e)||e==="[::1]"||e==="0.0.0.0"}function so(e){if(typeof e=="string"&&/^https?:\/\//i.test(e)&&io(new URL(e).hostname))throw new Error("An asset URL points to this computer. Use model and texture URLs reachable from the phone.");if(e&&typeof e=="object")for(let t of Object.values(e))so(t)}function xr(e,t){let o=new URL(e,t);if(!["https:","http:"].includes(o.protocol))throw new Error("AR handoff requires an HTTP(S) URL.");return o.toString()}function ao(e,t){if(JSON.stringify(e)!==JSON.stringify(t))return e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)?Object.fromEntries(Object.entries(e).map(([o,n])=>[o,ao(n,t[o])]).filter(([,o])=>o!==void 0)):e}function co(e,t,o=0){if(o>64)throw new Error("AR configuration is too deeply nested.");if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=e,r=t;return Object.fromEntries([...new Set([...Object.keys(r),...Object.keys(n)])].map(i=>[i,Object.prototype.hasOwnProperty.call(n,i)?co(n[i],r[i],o+1):r[i]]))}return e}function lo(e,t){let o=structuredClone(e);if(o.configuration){o.configuration.sceneConfig&&(o.configuration.sceneConfig=t(o.configuration.sceneConfig));for(let n of o.configuration.models??[])n.sceneConfig&&(n.sceneConfig=t(n.sceneConfig))}return o}function De(e){e?.throwIfAborted()}async function uo(e,t,o,n){De(n);let r=new URL(xr(t));if(io(r.hostname))throw new Error("Phone links need a viewer URL reachable from your phone. Download the USDZ for local uploads, or provide a public viewer URL.");let i=await Xe(e,r.toString());De(n),so(i);let s=new URLSearchParams(r.hash.slice(1));if(s.delete(Rt),s.delete(It),s.delete("view"),s.delete("viewId"),s.delete("view-id"),o){let a=await o.save(i);if(De(n),typeof a!="string"||!a||a.length>512)throw new Error("AR storage returned an invalid configuration ID.");s.set(It,a)}else{let a=(0,ue.zlibSync)((0,ue.strToU8)(JSON.stringify({ar:1,state:lo(i,l=>ao(l,pe)??{})})),{level:9});if(a.byteLength>ro)throw new Error("This configuration needs an AR storage adapter to share on a phone. The USDZ download is still available.");let c="";for(let l of a)c+=String.fromCharCode(l);s.set(Rt,btoa(c).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""))}if(r.hash=s.toString(),r.toString().length>yr)throw new Error("This configuration is too large for a reliable QR code. Use an AR storage adapter or download the USDZ.");return r.toString()}async function mo(e,t,o){let n=new URL(e),r=new URLSearchParams(n.hash.slice(1)),i=r.get(It),s=r.get(Rt);if(i!==null&&s!==null)throw new Error("AR link contains conflicting configurations.");if(i===null&&s===null)return null;De(o);let a;if(i!==null){if(!t)throw new Error("This AR link requires the application's configuration storage adapter.");if(!i||i.length>512)throw new Error("Invalid AR configuration ID.");a=await t.load(i)}else{if(!s||s.length>Math.ceil(ro*4/3)||!/^[\w-]+$/.test(s))throw new Error("Invalid or oversized AR link.");let l=atob(s.replace(/-/g,"+").replace(/_/g,"/")),d=Uint8Array.from(l,p=>p.charCodeAt(0)),u=(0,ue.unzlibSync)(d);if(u.byteLength>ae)throw new Error("AR configuration exceeds the 5 MiB limit.");let f=JSON.parse((0,ue.strFromU8)(u));if(f?.ar===1&&f.state){let p=f.state.configuration,O=(p?.sceneConfig?1:0)+(Array.isArray(p?.models)?p.models.filter(T=>T?.sceneConfig).length:0);if(u.byteLength+O*Sr>ae)throw new Error("Expanded AR configuration exceeds the 5 MiB limit.");a=lo(f.state,T=>co(T,pe))}else a=f}De(o);let c=Ce(a,n.toString());if(c.version!==1||!c.configuration)throw new Error("AR handoff requires a complete versioned viewer configuration.");return c}var go={id:"identity",modelObjectId:"identity",label:"identity",type:"identity",group:"identity",tags:"identity",style:"appearance",decals:"appearance",transform:"transform",visible:"visibility",removed:"visibility",status:"visibility",selectable:"behavior",hoverable:"behavior",actions:"behavior",cameraState:"behavior",metadata:"data",metrics:"data"},wr=Object.keys(go),Mr=new Set(["__proto__","prototype","constructor"]);function xe(e,t=new Set){if(e==null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new Error("Comparison values must be finite JSON data");return e}if(typeof e!="object"||t.has(e))throw new Error("Comparison values must be acyclic JSON data");t.add(e);let o=Array.isArray(e)?e.map(n=>xe(n,t)):Object.fromEntries(Object.entries(e).filter(([n,r])=>!Mr.has(n)&&r!==void 0).map(([n,r])=>[n,xe(r,t)]));return t.delete(e),o}var po=e=>e&&typeof e=="object"&&!Array.isArray(e)&&!Object.keys(e).length;function fo(e,t){let o=xe(e);o.visible=e.visible??!0,o.selectable=e.selectable??!0,o.hoverable=e.hoverable??!0,o.status=e.status??"normal",o.type=e.type??"other",o.tags=[...new Set(e.tags??[])].sort(),po(o.transform)&&delete o.transform,o.metadata=Object.fromEntries(Object.entries(e.metadata??{}).filter(([n])=>!t.includes(n)));for(let n of["metrics","style","metadata"])po(o[n])&&delete o[n];for(let n of["actions","decals"])Array.isArray(o[n])&&!o[n].length&&delete o[n];return o}function Ze(e,t,o,n,r,i){let s=c=>c===void 0||Array.isArray(c)&&c.length===0;if(Object.is(e,t)||s(e)&&s(t)||typeof e=="number"&&typeof t=="number"&&Math.abs(e-t)<=r)return;let a=c=>!!c&&typeof c=="object"&&!Array.isArray(c);if(a(e)&&a(t)){for(let c of[...new Set([...Object.keys(e),...Object.keys(t)])].sort())Ze(e[c],t[c],`${o}.${c}`,n,r,i);return}if(Array.isArray(e)&&Array.isArray(t)&&e.length===t.length){for(let c=0;c<e.length;c++)Ze(e[c],t[c],`${o}[${c}]`,n,r,i);return}i.push({path:o,category:n,...e!==void 0?{before:xe(e)}:{},...t!==void 0?{after:xe(t)}:{}})}function bo(e,t,o={}){let n=o.tolerance??1e-6;if(!Number.isFinite(n)||n<0)throw new Error("Comparison tolerance must be finite and nonnegative");let r=Object.entries(e.objectBindings).filter(([,w])=>!w.removed),i=Object.entries(t.objectBindings).filter(([,w])=>!w.removed),s=new Map(r),a=new Map(i),c=new Set,l=new Set,d=[],u=w=>{let A=o.matchBy??"modelObjectId",g=typeof A=="object"?w.metadata?.[A.metadataKey]:w[A];return typeof g=="string"&&g.length>0||typeof g=="number"?`${typeof g}:${g}`:null};function f(w,A,g){let y=w===void 0?void 0:s.get(w),v=A===void 0?void 0:a.get(A),B=[];if(y||v){let I=y?fo(y,o.ignoreMetadataKeys??[]):{},b=v?fo(v,o.ignoreMetadataKeys??[]):{};for(let m of wr)Ze(I[m],b[m],m,go[m],n,B)}let k=y?v?B.length?"modified":"unchanged":"removed":"added";d.push({id:JSON.stringify([w??null,A??null]),identity:g,label:v?.label??y?.label??v?.modelObjectId??y?.modelObjectId??g,status:k,beforeKey:w,afterKey:A,beforeObjectId:y?.modelObjectId,afterObjectId:v?.modelObjectId,changes:B}),w!==void 0&&c.add(w),A!==void 0&&l.add(A)}let p=new Set;for(let[w,A]of Object.entries(o.mapping??{})){if(!s.has(w)||!a.has(A)||p.has(A))throw new Error("Comparison mapping must reference existing, unique binding keys");p.add(A),f(w,A,`mapped:${w}`)}let O=new Map;for(let[w,A,g]of[[r,c,"a"],[i,l,"b"]])for(let[y,v]of w){if(A.has(y))continue;let B=u(v);if(B===null){d.push({id:JSON.stringify([g,y]),identity:"",label:v.label??v.modelObjectId,status:"ambiguous",...g==="a"?{beforeKey:y,beforeObjectId:v.modelObjectId}:{afterKey:y,afterObjectId:v.modelObjectId},changes:[],message:"Missing match identity. Supply an explicit mapping or another match field."});continue}let k=O.get(B)??{a:[],b:[]};k[g].push(y),O.set(B,k)}for(let[w,A]of O){if(A.a.length<=1&&A.b.length<=1){f(A.a[0],A.b[0],w);continue}for(let g of["a","b"])for(let y of A[g]){let v=(g==="a"?s:a).get(y);d.push({id:JSON.stringify([g,y]),identity:w,label:v.label??v.modelObjectId,status:"ambiguous",...g==="a"?{beforeKey:y,beforeObjectId:v.modelObjectId}:{afterKey:y,afterObjectId:v.modelObjectId},changes:[],message:"Duplicate match identity. Supply an explicit one-to-one mapping."})}}d.sort((w,A)=>w.label.localeCompare(A.label)||w.id.localeCompare(A.id));let T=[];Ze(xe(e.sceneConfig??{}),xe(t.sceneConfig??{}),"sceneConfig","scene",n,T);let x={added:0,removed:0,modified:0,unchanged:0,ambiguous:0};for(let w of d)x[w.status]++;return{version:1,objects:d,counts:x,sceneChanges:T}}0&&(module.exports={ACTION_CATALOG,DEFAULT_MODEL_VIEWER_LABELS,DEFAULT_SCENE_CONFIG,DEFAULT_SECTION_CONFIG,MATERIAL_BLENDING_MODES,MATERIAL_SIDES,MAX_VIEWER_STATE_BYTES,MEASUREMENT_UNITS,SEQUENCE_EASINGS,SEQUENCE_OBJECT_PROPERTIES,applyIsolation,applyProductOptions,applyStyleRules,buildBindingsFromNodes,calibrateMeasurements,chooseMaterialVariant,collectObjectHierarchy,colorScaleValue,compareViewerConfigurations,copyBindingStyle,createARHandoffUrl,createDefaultBinding,decodeProductSelections,defaultProductSelections,defineObjectBindings,encodeProductSelections,evaluateProductConfiguration,exportConfiguredUSDZ,findCatalogAction,formatProductPrice,generateProductSkus,groundAsset,inferType,inspectAsset,isolatedBindingKeys,material,measurementResult,measurementScale,measurementValue,measurementsToCsv,parseAssetTransform,parseMeasurements,parseProductConfiguration,parseProductDefinition,parseSceneProduct,parseSectionConfig,parseSelectionSets,parseSequences,parseViewerState,pasteBindingStyle,patchBindings,patchSceneConfig,prepareViewerState,productCheckoutUrl,productDefinitionWarnings,productOptionStates,productPriceFromDefinition,readARHandoffUrl,resolveProductSelections,sampleSequenceTrack,sceneLight,sectionSnapshot,selectBindingKeys,selectBindings,serializeMeasurements,serializeProductConfiguration,serializeViewerState,snapAssetToGrid,upsertSequenceKeyframe});
1
+ "use strict";var Ro=Object.create;var Fe=Object.defineProperty;var Io=Object.getOwnPropertyDescriptor;var Po=Object.getOwnPropertyNames;var Bo=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty;var Vo=(e,t)=>{for(var o in t)Fe(e,o,{get:t[o],enumerable:!0})},Ut=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Po(t))!Eo.call(e,r)&&r!==o&&Fe(e,r,{get:()=>t[r],enumerable:!(n=Io(t,r))||n.enumerable});return e};var _t=(e,t,o)=>(o=e!=null?Ro(Bo(e)):{},Ut(t||!e||!e.__esModule?Fe(o,"default",{value:e,enumerable:!0}):o,e)),Do=e=>Ut(Fe({},"__esModule",{value:!0}),e);var Nr={};Vo(Nr,{ACTION_CATALOG:()=>Ve,DEFAULT_MODEL_VIEWER_LABELS:()=>jt,DEFAULT_SCENE_CONFIG:()=>be,DEFAULT_SECTION_CONFIG:()=>on,MATERIAL_BLENDING_MODES:()=>nn,MATERIAL_SIDES:()=>tn,MAX_VIEWER_STATE_BYTES:()=>me,MEASUREMENT_UNITS:()=>xt,SEQUENCE_EASINGS:()=>bt,SEQUENCE_OBJECT_PROPERTIES:()=>gt,applyIsolation:()=>Yt,applyProductOptions:()=>In,applyStyleRules:()=>Wt,buildBindingsFromNodes:()=>en,calibrateMeasurements:()=>gn,chooseMaterialVariant:()=>qe,collectObjectHierarchy:()=>_n,colorScaleValue:()=>at,compareViewerConfigurations:()=>jo,copyBindingStyle:()=>zn,createARHandoffUrl:()=>Ao,createDefaultBinding:()=>dt,decodeProductSelections:()=>Cn,defaultProductSelections:()=>Te,defineObjectBindings:()=>zt,encodeProductSelections:()=>kt,evaluateProductConfiguration:()=>ae,exportConfiguredUSDZ:()=>bo,findCatalogAction:()=>Zt,formatProductPrice:()=>An,generateProductSkus:()=>kn,groundAsset:()=>cn,inferType:()=>ut,inspectAsset:()=>qn,isolatedBindingKeys:()=>ct,material:()=>qt,measurementResult:()=>At,measurementScale:()=>Mt,measurementValue:()=>Xe,measurementsToCsv:()=>hn,parseAssetTransform:()=>je,parseMeasurements:()=>we,parseProductConfiguration:()=>Rn,parseProductDefinition:()=>Ct,parseSceneProduct:()=>Ze,parseSectionConfig:()=>De,parseSelectionSets:()=>Ye,parseSequences:()=>Oe,parseViewerState:()=>Re,pasteBindingStyle:()=>Fn,patchBindings:()=>$e,patchSceneConfig:()=>Gt,prepareViewerState:()=>Qe,productCheckoutUrl:()=>vn,productDefinitionWarnings:()=>On,productOptionStates:()=>jn,productPriceFromDefinition:()=>Mn,readARHandoffUrl:()=>vo,resolveProductSelections:()=>Je,sampleSequenceTrack:()=>We,sceneLight:()=>Ht,sectionSnapshot:()=>rn,selectBindingKeys:()=>Q,selectBindings:()=>$t,serializeMeasurements:()=>bn,serializeProductConfiguration:()=>Tn,serializeViewerState:()=>Un,snapAssetToGrid:()=>an,upsertSequenceKeyframe:()=>sn});module.exports=Do(Nr);function zt(e){return e}function it(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Be(e,t){if(!it(t))return t;let o=it(e)?{...e}:{};for(let n of Object.keys(t)){let r=t[n];o[n]=it(r)?Be(o[n],r):r}return o}function Ft(e,t){if(e[t])return t;let o=Object.entries(e).find(([,r])=>r.id===t)?.[0];return o||(Object.entries(e).find(([,r])=>r.modelObjectId===t)?.[0]??null)}function No(e){return typeof e=="object"&&!Array.isArray(e)}function Lo(e,t){return"group"in t?e.group===t.group:"tag"in t?e.tags?.includes(t.tag)??!1:(e.type??"other")===t.type}function Q(e,t){if(No(t))return Object.entries(e).filter(([,r])=>Lo(r,t)).map(([r])=>r);let n=(typeof t=="string"?[t]:t).map(r=>Ft(e,r)).filter(r=>r!==null);return[...new Set(n)]}function $t(e,t){return Q(e,t).map(o=>e[o]).filter(o=>o!==void 0)}function Uo(e){return Array.isArray(e)&&e.length>0&&typeof e[0]!="string"}function $e(e,t,o){let n=Uo(t)?t:[{ids:t,patch:o??{}}],r=e;for(let s of n)for(let a of Q(r,s.ids)){let i=r[a];if(!i)continue;let c=Be(i,s.patch);r===e&&(r={...e}),r[a]=c}return r}function qt(e){return{style:{material:e}}}function Gt(e,t){return Be(e,t)}var _o={type:"point",color:"#ffffff",intensity:1,position:[0,0,0],distance:0,decay:2,attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0};function Ht(e){return{..._o,...e}}var zo="#ff3b30",Fo=Object.freeze({}),Kt=e=>e;function $o(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qo(e,t){let o=e.metadata;for(let n of t.split(".")){if(!$o(o))return;o=o[n]}return o}function Go(e,t){if("metric"in t){let o=e.metrics?.[t.metric];return!(typeof o!="number"||!Number.isFinite(o)||t.above!==void 0&&!(o>t.above)||t.below!==void 0&&!(o<t.below))}if("status"in t){let o=e.status??"normal";return Array.isArray(t.status)?t.status.includes(o):t.status===o}return qo(e,t.metadata)===t.equals}function Ho(e){let t=e.trim().replace(/^#/,""),o=t.length===3?t.split("").map(n=>n+n).join(""):t;return/^[0-9a-f]{6}$/i.test(o)?[0,2,4].map(n=>parseInt(o.slice(n,n+2),16)):null}var st=e=>`#${e.map(t=>Math.round(t).toString(16).padStart(2,"0")).join("")}`;function at(e,t){let o=e.map(([c,l])=>({at:c,rgb:Ho(l)})).filter(c=>Number.isFinite(c.at)&&c.rgb!==null).sort((c,l)=>c.at-l.at);if(o.length===0||!Number.isFinite(t))return null;if(t<=o[0].at)return st(o[0].rgb);let n=o[o.length-1];if(t>=n.at)return st(n.rgb);let r=o.findIndex(c=>c.at>=t),s=o[r-1],a=o[r],i=a.at===s.at?1:(t-s.at)/(a.at-s.at);return st(s.rgb.map((c,l)=>c+(a.rgb[l]-c)*i))}function Wt(e,t){if(!t?.length)return{bindings:e,pulses:Fo,sourceOf:Kt};let o=new Map,n={};for(let a of t){let i=a.target?Q(e,a.target):Object.keys(e),c=a.when?Array.isArray(a.when)?a.when:[a.when]:[];for(let l of i){let u=e[l];if(!c.every(p=>Go(u,p)))continue;let d={...a.material};if(a.colorScale){let p=u.metrics?.[a.colorScale.metric],f=typeof p=="number"?at(a.colorScale.stops,p):null;f&&(d={...d,[a.colorScale.channel??"baseColor"]:f})}if(a.pulse){let p=a.pulse===!0?{}:a.pulse;n[l]={color:p.color??zo,speed:p.speed!==void 0&&p.speed>0?p.speed:1};let f=d.emissiveIntensity??o.get(l)?.emissiveIntensity??u.style?.material?.emissiveIntensity;f!==void 0&&f>0||(d.emissiveIntensity=1)}Object.keys(d).length>0&&o.set(l,{...o.get(l),...d})}}if(o.size===0)return{bindings:e,pulses:n,sourceOf:Kt};let r={...e},s=new WeakMap;for(let[a,i]of o){let c=e[a],l={...c,style:{...c.style,material:{...c.style?.material,...i}}};r[a]=l,s.set(l,c)}return{bindings:r,pulses:n,sourceOf:a=>s.get(a)??a}}function qe(e,t,o){let n=o.find(s=>s.variants.some(a=>a.name===t)),r=new Set(n?.variants.map(s=>s.name)??[t]);return[...e.filter(s=>!r.has(s)),t]}var Ko=.12,Xt=new Set;function ct(e,t){return t?new Set(Q(e,t.target)):Xt}function Yt(e,t){let o=ct(e.bindings,t);if(!t||o.size===0)return{...e,setAside:Xt};let n=Math.min(Math.max(t.ghostOpacity??Ko,0),1),r={...e.bindings},s=new WeakMap,a=new Set;for(let[i,c]of Object.entries(e.bindings)){if(o.has(i))continue;a.add(i);let l=t.mode==="hide"?{...c,visible:!1}:{...c,style:{...c.style,material:{...c.style?.material,opacity:Math.min(c.style?.material?.opacity??1,n)}}};r[i]=l,s.set(l,e.sourceOf(c))}return{bindings:r,pulses:e.pulses,sourceOf:i=>s.get(i)??e.sourceOf(i),setAside:a}}var Wo=require("three"),lt=Symbol("react-immersive.model-node-id");function Xo(e,t){Object.defineProperty(e,lt,{value:t,configurable:!0})}function Ge(e){let t=new Map;e.traverse(c=>{if(!c.name)return;let l=t.get(c.name);l?l.push(c):t.set(c.name,[c])});let o=Object.create(null),n=new WeakMap,r=new Map,s=new Set(Array.from(t,([c,l])=>l.length===1?c:null).filter(c=>c!==null)),a=new Set,i=(c,l)=>{Xo(c,l),o[l]=c,n.set(c,l),a.add(l)};for(let[c,l]of t)l.length===1&&i(l[0],c);for(let[c,l]of t){if(l.length<2)continue;let u=[];l.forEach((d,p)=>{let f=`${c} [${p+1}]`,C=f,R=2;for(;s.has(C)||a.has(C);)C=`${f}.${R++}`;i(d,C),u.push(C)}),r.set(c,u)}return{nodesById:o,idByNode:n,duplicateNames:r}}function Ee(e){return e[lt]??e.name??null}function Jt(e,t){let o=null,n=[];return e.traverse(r=>{r[lt]===t&&(o=r),r.name===t&&n.push(r)}),o??(n.length===1?n[0]:null)}var Ve=Object.freeze([{id:"change-color",label:"Change Color",handling:"viewer",description:"Opens a color picker docked under the action and commits the result to style.material.baseColor."},{id:"change-material",label:"Change Material",handling:"viewer",description:"Opens the material picker so the viewer can swap the object's texture."},{id:"add-text",label:"Add Text",handling:"viewer",description:"Opens a text box docked under the action; the viewer's user types, clicks the object to place it, and can resize, turn, move, or remove it. Saved to the binding's decals."},{id:"add-image",label:"Add Image",handling:"viewer",description:"Lets the viewer's user choose an image, click the object to place it, and resize, turn, move, or remove it. Saved to the binding's decals."},{id:"toggle-visibility",label:"Toggle Visibility",handling:"viewer",description:"Flips the binding's visible flag."},{id:"toggle-light",label:"Toggle Light",handling:"viewer",description:"Turns the scene lights attached to this object on or off, or the object's own glow when none is attached."},{id:"change-light-color",label:"Change Light Color",handling:"viewer",description:"Opens a color picker docked under the action for the scene lights attached to this object, or the object's own glow."},{id:"set-brightness",label:"Set Brightness",handling:"viewer",description:"Opens a brightness slider docked under the action for the scene lights attached to this object, or the object's own glow."}]);function Zt(e){return Ve.find(t=>t.id===e)}var ni=Ve.filter(e=>e.handling==="viewer").map(e=>e.id),oi=new Set(["","New Action",...Ve.map(e=>e.label)]);var ge=require("three");function He(e){return Number.isFinite(e)&&e>0?e:1}function Qt(e){return e?.loopMode??"repeat"}function Yo(e){return e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").replace(/[^a-zA-Z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").toLowerCase()}function Jo(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function ut(e){let t=e.toLowerCase();return t.includes("light")?"light":t.includes("wheel")||t.includes("rim")||t.includes("tire")?"wheel":t.includes("glass")||t.includes("window")||t.includes("windshield")||t.includes("sunroof")?"glass":t.includes("seat")||t.includes("dashboard")||t.includes("console")||t.includes("doorpanel")?"interior":t.includes("floor")?"floor":t.includes("wall")?"wall":t.includes("door")?"door":t.includes("chair")||t.includes("table")||t.includes("sofa")||t.includes("bed")?"furniture":"other"}function Zo(e,t=!0){return e==="light"||e.endsWith("light")?[{id:"toggle-light",label:"Toggle Light",type:"command"},{id:"change-light-color",label:"Change Light Color",type:"command"},{id:"set-brightness",label:"Set Brightness",type:"command"}]:[{id:"change-color",label:"Change Color",type:"command"},...t?[{id:"change-material",label:"Change Material",type:"command"}]:[],{id:"toggle-visibility",label:"Toggle Visibility",type:"command"}]}function dt(e,t=!0){let o=ut(e);return{id:Yo(e),modelObjectId:e,type:o,label:Jo(e),status:"normal",selectable:!0,hoverable:!0,visible:!0,style:{},actions:Zo(o,t),metrics:{},metadata:{}}}function en(e,t){return Object.fromEntries(e.map(o=>[o,dt(o,!t?.has(o))]))}var tn=["front","back","double"],nn=["normal","additive"];var on={enabled:!1,axis:"y",position:.5,flip:!1},Qo={clips:[],autoplayClip:null},er={autofocus:{enabled:!1,focusDistance:5,focusRange:5,focalLength:.02,bokehScale:6,target:[0,0,0],mouse:!0,debug:0,manual:!1,smoothTime:.25},toneMapping:{enabled:!1,mode:"aces",exposure:1,resolution:256,whitePoint:4,middleGrey:.6,minLuminance:.01,averageLuminance:1,adaptationRate:1},brightnessContrast:{enabled:!1,brightness:0,contrast:0},hueSaturation:{enabled:!1,hue:0,saturation:0},colorAverage:{enabled:!1},dotScreen:{enabled:!1,angle:Math.PI/2,scale:1},glitch:{enabled:!1,mode:"sporadic",delay:[1.5,3.5],duration:[.6,1],strength:[.3,1],chromaticAberrationOffset:[0,0],columns:.05,ratio:.85},ssao:{enabled:!1,samples:30,rings:4,intensity:8,radius:.25,bias:.025,luminanceInfluence:.6,fade:.01,minRadiusScale:.33,worldDistanceThreshold:20,worldDistanceFalloff:5,worldProximityThreshold:6,worldProximityFalloff:3},bloom:{enabled:!1,intensity:.3,luminanceThreshold:.9,luminanceSmoothing:.2,mipmapBlur:!0,radius:0,levels:8},godRays:{enabled:!1,sunPosition:[5,10,5],samples:60,density:.96,decay:.9,weight:.4,exposure:.6,clampMax:1,blur:!0,kernelSize:"small"},grid:{enabled:!1,scale:1,lineWidth:0},noise:{enabled:!1,opacity:1,premultiply:!1},depthOfField:{enabled:!1,focusDistance:5,focusRange:5,focalLength:.02,bokehScale:6},chromaticAberration:{enabled:!1,offsetX:.002,offsetY:.002,radialModulation:!1,modulationOffset:.15},lensflare:{enabled:!1,lensPosition:[-25,6,-60],smoothTime:.07,glareSize:.2,flareSize:.01,flareSpeed:.01,flareShape:.01,animated:!0,anamorphic:!1,colorGain:"#141414",haloScale:.5,secondaryGhosts:!0,aditionalStreaks:!0,ghostScale:0,opacity:1,starBurst:!1},vignette:{enabled:!1,offset:.3,darkness:.3,eskil:!1},smaa:{enabled:!1},sepia:{enabled:!1,intensity:0},scanline:{enabled:!1,density:1.25},pixelation:{enabled:!1,granularity:5},outline:{enabled:!1,selectionLayer:10,edgeStrength:2.5,pulseSpeed:0,visibleEdgeColor:"#ffffff",hiddenEdgeColor:"#22090a",kernelSize:"large",blur:!1,xRay:!0},selectiveBloom:{enabled:!1,selectionLayer:10,intensity:1,luminanceThreshold:.9,luminanceSmoothing:.025,kernelSize:"large",mipmapBlur:!0,inverted:!1,ignoreBackground:!1},ramp:{enabled:!1,rampType:"linear",rampStart:[.5,.5],rampEnd:[1,1],startColor:"#000000",endColor:"#ffffff",opacity:.5,rampBias:.5,rampGain:.5,rampMask:!1,rampInvert:!1}},be={model:{rotation:[0,0,0],showAdvancedRotation:!1,renderer:"pbr",shading:"lit",autoRotate:!1,autoRotateSpeed:1},camera:{fieldOfView:50,showAdvancedSettings:!1},lighting:{ambient:{intensity:.25,color:"#ffffff"},lights:[{id:"light-hemi",type:"hemisphere",color:"#ffffff",intensity:.3,position:[0,1,0],attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0},{id:"light-key",type:"directional",color:"#ffffff",intensity:2.5,position:[6,12,6],attachedToCamera:!1,castShadow:!0,shadowBias:-5e-4,visible:!0},{id:"light-fill",type:"directional",color:"#ffffff",intensity:0,position:[-6,8,-6],attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0}]},shadows:{enabled:!0,mapSize:2048,bias:-5e-4,normalBias:.02,radius:3},environment:{source:"preset",preset:"apartment",customEnvironmentUrl:"",intensity:.25,rotation:0,shadowLight:{enabled:!1,intensity:2.5,bias:-5e-4}},wireframe:{enabled:!1,color:"#000000",opacity:1},background:{enabled:!1,type:"color",color:"#1c1c1d",imageUrl:""},groundShadows:{enabled:!1,mode:"shadowCatcher",intensity:.7,borderFade:1,height:0,size:10},postProcessing:er,animations:Qo,annotations:[]};function De(e){let t=u=>{throw new Error(`Invalid section: ${u}`)},o=u=>u&&typeof u=="object"&&!Array.isArray(u)?u:t("expected an object"),n=u=>typeof u=="string"&&u.trim().length>0&&u.length<=200?u:t("expected a nonempty name or id (up to 200 characters)"),r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0&&u<=1?u:t("position must be between 0 and 1"),s=u=>!Array.isArray(u)||u.length!==3||!u.every(d=>typeof d=="number"&&Number.isFinite(d))||Math.hypot(...u)<1e-8?t("normal must be a finite, nonzero vector"):[...u],a=u=>{let d=o(u);return!["x","y","z"].includes(d.axis)||typeof d.enabled!="boolean"||typeof d.flip!="boolean"?t("invalid plane"):{enabled:d.enabled,axis:d.axis,position:r(d.position),flip:d.flip,...d.normal!==void 0?{normal:s(d.normal)}:{}}},i=u=>{let d=o(u),p=a(d);if(d.mode!==void 0){if(!["plane","planes","box"].includes(d.mode))return t("invalid mode");p.mode=d.mode}if(d.planes!==void 0){if(!Array.isArray(d.planes)||d.planes.length>6)return t("at most six planes are supported");let f=new Set;p.planes=d.planes.map(C=>{let R=o(C),S=n(R.id);return f.has(S)?t("duplicate plane id"):(f.add(S),{...a(R),id:S,name:n(R.name)})})}if(d.activePlaneId!==void 0&&(p.activePlaneId=n(d.activePlaneId)),d.invertBox!==void 0){if(typeof d.invertBox!="boolean")return t("invalid box inversion");p.invertBox=d.invertBox}if(d.box!==void 0){let f=o(d.box),C=w=>!Array.isArray(w)||w.length!==3?t("invalid box bounds"):w.map(r),R=C(f.min),S=C(f.max);if(R.some((w,A)=>w>=S[A]))return t("box minimum must be below its maximum on every axis");p.box={min:R,max:S}}return p},c=o(e),l=i(c);if(c.presets!==void 0){if(!Array.isArray(c.presets)||c.presets.length>32)return t("at most 32 presets are supported");let u=new Set;l.presets=c.presets.map(d=>{let p=o(d),f=n(p.id);return u.has(f)?t("duplicate preset id"):(u.add(f),{id:f,name:n(p.name),settings:i(p.settings)})})}return l}function rn(e){let{presets:t,...o}=De(e);return o}var ft=require("three"),gt=["position","rotation","scale","visible","baseColor","emissive","opacity","roughness","metalness","emissiveIntensity"],bt=["linear","ease-in","ease-out","ease-in-out","step"],tr=new Set(["position","rotation","scale"]),nr=new Set(["baseColor","emissive"]),ye=e=>typeof e=="string"&&e.length>0&&e.length<=256,xe=e=>typeof e=="number"&&Number.isFinite(e),mt=e=>Array.isArray(e)&&e.length===3&&e.every(xe);function Ne(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Se(e){throw new Error(`Invalid sequences: ${e}`)}function or(e){return e.kind==="object"?JSON.stringify([e.kind,e.objectId,e.property]):e.kind==="clip"?JSON.stringify([e.kind,e.clip]):"camera"}function rr(e,t){if(t.kind==="camera")return Ne(e)&&mt(e.position)&&mt(e.target)&&(e.fov===null||xe(e.fov)&&e.fov>0&&e.fov<180)&&xe(e.zoom)&&e.zoom>0;if(t.kind==="clip")return xe(e)&&e>=0;let o=t.property;return tr.has(o)?mt(e)&&(o!=="scale"||e.every(n=>n!==0)):nr.has(o)?typeof e=="string"&&/^#[\da-f]{6}$/i.test(e):o==="visible"?typeof e=="boolean":xe(e)&&e>=0&&(o==="emissiveIntensity"||e<=1)}function Oe(e){(!Array.isArray(e)||e.length>64)&&Se("expected up to 64 sequences.");let t=new Set,o=0;return e.map(n=>{(!Ne(n)||!ye(n.id)||t.has(n.id)||!(typeof n.name=="string"&&ye(n.name.trim()))||!xe(n.duration)||n.duration<.1||n.duration>3600||typeof n.loop!="boolean"||typeof n.autoPlay!="boolean"||!Array.isArray(n.tracks)||n.tracks.length>128)&&Se("each sequence needs a unique id, name, 0.1\u20133600 second duration, loop/autoplay flags and up to 128 tracks."),t.add(n.id);let r=new Set,s=new Set,a=n.tracks.map(i=>{(!Ne(i)||!ye(i.id)||r.has(i.id)||!(typeof i.name=="string"&&ye(i.name.trim()))||!Ne(i.target)||!Array.isArray(i.keyframes)||i.keyframes.length>2048||i.muted!==void 0&&typeof i.muted!="boolean")&&Se("invalid or duplicate track."),r.add(i.id);let c;i.target.kind==="camera"?c={kind:"camera"}:i.target.kind==="clip"&&ye(i.target.clip)?c={kind:"clip",clip:i.target.clip}:i.target.kind==="object"&&ye(i.target.objectId)&&gt.includes(i.target.property)?c={kind:"object",objectId:i.target.objectId,property:i.target.property}:Se("unknown track target or property.");let l=or(c);s.has(l)&&Se("only one track may own each target property in a sequence."),s.add(l);let u=new Set,d=new Set,p=i.keyframes.map(f=>{++o>2e4&&Se("too many keyframes."),(!Ne(f)||!ye(f.id)||u.has(f.id)||!xe(f.time)||f.time<0||f.time>n.duration||d.has(f.time)||f.easing!==void 0&&!bt.includes(f.easing)||!rr(f.value,c))&&Se("keyframes need unique ids/times, valid values and times inside the sequence."),u.add(f.id),d.add(f.time);let C=f.value,R=c.kind==="camera"?{position:[...C.position],target:[...C.target],fov:C.fov,zoom:C.zoom}:Array.isArray(f.value)?[...f.value]:f.value;return{id:f.id,time:f.time,value:R,...f.easing?{easing:f.easing}:{}}}).sort((f,C)=>f.time-C.time);return{id:i.id,name:i.name.trim(),target:c,keyframes:p,...i.muted!==void 0?{muted:i.muted}:{}}});return{id:n.id,name:n.name.trim(),duration:n.duration,loop:n.loop,autoPlay:n.autoPlay,tracks:a}})}function ir(e,t="ease-in-out"){let o=Math.max(0,Math.min(1,e));return t==="step"?0:t==="ease-in"?o*o:t==="ease-out"?1-(1-o)**2:t==="ease-in-out"?o*o*(3-2*o):o}var Ke=(e,t,o)=>e+(t-e)*o,pt=(e,t,o)=>e.map((n,r)=>Ke(n,t[r],o));function We(e,t){if(e.muted||!e.keyframes.length||!Number.isFinite(t))return null;let o=e.keyframes;if(t<o[0].time)return null;let n=o[0],r;for(let c of o)if(c.time<=t)n=c;else{r=c;break}if(!r||typeof n.value=="boolean")return structuredClone(n.value);let s=ir((t-n.time)/(r.time-n.time),n.easing);if(typeof n.value=="number"&&typeof r.value=="number")return Ke(n.value,r.value,s);if(typeof n.value=="string"&&typeof r.value=="string")return`#${new ft.Color(n.value).lerp(new ft.Color(r.value),s).getHexString()}`;if(Array.isArray(n.value)&&Array.isArray(r.value))return pt(n.value,r.value,s);let a=n.value,i=r.value;return{position:pt(a.position,i.position,s),target:pt(a.target,i.target,s),fov:a.fov!==null&&i.fov!==null?Ke(a.fov,i.fov,s):a.fov,zoom:Ke(a.zoom,i.zoom,s)}}function sn(e,t){return{...e,keyframes:[...e.keyframes.filter(o=>o.id!==t.id&&Math.abs(o.time-t.time)>1e-6),t].sort((o,n)=>o.time-n.time)}}var ee=require("three");function ht(e){return e.id??e.url}function je(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected an asset transform object.");let t={};for(let o of["position","rotation","scale"]){let n=e[o];if(n!==void 0){if(!Array.isArray(n)||n.length!==3||!n.every(r=>typeof r=="number"&&Number.isFinite(r))||o==="scale"&&n.some(r=>r===0))throw new Error(`Invalid asset ${o}: expected three finite ${o==="scale"?"nonzero ":""}numbers.`);t[o]=[...n]}}return t}function an(e,t){if(!Number.isFinite(t)||t<=0)throw new Error("Grid size must be positive.");let o=je(e),[n,r,s]=o.position??[0,0,0];return{...o,position:[Math.round(n/t)*t,r,Math.round(s/t)*t]}}function cn(e,t){let o=je(e),n=o.position??[0,0,0],r=new ee.Matrix4().compose(new ee.Vector3(...n),new ee.Quaternion().setFromEuler(new ee.Euler(...o.rotation??[0,0,0])),new ee.Vector3(...o.scale??[1,1,1])),s=new ee.Box3(new ee.Vector3(...t.min),new ee.Vector3(...t.max)).applyMatrix4(r);if(!Number.isFinite(s.min.y))throw new Error("Cannot place an asset with empty bounds.");return{...o,position:[n[0],n[1]-s.min.y,n[2]]}}var ue=require("three"),sr=new Map,yt={color:"#93c5fd",intensity:.07},Si=new ue.Color(yt.color).multiplyScalar(yt.intensity),xi=new ue.Color(yt.color);var ar=new Map;function ln(e){return ar.get(e)}function un(e){for(let t of sr.values())if(t.texture.source===e.source&&(!t.loaded||t.failed))return!0;return!1}var H=require("three");function dn(e){if(e.length!==3)return null;let t=new H.Vector3(...e[0]).sub(new H.Vector3(...e[1])),o=new H.Vector3(...e[2]).sub(new H.Vector3(...e[1]));return t.lengthSq()===0||o.lengthSq()===0?null:Math.acos(Math.max(-1,Math.min(1,t.normalize().dot(o.normalize()))))*180/Math.PI}function mn(e,t){if(!e.normal)return null;let o=new H.Vector3(...e.normal);if(o.lengthSq()===0)return null;o.normalize();let n=new H.Vector3(...t),r=n.clone().sub(new H.Vector3(...e.position)).dot(o);return{distance:Math.abs(r),projection:n.addScaledVector(o,-r).toArray()}}function pn(e){if(e.length<3)return{error:"Pick at least three points to finish the area."};let t=new H.Vector3(...e[0]),o=e.map(S=>new H.Vector3(...S).sub(t)),n=Math.max(...o.map(S=>S.length()));if(n===0)return{error:"Area points must be distinct."};let r=new H.Vector3;for(let S=1;S<o.length-1;S+=1){let w=o[S].clone().cross(o[S+1]);w.lengthSq()>r.lengthSq()&&r.copy(w)}if(r.length()<=n*n*1e-10)return{error:"Area points must not lie on one straight line."};r.normalize();let s=Math.max(n*1e-5,Number.EPSILON*Math.max(...e.flat().map(Math.abs))*32);if(o.some(S=>Math.abs(S.dot(r))>s))return{error:"Area points must lie on one plane."};let a=o.find(S=>S.length()>n*1e-10).clone().normalize(),i=r.clone().cross(a).normalize(),c=o.map(S=>new H.Vector2(S.dot(a),S.dot(i))),l=(S,w,A)=>(w.x-S.x)*(A.y-S.y)-(w.y-S.y)*(A.x-S.x),u=n*n*1e-10,d=(S,w,A)=>Math.abs(l(S,w,A))<=u&&A.x>=Math.min(S.x,w.x)-n*1e-10&&A.x<=Math.max(S.x,w.x)+n*1e-10&&A.y>=Math.min(S.y,w.y)-n*1e-10&&A.y<=Math.max(S.y,w.y)+n*1e-10;for(let S=0;S<c.length;S+=1){let w=c[S],A=c[(S+1)%c.length];if(w.distanceTo(A)<=n*1e-10)return{error:"Area points must be distinct."};for(let h=S+1;h<c.length;h+=1){if(h===S+1||S===0&&h===c.length-1)continue;let x=c[h],M=c[(h+1)%c.length],E=l(w,A,x),j=l(w,A,M),D=l(x,M,w),g=l(x,M,A);if(E*j<0&&D*g<0||d(w,A,x)||d(w,A,M)||d(x,M,w)||d(x,M,A))return{error:"Area edges must not cross or touch each other."}}}let p=0,f=0,C=0;for(let S=0;S<c.length;S+=1){let w=c[S],A=c[(S+1)%c.length],h=w.x*A.y-A.x*w.y;p+=h,f+=(w.x+A.x)*h,C+=(w.y+A.y)*h}if(Math.abs(p)<=u)return{error:"The polygon has no measurable area."};let R=t.clone().addScaledVector(a,f/(3*p)).addScaledVector(i,C/(3*p));return{area:Math.abs(p)/2,center:R.toArray(),triangles:H.ShapeUtils.triangulateShape(c,[])}}function fn(e,t){if(e.length<2)return 0;let o=0;for(let n=1;n<e.length;n+=1)o+=new H.Vector3(...e[n]).distanceTo(new H.Vector3(...e[n-1]));return t&&(o+=new H.Vector3(...e[e.length-1]).distanceTo(new H.Vector3(...e[0]))),o}var xt=["m","cm","mm","in","ft"],St={m:1,cm:.01,mm:.001,in:.0254,ft:.3048},cr=["distance","angle","area","pointToPlane","wrap","wrapHorizontal"];function wt(e){return xt.includes(e)}function Mt(e={},t="m"){let o=e.displayUnit??t,n=e.metersPerUnit??St[e.sourceUnit??"m"];if(!Number.isFinite(n)||n<=0)throw new Error("Measurement scale must be a positive finite number.");return{displayUnit:o,metersPerUnit:n,factor:wt(o)?n/St[o]:1}}function gn(e,t,o,n={}){if(!wt(o)||!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)throw new Error("Calibration needs two distinct points and a positive known distance.");let r=t*St[o]/e;if(!Number.isFinite(r)||r<=0)throw new Error("Calibration scale is outside the supported range.");return{...n,metersPerUnit:r}}function Xe(e,t){let o=t.map(n=>n.position);if(e==="angle"){let n=dn(o);return n===null?null:{value:n,dimension:0}}if(e==="area"){let n=pn(o);return"error"in n?null:{value:n.area,dimension:2}}if(e==="pointToPlane"){let n=t.length===2?mn(t[0],t[1].position):null;return n?{value:n.distance,dimension:1}:null}return t.length<(e==="distance"?2:3)?null:{value:fn(o,e!=="distance"),dimension:1}}function At(e,t={},o="m",n=e.points,r=e.approximate?"approximate":"ready"){let s=Xe(e.tool,n),{factor:a,displayUnit:i}=Mt(t,o),c=r==="ready"||r==="approximate",l=c&&s?s.value*a**s.dimension:null;return{id:e.id,status:c?s&&l!==null&&Number.isFinite(l)?r:"invalid":r,rawValue:c&&s&&Number.isFinite(s.value)?s.value:null,value:l!==null&&Number.isFinite(l)?l:null,unit:e.tool==="angle"?"\xB0":e.tool==="area"?`${i}\xB2`:i}}function we(e){function t(){throw new Error("Invalid measurements: expected settings and valid named measurements with finite points.")}let o=i=>!!i&&typeof i=="object"&&!Array.isArray(i),n=i=>Array.isArray(i)&&i.length===3&&i.every(c=>typeof c=="number"&&Number.isFinite(c));typeof e=="string"&&(e.length>5*1024*1024&&t(),e=JSON.parse(e)),(!o(e)||e.version!==void 0&&e.version!==1||!o(e.settings)||!Array.isArray(e.items)||e.items.length>256)&&t();let r={};for(let i of["sourceUnit","displayUnit"])e.settings[i]!==void 0&&(wt(e.settings[i])||t(),r[i]=e.settings[i]);e.settings.metersPerUnit!==void 0&&((typeof e.settings.metersPerUnit!="number"||!Number.isFinite(e.settings.metersPerUnit)||e.settings.metersPerUnit<=0)&&t(),r.metersPerUnit=e.settings.metersPerUnit);let s=new Set,a=e.items.map(i=>{(!o(i)||typeof i.id!="string"||!i.id||s.has(i.id)||typeof i.name!="string"||!i.name.trim()||typeof i.modelId!="string"||!i.modelId||!cr.includes(i.tool)||!Array.isArray(i.points)||i.points.length>8192||typeof i.createdAt!="string"||!Number.isFinite(Date.parse(i.createdAt)))&&t(),s.add(i.id),i.tilesetUrl!==void 0&&i.tilesetUrl!==null&&typeof i.tilesetUrl!="string"&&t(),(i.visible!==void 0&&typeof i.visible!="boolean"||i.approximate!==void 0&&typeof i.approximate!="boolean")&&t();let c=new Set,l=i.points.map(d=>{if((!o(d)||typeof d.id!="number"||!Number.isFinite(d.id)||!n(d.position))&&t(),c.has(d.id)&&t(),c.add(d.id),d.normal!==void 0&&!n(d.normal)&&t(),d.faceVertices!==void 0&&(!Array.isArray(d.faceVertices)||d.faceVertices.length!==3||!d.faceVertices.every(n))&&t(),d.snapped!==void 0&&!["vertex","edge"].includes(d.snapped)&&t(),d.anchor!==void 0){let f=d.anchor;(!o(f)||typeof f.nodeId!="string"||!f.nodeId||!n(f.localPosition)||typeof f.geometrySignature!="string"||typeof f.poseSignature!="string")&&t(),f.localNormal!==void 0&&!n(f.localNormal)&&t(),f.localFaceVertices!==void 0&&(!Array.isArray(f.localFaceVertices)||f.localFaceVertices.length!==3||!f.localFaceVertices.every(n))&&t(),f.instanceId!==void 0&&(!Number.isInteger(f.instanceId)||f.instanceId<0)&&t()}let p=d.anchor;return{id:d.id,position:[...d.position],...d.normal?{normal:[...d.normal]}:{},...d.faceVertices?{faceVertices:d.faceVertices.map(f=>[...f])}:{},...d.snapped?{snapped:d.snapped}:{},...p?{anchor:{nodeId:p.nodeId,localPosition:[...p.localPosition],geometrySignature:p.geometrySignature,poseSignature:p.poseSignature,...p.localNormal?{localNormal:[...p.localNormal]}:{},...p.localFaceVertices?{localFaceVertices:p.localFaceVertices.map(f=>[...f])}:{},...p.instanceId!==void 0?{instanceId:p.instanceId}:{}}}:{}}}),u={id:i.id,name:i.name,modelId:i.modelId,tool:i.tool,points:l,createdAt:i.createdAt,...i.tilesetUrl!==void 0?{tilesetUrl:i.tilesetUrl}:{},...i.visible!==void 0?{visible:i.visible}:{},...i.approximate!==void 0?{approximate:i.approximate}:{}};return Xe(u.tool,l)||t(),u});return{settings:r,items:a}}function bn(e){return JSON.stringify({version:1,...we(e)},null,2)}function hn(e,t,o="m"){let n=we(e),r=new Map(t?.map(a=>[a.id,a])),s=a=>{let i=String(a??"");return/^[=+@-]/.test(i)&&(i=`'${i}`),`"${i.replace(/"/g,'""')}"`};return[["id","name","modelId","type","status","value","unit","createdAt"],...n.items.map(a=>{let i=r.get(a.id)??At(a,n.settings,o);return[a.id,a.name,a.modelId,a.tool,i.status,i.value,i.unit,a.createdAt]})].map(a=>a.map(s).join(",")).join(`\r
2
+ `)}function Ye(e){if(!Array.isArray(e)||e.length>128)throw new Error("Invalid selections: expected up to 128 named selection sets.");let t=new Set;return e.map(o=>{if(!o||typeof o!="object"||typeof o.id!="string"||!o.id||t.has(o.id)||typeof o.name!="string"||!o.name.trim()||o.name.length>200||!Array.isArray(o.objectIds)||o.objectIds.length>1e5||o.objectIds.some(n=>typeof n!="string"||!n))throw new Error("Invalid selections: each set needs a unique id, a name, and model object ids.");return t.add(o.id),{id:o.id,name:o.name.trim(),objectIds:[...new Set(o.objectIds)]}})}var Sn=new Set(["__proto__","constructor","prototype"]),vt=(e,t)=>e<t?-1:e>t?1:0;function _(e){throw new Error(`Invalid product: ${e}`)}var Y=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Le=e=>typeof e=="string"&&e.length>0&&e.length<=200&&!Sn.has(e),de=e=>typeof e=="string"&&e.trim().length>0&&e.length<=500;function xn(e){let t=0;function o(n,r){return(++t>1e5||r>32)&&_("definition is too complex."),n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)?n:Array.isArray(n)?n.map(s=>o(s,r+1)):(Y(n)||_("expected JSON data."),Object.fromEntries(Object.entries(n).filter(([,s])=>s!==void 0).map(([s,a])=>(Sn.has(s)&&_("reserved property name."),[s,o(a,r+1)]))))}return o(e,0)}function lr(e){if(typeof e!="string"||e.length>2048)return!1;try{return["http:","https:"].includes(new URL(e.replace(/\{[a-zA-Z]+\}/g,"x")).protocol)}catch{return!1}}function Ct(e){let t=xn(typeof e=="string"?JSON.parse(e):e);(!Y(t)||!Le(t.id)||!de(t.label)||!Le(t.revision)||!Array.isArray(t.groups)||!t.groups.length||t.groups.length>64)&&_("id, label, revision, and 1\u201364 option groups are required.");let o=new Map;for(let r of t.groups){(!Y(r)||!Le(r.id)||o.has(r.id)||!de(r.label)||r.required!==void 0&&typeof r.required!="boolean"||!Array.isArray(r.options)||!r.options.length||r.options.length>128)&&_("groups need unique ids, labels, and 1\u2013128 options.");let s=new Set;o.set(r.id,s);for(let a of r.options)if((!Y(a)||!Le(a.id)||s.has(a.id)||!de(a.label)||a.sku!==void 0&&!de(a.sku))&&_("options need unique ids and labels."),s.add(a.id),a.description!==void 0&&!de(a.description)&&_("an option description must be text."),a.swatch!==void 0&&!(typeof a.swatch=="string"&&/^#[0-9a-f]{3,8}$/i.test(a.swatch))&&_("a swatch must be a hex color."),a.priceDeltaMinor!==void 0&&!Number.isSafeInteger(a.priceDeltaMinor)&&_("a price change must be a whole number of minor units."),a.variants!==void 0&&(!Array.isArray(a.variants)||a.variants.some(i=>!de(i)))&&_("variant names must be strings."),a.appearance!==void 0){(!Array.isArray(a.appearance)||a.appearance.length>128)&&_("invalid appearance edits.");for(let i of a.appearance){Y(i)||_("invalid appearance edit.");let c=i.target;typeof c=="string"&&c||Array.isArray(c)&&c.every(l=>typeof l=="string"&&!!l)||Y(c)&&Object.keys(c).length===1&&["group","tag","type"].some(l=>typeof c[l]=="string")||_("appearance needs an object id, id list, or selector."),i.visible!==void 0&&typeof i.visible!="boolean"&&_("visibility must be boolean."),i.material!==void 0&&!Y(i.material)&&_("material must be an object.");for(let l of Object.values(i.material??{}))typeof l=="string"||typeof l=="number"||typeof l=="boolean"||l===null||Y(l)&&typeof l.path=="string"&&(l.offset===void 0||Array.isArray(l.offset)&&l.offset.length===2&&l.offset.every(u=>typeof u=="number"))||_("invalid material field.")}}r.defaultOptionId!==void 0&&!s.has(r.defaultOptionId)&&_("a default must name an option in its group."),r.display!==void 0&&!["list","chips","swatches"].includes(r.display)&&_("a group's display must be list, chips or swatches.")}t.pricing!==void 0&&!(Y(t.pricing)&&/^[A-Z]{3}$/.test(t.pricing.currency)&&Number.isSafeInteger(t.pricing.basePriceMinor)&&t.pricing.basePriceMinor>=0)&&_("pricing needs a 3-letter currency and a base price of zero or more."),t.checkout!==void 0&&(!Y(t.checkout)||t.checkout.label!==void 0&&!de(t.checkout.label)||!lr(t.checkout.urlTemplate))&&_("a checkout link needs an http or https URL.");let n=r=>Y(r)&&typeof r.groupId=="string"&&typeof r.optionId=="string"&&!!o.get(r.groupId)?.has(r.optionId);if(t.rules!==void 0){(!Array.isArray(t.rules)||t.rules.length>2048)&&_("invalid rules.");let r=new Set;for(let s of t.rules){(!Y(s)||!Le(s.id)||r.has(s.id)||!n(s.when)||s.message!==void 0&&!de(s.message))&&_("rules need unique ids and valid option references."),r.add(s.id),["requires","excludes"].some(a=>Array.isArray(s[a])&&s[a].length>0)||_("a rule needs a requires or excludes constraint.");for(let a of["requires","excludes"])s[a]!==void 0&&(!Array.isArray(s[a])||s[a].length>128||!s[a].every(n))&&_("rule references must name existing options.")}}if(t.skus!==void 0){(!Array.isArray(t.skus)||t.skus.length>4096)&&_("invalid SKU table.");let r=new Set;for(let s of t.skus){(!Y(s)||!de(s.sku)||!Y(s.selections)||Object.keys(s.selections).length!==o.size)&&_("SKU mappings need one selection per group.");for(let[i,c]of Object.entries(s.selections))(!o.has(i)||c!==null&&!o.get(i).has(c))&&_("SKU mapping references an unknown option.");let a=JSON.stringify(Object.entries(s.selections).sort(([i],[c])=>vt(i,c)));r.has(a)&&_("a combination can map to only one SKU."),r.add(a)}}return{id:t.id,label:t.label,revision:t.revision,groups:t.groups.map(r=>({id:r.id,label:r.label,...r.required!==void 0?{required:r.required}:{},...r.defaultOptionId!==void 0?{defaultOptionId:r.defaultOptionId}:{},...r.display!==void 0?{display:r.display}:{},options:r.options.map(s=>({id:s.id,label:s.label,...s.sku!==void 0?{sku:s.sku}:{},...s.description!==void 0?{description:s.description}:{},...s.swatch!==void 0?{swatch:s.swatch}:{},...s.priceDeltaMinor!==void 0?{priceDeltaMinor:s.priceDeltaMinor}:{},...s.variants!==void 0?{variants:s.variants}:{},...s.appearance!==void 0?{appearance:s.appearance.map(a=>({target:a.target,...a.material!==void 0?{material:a.material}:{},...a.visible!==void 0?{visible:a.visible}:{}}))}:{}}))})),...t.rules!==void 0?{rules:t.rules.map(r=>({id:r.id,when:r.when,...r.requires?{requires:r.requires}:{},...r.excludes?{excludes:r.excludes}:{},...r.message?{message:r.message}:{}}))}:{},...t.skus!==void 0?{skus:t.skus.map(r=>({sku:r.sku,selections:r.selections}))}:{},...t.pricing!==void 0?{pricing:{currency:t.pricing.currency,basePriceMinor:t.pricing.basePriceMinor}}:{},...t.checkout!==void 0?{checkout:{urlTemplate:t.checkout.urlTemplate,...t.checkout.label!==void 0?{label:t.checkout.label}:{}}}:{}}}function Te(e){return Object.fromEntries(e.groups.map(t=>[t.id,t.defaultOptionId??null]))}function ur(e,t){let o=[];for(let n of e.groups){if(t[n.id]===null)continue;let r=n.options.find(s=>s.id===t[n.id])?.sku;if(!r)return null;o.push(r)}return o.length?o.join("-"):null}function ae(e,t=Te(e),o=1){if(!Number.isSafeInteger(o)||o<1||o>9999)throw new Error("Quantity must be an integer from 1 to 9999.");if(!Y(t)||Object.values(t).some(u=>u!==null&&typeof u!="string"))throw new Error("Product selections must map group ids to option ids or null.");let n=[],r=[...e.groups].sort((u,d)=>vt(u.id,d.id)),s=Object.fromEntries(r.map(u=>[u.id,!Object.prototype.hasOwnProperty.call(t,u.id)||t[u.id]===void 0?u.defaultOptionId??null:t[u.id]]));for(let u of Object.keys(t).sort())e.groups.some(d=>d.id===u)||n.push({code:"unknown-group",groupIds:[u],message:`Unknown option group: ${u}.`});let a=[];for(let u of r){let d=s[u.id],p=u.options.find(f=>f.id===d);d!==null&&!p?n.push({code:"unknown-option",groupIds:[u.id],message:`Unknown choice for ${u.label}: ${d}.`}):u.required&&d===null&&n.push({code:"required",groupIds:[u.id],message:`Choose ${u.label}.`}),p&&a.push({groupId:u.id,optionId:p.id,label:p.label,...p.sku?{sku:p.sku}:{}})}let i=u=>e.groups.find(d=>d.id===u.groupId)?.options.find(d=>d.id===u.optionId)?.label??u.optionId;for(let u of[...e.rules??[]].sort((d,p)=>vt(d.id,p.id)))if(s[u.when.groupId]===u.when.optionId){for(let d of u.requires??[])s[d.groupId]!==d.optionId&&n.push({code:"requires",ruleId:u.id,groupIds:[...new Set([u.when.groupId,d.groupId])],message:u.message??`${i(u.when)} requires ${i(d)}.`});for(let d of u.excludes??[])s[d.groupId]===d.optionId&&n.push({code:"excludes",ruleId:u.id,groupIds:[...new Set([u.when.groupId,d.groupId])],message:u.message??`${i(u.when)} cannot be combined with ${i(d)}.`})}let c=e.skus?.length?e.skus.find(u=>r.every(d=>u.selections[d.id]===s[d.id]))?.sku??null:ur(e,s);e.skus?.length&&!c&&!n.length&&n.push({code:"sku",groupIds:r.map(u=>u.id),message:"This combination has no product SKU."});let l=JSON.stringify({productId:e.id,revision:e.revision,quantity:o,selections:s});return{version:1,productId:e.id,revision:e.revision,key:l,quantity:o,selections:s,sku:c,items:a,valid:!n.length,issues:n}}var wn=new Set(["requires","excludes"]);function Je(e,t,o,n,r=1){let s={...ae(e,t,r).selections,[o]:n},a=new Set([JSON.stringify(s)]),i=[s];for(let c=0;c<i.length&&c<2e3;c++){let l=i[c],u=ae(e,l,r).issues.filter(d=>wn.has(d.code));if(!u.length)return l;for(let d of new Set(u.flatMap(p=>p.groupIds))){if(d===o)continue;let p=e.groups.find(f=>f.id===d);if(p)for(let f of[...p.options.map(C=>C.id),...p.required?[]:[null]]){let C={...l,[d]:f},R=JSON.stringify(C);a.has(R)||(a.add(R),i.push(C))}}}return null}function dr(e,t,o,n,r){let s=Je(e,t,o,n,r);return s?Object.entries(s).filter(([a,i])=>a!==o&&i!==t[a]&&i!==null).map(([a,i])=>({groupId:a,optionId:i})):null}function Mn(e,t){if(!e.pricing)return null;let o=e.pricing.basePriceMinor;for(let n of t.items)o+=e.groups.find(r=>r.id===n.groupId)?.options.find(r=>r.id===n.optionId)?.priceDeltaMinor??0;return{amountMinor:Math.max(0,o)*t.quantity,currency:e.pricing.currency}}function An(e,t,o=!1){try{let n=new Intl.NumberFormat(void 0,{style:"currency",currency:t,...o?{signDisplay:"exceptZero"}:{}});return n.format(e/10**(n.resolvedOptions().maximumFractionDigits??2))}catch{return`${e} ${t}`}}function vn(e,t){let o=e.checkout?.urlTemplate;if(!o||!t.valid||o.includes("{sku}")&&!t.sku)return null;let n={sku:t.sku??"",quantity:String(t.quantity),productId:e.id,revision:e.revision,selections:kt(t.selections)};return o.replace(/\{([a-zA-Z]+)\}/g,(r,s)=>Object.prototype.hasOwnProperty.call(n,s)?encodeURIComponent(n[s]):r)}function kt(e){return Object.entries(e).filter(([,t])=>t!==null).map(([t,o])=>`${encodeURIComponent(t)}:${encodeURIComponent(o)}`).join(",")}function Cn(e,t){let o={...Te(t)};for(let n of e.split(",")){let[r,s]=n.split(":");if(!r||!s)continue;let a,i;try{a=decodeURIComponent(r),i=decodeURIComponent(s)}catch{continue}t.groups.find(c=>c.id===a)?.options.some(c=>c.id===i)&&(o[a]=i)}return o}var yn=4096;function kn(e,t="-"){let o=[{}];for(let s of e.groups){let a=[...s.options.map(i=>i.id),...s.required?[]:[null]];if(o.length*a.length>yn*8)throw new Error("This product has too many combinations to list. Use a pricing service to resolve SKUs instead.");o=o.flatMap(i=>a.map(c=>({...i,[s.id]:c})))}let n={...e,skus:void 0},r=[];for(let s of o){if(ae(n,s).issues.length)continue;let a=e.groups.flatMap(i=>{let c=s[i.id];return c===null?[]:[i.options.find(l=>l.id===c)?.sku??null]});if(!(!a.length||a.includes(null))&&(r.push({sku:a.join(t),selections:s}),r.length>yn))throw new Error("This product has too many combinations to list. Use a pricing service to resolve SKUs instead.")}return r}function On(e,t={},o){let n=[],r=Te(e),s=ae({...e,skus:void 0},r).issues.filter(i=>wn.has(i.code));for(let i of s)n.push({code:"invalid-default",message:`The default choices conflict: ${i.message}`});e.checkout?.urlTemplate.includes("{sku}")&&!e.skus?.length&&e.groups.some(i=>i.options.some(c=>!c.sku))&&n.push({code:"missing-sku",message:"The buy link uses {sku}, but it won't appear until every option has an SKU."});let a=Object.keys(t).length>0;for(let i of e.groups)for(let c of i.options){let l=`${i.label} \u203A ${c.label}`,u={groupId:i.id,optionId:c.id};if(a)for(let p of c.appearance??[])Q(t,p.target).length||n.push({code:"no-objects",message:`${l} changes objects that aren't in this model.`,...u});if(o)for(let p of c.variants??[])o.includes(p)||n.push({code:"missing-variant",message:`${l} uses a material variant this model doesn't have: ${p}.`,...u});let d={...r,[i.id]:c.id};Je(e,d,i.id,c.id)||n.push({code:"unreachable",message:`The rules leave no way to choose ${l}.`,...u})}return n}function jn(e,t,o,n=1){return t=ae(e,t,n).selections,e.groups.flatMap(r=>r.options.map(s=>{let i=ae(e,{...t,[r.id]:s.id},n).issues.filter(u=>u.groupIds.includes(r.id)&&u.code!=="sku").map(u=>u.message),c=o?.options?.find(u=>u.groupId===r.id&&u.optionId===s.id);c?.available===!1&&i.push(c.reason??"Currently unavailable.");let l=i.length&&c?.available!==!1?dr(e,t,r.id,s.id,n):null;return{groupId:r.id,optionId:s.id,selected:t[r.id]===s.id,available:!i.length,...l?{fix:l}:{},reasons:[...new Set(i)]}}))}function Ze(e){Y(e)||_("expected a product definition and selections.");let t=Ct(e.definition),o=ae(t,e.selections??Te(t));return o.issues.some(n=>n.code==="unknown-group"||n.code==="unknown-option")&&_("selections reference unknown options."),{definition:t,selections:o.selections}}function Tn(e){return JSON.stringify({version:1,productId:e.productId,revision:e.revision,quantity:e.quantity,selections:e.selections})}function Rn(e,t){let o=xn(typeof e=="string"?JSON.parse(e):e);if(!Y(o)||o.version!==1||o.productId!==t.id||o.revision!==t.revision)throw new Error("This configuration belongs to a different product or revision.");if(!Y(o.selections)||!Number.isSafeInteger(o.quantity))throw new Error("Invalid product configuration selections or quantity.");let n=ae(t,o.selections,o.quantity);if(n.issues.some(r=>r.code==="unknown-group"||r.code==="unknown-option"))throw new Error("This configuration references unknown product options.");return n}function In(e,t,o=[],n=[]){let r=e,s=[...o];if(!t)return{objectBindings:r,activeVariants:s};for(let a of t.definition.groups){let i=a.options.find(c=>c.id===(t.selections[a.id]===void 0?a.defaultOptionId:t.selections[a.id]));if(i){for(let c of i.appearance??[])r=$e(r,c.target,{...c.material!==void 0?{style:{material:c.material}}:{},...c.visible!==void 0?{visible:c.visible}:{}});if(i.variants?.length){let c=new Set(a.options.flatMap(l=>l.variants??[]));s=s.filter(l=>!c.has(l));for(let l of i.variants)s=qe(s,l,n)}}}return{objectBindings:r,activeVariants:s}}var me=5*1024*1024,mr=["activeModelId","modelUrl","modelFormat","tilesetUrl","models","mergeModels","sceneConfig","isolation","multiSelectedKeys","activeAnnotation","annotationCategories","backgroundColor","shadows","cinematic","cameraControllerType","objectTransformSpace","arScaleMode","usdzUrl","measurements","measurementSettings","measurementUnit","measurementModelId"];function O(e,t){throw new Error(`Invalid viewer state at ${e}: ${t}`)}function W(e,t){(!e||typeof e!="object"||Array.isArray(e))&&O(t,"expected an object.")}function Ue(e,t){(!Array.isArray(e)||!e.every(o=>typeof o=="string"))&&O(t,"expected strings.")}function oe(e,t,o){(!Array.isArray(e)||e.length!==t||!e.every(n=>typeof n=="number"&&Number.isFinite(n)))&&O(o,`expected ${t} finite numbers.`)}function pr(e){let t=new Set,o=0;function n(r,s,a){if((++o>2e5||a>64)&&O(s,"configuration is too complex."),r===null||typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return r;(typeof r!="object"||!r)&&O(s,"expected JSON data (finite numbers, no functions)."),t.has(r)&&O(s,"cyclic data."),!Array.isArray(r)&&Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null&&O(s,"expected plain JSON data."),t.add(r);let i=Array.isArray(r)?[]:{};for(let[c,l]of Object.entries(r))["__proto__","constructor","prototype"].includes(c)&&O(`${s}.${c}`,"reserved property."),l!==void 0?i[c]=n(l,`${s}.${c}`,a+1):Array.isArray(r)&&O(s,"undefined array entry.");return t.delete(r),i}return n(e,"state",0)}function re(e,t,o,n,r=!1,s){let a=e[t];if(a==null||a==="")return;typeof a!="string"&&O(o,"expected a URL.");let i=r?ln(a)??a:a;if(i.trim().startsWith("blob:")){if(r&&s){s.set(a,{source:i,path:o});return}O(o,r?"this image is temporary. Use getStateAsync() for JSON or createShareUrl() to include it.":"upload this model/environment asset to a durable URL before saving or sharing.")}if(i!==a&&(a=i,e[t]=i),r&&/^data:image\//i.test(a))return;let c;try{c=new URL(a,n??"https://relative.invalid/")}catch{O(o,"invalid asset URL.")}["http:","https:"].includes(c.protocol)||O(o,"use an HTTP(S) asset URL."),n&&(e[t]=c.href)}function fr(e,t){W(e,t),oe(e.position,3,`${t}.position`),oe(e.target,3,`${t}.target`),(typeof e.zoom!="number"||e.zoom<=0)&&O(t,"zoom must be positive."),e.fov!==null&&(typeof e.fov!="number"||e.fov<=0||e.fov>=180)&&O(t,"fov must be null or between 0 and 180.");for(let o of["azimuthAngle","polarAngle"])e[o]!==void 0&&typeof e[o]!="number"&&O(t,`${o} must be a number.`)}function En(e,t,o,n){W(e,t),(typeof e.id!="number"||typeof e.title!="string"||typeof e.description!="string")&&O(t,"expected an annotation id, title and description.");for(let r of["worldPosition","localPosition"])oe(e[r],3,`${t}.${r}`);e.images!==void 0&&(Array.isArray(e.images)||O(t,"images must be an array."),e.images.forEach(r=>{W(r,t),re(r,"src",t,o,!0,n)})),e.links!==void 0&&(Array.isArray(e.links)||O(t,"links must be an array."),e.links.forEach(r=>{W(r,t),re(r,"href",t,o,!1,n)}))}function Vn(e,t){W(e,t),e.waypoints!==void 0&&(Array.isArray(e.waypoints)||O(t,"expected waypoints."),e.waypoints.forEach(o=>{W(o,t),oe(o.position,3,t),oe(o.target,3,t)}));for(let o of["enabled","loop","autoPlay"])e[o]!==void 0&&typeof e[o]!="boolean"&&O(t,`${o} must be boolean.`);e.duration!==void 0&&(typeof e.duration!="number"||e.duration<=0)&&O(t,"duration must be positive.")}function Ot(e,t,o){if(t!==null)if(Array.isArray(t))Array.isArray(e)||O(o,"expected an array."),t.length&&e.forEach(n=>Ot(n,t[0],o));else if(typeof t=="object"){W(e,o);for(let[n,r]of Object.entries(t))Ot(e[n],r,`${o}.${n}`)}else typeof e!=typeof t&&O(o,`expected ${typeof t}.`)}function Pn(e,t,o,n){if(Ot(e,be,t),e.measurements!==void 0&&(e.measurements=we(e.measurements)),e.sequences!==void 0&&(e.sequences=Oe(e.sequences)),e.selectionSets!==void 0&&(e.selectionSets=Ye(e.selectionSets)),e.product!==void 0&&(e.product=Ze(e.product),e.product.definition.groups.forEach(r=>r.options.forEach(s=>s.appearance?.forEach(a=>{for(let[i,c]of Object.entries(a.material??{}))c&&typeof c=="object"&&!Array.isArray(c)&&"path"in c&&re(c,"path",`${t}.product.material.${i}.path`,o,!0,n)})))),oe(e.model.rotation,3,`${t}.model.rotation`),e.lighting.lights.forEach(r=>oe(r.position,3,`${t}.lighting.lights`)),e.annotations.forEach(r=>En(r,`${t}.annotations`,o,n)),e.animations.autoplayClip!==null&&typeof e.animations.autoplayClip!="string"&&O(t,"invalid autoplay clip."),e.animations.clips.forEach(r=>{W(r,t),(typeof r.sourceName!="string"||typeof r.displayName!="string"||typeof r.hidden!="boolean"||typeof r.speed!="number"||!["repeat","once","ping-pong"].includes(r.loopMode))&&O(t,"invalid animation clip settings.")}),e.cinematic!==void 0&&Vn(e.cinematic,`${t}.cinematic`),e.styleRules!==void 0&&!Array.isArray(e.styleRules)&&O(t,"styleRules must be an array."),re(e.environment,"customEnvironmentUrl",`${t}.environment`,o,!1,n),re(e.background,"imageUrl",`${t}.background`,o,!0,n),e.model.activeVariants!==void 0&&Ue(e.model.activeVariants,t),e.section!==void 0)try{e.section=De(e.section)}catch(r){O(`${t}.section`,r.message)}}function Dn(e,t,o,n){W(e,t);for(let[r,s]of Object.entries(e)){let a=`${t}.${r}`;W(s,a),(typeof s.id!="string"||typeof s.modelObjectId!="string")&&O(a,"expected binding id and modelObjectId.");for(let i of["label","group","type","status"])s[i]!==void 0&&typeof s[i]!="string"&&O(a,`${i} must be a string.`);s.tags!==void 0&&Ue(s.tags,a),s.metadata!==void 0&&W(s.metadata,`${a}.metadata`),s.metrics!==void 0&&(W(s.metrics,a),Object.values(s.metrics).some(i=>typeof i!="number")&&O(a,"metrics must be numbers.")),s.actions!==void 0&&(Array.isArray(s.actions)||O(a,"actions must be an array."),s.actions.forEach(i=>{W(i,a),(typeof i.id!="string"||typeof i.label!="string"||i.type!=="command"||i.effects!==void 0&&!Array.isArray(i.effects))&&O(a,"invalid action.")}));for(let i of["visible","removed","selectable","hoverable"])s[i]!==void 0&&typeof s[i]!="boolean"&&O(a,`${i} must be boolean.`);if(s.transform!==void 0){W(s.transform,a);for(let i of["position","rotation","scale","shear"])s.transform[i]!==void 0&&oe(s.transform[i],3,`${a}.transform.${i}`);s.transform.pivot!==void 0&&(W(s.transform.pivot,a),oe(s.transform.pivot.point,3,a),oe(s.transform.pivot.offset,3,a))}if(s.style!==void 0&&(W(s.style,a),s.style.material!==void 0)){W(s.style.material,a);for(let[i,c]of Object.entries(s.style.material))c&&typeof c=="object"&&!Array.isArray(c)&&"path"in c&&re(c,"path",`${a}.style.material.${i}.path`,o,!0,n)}s.decals!==void 0&&(Array.isArray(s.decals)||O(a,"decals must be an array."),s.decals.forEach(i=>{W(i,a),(typeof i.id!="string"||typeof i.size!="number"||i.size<=0)&&O(a,"invalid decal."),oe(i.position,3,a),oe(i.normal,3,a),re(i,"image",a,o,!0,n)}))}}function Bn(e,t,o,n){Array.isArray(e)||O(t,"expected merge sources."),e.forEach(r=>{W(r,t),(typeof r.url!="string"||!r.url||typeof r.namePrefix!="string")&&O(t,"expected source URL and prefix."),re(r,"url",t,o,!1,n)})}function gr(e,t,o){W(e,"configuration");let n=Object.fromEntries(mr.filter(r=>e[r]!==void 0).map(r=>[r,e[r]]));(typeof n.modelUrl!="string"||!n.modelUrl)&&O("configuration.modelUrl","expected the active model URL.");for(let r of["modelUrl","tilesetUrl","usdzUrl"])re(n,r,`configuration.${r}`,t,!1,o);if(n.sceneConfig!==void 0&&Pn(n.sceneConfig,"configuration.sceneConfig",t,o),n.mergeModels!==void 0&&Bn(n.mergeModels,"configuration.mergeModels",t,o),n.models!==void 0){(!Array.isArray(n.models)||n.models.length===0)&&O("configuration.models","expected model entries.");let r=new Set,s=new Set;n.models.forEach(a=>{W(a,"model"),(typeof a.url!="string"||!a.url)&&O("model.url","expected a URL."),re(a,"url","model.url",t,!1,o),a.id!==void 0&&(typeof a.id!="string"||!a.id.trim())&&O("model.id","expected a nonempty instance ID.");let i=ht({id:a.id,url:a.url});s.has(i)&&O("configuration.models","instance identities must be unique; assign IDs when reusing a URL."),s.add(i),a.transform!==void 0&&(a.transform=je(a.transform)),a.visible!==void 0&&typeof a.visible!="boolean"&&O("model.visible","expected boolean."),r.add(a.url),Dn(a.objectBindings,"model.objectBindings",t,o),a.sceneConfig!==void 0&&Pn(a.sceneConfig,"model.sceneConfig",t,o),a.mergeModels!==void 0&&Bn(a.mergeModels,"model.mergeModels",t,o)}),n.activeModelId!==void 0&&(typeof n.activeModelId!="string"||!s.has(n.activeModelId))&&O("configuration.activeModelId","active instance is not in models."),n.activeModelId!==void 0&&n.models.find(a=>ht(a)===n.activeModelId)?.url!==n.modelUrl&&O("configuration.modelUrl","source does not match the active instance."),r.has(n.modelUrl)||O("configuration.modelUrl","active model is not in models.")}if(n.multiSelectedKeys!==void 0&&Ue(n.multiSelectedKeys,"configuration.multiSelectedKeys"),n.annotationCategories!==void 0&&n.annotationCategories!==null&&Ue(n.annotationCategories,"configuration.annotationCategories"),n.activeAnnotation!==void 0&&n.activeAnnotation!==null&&En(n.activeAnnotation,"configuration.activeAnnotation",t,o),n.measurements!==void 0||n.measurementSettings!==void 0){let r=we({items:n.measurements??[],settings:n.measurementSettings??{}});n.measurements!==void 0&&(n.measurements=r.items),n.measurementSettings!==void 0&&(n.measurementSettings=r.settings)}n.measurementModelId!==void 0&&typeof n.measurementModelId!="string"&&O("configuration.measurementModelId","expected a stable id."),n.measurementUnit!==void 0&&typeof n.measurementUnit!="string"&&O("configuration.measurementUnit","expected a unit label.");for(let r of["backgroundColor"])n[r]!==void 0&&typeof n[r]!="string"&&O(r,"expected a string.");n.shadows!==void 0&&typeof n.shadows!="boolean"&&O("shadows","expected boolean.");for(let[r,s]of Object.entries({modelFormat:["glb","gltf","obj","fbx","usdz","stl","ply"],cameraControllerType:["orbit","pointerLock"],objectTransformSpace:["world","local"],arScaleMode:["normalized","real-world"]}))n[r]!==void 0&&!s.includes(n[r])&&O(r,"unsupported value.");if(n.cinematic!==void 0&&Vn(n.cinematic,"cinematic"),n.isolation!==void 0&&n.isolation!==null){let{target:r,mode:s,ghostOpacity:a}=n.isolation;typeof r=="string"||Array.isArray(r)&&r.every(i=>typeof i=="string")||r&&typeof r=="object"&&["group","tag","type"].some(i=>typeof r[i]=="string")||O("configuration.isolation","invalid target."),s!==void 0&&!["ghost","hide"].includes(s)&&O("configuration.isolation","invalid mode."),a!==void 0&&(typeof a!="number"||a<0||a>1)&&O("configuration.isolation","opacity must be between 0 and 1.")}return n}function Nn(e,t,o,n){if(!(!e||typeof e!="object"))for(let[r,s]of Object.entries(e))r!=="metadata"&&(typeof s=="string"&&["url","modelUrl","tilesetUrl","usdzUrl","path","image","src","href","imageUrl","customEnvironmentUrl"].includes(r)?re(e,r,`${t}.${r}`,o,["path","image","src","imageUrl"].includes(r),n):Nn(s,`${t}.${r}`,o,n))}function Ln(e,t,o){typeof e=="string"&&(new TextEncoder().encode(e).length>me&&O("state","exceeds the 5 MiB limit."),e=JSON.parse(e));let n=pr(e);W(n,"state"),new TextEncoder().encode(JSON.stringify(n)).length>me&&O("state","exceeds the 5 MiB limit."),n.version!==void 0&&n.version!==1&&O("version","unsupported version."),n.version===void 0&&(n.objectBindings!==void 0||n.configuration!==void 0)&&O("version","full configurations require version 1.");let r={};return n.version!==void 0&&(r.version=1),n.camera!==void 0&&(fr(n.camera,"camera"),r.camera=n.camera),n.hidden!==void 0&&(Ue(n.hidden,"hidden"),r.hidden=n.hidden),n.selected!==void 0&&(n.selected!==null&&typeof n.selected!="string"&&O("selected","expected an object id or null."),r.selected=n.selected),n.objectBindings!==void 0&&(Dn(n.objectBindings,"objectBindings",t,o),r.objectBindings=n.objectBindings),n.configuration!==void 0&&(r.configuration=gr(n.configuration,t,o)),Nn(r,"state",t,o),new TextEncoder().encode(JSON.stringify(r)).length>me&&O("state","exceeds the 5 MiB limit."),r}function Un(e,t){return JSON.stringify(Re(e,t))}function Re(e,t){return Ln(e,t)}async function Qe(e,t){let o=new Map,n=Ln(e,t,o),r=new Map,s=new Map;for(let[i,{source:c,path:l}]of o){let u=r.get(c);u||(u=(async()=>{let d;try{d=await fetch(c)}catch{O(l,"this temporary image is no longer available. Reload or reselect it before saving.")}d.ok||O(l,"could not read the temporary image. Reload or reselect it before saving.");let p=await d.blob();p.size>me*3/4&&O(l,"embedded image exceeds the 5 MiB configuration limit. Use a hosted image URL.");let f=new Uint8Array(await p.arrayBuffer()),C=p.type.split(";")[0].toLowerCase(),R=C.startsWith("image/")?C:br(f);R||O(l,"temporary asset is not a supported image. Use a hosted asset URL.");let S="";for(let w=0;w<f.length;w+=32768)S+=String.fromCharCode(...f.subarray(w,w+32768));return`data:${R};base64,${btoa(S)}`})(),r.set(c,u)),s.set(i,await u)}function a(i){if(!(!i||typeof i!="object"))for(let[c,l]of Object.entries(i))c!=="metadata"&&(["path","image","src","imageUrl"].includes(c)&&typeof l=="string"&&s.has(l)?i[c]=s.get(l):a(l))}return a(n),Re(n,t)}function br(e){let t=(o,n)=>String.fromCharCode(...e.subarray(o,n));if(e[0]===137&&t(1,4)==="PNG")return"image/png";if(e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(t(0,3)==="GIF")return"image/gif";if(t(0,4)==="RIFF"&&t(8,12)==="WEBP")return"image/webp";if(t(4,8)==="ftyp"&&["avif","avis"].includes(t(8,12)))return"image/avif";if(/<svg[\s>]/i.test(new TextDecoder().decode(e.subarray(0,1024))))return"image/svg+xml"}var jt={verifyingLicense:"Verifying License",checkingYourLicenseKey:"Checking your license key...",createDevelopmentKey:"Create a free development key",invalidLicense:"Invalid License",licenseHasBeenRevokedOrHasExpired:"License has been revoked or has expired",failedToLoadPleaseContactTheSiteAdministrator:"Failed to load. Please contact the site administrator.",contextRestoringTitle:"Reloading viewer\u2026",contextLostTitle:"3D view interrupted",contextRestoringMessage:"Rebuilding the 3D view. Please wait\u2026",contextLostMessage:"The graphics connection was interrupted. The viewer will rebuild when it returns, or you can reload it now.",reloadViewer:"Reload viewer",texturePositioningHint:"Drag to move \xB7 Scroll to zoom \xB7 Click elsewhere to finish",texturePositioningStartHint:"Double-click to move or zoom",dismiss:"Dismiss",missingUVsAreShownInMagenta:"Missing UVs are shown in magenta.",viewThisModelInARWithAppleQuickLook:"View this model in AR with Apple Quick Look",sequencePlayer:"Sequence player",sequenceSelect:"Sequence",sequencePlay:"Play sequence",sequencePause:"Pause sequence",sequenceStop:"Stop and restore scene",sequencePlayhead:"Sequence playhead",sequenceTime:"Sequence time",sequenceIssues:"Unavailable sequence targets",arConfiguredButton:"AR handoff",arConfiguredTitle:"Take this configuration to AR",arConfiguredDescription:"Your current materials, visible models and placements are included.",arSnapshotStale:"Updating AR to include your latest changes\u2026",arPreparing:"Preparing your scene\u2026",arStart:"Start AR",arStarting:"Starting AR\u2026",arCheckingSupport:"Checking AR support\u2026",arUnavailable:"AR is unavailable in this browser. Open this link in an AR-capable browser on your phone.",arStartFailed:"Could not start AR. Check camera permissions and try again.",arAnimations:"AR animations",arAnimationSelect:"Animation",arAnimationSaved:"Default",arAnimationNone:"No animation",arAnimationClips:"Model clips",arAnimationSequences:"Sequences",arAnimationPlay:"Play animation",arAnimationPause:"Pause animation",arRefresh:"Refresh AR",arRetry:"Try again",arExportDetails:"Export details",arPrepare:"Prepare AR",arPrepareAgain:"Prepare again",arDownloadUSDZ:"Download USDZ for iPhone/iPad",arScanConfigured:"Scan to open this configuration on your phone.",arOpenConfiguredLink:"Open configuration link",viewInAR:"View in AR",openThisExperienceOnAPhoneForAR:"Open this experience on a phone for AR",openOnPhone:"Open on phone",viewThisModelInYourSpace:"View this model in your space",viewThisModelInVR:"View this model in VR",closePhoneHandoff:"Close phone handoff",arScanCode:"Scan the code and choose AR.",qrCodeToOpenThisModelOnAPhone:"QR code to open this model on a phone",disableUVChecker:"Disable UV checker",enableUVChecker:"Enable UV checker",explodedView:"Exploded view",explodeAmount:"Explode amount",removeSectionCut:"Remove section cut",sectionCut:"Section cut",sectionAxis:"Section axis",sectionPosition:"Section position",keepTheOtherSide:"Keep the other side",pauseCinematic:"Pause cinematic",playCinematic:"Play cinematic",stopCinematicAndResetCamera:"Stop cinematic and reset camera",cancel:"Cancel",annotationCategories:"Annotation categories",annotations:"Annotations",all:"All",uncategorized:"Uncategorized",decalDragHint:"Drag the decal on the object. Release to save; Escape to cancel.",showAll:"Show all",materialVariants:"Material variants",startGuidedTour:"Start guided tour",guidedTour:"Guided Tour",previousAnnotation:"Previous annotation",previous:"Prev",stopGuidedTour:"Stop guided tour",nextAnnotation:"Next annotation",next:"Next",exitFullscreen:"Exit fullscreen",enterFullscreen:"Enter fullscreen",resetCameraView:"Reset camera view",orbitControl:"Orbit Control",pointLock:"Pointer lock",cameraController:"Camera controller",cameraControllerSettings:"Camera controller settings",downloadGLB:"Download GLB",downloadGLBDescription:"All visible models, material edits and animations in one file. No annotations or separate editor model slots. Duplicate mesh names may change on reimport.",downloadCombinedGLB:"Download as one GLB",downloadSeparateGLBs:"Download separate GLBs",downloadSeparateGLBsDescription:"One GLB file per model",downloadPNG:"Download PNG",downloadUVLayout:"Download UV Layout",videoFormat:"Video format",auto:"Auto",recordTurntableVideo:"Record turntable video",recordCinematicVideo:"Record cinematic video",videoUnsupported:"Video recording is not supported in this browser.",downloadOptions:"Download options",exporting:"Exporting\u2026",download:"Download",annotationTitlePlaceholder:"Title *",description:"Description",ok:"OK",arRelocate:"Relocate",tapToPlace:"Tap to place",closeAnnotation:"Close annotation",learnMore:"Learn more",stopMeasuring:"Stop measuring",startMeasuring:"Start measuring",toggleBoundingDimensions:"Toggle bounding dimensions",measurementTool:"Measurement tool",distance:"Distance",angle:"Angle",area:"Area",pointToPlane:"Point to plane",wrap:"Circumference (Edge)",wrapHorizontal:"Circumference (Horizontal)",measurementSnapping:"Measurement snapping",noSnapping:"No snapping",snapAuto:"Snap: auto",snapVertex:"Snap: vertex",snapEdge:"Snap: edge",undoMeasurementPoint:"Undo measurement point",clearMeasurements:"Clear measurements",finishArea:"Finish area",savedMeasurements:"Saved measurements ({count})",noSavedMeasurements:"No saved measurements yet. Pick points in the preview, then save a measurement here.",measurementFiles:"Import / export",measurementSourceUnit:"Model units",measurementDisplayUnit:"Display units",measurementName:"Name",measurementNamePlaceholder:"e.g. Door width",saveMeasurement:"Save",knownMeasurementDistance:"Known length",calibrationUnit:"Calibration unit",calibrateMeasurement:"Calibrate",measurementCalibrationHint:"Pick two distance points, enter their known length, then calibrate.",measurementCalibratedScale:"Calibrated: 1 model unit = {scale} m",resetMeasurementCalibration:"Reset calibration",showSavedMeasurement:"Show {name}",renameSavedMeasurement:"Rename {name}",deleteSavedMeasurement:"Delete {name}",exportMeasurementJson:"Export JSON",exportMeasurementCsv:"Export CSV",importMeasurementJson:"Import JSON",measurementReady:"Ready",measurementApproximate:"Approximate LOD",measurementModelChanged:"Different model",measurementObjectMissing:"Object unavailable",measurementGeometryChanged:"Geometry changed \u2014 measure again",measurementPoseChanged:"Pose changed \u2014 measure again",measurementObjectHidden:"Object hidden",measurementInvalid:"Invalid measurement",measurementWaiting:"Waiting for model",openSceneObjectsPanel:"Open scene objects panel",sceneObjects:"Scene Objects",searchNodesLabels:"Search nodes, labels",closeSceneObjectsPanel:"Close scene objects panel",objectNavigator:"Objects in the 3D view",compareBefore:"Before",compareAfter:"After",compareDivider:"Comparison divider",viewIn3D:"View in 3D",objectNavigatorHint:"Arrow keys browse \xB7 Enter selects \xB7 Esc clears",selectionCleared:"Selection cleared",cameraKeyboardHelp:"3D view. Arrow keys orbit, Shift with Up or Down zooms, and W, A, S, D, Space and C move the camera.",isolate:"Isolate",hide:"Hide",show:"Show",closePanel:"Close panel",actions:"Actions",openPanel:"Open panel",close:"Close",position:"Position",decalNudgeHint:"Click to fine-tune \xB7 Hold to move",decalNudgeControls:"Move decal in small steps",text:"Text",yourText:"Your text",textToAdd:"Text to add",textColour:"Text color",addText:"Add text",image:"Image",chooseImage:"Choose image",imageToAdd:"Image to add",added:"Added",colour:"Color",size:"Size",turn:"Turn",rotation:"Rotation",dragTheDecalAcrossTheObjectsSurface:"Drag the decal across the object's surface",move:"Move",remove:"Remove",noneAddedYet:"None added yet",done:"Done",moveForward:"Move forward",moveLeft:"Move left",moveRight:"Move right",moveBackward:"Move backward",productOptions:"Options",productOptionsFor:"{product} options",productReset:"Reset",productOptional:"optional",productNone:"None",productAlsoChanges:"Also changes: {changes}",productUnavailable:"Currently unavailable.",productQuantity:"Quantity",productCheckingPrice:"Checking price and availability\u2026",productTotal:"Total",productAddToCart:"Add to cart",productAddingToCart:"Adding\u2026",productRequestQuote:"Request quote",productRequestingQuote:"Requesting\u2026",productRefresh:"Refresh",productBuy:"Buy now",productCopyLink:"Copy link",productLinkCopied:"Link copied",productShowOptions:"Show options",productHideOptions:"Hide options",productIssues:"Configuration issues",productRequestDone:"Request completed.",productSaved:"Saved: {id}",sceneSettings:"Scene Settings",background:"Background",backgroundColor:"Background Color",showEnvironmentAsBackground:"Show as background",backgroundBlur:"Background Blur",environmentPreset:"Preset",environmentIntensity:"Intensity",toneMapping:"Tone Mapping",toneMappingAces:"ACES Filmic",toneMappingAgx:"AgX",toneMappingNeutral:"Neutral",toneMappingNone:"None",ground:"Ground",groundShadow:"Ground Shadow",groundShadowOpacity:"Shadow Opacity",floorGrid:"Floor Grid",display:"Display",wireframe:"Wireframe",autoRotateSpeed:"Rotation Speed",fieldOfView:"Field of View",modelInfo:"Model",modelInfoObjects:"Objects",modelInfoTriangles:"Triangles",modelInfoMaterials:"Materials",resetSettings:"Reset Settings",environment:"Environment",autoRotate:"Auto Rotate",lighting:"Lighting",exposure:"Exposure",ambientLightIntensity:"Ambient Light Intensity",ambientLightColor:"Ambient Light Color",directLightIntensity:"Direct Light Intensity",directLightColor:"Direct Light Color",searchObjects:"Search objects",uploadedModel:"Uploaded model",clear:"Clear",chooseModel:"Choose model",loadingModel:"Loading model...",releaseToLoadYourModel:"Release to load your model",arFindSurface:"Move your device over a flat surface",arReleaseToPlace:"Release to place",arGestureHint:"Pinch to resize \xB7 Twist to rotate",angleFirstArmHint:"Pick the first arm",angleVertexHint:"Pick the angle's vertex",angleSecondArmHint:"Pick the second arm",angleNewHint:"Pick a point to start a new angle",areaNewHint:"Pick a point to start a new area",areaCornersHint:"Pick polygon corners in order, then Finish area",pointToPlaneFaceHint:"Pick the reference face",pointToPlanePointHint:"Pick a point to measure its perpendicular distance",pointToPlaneNewHint:"Pick a face to start a new measurement",distanceHint:"Pick points on the model to measure distances",wrapHint:"Click a point on the surface to measure its circumference, following the surface (best for limbs)",wrapHorizontalHint:"Click a point to measure a level circumference around it (best for the torso/waist)",visibleEntries:"{count} visible entries",objectCount:"{count} objects",annotationMarker:"Annotation {id}: {title}",recordingVideo:"Recording video \xB7 {progress}%",isolatedObjects:"Isolated: {count} objects",largeModelWarning:"Very large model ({millions}M triangles) \u2014 it may render and move slowly on this device, and click/hover selection on the model is disabled. Use the objects panel to select parts.",preparingLargeModel:"Preparing large model ({millions}M triangles) \u2014 the first display can take a while on this device...",enterAR:"Enter AR",enterVR:"Enter VR",decalImage:"Image {index}",decalText:"Text {index}",decalAdded:"{count} added",up:"up",down:"down",left:"left",right:"right",moveDecal:"Move decal {direction}",moveDecalOnSurface:"Move {direction} on the visible surface",showAllObject:"Show all {name}",isolateObject:"Isolate {name}",isolatedObject:"Isolated: {name}",hideObject:"Hide {name}",showObject:"Show {name}",objectSelected:"{name} selected",objectNavigatorPosition:"{position} of {count}",compareDividerValue:"{before} {percent}%, {after} {rest}%",bindingMismatchOne:"1 object binding doesn't match this model",bindingMismatchMany:"{count} object bindings don't match this model",simpleLargeModelWarning:"Very large model detected ({millions}M triangles) \u2014 it may render and move slowly on this device, and click/hover selection on the model is disabled. Use the scene objects panel to select parts.",dropModelHint:"Drag and drop {formats} here",retryModelLoad:"Retry loading model",loadErrorTitle:"This model couldn't be loaded",loadErrorNotFound:"Nothing was found at this address ({status}). Check that modelUrl points to the file.",loadErrorDenied:"The server refused access to the file ({status}). Check that the file is public, or that a signed URL hasn't expired.",loadErrorStatus:"The server responded with {status} when the file was requested.",loadErrorNetwork:"The download was blocked or failed. Check that the URL is correct and, if the file is on another domain, that its server allows cross-origin requests (CORS) from this site.",loadErrorHtml:"The server sent back a web page instead of a model. There's probably no file at this path: many servers answer a missing file with their index.html.",loadErrorInvalidFile:"The file couldn't be read as {format}. Check that it's a valid {format} file.",loadErrorInvalidExplicitFormat:"The file couldn't be read as {format}. Check that it's a valid {format} file and that modelFormat matches it.",loadErrorMissingFormat:"The file couldn't be read as {format}. The URL has no file extension, so set modelFormat to the file's format.",loadErrorPointCloud:"This PLY file is a point cloud: it has points but no faces, and the viewer shows meshes. Turn it into a mesh first, for example with MeshLab or Blender.",measurementReferenceFaceRequired:"Pick a triangle face to define the reference plane.",measurementTooManyPoints:"Finish or clear this measurement before adding more points.",measurementAngleDistinct:"Pick a point away from the angle's vertex.",areaMinimumPoints:"Pick at least three points to finish the area.",areaDistinctPoints:"Area points must be distinct.",areaStraightLine:"Area points must not lie on one straight line.",areaNotPlanar:"Area points must lie on one plane.",areaEdgesCross:"Area edges must not cross or touch each other.",areaZero:"The polygon has no measurable area.",decalSurfaceMissing:"Could not find a surface on this object for the decal.",decalDirectionMissing:"No visible surface in that direction. Try another arrow or rotate the view.",fullscreenExitFailed:"Could not exit fullscreen. Press Escape to exit.",fullscreenEnterFailed:"Could not enter fullscreen. Check your browser or iframe fullscreen permissions and try again.",uvCoordinatesMissing:"This model does not contain UV coordinates.",uvExportFailed:"Could not create the UV layout archive.",videoExportFailed:"Could not export the video.",videoNotReady:"Viewer not ready for video export.",videoExitXR:"Exit the XR session before recording a video.",videoAlreadyRecording:"A video export is already in progress.",videoPathRequired:"Enable a cinematic camera path before recording it.",videoDurationInvalid:"Video duration must be greater than 0 and at most 300 seconds.",videoFrameRateInvalid:"Video frame rate must be between 1 and 60.",videoBitrateInvalid:"Video bitrate must be a positive number.",videoContextLost:"Video export stopped because the WebGL context was lost.",videoTimedOut:"Video export timed out. Keep the viewer tab visible while recording.",videoEncodingFailed:"The browser could not encode the video.",videoEmpty:"The browser produced an empty video.",videoDidNotStart:"Video recording did not start.",videoWebMUnsupported:"Video recording as WEBM is not supported in this browser.",videoMP4Unsupported:"Video recording as MP4 is not supported in this browser.",videoGIFUnsupported:"Video recording as GIF is not supported in this browser.",videoGifWidthInvalid:"GIF width must be a whole number of pixels from 16 to 4096.",environmentApartment:"apartment",environmentCity:"city",environmentDawn:"dawn",environmentForest:"forest",environmentLobby:"lobby",environmentNight:"night",environmentPark:"park",environmentStudio:"studio",environmentSunset:"sunset",environmentWarehouse:"warehouse",color:"Color",material:"Material",texturePreview:"texture preview",noTextureApplied:"No texture applied",noTextureCoordinates:"This part has no texture coordinates, so an image can't be placed on it.",replaceImage:"Replace image",uploadImage:"Upload image",removeTexture:"Remove texture",texturePosition:"Texture position",offsetX:"Offset X",offsetY:"Offset Y",confirmTexturePosition:"Confirm this texture position and exit positioning mode",donePositioning:"Done positioning",textureOffsetHint:"Double-click the object in the preview to drag its texture directly (scroll to zoom), or edit its offset numerically.",actionToggleLight:"Toggle Light",actionChangeLightColor:"Change Light Color",actionSetBrightness:"Set Brightness",actionChangeColor:"Change Color",actionChangeMaterial:"Change Material",actionToggleVisibility:"Toggle Visibility"};var Ui=new Map(Object.entries(jt).map(([e,t])=>[t,e]));function _n(e){Ge(e);let t=[],o=[{node:e,path:"0",parentId:null}];for(;o.length;){let{node:r,path:s,parentId:a}=o.pop(),i=`node:${s}`,c=r.isMesh&&r.name?Ee(r):null;t.push({id:i,parentId:a,name:r.name||r.type||"Group",...c?{objectId:c}:{}});for(let l=r.children.length-1;l>=0;l--)o.push({node:r.children[l],path:`${s}/${l}`,parentId:i})}let n=new Set;for(let r=t.length-1;r>=0;r--){let s=t[r];(s.objectId||n.has(s.id))&&(n.add(s.id),s.parentId&&n.add(s.parentId))}return t.filter(r=>n.has(r.id))}function zn(e){return structuredClone(e.style??{})}function Fn(e,t,o){let n=Q(e,t).filter(s=>!e[s].removed);if(!n.length)return e;let r={...e};for(let s of n)r[s]={...e[s],style:structuredClone(o)};return r}var Me=require("three"),hr=new Set(["KHR_binary_glTF","KHR_draco_mesh_compression","KHR_lights_punctual","KHR_materials_clearcoat","KHR_materials_dispersion","KHR_materials_ior","KHR_materials_sheen","KHR_materials_specular","KHR_materials_transmission","KHR_materials_iridescence","KHR_materials_anisotropy","KHR_materials_unlit","KHR_materials_volume","KHR_texture_basisu","KHR_texture_transform","KHR_mesh_quantization","KHR_materials_emissive_strength","KHR_materials_variants","EXT_materials_bump","EXT_texture_webp","EXT_texture_avif","EXT_meshopt_compression","EXT_mesh_gpu_instancing"]),yr=new WeakMap;function Sr(e){let t=yr.get(e);return t?structuredClone(t):void 0}function $n(e){if(/^(blob|data):/i.test(e))return"Local resource";let t=e.split(/[?#]/,1)[0].replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).slice(0,300)||"Resource"}function xr(e){return/^(blob|data):/i.test(e)?"Local resource":e.split(/[?#]/,1)[0].replace(/\\/g,"/").replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i,"").replace(/^\/+/,"").slice(0,500)||"Resource"}function wr(e){let t=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0?o:null;return{...e.format?{format:e.format}:{},...e.name?{name:$n(e.name)}:{},sourceBytes:t(e.sourceBytes),loadDurationMs:t(e.loadDurationMs),extensionsUsed:[...new Set(e.extensionsUsed??[])].sort(),extensionsRequired:[...new Set(e.extensionsRequired??[])].sort(),failedResources:[...new Set((e.failedResources??[]).map(xr))].slice(0,50)}}function Mr(e){let t=new Set(e.extensionsRequired);return[...new Set([...e.extensionsUsed??[],...t])].sort().map(o=>({name:o,required:t.has(o),recognized:hr.has(o)}))}function Ar(e,t){let o=e.image,n=l=>typeof l=="number"&&Number.isSafeInteger(l)&&l>0?l:null,r=n(o?.naturalWidth??o?.width),s=n(o?.naturalHeight??o?.height),a=!!e.isCompressedTexture,i=e.mipmaps.reduce((l,u)=>l+(u.data?.byteLength??0),0),c=r&&s?Math.ceil(r*s*4*(e.generateMipmaps?4/3:1)):null;return{name:e.name?$n(e.name):t,width:r,height:s,compressed:a,estimatedBytes:a?i||null:c!==null&&Number.isSafeInteger(c)?c:null}}function qn(e,t={}){let o=wr({...Sr(e),...t.source}),n=[],r=new Set,s=new Map,a=new Set,i=new Map,c=new Map,l=new Set,u=new Map,d=0,p=0,f=0,C=0,R=0,S=(g,m)=>{let b=u.get(g)??{count:0,names:[]};b.count++,b.names.length<20&&b.names.push(m||"Unnamed object"),u.set(g,b)},w=g=>{let m=g?.array??g?.data?.array;m?.buffer&&!l.has(m.buffer)&&(l.add(m.buffer),R+=m.buffer.byteLength)};e.traverse(g=>{let m=g;if(!m.isMesh||!m.geometry)return;d++,p+=m.isInstancedMesh?Number.isSafeInteger(m.count)?Math.max(0,m.count??0):0:1;let b=m.geometry,y=b.getAttribute("position"),k=b.getAttribute("uv"),I=m.material?Array.isArray(m.material)?m.material:[m.material]:[];if(!s.has(b)){let T=!!y&&(!Number.isSafeInteger(y.count)||y.count<0);for(let P=0;!T&&y&&P<y.count;P++)if(!Number.isFinite(y.getX(P))||!Number.isFinite(y.getY(P))||!Number.isFinite(y.getZ(P))){T=!0;break}s.set(b,T)}if(s.get(b)&&S("invalid-positions",g.name),y?.count||S("empty-geometry",g.name),k||S("missing-uv",g.name),b.getAttribute("normal")||S("missing-normals",g.name),b.boundingBox&&[...b.boundingBox.min.toArray(),...b.boundingBox.max.toArray()].some(T=>!Number.isFinite(T))&&S("invalid-bounds",g.name),!r.has(b)){r.add(b),f+=Number.isSafeInteger(y?.count)?Math.max(0,y?.count??0):0;let T=b.index?.count??y?.count??0;C+=Number.isSafeInteger(T)?Math.floor(Math.max(0,T)/3):0,Object.values(b.attributes).forEach(w),Object.values(b.morphAttributes).flat().forEach(w),w(b.index)}let N=!1;for(let T of I){a.add(T);let P=i.get(T);if(!P){P=Object.values(T).filter(F=>!!F&&F.isTexture===!0),i.set(T,P);for(let F of P)c.has(F)||c.set(F,`Texture ${c.size+1}`)}for(let F of P){let te=F.channel??0;b.getAttribute(te===0?"uv":`uv${te}`)||(N=!0)}}N&&S("textured-missing-uv",g.name)});let A=(g,m,b,y,k)=>{let I=u.get(g);I&&n.push({code:g,severity:m,title:b,detail:y,suggestion:k,count:I.count,objects:I.names})};A("empty-geometry","error","Empty mesh geometry","Some meshes have no position data.","Remove empty meshes or export their geometry again."),A("invalid-positions","error","Invalid vertex coordinates","Some vertices contain non-finite coordinates.","Repair NaN or infinite vertex positions in the source application, then re-export."),A("invalid-bounds","error","Invalid geometry bounds","Some cached bounds contain non-finite values.","Repair invalid coordinates in the source application and re-export."),A("textured-missing-uv","warning","Textures have no matching UV coordinates","A texture references a UV channel that its mesh does not contain.","Unwrap the affected meshes and export the UV channel used by each texture."),A("missing-uv","info","Meshes without UVs","Solid colors can work without UVs; image textures and surface decals need them.","Add a UV map before applying image textures or decals."),A("missing-normals","info","Meshes without normals","Some loaded meshes lack vertex normals; generated shading may differ from the source.","Export vertex normals to preserve hard edges and smooth surfaces."),d||n.push({code:"no-meshes",severity:"warning",title:"No mesh geometry found",detail:"This scene contains no loaded meshes.",suggestion:"Check that meshes were included in the export. Streamed scenes may still be loading."});let h=[...c].map(([g,m])=>Ar(g,m)),x=h.filter(g=>(g.width??0)>4096||(g.height??0)>4096);x.length&&n.push({code:"large-textures",severity:"warning",title:"Large texture dimensions",detail:"Some textures exceed 4096 pixels on one side.",suggestion:"Resize textures for the visible detail needed; use KTX2/Basis where appropriate.",count:x.length,objects:x.slice(0,20).map(g=>g.name)}),C>1e6&&n.push({code:"high-triangle-count",severity:"warning",title:"High geometry count",detail:"The loaded geometry contains more than one million unique triangles.",suggestion:"Simplify hidden detail, create lower-detail exports, or use streamed assets for large scenes."}),a.size>100&&n.push({code:"many-materials",severity:"warning",title:"Many material definitions",detail:"More than 100 materials can increase rendering work.",suggestion:"Reuse materials and atlas compatible textures; inspect runtime draw calls to confirm the cost."});let M=Mr(o);for(let g of M.filter(m=>!m.recognized))n.push({code:"unrecognized-extension",severity:g.required?"error":"warning",title:`${g.required?"Required":"Optional"} extension not recognized`,detail:g.name,suggestion:"Export with extensions supported by the bundled loader, or verify the asset's fallback appearance."});o.failedResources?.length&&n.push({code:"failed-resources",severity:"error",title:"Some resources failed to load",detail:"The model may be missing textures or other referenced resources.",suggestion:"Include sidecar files in the ZIP, correct their paths, and check HTTP access and CORS.",count:o.failedResources.length,objects:o.failedResources.slice(0,20)});let E=null,j=[...s.values()].some(Boolean)?new Me.Box3:new Me.Box3().setFromObject(e);!j.isEmpty()&&[...j.min.toArray(),...j.max.toArray(),...j.getSize(new Me.Vector3).toArray()].every(Number.isFinite)&&(E={min:j.min.toArray(),max:j.max.toArray(),center:j.getCenter(new Me.Vector3).toArray(),size:j.getSize(new Me.Vector3).toArray()}),t.scope==="resident-tiles"&&n.unshift({code:"partial-stream",severity:"info",title:"Loaded tiles only",detail:"Geometry and texture counts cover the current resident tiles, not the entire source asset.",suggestion:"Use the live cache/detail statistics to inspect streaming pressure. Rescan after moving the camera."});let D=g=>g.code==="partial-stream"?-1:g.severity==="error"?0:g.severity==="warning"?1:2;return n.sort((g,m)=>D(g)-D(m)),{version:1,status:"ready",scope:t.scope??"asset",source:o,units:o.format==="glb"||o.format==="gltf"?"meters (glTF convention)":"unknown",bounds:E,statistics:{meshes:d,instances:p,geometries:r.size,materials:a.size,textures:c.size,vertices:f,triangles:C,geometryBytes:R,estimatedTextureBytes:h.reduce((g,m)=>g+(m.estimatedBytes??0),0),unknownTextureSizes:h.filter(g=>g.estimatedBytes===null).length,meshesWithoutUvs:u.get("missing-uv")?.count??0,meshesWithoutNormals:u.get("missing-normals")?.count??0},textures:h,extensions:M,issues:n}}var vr=new WeakMap;function Gn(e){e.traverse(t=>{let o=vr.get(t);if(o)throw new Error(o)})}var z=require("three");var et=require("three");function Ie(e){return e.isSkinnedMesh===!0}function Hn(e){let t=[];return e.traverse(o=>{Ie(o)&&t.push(o)}),t}var Ae="reactImmersiveSkinFreeze";function Kn(e){return!!e.userData[Ae]}function tt(e,t,o=[t]){let n=e.userData,r=new et.Matrix4().copy(t).invert(),s=n[Ae];if(s){s.frozenInverse.copy(r),s.restWorldTransforms=o.map(c=>c.clone()),e.bindMatrixInverse.copy(r);return}let a={frozenInverse:r,restWorldTransforms:o.map(c=>c.clone()),previousOnBeforeRender:e.onBeforeRender,previousUpdateMatrixWorld:Object.prototype.hasOwnProperty.call(e,"updateMatrixWorld")?e.updateMatrixWorld:void 0};e.bindMatrixInverse.copy(r);let i=e.updateMatrixWorld;e.updateMatrixWorld=function(c){i.call(this,c),e.bindMatrixInverse.copy(a.frozenInverse)},e.onBeforeRender=function(c,l,u,d,p,f){a.previousOnBeforeRender.call(this,c,l,u,d,p,f),e.bindMatrixInverse.copy(a.frozenInverse)},n[Ae]=a}function _e(e){return e.userData[Ae]?.frozenInverse??null}function Wn(e){return e.userData[Ae]?.restWorldTransforms??null}function Xn(e){let t=e.userData,o=t[Ae];o&&(e.onBeforeRender=o.previousOnBeforeRender,o.previousUpdateMatrixWorld?e.updateMatrixWorld=o.previousUpdateMatrixWorld:delete e.updateMatrixWorld,delete t[Ae],e.updateMatrixWorld(!0))}function Yn(e){let t=e,o=_e(e);o&&t.bindMatrixInverse.copy(o),t.skeleton?.update?.();let n=t.geometry.clone(),r=n.getAttribute("position");if(r){let s=new et.Vector3;for(let a=0;a<r.count;a++)t.getVertexPosition(a,s),r.setXYZ(a,s.x,s.y,s.z);r.needsUpdate=!0}return n.deleteAttribute("skinIndex"),n.deleteAttribute("skinWeight"),n.morphAttributes={},n.morphTargetsRelative=!1,n.computeVertexNormals(),n.computeBoundingBox(),n.computeBoundingSphere(),n}var ie=require("three"),po=require("three/examples/jsm/utils/SkeletonUtils.js"),le=require("fflate");var pe=require("three");function Jn(e){let t=e._loopCount;return e.loop===pe.LoopPingPong&&(t&1)===1}function Cr(e){return Jn(e)?e.getClip().duration-e.time:e.time}function Zn({root:e,clips:t,getClipConfig:o,onChange:n}){let r=new pe.AnimationMixer(e),s=new Map;for(let{clip:m,sourceName:b}of t)s.set(b,r.clipAction(m));let a=new Map,i=new Set,c=new Map,l=1,u=m=>typeof m=="string",d=m=>u(m)?a.has(m)?[m]:[]:[...a.keys()],p=(m,b)=>{let y=Qt(o(b));y==="once"?m.setLoop(pe.LoopOnce,1):y==="ping-pong"?m.setLoop(pe.LoopPingPong,1/0):m.setLoop(pe.LoopRepeat,1/0),m.clampWhenFinished=y==="once"},f=m=>{m.action.setEffectiveTimeScale(m.reverse?-m.speed:m.speed)},C=m=>{let b=a.get(m);b&&(b.action.stop(),a.delete(m))},R=(m,b={})=>{let y=s.get(m);if(!y||o(m)?.hidden)return;let k=Number.isFinite(b.fade)&&b.fade>0?b.fade:0,I=b.reverse??!1;if(!b.alongside)for(let[F,te]of[...a])F!==m&&(k>0?(a.delete(F),te.action.fadeOut(k),i.add(te.action)):C(F));i.delete(y)&&y.stop();let N=y.getClip().duration,T=a.get(m),P=()=>{y.reset(),I&&(y.time=N),y.play()};if(!T)P(),k>0&&y.fadeIn(k);else{let F=I?y.time<=0:y.time>=N;T.finished&&F&&P(),y.paused=!1,y.enabled=!0,a.delete(m)}p(y,m),T={action:y,speed:o(m)?.speed??c.get(m)??l,reverse:I,finished:!1},T.speed=He(T.speed),f(T),a.set(m,T),n()},S=m=>{for(let b of d(m))a.get(b).action.paused=!0;n()},w=m=>{for(let b of d(m))C(b);if(!u(m)){for(let b of i)b.stop();i.clear()}n()},A=(m,b)=>{let y=He(m);u(b)?c.set(b,y):l=y;for(let k of d(b)){let I=a.get(k);c.set(k,y),I.speed=y,f(I)}n()},h=(m,b)=>{for(let y of d(b)){let k=a.get(y),I=k.action.getClip().duration,N=Math.min(Math.max(m,0),I);k.action.time=Jn(k.action)?I-N:N,k.finished&&(k.finished=!1,k.action.paused=!0)}r.update(0),n()},x=()=>{for(let[m,b]of[...a]){let y=o(m);if(y?.hidden){C(m);continue}p(b.action,m),y?.speed!==void 0&&(b.speed=He(y.speed),f(b))}n()},M=m=>{for(let b of a.values())b.action===m.action&&(b.finished=!0);n()};return r.addEventListener("finished",M),{play:R,pause:S,stop:w,setSpeed:A,seek:h,getState:()=>{let m=[...a].map(([y,k])=>({clip:y,status:k.finished?"finished":k.action.paused?"paused":"playing",time:Cr(k.action),duration:k.action.getClip().duration,speed:k.speed,reverse:k.reverse})),b=m[m.length-1];return{currentClip:b?.clip??null,isPlaying:m.some(y=>y.status==="playing"),speed:b?.speed??l,time:b?.time??0,duration:b?.duration??0,active:m}},applyClipConfigs:x,isRunning:()=>{if(i.size>0)return!0;for(let{action:m}of a.values())if(!m.paused&&m.enabled)return!0;return!1},update:m=>{r.update(m);for(let b of i)(!b.enabled||b.getEffectiveWeight()<=0)&&(b.stop(),i.delete(b))},dispose:()=>{r.removeEventListener("finished",M),r.stopAllAction(),r.uncacheRoot(e),a.clear(),i.clear()}}}var Pt=require("three");var nt=require("react"),Tt=require("three");function Qn(e){return[e.x,e.y,e.z]}function eo(e,t){let o=new Tt.Vector3,n=new Tt.Vector3;return t.getPosition(o),t.getTarget(n),{position:Qn(o),target:Qn(n),fov:"fov"in e&&typeof e.fov=="number"?e.fov:null,zoom:"zoom"in e&&typeof e.zoom=="number"?e.zoom:1,azimuthAngle:t.azimuthAngle,polarAngle:t.polarAngle}}var ce=require("three");function kr(e){return new ce.Matrix4().set(1,e[0],e[1],0,0,1,e[2],0,0,0,1,0,0,0,0,1)}function Rt(e,t){e.matrixAutoUpdate=!t,e.updateMatrix(),t&&(e.matrix.makeRotationFromQuaternion(e.quaternion).multiply(kr(t)).scale(e.scale).setPosition(e.position),e.matrixWorldNeedsUpdate=!0)}function to(e,t,o){let n=new ce.Vector3().setFromMatrixColumn(e,0),r=new ce.Vector3().setFromMatrixColumn(e,1),s=new ce.Vector3().setFromMatrixColumn(e,2),a=(C,R)=>{let S=C*(R<0?-1:1);return Math.abs(S-R)<1e-10?R:S},i=a(n.length(),t.x);if(Math.abs(i)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};n.divideScalar(i);let c=n.dot(r);r.addScaledVector(n,-c);let l=a(r.length(),t.y);if(Math.abs(l)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};r.divideScalar(l);let u=n.dot(s);s.addScaledVector(n,-u);let d=r.dot(s);s.addScaledVector(r,-d);let p=a(s.length(),t.z);if(Math.abs(p)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};s.divideScalar(p);let f=[c/l,u/p,d/p].map(C=>Math.abs(C)<1e-10?0:C);return{rotation:new ce.Quaternion().setFromRotationMatrix(new ce.Matrix4().makeBasis(n,r,s)).normalize(),scale:new ce.Vector3(i,l,p),shear:f.some(Boolean)?f:void 0}}var It=e=>e==="baseColor"?"color":e;function no(e){let t=new Set;return e.traverse(o=>{let n=o;if(n.isMesh)for(let r of Array.isArray(n.material)?n.material:[n.material])r&&t.add(r)}),[...t]}function oo({root:e,controls:t,animations:o,invalidate:n,cameraEnabled:r=()=>!0}){let s=new Map,a=new Map,i=new Map,c=new Set,l=new Map,u=null,d="",p=h=>e()?Jt(e(),h):null,f=h=>{if(h.kind==="camera"){let D=t();if(!D)return null;let g=eo(D.camera,D);return{position:g.position,target:g.target,fov:g.fov,zoom:g.zoom}}if(h.kind==="clip"){let D=o();return D?.clips.includes(h.clip)?D.getState?.().active.find(g=>g.clip===h.clip)?.time??0:null}let x=p(h.objectId);if(!x)return null;let M=h.property;if(M==="position"||M==="rotation"||M==="scale")return[x[M].x,x[M].y,x[M].z];if(M==="visible")return x.visible;let E=no(x).find(D=>D[It(M)]!==void 0),j=E?E[It(M)]:void 0;return j?.isColor?`#${j.getHexString()}`:typeof j=="number"?j:null},C=h=>{if(!r())return;let x=t();x&&(x.stop(),x.setLookAt(...h.position,...h.target,!1),h.fov!==null&&"fov"in x.camera&&(x.camera.fov=h.fov,x.camera.updateProjectionMatrix()),x.zoomTo(h.zoom,!1),x.update(0))},R=h=>{if(s.has(h))return;h.updateWorldMatrix(!0,!0);let x=h.matrixAutoUpdate?void 0:to(h.matrix,h.scale,h.quaternion).shear;s.set(h,{position:h.position.toArray(),rotation:[h.rotation.x,h.rotation.y,h.rotation.z],scale:h.scale.toArray(),matrix:h.matrix.clone(),auto:h.matrixAutoUpdate,shear:x});for(let M of Hn(h))Kn(M)||(tt(M,M.matrixWorld),c.add(M))},S=(h,x)=>{let M=o();M?.stop(h),x&&M&&(M.play(h,{alongside:!0,reverse:x.reverse}),M.setSpeed(x.speed,h),M.seek?.(x.time,h),x.status!=="playing"&&M.pause(h))};return{capture:f,restore:()=>{for(let[h,x]of l)S(h,x);l.clear();for(let[h,x]of s)h.position.fromArray(x.position),h.rotation.set(...x.rotation),h.scale.fromArray(x.scale),h.matrix.copy(x.matrix),h.matrixAutoUpdate=x.auto,h.matrixWorldNeedsUpdate=!0;s.clear(),a.forEach((h,x)=>x.visible=h),a.clear(),i.forEach((h,x)=>{h.forEach((M,E)=>{M instanceof Pt.Color?x[E].copy(M):x[E]=M}),x.needsUpdate=!0}),i.clear(),c.forEach(Xn),c.clear(),u&&C(u),u=null,d="",e()?.updateWorldMatrix(!0,!0),n()},inspect:h=>h.tracks.filter(x=>!x.muted&&x.keyframes.length&&(x.target.kind!=="camera"||r())&&f(x.target)===null).map(x=>`Unavailable target: ${x.name}.`),invalidate:n,apply:({sequence:h,time:x,playing:M})=>{let E=h.tracks.filter(g=>g.target.kind!=="camera"||r()).map(g=>({track:g,value:We(g,x)})).filter(g=>g.value!==null);for(let[g,m]of l)E.some(({track:b})=>b.target.kind==="clip"&&b.target.clip===g)||(S(g,m),l.delete(g));for(let{track:g}of E)if(g.target.kind==="object"&&["position","rotation","scale"].includes(g.target.property)){let m=p(g.target.objectId);m&&R(m)}let j=new Map([...i.keys()].map(g=>[g,g.transparent]));a.forEach((g,m)=>m.visible=g),s.forEach((g,m)=>{m.position.fromArray(g.position),m.rotation.set(...g.rotation),m.scale.fromArray(g.scale),Rt(m,g.shear)}),i.forEach((g,m)=>g.forEach((b,y)=>{b instanceof Pt.Color?m[y].copy(b):m[y]=b}));let D=o();for(let{track:g,value:m}of E){if(g.target.kind!=="clip"||!D?.seek||!D.clips.includes(g.target.clip))continue;let b=g.target.clip;l.has(b)||(l.set(b,D.getState?.().active.find(y=>y.clip===b)),D.play(b,{alongside:!0}),D.pause(b)),D.seek(m,b)}for(let{track:g,value:m}of E){let b=g.target;if(b.kind==="clip")continue;if(b.kind==="camera"){u||(u=f(b));let I=JSON.stringify(m);(M||I!==d)&&(C(m),d=I);continue}let y=p(b.objectId);if(!y)continue;let k=b.property;if(k==="visible")a.has(y)||a.set(y,y.visible),y.visible=m;else if(k==="position"||k==="rotation"||k==="scale")k==="rotation"?y.rotation.set(...m):y[k].fromArray(m),Rt(y,s.get(y)?.shear);else for(let I of no(y)){let N=It(k),T=I[N];if(T===void 0)continue;let P=i.get(I);if(P||(P=new Map,i.set(I,P)),j.has(I)||j.set(I,I.transparent),P.has(N)||P.set(N,T?.isColor?T.clone():T),T?.isColor?T.set(m):I[N]=m,k==="opacity"){P.has("transparent")||P.set("transparent",I.transparent);let F=m<1||P.get("transparent")===!0;I.transparent=F}}}u&&!E.some(({track:g})=>g.target.kind==="camera")&&(C(u),d=""),j.forEach((g,m)=>{g!==m.transparent&&(m.needsUpdate=!0)}),e()?.updateWorldMatrix(!0,!0)}}}function ro(e){let t=new Map;return e.map((o,n)=>{let s=o.name.trim()||`Animation ${n+1}`,a=t.get(s)??0;return t.set(s,a+1),{clip:o,sourceName:a===0?s:`${s} (${a+1})`,duration:o.duration}})}var X=require("three");function Or(e){let t=e.getAttribute("arSourceVertex"),o=e.getAttribute("arNormalSign");if(!t)return;let n=new Map,r=[],s=[];for(let i=0;i<t.count;i++){let c=`${t.getX(i)}:${o?.getX(i)??1}`,l=n.get(c);l===void 0&&(l=r.length,r.push(i),n.set(c,l)),s.push(l)}let a=e.index?Array.from(e.index.array,i=>s[i]):s;for(let[i,c]of Object.entries(e.attributes)){let l=new Float32Array(r.length*c.itemSize);r.forEach((u,d)=>{for(let p=0;p<c.itemSize;p++)l[d*c.itemSize+p]=c.getComponent(u,p)}),e.setAttribute(i,new X.BufferAttribute(l,c.itemSize))}e.setIndex(a)}function io(e,t,o,n){let r=[],s=[],a=new Map;for(let i of e){let c=i.source;if(!c.isSkinnedMesh)continue;let l=t.get(c),u=c.skeleton,d=JSON.stringify(u.bones.map((g,m)=>[g.uuid,u.boneInverses[m].elements])),p=a.get(d);if(!p){let g=new Map(u.bones.map((T,P)=>[T,P])),m=u.bones.map(T=>{for(let P=T.parent;P;P=P.parent)if(g.has(P))return g.get(P);return-1}),b=[],y=T=>{b.includes(T)||(m[T]>=0&&y(m[T]),b.push(T))};u.bones.forEach((T,P)=>y(P));let k=b.map(T=>b.indexOf(m[T])),I=[];b.forEach((T,P)=>I.push(`${k[P]<0?"":I[k[P]]+"/"}J_${T}`));let N={name:`${n}_${r.length}`,joints:I,parents:k,bones:b.map(T=>t.get(u.bones[T])),bindTransforms:b.map(T=>u.boneInverses[T].clone().invert()),restTransforms:[],worlds:b.map(()=>new X.Matrix4),referenceInverse:o.clone().invert(),frames:[]};if(N.bones.some(T=>!T))throw new Error("The AR skeleton has joints outside the exported scene.");p={rig:N,order:b},a.set(d,p),r.push(N)}Or(i.exported.geometry);let f=i.exported.geometry.getAttribute("arSourceVertex"),C=c.geometry.getAttribute("skinIndex"),R=c.geometry.getAttribute("skinWeight");if(!f||!C||!R||C.itemSize!==4||R.itemSize!==4)throw new Error("AR skeletal animation needs four joint indices and weights per vertex.");let S={target:i,node:l,rig:p.rig,reference:o,geomBind:c.bindMatrix.clone(),jointIndices:[],jointWeights:[],jointBounds:p.order.map(()=>new X.Box3),extent:new X.Box3},w=i.exported.geometry.getAttribute("position"),A=i.exported.geometry.getAttribute("normal"),h=c.geometry.getAttribute("normal"),x=i.exported.geometry.getAttribute("arNormalSign"),M=new X.Vector3,E=new X.Vector3,j=new Map(p.order.map((g,m)=>[g,m])),D=S.rig.bindTransforms.map(g=>g.clone().invert().multiply(c.bindMatrix));for(let g=0;g<f.count;g++){let m=f.getX(g);if(X.Mesh.prototype.getVertexPosition.call(c,m,M),w.setXYZ(g,M.x,M.y,M.z),h&&A){E.fromBufferAttribute(h,m);let y=E.clone();c.geometry.morphAttributes.normal?.forEach((k,I)=>{let N=c.morphTargetInfluences?.[I]??0;N&&E.addScaledVector(new X.Vector3().fromBufferAttribute(k,m).sub(c.geometry.morphTargetsRelative?new X.Vector3:y),N)}),E.normalize().multiplyScalar(x?.getX(g)??1),A.setXYZ(g,E.x,E.y,E.z)}let b=[0,1,2,3].reduce((y,k)=>y+R.getComponent(m,k),0);if(!Number.isFinite(b)||b<=0)throw new Error("The AR skin has a vertex without valid joint weights.");for(let y=0;y<4;y++){let k=R.getComponent(m,y)/b,I=k?j.get(C.getComponent(m,y))??-1:0;if(I<0||!Number.isFinite(k)||k<0)throw new Error("The AR skin has invalid joint indices or weights.");S.jointIndices.push(I),S.jointWeights.push(k),k&&S.jointBounds[I].expandByPoint(M.clone().applyMatrix4(D[I]))}}w.needsUpdate=!0,A?A.needsUpdate=!0:i.exported.geometry.computeVertexNormals(),i.exported.geometry.computeBoundingBox(),i.exported.matrixAutoUpdate=!1,i.exported.matrix.copy(Vt(S)),s.push(S)}return{rigs:r,skins:s}}function Vt(e){return e.node.matrixWorld.clone().multiply(e.node.bindMatrixInverse).multiply(e.reference)}function so(e,t,o){let n=new X.Vector3,r=new X.Quaternion,s=new X.Vector3,a=new X.Matrix4;for(let i of e){let c={time:o,translations:[],rotations:[],scales:[]};i.bones.forEach((l,u)=>i.worlds[u].multiplyMatrices(i.referenceInverse,l.matrixWorld)),i.worlds.forEach((l,u)=>{let d=i.parents[u],p=d<0?l.clone():i.worlds[d].clone().invert().multiply(l);p.decompose(n,r,s),r.normalize(),a.compose(n,r,s);let f=1e-5*Math.max(1,...p.elements.map(Math.abs));if(!p.elements.every(Number.isFinite)||p.elements.some((C,R)=>Math.abs(C-a.elements[R])>f)||Math.abs(p.determinant())<1e-15)throw new Error("The AR skeleton contains a sheared or zero-scale joint that Quick Look cannot preserve. Use arHandoff.createUSDZ for this rig.");c.translations.push(...n.toArray()),c.rotations.push(r.w,r.x,r.y,r.z),c.scales.push(...s.toArray()),i.frames.length||i.restTransforms.push(p)}),i.frames.push(c)}for(let i of t)i.jointBounds.forEach((c,l)=>{c.isEmpty()||i.extent.union(c.clone().applyMatrix4(i.rig.worlds[l]))})}var Dt=e=>String(Number(e.toPrecision(9))),Bt=e=>{let t=Array.isArray(e)?e:e.elements;return`(${[0,4,8,12].map(o=>`(${t.slice(o,o+4).map(Dt).join(", ")})`).join(", ")})`},Et=(e,t)=>Array.from({length:e.length/t},(o,n)=>`(${e.slice(n*t,(n+1)*t).map(Dt).join(", ")})`).join(", ");function ao(e){let t=(a,i,c=1e-7)=>Math.abs(a-i)>c*Math.max(1,Math.abs(a),Math.abs(i)),o=[["translations",3,"float3"],["rotations",4,"quatf"],["scales",3,"half3"]],n=e.frames[0],r=e.joints.map((a,i)=>i).filter(a=>o.some(([i,c])=>e.frames.some(l=>l[i].slice(a*c,(a+1)*c).some((u,d)=>t(u,n[i][a*c+d])))));r.length||(r=e.joints.map((a,i)=>i));let s=o.map(([a,i,c])=>{let l=e.frames.map(d=>r.flatMap(p=>d[a].slice(p*i,(p+1)*i)));return l.some(d=>d.some((p,f)=>t(p,l[0][f],c==="half3"?1e-4:1e-7)))?`${c}[] ${a}.timeSamples = {${e.frames.map((d,p)=>`${d.time}: [${Et(l[p],i)}]`).join(`,
3
+ `)}}`:`${c}[] ${a} = [${Et(l[0],i)}]`}).join(`
4
+ `);return`#usda 1.0
5
+ (
6
+ defaultPrim = "Skeleton"
7
+ metersPerUnit = 1
8
+ upAxis = "Y"
9
+ timeCodesPerSecond = 30
10
+ framesPerSecond = 30
11
+ )
12
+ def Skeleton "Skeleton" (prepend apiSchemas = ["SkelBindingAPI"]) {
13
+ uniform token[] joints = ${JSON.stringify(e.joints)}
14
+ uniform matrix4d[] bindTransforms = [${e.bindTransforms.map(Bt).join(", ")}]
15
+ uniform matrix4d[] restTransforms = [${e.restTransforms.map(Bt).join(", ")}]
16
+ rel skel:animationSource = <Animation>
17
+ def SkelAnimation "Animation" {
18
+ uniform token[] joints = ${JSON.stringify(r.map(a=>e.joints[a]))}
19
+ ${s}
20
+ }
21
+ }
22
+ `}function co(e,t){let o=new Map;for(let n of e){let r=n.target.exported,s=t.get(r.name),a=l=>Math.round(l*1e7)/1e7,i=JSON.stringify([n.rig.name,s?.map(l=>l.matrix.map(a))??r.matrix.elements.map(a)]),c=o.get(i);if(!c){let l=new X.Group;l.name=`AR_Rig_${o.size}`,l.matrixAutoUpdate=!1,l.matrix.copy(r.matrix),r.parent.add(l),c={node:l,rig:n.rig,skins:[],extent:new X.Box3},o.set(i,c),s&&t.set(l.name,s)}c.node.add(r),r.matrix.identity(),t.delete(r.name),c.skins.push(n),c.extent.union(n.extent)}return[...o.values()]}function lo(e){return`
23
+ rel skel:skeleton = <Skeleton>
24
+ rel skel:animationSource = <Skeleton/Animation>
25
+ float3[] extent = [${Et([...e.extent.min.toArray(),...e.extent.max.toArray()],3)}]
26
+ def Skeleton "Skeleton" (prepend references = @./rigs/${e.rig.name}.usda@</Skeleton>) {}
27
+ `}function uo(e){return`
28
+ over "Geometry" (prepend apiSchemas = ["SkelBindingAPI"]) {
29
+ rel skel:skeleton = <../../Skeleton>
30
+ uniform token[] skel:joints = ${JSON.stringify(e.rig.joints)}
31
+ uniform token primvars:skel:skinningMethod = "classicLinear"
32
+ matrix4d primvars:skel:geomBindTransform = ${Bt(e.geomBind)}
33
+ int[] primvars:skel:jointIndices = [${e.jointIndices.join(", ")}] (
34
+ interpolation = "vertex"
35
+ elementSize = 4
36
+ )
37
+ float[] primvars:skel:jointWeights = [${e.jointWeights.map(Dt).join(", ")}] (
38
+ interpolation = "vertex"
39
+ elementSize = 4
40
+ )
41
+ }
42
+ `}var ve=30,jr=12e4,Tr=1e6,mo=new Set(["position","quaternion","rotation","scale"]);function Rr(e){let t=Oe(e.sceneConfig?.sequences??[]).find(l=>l.autoPlay),o=e.sceneConfig?.animations.autoplayClip,n=ro(e.scene.animations),r=n.find(l=>l.sourceName===o),s=e.sceneConfig?.animations.clips.find(l=>l.sourceName===o),a=s?.speed??1,i=Number.isFinite(a)&&a>0?a:1,c=r&&!s?.hidden?r.duration*(s?.loopMode==="ping-pong"?2:1)/i:0;return{sequence:t,autoplay:o,clips:n,duration:Math.max(c,t?.duration??0)}}function fo(e,t,o){let n=new Set,r=new Map,s=0,a=0,i=0,c=[],l=[],u=e.map(Rr),d=Math.max(0,...u.map(p=>p.duration));for(let[p,f]of e.entries()){o?.throwIfAborted();let{sequence:C,autoplay:R}=u[p];if(!C&&!R)continue;let S=(0,po.clone)(f.scene),w=[],A=[];f.scene.traverse(v=>w.push(v)),S.traverse(v=>A.push(v));let h=new Map;w.forEach((v,U)=>{A[U].uuid=v.uuid,h.set(v,A[U]);let L=_e(v);L&&v.isSkinnedMesh&&(delete A[U].userData.reactImmersiveSkinFreeze,tt(A[U],L.clone().invert(),Wn(v)??void 0))});let x=Ge(S),M=new ie.Group;M.matrixAutoUpdate=!1,M.matrix.copy(f.scene.parent?.matrixWorld??new ie.Matrix4),M.add(S),M.updateMatrixWorld(!0);let E=t.filter(v=>v.sourceIndex===p),j=E.some(v=>v.source.isSkinnedMesh),D=new Set(C?.tracks.filter(v=>!v.muted&&v.target.kind==="clip").map(v=>v.target.kind==="clip"?v.target.clip:"")??[]);R&&D.add(R);let g=u[p].clips.map(v=>{if(!D.has(v.sourceName))return v;let U=v.clip.tracks.filter(L=>{let G=ie.PropertyBinding.parseTrackName(L.name),ne=ie.PropertyBinding.findNode(S,G.nodeName),V=!!ne&&mo.has(G.propertyName)&&(ne?.type!=="Bone"||j)&&!G.objectName;return V||n.add(ne?.type==="Bone"?"Skeletal tracks without an exported skinned mesh are omitted.":"Quick Look exports object and skeletal motion. Morph and other unsupported clip tracks keep their captured pose."),V});return{...v,clip:new ie.AnimationClip(v.clip.name,v.duration,U)}}),m=v=>f.sceneConfig?.animations.clips.find(U=>U.sourceName===v),b=Zn({root:S,clips:g,getClipConfig:m,onChange(){}}),y={...b,clips:g.map(v=>v.sourceName)},k=oo({root:()=>S,controls:()=>null,animations:()=>y,invalidate(){},cameraEnabled:()=>!1}),I=C?.tracks.filter(v=>{if(!j&&v.target.kind==="object"&&x.nodesById[v.target.objectId]?.type==="Bone")return v.muted||n.add("Quick Look keeps skeletal deformation at its captured pose."),!1;let U=v.target.kind==="clip"||v.target.kind==="object"&&mo.has(v.target.property);return!U&&!v.muted&&n.add("Quick Look exports sequence object motion. Camera, visibility and appearance tracks stay in WebXR."),U}),N=C?{...C,tracks:I??[]}:void 0;N&&k.inspect(N).forEach(v=>n.add(v));let T=g.some(v=>D.has(v.sourceName)&&v.clip.tracks.length&&!m(v.sourceName)?.hidden),P=I?.some(v=>!v.muted&&v.keyframes.length&&v.target.kind==="object");if(!T&&!P){b.dispose();continue}let F=io(E,h,M.matrix,`Skin_${p}`),te=new Map(F.skins.map(v=>[v.target,v])),Z=d,se=Math.ceil(Z*ve);if(a+=(se+1)*E.length,i+=(se+1)*F.rigs.reduce((v,U)=>v+U.joints.length,0),!Number.isFinite(Z)||a>jr||i>Tr)throw b.dispose(),new Error("This animation is too large for browser USDZ conversion. Use arHandoff.createUSDZ for this model.");let Pe=Object.entries(f.objectBindings??{}).flatMap(([v,U])=>{if(!U.transform)return[];let L=x.nodesById[U.modelObjectId??v];return L?[{node:L,matrix:L.matrix.clone(),position:L.position.clone(),quaternion:L.quaternion.clone(),scale:L.scale.clone()}]:[]}),q=E.map(v=>({target:v,node:h.get(v.source),inverse:v.bakedMatrix.clone().invert(),frames:[]}));try{R&&b.play(R);let v=0;for(let U=0;U<=se;U++){o?.throwIfAborted();let L=Math.min(U/ve,Z);b.update(L-v),v=L;for(let G of Pe)G.node.position.copy(G.position),G.node.quaternion.copy(G.quaternion),G.node.scale.copy(G.scale),G.node.matrix.copy(G.matrix);if(N){let G=N.loop&&L>N.duration?L%N.duration:Math.min(L,N.duration);k.apply({sequence:N,time:G,playing:!1})}M.updateMatrixWorld(!0),so(F.rigs,F.skins,L*ve);for(let G of q){let ne=te.get(G.target),V=ne?Vt(ne):G.node.matrixWorld.clone().multiply(G.target.instanceMatrix).multiply(G.inverse);if(!V.elements.every(Number.isFinite)||V.determinant()<=0)throw new Error("Quick Look animation cannot preserve a reflected or zero-scale transform. Use arHandoff.createUSDZ.");G.frames.push({time:L*ve,matrix:V.toArray()})}}for(let U of q){let L=U.frames[0]?.matrix;L&&U.frames.some(G=>G.matrix.some((ne,V)=>Math.abs(ne-L[V])>1e-8))&&(r.set(U.target.exported.name,U.frames),s=Math.max(s,Z))}if(F.skins.length){for(let U of F.skins)U.extent.expandByScalar(Math.max(1e-6,U.extent.getSize(new ie.Vector3).length()*.001));c.push(...F.rigs),l.push(...F.skins),s=Math.max(s,Z)}}finally{k.restore(),b.dispose()}}return{samples:r,rigs:c,skins:l,duration:s,warnings:[...n]}}function go(e,t,o){if(!t.samples.size&&!t.skins.length)return e;let n=(0,le.unzipSync)(e),r=(0,le.strFromU8)(n["model.usda"]);r=r.replace(" metersPerUnit = 1",` startTimeCode = 0
43
+ endTimeCode = ${t.duration*ve}
44
+ timeCodesPerSecond = ${ve}
45
+ framesPerSecond = ${ve}
46
+ autoPlay = true
47
+ metersPerUnit = 1`);for(let[i,c]of t.samples){let l=new RegExp(`(def Xform "${i}"[\\s\\S]*?\\n[\\t ]*)matrix4d xformOp:transform = [^\\n]+`);if(!l.test(r))throw new Error("The USDZ exporter produced an unsupported animation layout.");let u=c.map(d=>{let p=[0,4,8,12].map(f=>`(${d.matrix.slice(f,f+4).join(", ")})`);return`${d.time}: (${p.join(", ")})`}).join(`,
48
+ `);r=r.replace(l,(d,p)=>`${p}matrix4d xformOp:transform.timeSamples = {
49
+ ${u}
50
+ }`)}for(let i of t.rigs)n[`rigs/${i.name}.usda`]=(0,le.strToU8)(ao(i));for(let i of o){let c=new RegExp(`def Xform "${i.node.name}"(\\s*\\{)`);if(!c.test(r))throw new Error("The USDZ exporter produced an unsupported skeleton root layout.");r=r.replace(c,`def SkelRoot "${i.node.name}" (prepend apiSchemas = ["SkelBindingAPI"]) $1${lo(i)}`)}for(let i of t.skins){let c=new RegExp(`def Xform "${i.target.exported.name}"(\\s*\\([\\s\\S]*?\\)\\s*\\{)`);if(!c.test(r))throw new Error("The USDZ exporter produced an unsupported skeleton layout.");r=r.replace(c,(l,u)=>`def Xform "${i.target.exported.name}"${u}${uo(i)}`)}n["model.usda"]=(0,le.strToU8)(r);let s={},a=0;for(let[i,c]of Object.entries(n)){a+=34+(0,le.strToU8)(i).length;let l=a&63;s[i]=l===4?c:[c,{extra:{12345:new Uint8Array(64-l)}}],a=c.length}return(0,le.zipSync)(s,{level:0})}function Ir(e,t={}){t.signal?.throwIfAborted();let o=new z.Group,n=new z.Group;o.add(n);let r=new Set,s=[],a=[],i=[],c=new Map,l=[],u=0,d=0,p=()=>{s.forEach(f=>f.dispose()),a.forEach(f=>f.dispose()),i.forEach(f=>f.dispose())};try{for(let[w,{scene:A,objectBindings:h={},materialOverrides:x={}}]of e.entries()){Gn(A),A.updateWorldMatrix(!0,!0);let M=new Map(Object.entries(h).map(([E,j])=>[j.modelObjectId??E,E]));A.traverse(E=>{let j=E;if(!j.isMesh||!j.geometry)return;for(let k=E;k;k=k.parent){let I=Ee(k)??k.name??k.uuid;if(!k.visible||h[M.get(I)??I]?.visible===!1||h[M.get(I)??I]?.removed)return}let D=Ee(j)??j.name??j.uuid,g=x[M.get(D)??D]??j.material;if(!g)throw new Error(`Material for ${D} is not ready. Wait for the model to finish loading.`);let m=Array.isArray(g)?g:[g],b=j.isInstancedMesh?j.count:1;if(j.userData.riDecal&&Ie(j)&&j.parent){let k=_e(j.parent);k&&j.bindMatrixInverse.copy(k)}let y=Ie(j)?Yn(j):j.geometry.clone();try{if(!Ie(j)&&j.morphTargetInfluences?.some(N=>N!==0)){let N=y.getAttribute("position"),T=new z.Vector3;for(let P=0;P<N.count;P++)j.getVertexPosition(P,T),N.setXYZ(P,T.x,T.y,T.z);y.morphAttributes={},y.computeVertexNormals()}if(!y.getAttribute("position"))throw new Error(`Mesh ${D} has no positions.`);let k=y.index?.count??y.getAttribute("position").count,I=Array.isArray(g)?y.groups:[{start:0,count:k,materialIndex:0}];if(!I.length)throw new Error(`Mesh ${D} has multiple materials without geometry groups.`);for(let N=0;N<b;N++){let T=j.matrixWorld.clone(),P=new z.Matrix4;j.isInstancedMesh&&(j.getMatrixAt(N,P),T.multiply(P));for(let F of I){let te=m[F.materialIndex??0];if(!te)throw new Error(`A material group on ${D} is missing its material.`);if(!te.visible)continue;let Z=te;if(!Z.isMeshStandardMaterial||Z.wireframe||Z.vertexColors)throw new Error(`AR snapshot cannot preserve ${te.type}${Z.wireframe?" wireframe":Z.vertexColors?" vertex colors":""} on ${D}. Use a PBR material or provide arHandoff.createUSDZ.`);let se=Math.max(F.start,y.drawRange.start),Pe=Math.min(k,F.start+F.count,y.drawRange.start+y.drawRange.count);if(Pe<=se)continue;if(se%3||(Pe-se)%3)throw new Error(`Mesh ${D} has an incomplete triangle range.`);let q=new z.BufferGeometry;s.push(q);let v=Array.from({length:Pe-se},(V,$)=>y.index?y.index.getX(se+$):se+$);if(T.determinant()<0)for(let V=0;V<v.length;V+=3)[v[V+1],v[V+2]]=[v[V+2],v[V+1]];for(let[V,$]of Object.entries(y.attributes)){let K=new Float32Array(v.length*$.itemSize);for(let B=0;B<v.length;B++)for(let J=0;J<$.itemSize;J++)K[B*$.itemSize+J]=$.getComponent(v[B],J);q.setAttribute(V,new z.BufferAttribute(K,$.itemSize))}Ie(j)&&(q.setAttribute("arSourceVertex",new z.BufferAttribute(new Float32Array(v),1)),q.setAttribute("arNormalSign",new z.BufferAttribute(new Float32Array(v.length).fill(1),1))),q.setIndex(v.map((V,$)=>$)),q.applyMatrix4(T);let U=q.getAttribute("position");for(let V=0;V<U.count;V++)if(![U.getX(V),U.getY(V),U.getZ(V)].every(Number.isFinite))throw new Error(`Mesh ${D} contains invalid coordinates.`);q.getAttribute("normal")||q.computeVertexNormals();let L=Z.clone();a.push(L);let G=Z.userData.reactImmersiveConfiguredEmissive;if(G?.isColor&&L.emissive.copy(G),L.side===z.DoubleSide){let V=q.toNonIndexed();s.push(V);let $=V.getAttribute("position").count,K=new z.BufferGeometry;s.push(K);for(let[B,J]of Object.entries(V.attributes)){let rt=new Float32Array($*J.itemSize*2);for(let he=0;he<$;he++)for(let ke=0;ke<J.itemSize;ke++){rt[he*J.itemSize+ke]=J.getComponent(he,ke);let To=Math.floor(he/3)*3+(2-he%3);rt[($+he)*J.itemSize+ke]=J.getComponent(To,ke)*(B==="normal"||B==="arNormalSign"?-1:1)}K.setAttribute(B,new z.BufferAttribute(rt,J.itemSize))}L.side=z.FrontSide,q.copy(K)}else if(L.side!==z.FrontSide){let V=q.getIndex();for(let B=0;B<V.count;B+=3){let J=V.getX(B+1);V.setX(B+1,V.getX(B+2)),V.setX(B+2,J)}let $=q.getAttribute("normal");for(let B=0;B<$.count;B++)$.setXYZ(B,-$.getX(B),-$.getY(B),-$.getZ(B));let K=q.getAttribute("arNormalSign");if(K)for(let B=0;B<K.count;B++)K.setX(B,-K.getX(B));L.side=z.FrontSide}if(j.isInstancedMesh&&j.instanceColor){let V=new z.Color;j.getColorAt(N,V),L.color.multiply(V)}for(let[V,$]of Object.entries(L)){if(!$?.isTexture)continue;let K=$;if(un(K)||!K.image||K.image.complete===!1)throw new Error(`Texture on ${D} is not ready. Wait for image loading or replace failed textures before preparing AR.`);let B=c.get(K);if(B||(B=K.clone(),c.set(K,B),i.push(B)),L[V]=B,!q.getAttribute(B.channel?`uv${B.channel}`:"uv"))throw new Error(`Texture on ${D} needs UV coordinates missing from this geometry.`)}if(j.userData.riDecal){q.computeBoundingBox();let V=Math.max(1e-6,q.boundingBox.getSize(new z.Vector3).length()*1e-4),$=q.getAttribute("position"),K=q.getAttribute("normal");for(let B=0;B<$.count;B++)$.setXYZ(B,$.getX(B)+K.getX(B)*V,$.getY(B)+K.getY(B)*V,$.getZ(B)+K.getZ(B)*V)}let ne=new z.Mesh(q,L);ne.name=`AR_${u++}`,n.add(ne),l.push({sourceIndex:w,source:j,exported:ne,bakedMatrix:T.clone(),instanceMatrix:P}),d+=(q.index?.count??q.getAttribute("position").count)/3,(L.clearcoat||L.transmission||L.iridescence||L.anisotropy)&&r.add("Advanced PBR effects may look different in Quick Look.")}}}finally{y.dispose()}})}if(!u||!d)throw new Error("There is no visible model geometry to send to AR.");let f=new z.Box3().setFromObject(n),C=f.getSize(new z.Vector3),R=f.getCenter(new z.Vector3),S=t.scaleMode==="real-world"?1:1/Math.max(C.x,C.y,C.z,1e-9);return n.position.set(-R.x*S,-f.min.y*S,-R.z*S),n.scale.setScalar(S),o.updateMatrixWorld(!0),r.add("Viewer lighting, background, post-processing, annotations and measurement overlays stay in the web viewer."),{root:o,meshCount:u,triangleCount:d,scale:S,warnings:[...r],textures:i,motionMeshes:l,dispose:p}}catch(f){throw p(),f}}async function bo(e,t={}){let o=t.maxTextureSize??2048;if(!Number.isInteger(o)||o<256||o>4096)throw new Error("AR maxTextureSize must be an integer from 256 to 4096.");let n=Ir(e,t),r=[];try{let s=fo(e,n.motionMeshes,t.signal),a=co(s.skins,s.samples);n.root.updateMatrixWorld(!0);let{USDZExporter:i}=await import("three/examples/jsm/exporters/USDZExporter.js");t.signal?.throwIfAborted();for(let u of n.textures){if(!u.isCompressedTexture)continue;let{decompress:d}=await import("three/examples/jsm/utils/WebGLTextureUtils.js"),p=d(u,o);r.push(p),n.root.traverse(f=>{let C=f.material;if(C)for(let R of Object.keys(C))C[R]===u&&(C[R]=p)})}let c=await new i().parseAsync(n.root,{onlyVisible:!0,quickLookCompatible:!0,maxTextureSize:o});t.signal?.throwIfAborted();let l=go(c,s,a);return{blob:new Blob([new Uint8Array(l)],{type:"model/vnd.usdz+zip"}),meshCount:n.meshCount,triangleCount:n.triangleCount,scale:n.scale,warnings:[...n.warnings,...s.warnings]}}catch(s){if(t.signal?.aborted)throw s;let a=s instanceof Error&&s.name==="SecurityError"?" Textures must allow cross-origin canvas access.":"";throw new Error(`Could not prepare the configured USDZ: ${s instanceof Error?s.message:"export failed"}${a}`)}finally{n.dispose(),r.forEach(s=>s.dispose())}}var fe=require("fflate");var Nt="ri-ar",Lt="ri-ar-id",ho=4096,Pr=2200,Br=(0,fe.strToU8)(JSON.stringify(be)).byteLength;function yo(e){return e==="localhost"||e.endsWith(".localhost")||/^127\./.test(e)||e==="[::1]"||e==="0.0.0.0"}function So(e){if(typeof e=="string"&&/^https?:\/\//i.test(e)&&yo(new URL(e).hostname))throw new Error("An asset URL points to this computer. Use model and texture URLs reachable from the phone.");if(e&&typeof e=="object")for(let t of Object.values(e))So(t)}function Er(e,t){let o=new URL(e,t);if(!["https:","http:"].includes(o.protocol))throw new Error("AR handoff requires an HTTP(S) URL.");return o.toString()}function xo(e,t){if(JSON.stringify(e)!==JSON.stringify(t))return e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)?Object.fromEntries(Object.entries(e).map(([o,n])=>[o,xo(n,t[o])]).filter(([,o])=>o!==void 0)):e}function wo(e,t,o=0){if(o>64)throw new Error("AR configuration is too deeply nested.");if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=e,r=t;return Object.fromEntries([...new Set([...Object.keys(r),...Object.keys(n)])].map(s=>[s,Object.prototype.hasOwnProperty.call(n,s)?wo(n[s],r[s],o+1):r[s]]))}return e}function Mo(e,t){let o=structuredClone(e);if(o.configuration){o.configuration.sceneConfig&&(o.configuration.sceneConfig=t(o.configuration.sceneConfig));for(let n of o.configuration.models??[])n.sceneConfig&&(n.sceneConfig=t(n.sceneConfig))}return o}function ze(e){e?.throwIfAborted()}async function Ao(e,t,o,n){ze(n);let r=new URL(Er(t));if(yo(r.hostname))throw new Error("Phone links need a viewer URL reachable from your phone. Download the USDZ for local uploads, or provide a public viewer URL.");let s=await Qe(e,r.toString());ze(n),So(s);let a=new URLSearchParams(r.hash.slice(1));if(a.delete(Nt),a.delete(Lt),a.delete("view"),a.delete("viewId"),a.delete("view-id"),o){let i=await o.save(s);if(ze(n),typeof i!="string"||!i||i.length>512)throw new Error("AR storage returned an invalid configuration ID.");a.set(Lt,i)}else{let i=(0,fe.zlibSync)((0,fe.strToU8)(JSON.stringify({ar:1,state:Mo(s,l=>xo(l,be)??{})})),{level:9});if(i.byteLength>ho)throw new Error("This configuration needs an AR storage adapter to share on a phone. The USDZ download is still available.");let c="";for(let l of i)c+=String.fromCharCode(l);a.set(Nt,btoa(c).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""))}if(r.hash=a.toString(),r.toString().length>Pr)throw new Error("This configuration is too large for a reliable QR code. Use an AR storage adapter or download the USDZ.");return r.toString()}async function vo(e,t,o){let n=new URL(e),r=new URLSearchParams(n.hash.slice(1)),s=r.get(Lt),a=r.get(Nt);if(s!==null&&a!==null)throw new Error("AR link contains conflicting configurations.");if(s===null&&a===null)return null;ze(o);let i;if(s!==null){if(!t)throw new Error("This AR link requires the application's configuration storage adapter.");if(!s||s.length>512)throw new Error("Invalid AR configuration ID.");i=await t.load(s)}else{if(!a||a.length>Math.ceil(ho*4/3)||!/^[\w-]+$/.test(a))throw new Error("Invalid or oversized AR link.");let l=atob(a.replace(/-/g,"+").replace(/_/g,"/")),u=Uint8Array.from(l,f=>f.charCodeAt(0)),d=(0,fe.unzlibSync)(u);if(d.byteLength>me)throw new Error("AR configuration exceeds the 5 MiB limit.");let p=JSON.parse((0,fe.strFromU8)(d));if(p?.ar===1&&p.state){let f=p.state.configuration,C=(f?.sceneConfig?1:0)+(Array.isArray(f?.models)?f.models.filter(R=>R?.sceneConfig).length:0);if(d.byteLength+C*Br>me)throw new Error("Expanded AR configuration exceeds the 5 MiB limit.");i=Mo(p.state,R=>wo(R,be))}else i=p}ze(o);let c=Re(i,n.toString());if(c.version!==1||!c.configuration)throw new Error("AR handoff requires a complete versioned viewer configuration.");return c}var Oo={id:"identity",modelObjectId:"identity",label:"identity",type:"identity",group:"identity",tags:"identity",style:"appearance",decals:"appearance",transform:"transform",visible:"visibility",removed:"visibility",status:"visibility",selectable:"behavior",hoverable:"behavior",actions:"behavior",cameraState:"behavior",metadata:"data",metrics:"data"},Vr=Object.keys(Oo),Dr=new Set(["__proto__","prototype","constructor"]);function Ce(e,t=new Set){if(e==null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new Error("Comparison values must be finite JSON data");return e}if(typeof e!="object"||t.has(e))throw new Error("Comparison values must be acyclic JSON data");t.add(e);let o=Array.isArray(e)?e.map(n=>Ce(n,t)):Object.fromEntries(Object.entries(e).filter(([n,r])=>!Dr.has(n)&&r!==void 0).map(([n,r])=>[n,Ce(r,t)]));return t.delete(e),o}var Co=e=>e&&typeof e=="object"&&!Array.isArray(e)&&!Object.keys(e).length;function ko(e,t){let o=Ce(e);o.visible=e.visible??!0,o.selectable=e.selectable??!0,o.hoverable=e.hoverable??!0,o.status=e.status??"normal",o.type=e.type??"other",o.tags=[...new Set(e.tags??[])].sort(),Co(o.transform)&&delete o.transform,o.metadata=Object.fromEntries(Object.entries(e.metadata??{}).filter(([n])=>!t.includes(n)));for(let n of["metrics","style","metadata"])Co(o[n])&&delete o[n];for(let n of["actions","decals"])Array.isArray(o[n])&&!o[n].length&&delete o[n];return o}function ot(e,t,o,n,r,s){let a=c=>c===void 0||Array.isArray(c)&&c.length===0;if(Object.is(e,t)||a(e)&&a(t)||typeof e=="number"&&typeof t=="number"&&Math.abs(e-t)<=r)return;let i=c=>!!c&&typeof c=="object"&&!Array.isArray(c);if(i(e)&&i(t)){for(let c of[...new Set([...Object.keys(e),...Object.keys(t)])].sort())ot(e[c],t[c],`${o}.${c}`,n,r,s);return}if(Array.isArray(e)&&Array.isArray(t)&&e.length===t.length){for(let c=0;c<e.length;c++)ot(e[c],t[c],`${o}[${c}]`,n,r,s);return}s.push({path:o,category:n,...e!==void 0?{before:Ce(e)}:{},...t!==void 0?{after:Ce(t)}:{}})}function jo(e,t,o={}){let n=o.tolerance??1e-6;if(!Number.isFinite(n)||n<0)throw new Error("Comparison tolerance must be finite and nonnegative");let r=Object.entries(e.objectBindings).filter(([,w])=>!w.removed),s=Object.entries(t.objectBindings).filter(([,w])=>!w.removed),a=new Map(r),i=new Map(s),c=new Set,l=new Set,u=[],d=w=>{let A=o.matchBy??"modelObjectId",h=typeof A=="object"?w.metadata?.[A.metadataKey]:w[A];return typeof h=="string"&&h.length>0||typeof h=="number"?`${typeof h}:${h}`:null};function p(w,A,h){let x=w===void 0?void 0:a.get(w),M=A===void 0?void 0:i.get(A),E=[];if(x||M){let D=x?ko(x,o.ignoreMetadataKeys??[]):{},g=M?ko(M,o.ignoreMetadataKeys??[]):{};for(let m of Vr)ot(D[m],g[m],m,Oo[m],n,E)}let j=x?M?E.length?"modified":"unchanged":"removed":"added";u.push({id:JSON.stringify([w??null,A??null]),identity:h,label:M?.label??x?.label??M?.modelObjectId??x?.modelObjectId??h,status:j,beforeKey:w,afterKey:A,beforeObjectId:x?.modelObjectId,afterObjectId:M?.modelObjectId,changes:E}),w!==void 0&&c.add(w),A!==void 0&&l.add(A)}let f=new Set;for(let[w,A]of Object.entries(o.mapping??{})){if(!a.has(w)||!i.has(A)||f.has(A))throw new Error("Comparison mapping must reference existing, unique binding keys");f.add(A),p(w,A,`mapped:${w}`)}let C=new Map;for(let[w,A,h]of[[r,c,"a"],[s,l,"b"]])for(let[x,M]of w){if(A.has(x))continue;let E=d(M);if(E===null){u.push({id:JSON.stringify([h,x]),identity:"",label:M.label??M.modelObjectId,status:"ambiguous",...h==="a"?{beforeKey:x,beforeObjectId:M.modelObjectId}:{afterKey:x,afterObjectId:M.modelObjectId},changes:[],message:"Missing match identity. Supply an explicit mapping or another match field."});continue}let j=C.get(E)??{a:[],b:[]};j[h].push(x),C.set(E,j)}for(let[w,A]of C){if(A.a.length<=1&&A.b.length<=1){p(A.a[0],A.b[0],w);continue}for(let h of["a","b"])for(let x of A[h]){let M=(h==="a"?a:i).get(x);u.push({id:JSON.stringify([h,x]),identity:w,label:M.label??M.modelObjectId,status:"ambiguous",...h==="a"?{beforeKey:x,beforeObjectId:M.modelObjectId}:{afterKey:x,afterObjectId:M.modelObjectId},changes:[],message:"Duplicate match identity. Supply an explicit one-to-one mapping."})}}u.sort((w,A)=>w.label.localeCompare(A.label)||w.id.localeCompare(A.id));let R=[];ot(Ce(e.sceneConfig??{}),Ce(t.sceneConfig??{}),"sceneConfig","scene",n,R);let S={added:0,removed:0,modified:0,unchanged:0,ambiguous:0};for(let w of u)S[w.status]++;return{version:1,objects:u,counts:S,sceneChanges:R}}0&&(module.exports={ACTION_CATALOG,DEFAULT_MODEL_VIEWER_LABELS,DEFAULT_SCENE_CONFIG,DEFAULT_SECTION_CONFIG,MATERIAL_BLENDING_MODES,MATERIAL_SIDES,MAX_VIEWER_STATE_BYTES,MEASUREMENT_UNITS,SEQUENCE_EASINGS,SEQUENCE_OBJECT_PROPERTIES,applyIsolation,applyProductOptions,applyStyleRules,buildBindingsFromNodes,calibrateMeasurements,chooseMaterialVariant,collectObjectHierarchy,colorScaleValue,compareViewerConfigurations,copyBindingStyle,createARHandoffUrl,createDefaultBinding,decodeProductSelections,defaultProductSelections,defineObjectBindings,encodeProductSelections,evaluateProductConfiguration,exportConfiguredUSDZ,findCatalogAction,formatProductPrice,generateProductSkus,groundAsset,inferType,inspectAsset,isolatedBindingKeys,material,measurementResult,measurementScale,measurementValue,measurementsToCsv,parseAssetTransform,parseMeasurements,parseProductConfiguration,parseProductDefinition,parseSceneProduct,parseSectionConfig,parseSelectionSets,parseSequences,parseViewerState,pasteBindingStyle,patchBindings,patchSceneConfig,prepareViewerState,productCheckoutUrl,productDefinitionWarnings,productOptionStates,productPriceFromDefinition,readARHandoffUrl,resolveProductSelections,sampleSequenceTrack,sceneLight,sectionSnapshot,selectBindingKeys,selectBindings,serializeMeasurements,serializeProductConfiguration,serializeViewerState,snapAssetToGrid,upsertSequenceKeyframe});