@spiffcommerce/preview 2.0.0 → 2.0.2

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.
package/dist/main.js CHANGED
@@ -1,2 +1,2 @@
1
- require("@babylonjs/core/Engines/Extensions/engine.views"),require("@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader"),require("@babylonjs/core/Materials/Textures/Loaders/envTextureLoader"),require("@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader"),require("@babylonjs/core/Misc/screenshotTools"),require("@babylonjs/core/Rendering/boundingBoxRenderer"),require("@babylonjs/loaders/glTF/2.0"),require("@babylonjs/core/Debug/debugLayer"),require("@babylonjs/core/Helpers/sceneHelpers");var e=require("@babylonjs/core/Loading/sceneLoader"),t=require("@babylonjs/core/Materials/PBR/pbrMaterial"),a=require("@babylonjs/core/Materials/Textures/mirrorTexture"),i=require("@babylonjs/core/Maths/math"),r=require("@babylonjs/core/Probes/reflectionProbe"),n=require("@babylonjs/loaders/glTF"),s=require("@babylonjs/core/Actions/actionManager"),o=require("@babylonjs/core/Actions/directActions"),c=require("@babylonjs/core/Engines/engine"),l=require("@babylonjs/core/Engines/nullEngine"),h=require("@babylonjs/core/Layers/glowLayer"),u=require("@babylonjs/core/Layers/highlightLayer"),d=require("@babylonjs/core/Materials/Textures/cubeTexture"),m=require("@babylonjs/core/Materials/Textures/dynamicTexture"),g=require("@babylonjs/core/Maths/math.color"),p=require("@babylonjs/core/Maths/math.vector"),b=require("@babylonjs/core/Meshes/Compression/dracoCompression"),f=require("@babylonjs/core/Misc/observable"),y=require("@babylonjs/core/Misc/tools"),v=require("@babylonjs/core/scene"),x=require("@babylonjs/core/Materials/Textures/texture"),w=require("@babylonjs/core/Animations/animation"),M=require("@babylonjs/core/Animations/easing"),T=require("@babylonjs/core/Cameras/arcRotateCamera"),C=require("@babylonjs/core/Misc/assetsManager"),L=require("@babylonjs/core/XR/features/WebXRHitTest"),A=require("@babylonjs/core/XR/webXRTypes");function R(e,t){return Object.keys(t).forEach((function(a){"default"===a||"__esModule"===a||e.hasOwnProperty(a)||Object.defineProperty(e,a,{enumerable:!0,get:function(){return t[a]}})})),e}function P(e,t,a,i){Object.defineProperty(e,t,{get:a,set:i,enumerable:!0,configurable:!0})}var O={};P(O,"RenderingConfiguration",(()=>E)),P(O,"REFLECTION_PROBE_RESOLUTION",(()=>S));class E{static getDynamicTextureResolution(){return this.getIsMobile()||!E.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}static shouldMipMap(){return!0}static offscreenRenderingSupported(){return!navigator.userAgent.includes("SamsungBrowser")&&(!!window.Worker&&!!window.OffscreenCanvas)}static getMirrorTextureResolution(){return this.getIsMobile()?512:1024}static getIsMobile(){return window.innerWidth<=480}}const S=128;n.GLTF2.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new I(e)})),e.SceneLoader.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){const t=e;t.useRangeRequests=!0,t.transparencyAsCoverage=!0}}));class I{constructor(e){this.name="glbPostProcessor",this.enabled=!0,this.loader=e}onReady(){this.applyReflections(this.loader.babylonScene)}loadNodeAsync(e,t,a){return this.loader.loadNodeAsync(e,t,(function(e){t.extras&&Object.keys(t.extras).forEach((a=>{const i=t.extras[a];e.metadata[a]=i})),a(e)}))}loadMaterialPropertiesAsync(e,t,a){return this.enableMaterialExtrasIfRequired(t,a),this.loader.loadMaterialPropertiesAsync(e,t,a)}dispose(){}enableMaterialExtrasIfRequired(e,a){if(e.extras&&a instanceof t.PBRMaterial){if(e.extras.sheen){const t=a;t.sheen.isEnabled=!0,t.sheen.intensity=e.extras.sheen}if(e.extras.translucency){const t=a;t.subSurface.isTranslucencyEnabled=!0,t.subSurface.translucencyIntensity=e.extras.translucency,e.extras.translucencyR&&e.extras.translucencyG&&e.extras.translucencyB&&(t.subSurface.tintColor=new(0,i.Color3)(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.useDepthPrePass){const e=a;e.needDepthPrePass=!0,e.forceIrradianceInFragment=!0}if(e.extras.useParallax){const t=a;t.useParallax=!0,t.useParallaxOcclusion=!0,t.parallaxScaleBias=e.extras.useParallax}}}applyReflections(e){function t(e){const t=[];return e.transformNodes.forEach((e=>{e.metadata&&e.metadata.reflective&&t.push(...e.getChildMeshes())})),e.meshes.forEach((e=>{e.metadata&&e.metadata.reflective&&!t.includes(e)&&t.push(e)})),t}e.meshes.forEach((n=>{const s=n.metadata;s&&(s.mirrorTexture&&function(r,n=1){const s=r.material;if(!s)return;const o=new(0,a.MirrorTexture)("mirror",E.getMirrorTextureResolution(),e,!0);o.renderList=t(e);const c=r.getVerticesData("normal");if(!c)throw new Error("Mirror attribute specified on: "+r.name+"But no normals exist to generate a mirror from!");r.computeWorldMatrix(!0);const l=r.getWorldMatrix(),h=i.Vector3.TransformNormal(new(0,i.Vector3)(c[0],c[1],c[2]),l).normalize(),u=i.Plane.FromPositionAndNormal(r.position,h.scale(-1));o.mirrorPlane=u,o.level=n,s.reflectionTexture=o}(n,s.mirrorTexture),s.reflectionProbe&&function(a){const i=a.material,n=new(0,r.ReflectionProbe)("probe-"+i.name,S,e);n.attachToMesh(a),n.renderList&&n.renderList.push(...t(e)),i.reflectionTexture=n.cubeTexture}(n))}))}}var B={};let F;var q;let N;var j;P(B,"ProductCameraRig",(()=>F)),P(B,"MaterialEffectMode",(()=>N)),(q=F||(F={}))[q.Orbit=0]="Orbit",q[q.Pan=1]="Pan",(j=N||(N={})).None="None",j.RemoveWhenSelected="RemoveWhenSelected",j.ApplyWhenSelected="ApplyWhenSelected";var D={};P(D,"SpiffCommerce3DPreviewService",(()=>ae)),P(D,"createBaseModel",(()=>ie));const k=new Map;async function _(t,a,i){return new Promise(((r,n)=>{const s=k.get(t);if(s&&s.scene.uid===a.uid)return r(s);e.SceneLoader.LoadAssetContainerAsync(t,void 0,a,i).then((e=>{k.set(t,e),r(e)})).catch(n)}))}class V{constructor(e){this.customOptions=e}get options(){return this.customOptions}get scene(){return{clearColor:this.getSceneClearColor(),transparentBackground:this.customOptions?.backgroundImage,environmentFile:this.customOptions?.environmentFile??"assets/model-viewer/default.env"}}get camera(){return{autoOrientation:this.customOptions?.disableAutomaticOrientation??!0,autoRotation:{enabled:this.customOptions?.autoRotation??!1,idleTimeMs:this.customOptions?.idleTimeBeforeRotation??5e3},limits:{min:{alpha:this.customOptions?.lowerAlphaLimitDeg?this.customOptions?.lowerAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.lowerBetaLimitDeg?this.customOptions?.lowerBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.minZoomOverride},max:{alpha:this.customOptions?.upperAlphaLimitDeg?this.customOptions?.upperAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.upperBetaLimitDeg?this.customOptions?.upperBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.maxZoomOverride}}}}get highlights(){return{enabled:this.customOptions?.highlightOnMaterialHover??!1,color:this.highlightColorFromConfig()}}getSceneClearColor=()=>{const e=this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions.backgroundImage)return new(0,g.Color4)(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=g.Color3.FromHexString(this.customOptions.backgroundColor);return new(0,g.Color4)(t.r,t.g,t.b,e).toLinearSpace()}return new(0,g.Color4)(.98,.98,.98,e).toLinearSpace()};highlightColorFromConfig=()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new(0,g.Color4)(.98,.98,.98,1).toLinearSpace();hexToColor4=(e,t=1)=>{const a=g.Color3.FromHexString(e);return new(0,g.Color4)(a.r,a.g,a.b,t).toLinearSpace()}}function z(e,t,a){t.forEach((t=>{const i=t.getID(),r=t.getName(),n=E.getDynamicTextureResolution();e.materials.filter((e=>e.name===r)).forEach((s=>{const o=a.get(i);if(o)H(s,o),o.update(false);else{const o=function(e,t,a,i){const r=new(0,m.DynamicTexture)(e,{width:a,height:i},t,E.shouldMipMap(),x.Texture.TRILINEAR_SAMPLINGMODE,c.Engine.TEXTUREFORMAT_RGBA),n=r.getContext();n&&(n.fillStyle="#f5f5f5",n.fillRect(0,0,a,i),r.update());return r}(r,e,n.width,n.height);a.set(i,o),t.setStaticContext(o.getContext()),H(s,o),o.onLoadObservable.addOnce((()=>{o.update(false)}))}}))}))}function H(e,a){if(e instanceof t.PBRMaterial){const t=e,i=t.albedoTexture;i?(a.wrapU=i.wrapU,a.wrapV=i.wrapV):(a.wrapU=1,a.wrapV=1),t.albedoTexture=a}else{const t=e,i=t.diffuseTexture;i&&(a.wrapU=i.wrapU,a.wrapV=i.wrapV),t.diffuseTexture=a}}function U(e,t,a,i){const r=e.animationGroups,n=e=>e.targetedAnimations.map((e=>e.animation.framePerSecond)).reduce(((e,t)=>e+t),0)/e.targetedAnimations.length||0;void 0===i||void 0===a||i!==a?r.forEach((e=>{e.stop();const r=n(e);e.start(t,1,i*r,a*r)})):r.forEach((e=>{e.stop();const a=n(e),r=i*a;e.start(t,1,r,r)}))}function W(e){e.animationGroups.forEach((e=>{e.stop()}))}function G(e,t,a){var i,r,n;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(i=t.alpha,r=0,n=2*Math.PI,i<r?n-(r-i)%(n-r):r+(i-r)%(n-r)));const s=[],o=a.target,c=o?1:0;if(a.target&&s.push(X("cameraTargetLerp","target",(new(0,p.Vector3)).copyFrom(t.target),new(0,p.Vector3)(a.target.x,a.target.y,a.target.z),w.Animation.ANIMATIONTYPE_VECTOR3,0)),s.push(X("cameraAlphaLerp","alpha",t.alpha,K(a.lonDeg),w.Animation.ANIMATIONTYPE_FLOAT,c)),s.push(X("cameraBetaLerp","beta",t.beta,K(a.latDeg),w.Animation.ANIMATIONTYPE_FLOAT,c)),void 0!==a.radius){const e=Math.max(.01,a.radius);s.push(X("cameraRadiusLerp","radius",t.radius,e,w.Animation.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...s);const l=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,o?120:60,!1,1,(()=>{t.animations=[],l&&t.enableAutoRotationBehavior()}))}function K(e){return e*Math.PI/180}function X(e,t,a,i,r,n=0,s=w.Animation.ANIMATIONLOOPMODE_CONSTANT){const o=new(0,M.QuadraticEase);o.setEasingMode(M.EasingFunction.EASINGMODE_EASEINOUT);const c=new(0,w.Animation)(e,t,60,r,s),l=[];return n>0&&l.push({frame:0,value:a}),l.push({frame:60*n,value:a}),l.push({frame:60*(n+1),value:i}),c.setKeys(l),c.setEasingFunction(o),c}class Z extends T.ArcRotateCamera{constructor(e,t,a,i,r,n,s,o){super(e,t,a,i,r,n,o),this.minZ=.01,this.maxZ=1e3*this.radius,this.lowerRadiusLimit=.01*this.radius,this.enableFramingBehavior(),this.upperRadiusLimit=1.5*this.radius,this.wheelPrecision=100/this.radius,this.pinchPrecision=300/this.radius,this.wheelDeltaPercentage=.01,this.pinchDeltaPercentage=.005,this.useNaturalPinchZoom=!0,s.camera.autoOrientation&&(this.alpha+=Math.PI),s&&(s.camera.limits.min.beta&&(this.lowerBetaLimit=s.camera.limits.min.beta),s.camera.limits.max.beta&&(this.upperBetaLimit=s.camera.limits.max.beta),s.camera.limits.min.alpha&&(this.lowerAlphaLimit=s.camera.limits.min.alpha),s.camera.limits.max.alpha&&(this.upperAlphaLimit=s.camera.limits.max.alpha),s.camera.limits.min.radius&&(this.lowerRadiusLimit=s.camera.limits.min.radius),s.camera.limits.max.radius&&(this.upperRadiusLimit=s.camera.limits.max.radius),s.camera.autoRotation.enabled&&this.enableAutoRotationBehavior(s.camera.autoRotation.idleTimeMs))}lastFocus=new(0,p.Vector3)(0,0,0);getFramingBehavior(){return this.getBehaviorByName("Framing")}getAutoRotationBehavior(){const e=this.getBehaviorByName("AutoRotation");return e||void 0}enableFramingBehavior(){this.useFramingBehavior=!0;const e=this.getFramingBehavior();e.attach(this),e.framingTime=0,e.elevationReturnTime=-1,e.zoomStopsAnimation=!1,this.lowerRadiusLimit=null;const t=Y(this._scene);return e.zoomOnBoundingInfo(t.min,t.max),this.wheelPrecision=100/this.radius,null===this.lowerRadiusLimit&&(this.lowerRadiusLimit=.1),this.lastFocus.copyFrom(this.target),e}rerunFramingBehavior(e){const t=this.getFramingBehavior();t.framingTime=800;const a=Y(this._scene);t.zoomOnBoundingInfo(a.min,a.max,void 0,(()=>{e()})),t.framingTime=0}enableAutoRotationBehavior(e=5e3){this.useAutoRotationBehavior=!0;const t=this.getAutoRotationBehavior();t&&(t.idleRotationWaitTime=e)}disableAutoRotationBehavior(){this.useAutoRotationBehavior=!1}static create(e,t){e.activeCamera&&(e.activeCamera.dispose(),e.activeCamera=null);const a=Y(e),i=a.max.subtract(a.min),r=a.min.add(i.scale(.5)),n=new Z("ProductCamera",-Math.PI/2,Math.PI/2,1.5*i.length(),r,e,t);return n.panningInertia=0,n.panningOriginTarget.copyFrom(r),n.onAfterCheckInputsObservable.add((()=>{n.panningSensibility=1e3/i.length()})),e.activeCamera=n,n}}function Y(e){const t=e.meshes.filter((e=>e.name.toLowerCase().endsWith("_t")||e.name.toLowerCase().includes("_t_")));return e.getWorldExtends((e=>e.isVisible&&e.isEnabled()&&(0===t.length||t.includes(e))))}const Q={albedoTexture:"albedoMapKey",bumpTexture:"normalMapKey",ambientTexture:"ambientMapKey",emissiveTexture:"emissionMapKey",opacityTexture:"alphaMapKey",metallicTexture:"metallicMapKey",refractionTexture:"refractionMapKey"};function $(e,t,a,i){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((r=>{!function(e,t,a,i,r){const n=Q[e];if(!n)throw new Error("Unexpected texture name encountered.");const s=t[n];s?i.addTextureTask(e,s,!1,!1):r&&a[e]&&(a[e]&&a[e].dispose(),a[e]=null,function(e,t){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!0);"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!1,t.useMetallnessFromMetallicTextureBlue=!1);"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!1,t.subSurface.refractionIntensity=1)}(e,a))}(r,e,t,a,i)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===N.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===N.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function J(e,t,a,i){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!1),"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!0,t.useMetallnessFromMetallicTextureBlue=!0),"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!0,t.subSurface.refractionIntensity=a.refractionIntensity||1),t[e]=i}class ee{materialVariantMap=new Map;keysThatRemovedBaseModel=[];loadedContainerForKey=new Map;async applyMaterial(e,t,a,i,r){return new Promise((n=>{const s=e.materials.filter((e=>e.name===t)),o=this.materialVariantMap.get(t);if(this.materialVariantMap.set(t,{...o,...a}),0===s.length)return void n(void 0);const c=new(0,C.AssetsManager)(e);c.useDefaultLoadingScreen=!1,s.forEach((e=>$(a,e,c,r))),c.onProgress=(e,t,a)=>{i&&i(e/t*100,100,a.name)},c.onFinish=e=>{e.forEach((e=>{const t=e;i&&i(100,100,e.name),s.forEach((i=>J(e.name,i,a,t.texture)))})),n(void 0)},c.loadAsync()}))}async applyModel(e,t,a,i,r){if(i&&a&&!this.keysThatRemovedBaseModel.includes(t)&&this.keysThatRemovedBaseModel.push(t),!i){const a=this.keysThatRemovedBaseModel.includes(t);return this.loadedContainerForKey.get(t)?.removeAllFromScene(),e&&a&&await ie(e.metadata.baseModel,e),Promise.resolve()}const n=await _(i,e,r);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),a){(await _(e.metadata.baseModel,e)).removeAllFromScene()}n.addAllToScene(),this.loadedContainerForKey.set(t,n);const s=[];this.materialVariantMap.forEach((async(t,a)=>{s.push(this.applyMaterial(e,a,t))})),await Promise.all(s)}}var te=async(e,t)=>{const a=await t.createDefaultXRExperienceAsync({uiOptions:{sessionMode:"immersive-ar",referenceSpaceType:"local-floor",onError:e=>{console.log(e)}}}),i=a.baseExperience.featuresManager.enableFeature(L.WebXRHitTest.Name,"latest",{disablePermanentHitTest:!0,enableTransientHitTest:!0,useReferenceSpace:!0});let r=null;i.onHitTestResultObservable.add((e=>{r=e.length?e[0]:void 0})),t.onPointerDown=()=>{if(r&&a.baseExperience.state===A.WebXRState.IN_XR){const e=t.getNodeByName("__root__");r.transformationMatrix.decompose(void 0,e.rotationQuaternion,e.position)}}};class ae{loadProgress=new Map([["initialScene",0]]);materialReadyToLoadCallbacks=new Map;modelReadyToLoadCallbacks=new Map;focusLostNotified=!1;loadObservable=new(0,f.Observable);focusLostObservable=new(0,f.Observable);dynamicTextures=new Map;variantManager=new ee;constructor(e,t){this.configuration=new V(t);b.DracoCompression.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_decoder_gltf.js"}},e&&(e.getContext("webgl2")||e.getContext("webgl"));const a=console.log;console.log=()=>{};const i=e?new(0,c.Engine)(e,!0,{premultipliedAlpha:!1,preserveDrawingBuffer:!!t?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new(0,l.NullEngine);console.log=a,i.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=i,this.scene=new(0,v.Scene)(i)}registerFocusLostListener(e){this.focusLostObservable.add(e)}unregisterFocusLostListener(e){this.focusLostObservable.removeCallback(e)}registerLoadProgressListener(e){this.loadObservable.add(e),e(this.getLoadListenerEvent())}unregisterLoadProgressListener(e){this.loadObservable.removeCallback(e)}registerView(e){const t=e.height,a=e.width;this.engine.registerView(e),e.setAttribute("height",t.toString()),e.setAttribute("width",a.toString()),this.orbitEnabled()||this.setCameraState(F.Pan)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e),this.engine.inputElement=null}shutdown(){this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(e,t){if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.metadata={baseModel:e},this.scene.environmentTexture=d.CubeTexture.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),e){const t=99;await ie(e,this.scene,(e=>{this.loadProgress.set("initialScene",e.loaded*t/e.total),this.notifyLoadHandlers()}))}this.configuration.highlights.enabled&&this.scene.meshes.forEach((e=>{"targetcube_t"!==e.name&&"backgroundShell"!==e.name&&(e.isPickable=!0,e.actionManager||(e.actionManager=new(0,s.ActionManager)(this.scene)),e.actionManager.registerAction(new(0,o.ExecuteCodeAction)(s.ActionManager.OnPointerOutTrigger,(()=>{this.setHighlights([])}))),e.actionManager.registerAction(new(0,o.ExecuteCodeAction)(s.ActionManager.OnPointerOverTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&this.setHighlights([t])}}))))}));const a=Z.create(this.scene,this.configuration),i=t?.getAll()||new Map;z(this.scene,i,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new(0,h.GlowLayer)("GlowLayer",this.scene).intensity=.5}W(this.scene),this.engine.runRenderLoop((()=>{if(!this.engine.views)return;const e=this.engine.views[0],t=this.engine.inputElement;(!t||e&&t&&t.id!==e.target.id)&&this.reattachControls(e.target),i.forEach(((e,t)=>{const a=this.dynamicTextures.get(t);a&&e.getStaticContextDirty()&&a.isReady()&&(a.update(!1),e.setStaticContextDirty(!1))})),this.configuration.scene.transparentBackground&&this.engine.views.forEach((e=>{const t=this.engine.getRenderingCanvas();e.target.getContext("2d").clearRect(0,0,t.width,t.height)})),this.scene.render(),100!==this.getSceneInitializationProgress()&&(this.loadProgress.set("initialScene",100),this.materialReadyToLoadCallbacks.forEach(((e,t)=>{e.forEach(((e,a)=>{this.applyMaterialVariant(t,a,e)}))})),this.materialReadyToLoadCallbacks.clear(),this.modelReadyToLoadCallbacks.forEach((e=>{e(this.scene)})),this.modelReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeModelAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0),this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0),this.notifyLoadHandlers()),a.target.equalsWithEpsilon(a.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0)}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?U(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?G(this.scene,this.scene.activeCamera,e):this.queuedCameraAnimation=e}getCameraPose(){if(this.scene){const e=this.scene.activeCamera;if(e)return{lonDeg:Math.round(180*e.alpha/Math.PI),latDeg:Math.round(180*e.beta/Math.PI),radius:Math.round(1e4*(e.radius+Number.EPSILON))/1e4,target:{x:e.target.x,y:e.target.y,z:e.target.z}}}}setCameraPose(e){if(this.scene){const t=this.scene.activeCamera;t&&(t.target=new(0,p.Vector3)(e.target.x,e.target.y,e.target.z),t.radius=e.radius,t.alpha=e.latDeg,t.beta=e.lonDeg)}}async applyMaterialVariant(e,t,a,i){if(100===this.getSceneInitializationProgress())await this.variantManager.applyMaterial(this.scene,e,a,((e,t,a)=>{this.loadProgress.set(`key_${a}`,e/t*100),this.notifyLoadHandlers()}),i);else if(this.materialReadyToLoadCallbacks.has(e)){this.materialReadyToLoadCallbacks.get(e)?.set(t,a)}else{this.materialReadyToLoadCallbacks.set(e,new Map);this.materialReadyToLoadCallbacks.get(e)?.set(t,a)}}async applyModelVariant(e,a,i){100===this.getSceneInitializationProgress()?(await this.variantManager.applyModel(this.scene,e,i||!1,a.model,(t=>{this.loadProgress.set(e,100*t.loaded/t.total),this.notifyLoadHandlers()})),this.scene.materials.forEach((e=>{if(e&&0===e.getBindedMeshes().length){const a=e instanceof t.PBRMaterial&&!(e.albedoTexture instanceof m.DynamicTexture);e.dispose(!1,a)}})),z(this.scene,a.contextService.getAll(),this.dynamicTextures),W(this.scene)):this.modelReadyToLoadCallbacks.set(e,(()=>{this.applyModelVariant(e,a,i)}))}setCameraState(e){if(!this.engine?.views||!this.engine?.views[0])throw new Error("No views attached, camera state requires a view to attach controls onto.");e===F.Orbit?this.reattachControls(this.engine.views[0].target,2):this.reattachControls(this.engine.views[0].target,0)}animateToLastCameraFocus(){return new Promise((e=>{const t=this.scene.activeCamera,a=this.configuration;t.rerunFramingBehavior((()=>{this.focusLostNotified=!1,a.camera.limits.min.radius&&(t.lowerRadiusLimit=a.camera.limits.min.radius),a.camera.limits.max.radius&&(t.upperRadiusLimit=a.camera.limits.max.radius),e()}))}))}setAutoRotation(e){const t=this.scene.activeCamera;this.configuration.camera.autoRotation.enabled&&t&&(e?t.enableAutoRotationBehavior(this.configuration.camera.autoRotation.idleTimeMs):t.disableAutoRotationBehavior())}getCurrentConfiguration(){return this.configuration.options}async renderSceneScreenshot(e,t){const a=this.scene.activeCamera;if(!a)throw new Error("Missing product camera, cannot render screenshot!");var i;(i=a).getScene().stopAnimation(i),i.animations=[];const r=a.alpha,n=a.beta,s=a.radius,o=t.latDeg*Math.PI/180,c=t.lonDeg*Math.PI/180;a.alpha=c,a.beta=o,a.radius=t.radius||a.radius;const l=await y.Tools.CreateScreenshotUsingRenderTargetAsync(this.engine,a,e,"image/png",2,!0);return a.alpha=r,a.beta=n,a.radius=s,l}orbitEnabled(){const e=this.configuration;if(!e)return!0;const t=e.camera.limits.min.alpha,a=e.camera.limits.max.alpha,i=e.camera.limits.min.beta,r=e.camera.limits.max.beta;if(void 0===t||void 0===a||void 0===i||void 0===r)return!0;const n=[i,r],s=[t,a].every((e=>e===t)),o=n.every((e=>e===i));return!s&&!o}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}onMaterialSelected(e){this.scene.meshes.forEach((t=>{"targetcube_t"!==t.name&&"backgroundShell"!==t.name&&(t.actionManager||(t.actionManager=new(0,s.ActionManager)(this.scene)),t.actionManager.registerAction(new(0,o.ExecuteCodeAction)(s.ActionManager.OnPickDownTrigger,(t=>{if(t.meshUnderPointer){const a=t.meshUnderPointer.material;a&&e({id:a.id,name:a.name})}}))))}))}listMaterials(){const e=this.scene?.materials;return e?e.map((e=>({id:e.id,name:e.name}))):[]}setHighlights(e,t){0===e.length&&(this.highlightLayer?.dispose(),this.highlightLayer=void 0),this.highlightLayer||(this.highlightLayer=new(0,u.HighlightLayer)("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const a=t?new(0,g.Color3)(t[0],t[1],t[2]).toLinearSpace():void 0;e.forEach((e=>{const t=this.scene.materials.find((t=>t.name===e.name&&t.id===e.id));t&&t.getBindedMeshes().forEach((e=>this.highlightLayer?.addMesh(e,a||g.Color3.FromHexString("#fcba03"))))}))}initXRExperience(e){te(0,this.scene)}reattachControls(e,t=2){this.scene.detachControl(),this.engine.inputElement=e;const a=this.scene.activeCamera;if(a){a.attachControl(!0,!1,t);a.inputs.attached.pointers.multiTouchPanning=!1}this.scene.attachControl(!0,!0,!0)}getLoadListenerEvent(){const e=Array.from(this.loadProgress.values()).filter((e=>e<100)),t=e.reduce(((e,t)=>e+t),0)/e.length||0;return{loadValue:0===e.length?100:t,sceneInitialized:100===this.getSceneInitializationProgress()}}notifyLoadHandlers(){this.loadObservable.notifyObservers(this.getLoadListenerEvent())}}async function ie(e,t,a){(await _(e,t,a)).addAllToScene()}R(module.exports,B),R(module.exports,D),R(module.exports,O);
1
+ require("@babylonjs/core/Engines/Extensions/engine.views"),require("@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader"),require("@babylonjs/core/Materials/Textures/Loaders/envTextureLoader"),require("@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader"),require("@babylonjs/core/Misc/screenshotTools"),require("@babylonjs/core/Rendering/boundingBoxRenderer"),require("@babylonjs/loaders/glTF/2.0"),require("@babylonjs/core/Debug/debugLayer"),require("@babylonjs/core/Helpers/sceneHelpers");var e=require("@babylonjs/core/Loading/sceneLoader"),t=require("@babylonjs/core/Materials/PBR/pbrMaterial"),i=require("@babylonjs/core/Materials/Textures/mirrorTexture"),a=require("@babylonjs/core/Maths/math"),r=require("@babylonjs/core/Probes/reflectionProbe"),n=require("@babylonjs/loaders/glTF"),s=require("@babylonjs/core/Actions/actionManager"),o=require("@babylonjs/core/Actions/directActions"),c=require("@babylonjs/core/Engines/engine"),l=require("@babylonjs/core/Engines/nullEngine"),h=require("@babylonjs/core/Layers/glowLayer"),u=require("@babylonjs/core/Layers/highlightLayer"),d=require("@babylonjs/core/Materials/Textures/cubeTexture"),m=require("@babylonjs/core/Materials/Textures/dynamicTexture"),g=require("@babylonjs/core/Maths/math.color"),b=require("@babylonjs/core/Maths/math.vector"),p=require("@babylonjs/core/Meshes/Compression/dracoCompression"),f=require("@babylonjs/core/Misc/observable"),y=require("@babylonjs/core/Misc/tools"),v=require("@babylonjs/core/scene"),w=require("@babylonjs/core/Materials/Textures/texture"),x=require("@babylonjs/core/Animations/animation"),M=require("@babylonjs/core/Animations/easing"),T=require("@babylonjs/core/Cameras/arcRotateCamera"),C=require("@babylonjs/core/Misc/assetsManager"),A=require("@babylonjs/core/XR/features/WebXRHitTest"),L=require("@babylonjs/core/XR/webXRTypes");function R(e,t){return Object.keys(t).forEach((function(i){"default"===i||"__esModule"===i||e.hasOwnProperty(i)||Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[i]}})})),e}function P(e,t,i,a){Object.defineProperty(e,t,{get:i,set:a,enumerable:!0,configurable:!0})}var O={};P(O,"RenderingConfiguration",(()=>E)),P(O,"REFLECTION_PROBE_RESOLUTION",(()=>S));class E{static getDynamicTextureResolution(){return this.getIsMobile()||!E.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}static shouldMipMap(){return!0}static offscreenRenderingSupported(){return!navigator.userAgent.includes("SamsungBrowser")&&(!!window.Worker&&!!window.OffscreenCanvas)}static getMirrorTextureResolution(){return this.getIsMobile()?512:1024}static getIsMobile(){return window.innerWidth<=480}}const S=128;function I(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}n.GLTF2.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new B(e)})),e.SceneLoader.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){const t=e;t.useRangeRequests=!0,t.transparencyAsCoverage=!0}}));class B{constructor(e){I(this,"name",void 0),I(this,"enabled",void 0),I(this,"loader",void 0),this.name="glbPostProcessor",this.enabled=!0,this.loader=e}onReady(){this.applyReflections(this.loader.babylonScene)}loadNodeAsync(e,t,i){return this.loader.loadNodeAsync(e,t,(function(e){t.extras&&Object.keys(t.extras).forEach((i=>{const a=t.extras[i];e.metadata[i]=a})),i(e)}))}loadMaterialPropertiesAsync(e,t,i){return this.enableMaterialExtrasIfRequired(t,i),this.loader.loadMaterialPropertiesAsync(e,t,i)}dispose(){}enableMaterialExtrasIfRequired(e,i){if(e.extras&&i instanceof t.PBRMaterial){if(e.extras.sheen){const t=i;t.sheen.isEnabled=!0,t.sheen.intensity=e.extras.sheen}if(e.extras.translucency){const t=i;t.subSurface.isTranslucencyEnabled=!0,t.subSurface.translucencyIntensity=e.extras.translucency,e.extras.translucencyR&&e.extras.translucencyG&&e.extras.translucencyB&&(t.subSurface.tintColor=new(0,a.Color3)(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.useDepthPrePass){const e=i;e.needDepthPrePass=!0,e.forceIrradianceInFragment=!0}if(e.extras.useParallax){const t=i;t.useParallax=!0,t.useParallaxOcclusion=!0,t.parallaxScaleBias=e.extras.useParallax}}}applyReflections(e){function t(e){const t=[];return e.transformNodes.forEach((e=>{e.metadata&&e.metadata.reflective&&t.push(...e.getChildMeshes())})),e.meshes.forEach((e=>{e.metadata&&e.metadata.reflective&&!t.includes(e)&&t.push(e)})),t}e.meshes.forEach((n=>{const s=n.metadata;s&&(s.mirrorTexture&&function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const s=r.material;if(!s)return;const o=new(0,i.MirrorTexture)("mirror",E.getMirrorTextureResolution(),e,!0);o.renderList=t(e);const c=r.getVerticesData("normal");if(!c)throw new Error("Mirror attribute specified on: "+r.name+"But no normals exist to generate a mirror from!");r.computeWorldMatrix(!0);const l=r.getWorldMatrix(),h=a.Vector3.TransformNormal(new(0,a.Vector3)(c[0],c[1],c[2]),l).normalize(),u=a.Plane.FromPositionAndNormal(r.position,h.scale(-1));o.mirrorPlane=u,o.level=n,s.reflectionTexture=o}(n,s.mirrorTexture),s.reflectionProbe&&function(i){const a=i.material,n=new(0,r.ReflectionProbe)("probe-"+a.name,S,e);n.attachToMesh(i),n.renderList&&n.renderList.push(...t(e)),a.reflectionTexture=n.cubeTexture}(n))}))}}var F={};let q;var j;let N;var D;P(F,"ProductCameraRig",(()=>q)),P(F,"MaterialEffectMode",(()=>N)),(j=q||(q={}))[j.Orbit=0]="Orbit",j[j.Pan=1]="Pan",(D=N||(N={})).None="None",D.RemoveWhenSelected="RemoveWhenSelected",D.ApplyWhenSelected="ApplyWhenSelected";var k={};P(k,"SpiffCommerce3DPreviewService",(()=>se)),P(k,"createBaseModel",(()=>oe));const _=new Map;async function V(t,i,a){return new Promise(((r,n)=>{const s=_.get(t);if(s&&s.scene.uid===i.uid)return r(s);e.SceneLoader.LoadAssetContainerAsync(t,void 0,i,a).then((e=>{_.set(t,e),r(e)})).catch(n)}))}function z(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class H{constructor(e){z(this,"customOptions",void 0),z(this,"getSceneClearColor",(()=>{const e=this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions.backgroundImage)return new(0,g.Color4)(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=g.Color3.FromHexString(this.customOptions.backgroundColor);return new(0,g.Color4)(t.r,t.g,t.b,e).toLinearSpace()}return new(0,g.Color4)(.98,.98,.98,e).toLinearSpace()})),z(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new(0,g.Color4)(.98,.98,.98,1).toLinearSpace())),z(this,"hexToColor4",(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=g.Color3.FromHexString(e);return new(0,g.Color4)(i.r,i.g,i.b,t).toLinearSpace()})),this.customOptions=e}get options(){return this.customOptions}get scene(){return{clearColor:this.getSceneClearColor(),transparentBackground:this.customOptions?.backgroundImage,environmentFile:this.customOptions?.environmentFile??"assets/model-viewer/default.env"}}get camera(){return{autoOrientation:this.customOptions?.disableAutomaticOrientation??!0,autoRotation:{enabled:this.customOptions?.autoRotation??!1,idleTimeMs:this.customOptions?.idleTimeBeforeRotation??5e3},limits:{min:{alpha:this.customOptions?.lowerAlphaLimitDeg?this.customOptions?.lowerAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.lowerBetaLimitDeg?this.customOptions?.lowerBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.minZoomOverride},max:{alpha:this.customOptions?.upperAlphaLimitDeg?this.customOptions?.upperAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.upperBetaLimitDeg?this.customOptions?.upperBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.maxZoomOverride}}}}get highlights(){return{enabled:this.customOptions?.highlightOnMaterialHover??!1,color:this.highlightColorFromConfig()}}}function U(e,t,i){t.forEach((t=>{const a=t.getID(),r=t.getName(),n=E.getDynamicTextureResolution();e.materials.filter((e=>e.name===r)).forEach((s=>{const o=i.get(a);if(o)W(s,o),o.update(false);else{const o=function(e,t,i,a){const r=new(0,m.DynamicTexture)(e,{width:i,height:a},t,E.shouldMipMap(),w.Texture.TRILINEAR_SAMPLINGMODE,c.Engine.TEXTUREFORMAT_RGBA),n=r.getContext();n&&(n.fillStyle="#f5f5f5",n.fillRect(0,0,i,a),r.update());return r}(r,e,n.width,n.height);i.set(a,o),t.setStaticContext(o.getContext()),W(s,o),o.onLoadObservable.addOnce((()=>{o.update(false)}))}}))}))}function W(e,i){if(e instanceof t.PBRMaterial){const t=e,a=t.albedoTexture;a?(i.wrapU=a.wrapU,i.wrapV=a.wrapV):(i.wrapU=1,i.wrapV=1),t.albedoTexture=i}else{const t=e,a=t.diffuseTexture;a&&(i.wrapU=a.wrapU,i.wrapV=a.wrapV),t.diffuseTexture=i}}function G(e,t,i,a){const r=e.animationGroups,n=e=>e.targetedAnimations.map((e=>e.animation.framePerSecond)).reduce(((e,t)=>e+t),0)/e.targetedAnimations.length||0;void 0===a||void 0===i||a!==i?r.forEach((e=>{e.stop();const r=n(e);e.start(t,1,a*r,i*r)})):r.forEach((e=>{e.stop();const i=n(e),r=a*i;e.start(t,1,r,r)}))}function K(e){e.animationGroups.forEach((e=>{e.stop()}))}function X(e,t,i){var a,r,n;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(a=t.alpha,r=0,n=2*Math.PI,a<r?n-(r-a)%(n-r):r+(a-r)%(n-r)));const s=[],o=i.target,c=o?1:0;if(i.target&&s.push(Y("cameraTargetLerp","target",(new(0,b.Vector3)).copyFrom(t.target),new(0,b.Vector3)(i.target.x,i.target.y,i.target.z),x.Animation.ANIMATIONTYPE_VECTOR3,0)),s.push(Y("cameraAlphaLerp","alpha",t.alpha,Z(i.lonDeg),x.Animation.ANIMATIONTYPE_FLOAT,c)),s.push(Y("cameraBetaLerp","beta",t.beta,Z(i.latDeg),x.Animation.ANIMATIONTYPE_FLOAT,c)),void 0!==i.radius){const e=Math.max(.01,i.radius);s.push(Y("cameraRadiusLerp","radius",t.radius,e,x.Animation.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...s);const l=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,o?120:60,!1,1,(()=>{t.animations=[],l&&t.enableAutoRotationBehavior()}))}function Z(e){return e*Math.PI/180}function Y(e,t,i,a,r){let n=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:x.Animation.ANIMATIONLOOPMODE_CONSTANT;const o=new(0,M.QuadraticEase);o.setEasingMode(M.EasingFunction.EASINGMODE_EASEINOUT);const c=new(0,x.Animation)(e,t,60,r,s),l=[];return n>0&&l.push({frame:0,value:i}),l.push({frame:60*n,value:i}),l.push({frame:60*(n+1),value:a}),c.setKeys(l),c.setEasingFunction(o),c}class Q extends T.ArcRotateCamera{constructor(e,t,i,a,r,n,s,o){var c,l,h;super(e,t,i,a,r,n,o),c=this,l="lastFocus",h=new(0,b.Vector3)(0,0,0),l in c?Object.defineProperty(c,l,{value:h,enumerable:!0,configurable:!0,writable:!0}):c[l]=h,this.minZ=.01,this.maxZ=1e3*this.radius,this.lowerRadiusLimit=.01*this.radius,this.enableFramingBehavior(),this.upperRadiusLimit=1.5*this.radius,this.wheelPrecision=100/this.radius,this.pinchPrecision=300/this.radius,this.wheelDeltaPercentage=.01,this.pinchDeltaPercentage=.005,this.useNaturalPinchZoom=!0,s.camera.autoOrientation&&(this.alpha+=Math.PI),s&&(s.camera.limits.min.beta&&(this.lowerBetaLimit=s.camera.limits.min.beta),s.camera.limits.max.beta&&(this.upperBetaLimit=s.camera.limits.max.beta),s.camera.limits.min.alpha&&(this.lowerAlphaLimit=s.camera.limits.min.alpha),s.camera.limits.max.alpha&&(this.upperAlphaLimit=s.camera.limits.max.alpha),s.camera.limits.min.radius&&(this.lowerRadiusLimit=s.camera.limits.min.radius),s.camera.limits.max.radius&&(this.upperRadiusLimit=s.camera.limits.max.radius),s.camera.autoRotation.enabled&&this.enableAutoRotationBehavior(s.camera.autoRotation.idleTimeMs))}getFramingBehavior(){return this.getBehaviorByName("Framing")}getAutoRotationBehavior(){const e=this.getBehaviorByName("AutoRotation");return e||void 0}enableFramingBehavior(){this.useFramingBehavior=!0;const e=this.getFramingBehavior();e.attach(this),e.framingTime=0,e.elevationReturnTime=-1,e.zoomStopsAnimation=!1,this.lowerRadiusLimit=null;const t=$(this._scene);return e.zoomOnBoundingInfo(t.min,t.max),this.wheelPrecision=100/this.radius,null===this.lowerRadiusLimit&&(this.lowerRadiusLimit=.1),this.lastFocus.copyFrom(this.target),e}rerunFramingBehavior(e){const t=this.getFramingBehavior();t.framingTime=800;const i=$(this._scene);t.zoomOnBoundingInfo(i.min,i.max,void 0,(()=>{e()})),t.framingTime=0}enableAutoRotationBehavior(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e3;this.useAutoRotationBehavior=!0;const t=this.getAutoRotationBehavior();t&&(t.idleRotationWaitTime=e)}disableAutoRotationBehavior(){this.useAutoRotationBehavior=!1}static create(e,t){e.activeCamera&&(e.activeCamera.dispose(),e.activeCamera=null);const i=$(e),a=i.max.subtract(i.min),r=i.min.add(a.scale(.5)),n=new Q("ProductCamera",-Math.PI/2,Math.PI/2,1.5*a.length(),r,e,t);return n.panningInertia=0,n.panningOriginTarget.copyFrom(r),n.onAfterCheckInputsObservable.add((()=>{n.panningSensibility=1e3/a.length()})),e.activeCamera=n,n}}function $(e){const t=e.meshes.filter((e=>e.name.toLowerCase().endsWith("_t")||e.name.toLowerCase().includes("_t_")));return e.getWorldExtends((e=>e.isVisible&&e.isEnabled()&&(0===t.length||t.includes(e))))}const J={albedoTexture:"albedoMapKey",bumpTexture:"normalMapKey",ambientTexture:"ambientMapKey",emissiveTexture:"emissionMapKey",opacityTexture:"alphaMapKey",metallicTexture:"metallicMapKey",refractionTexture:"refractionMapKey"};function ee(e,t,i,a){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((r=>{!function(e,t,i,a,r){const n=J[e];if(!n)throw new Error("Unexpected texture name encountered.");const s=t[n];s?a.addTextureTask(e,s,!1,!1):r&&i[e]&&(i[e]&&i[e].dispose(),i[e]=null,function(e,t){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!0);"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!1,t.useMetallnessFromMetallicTextureBlue=!1);"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!1,t.subSurface.refractionIntensity=1)}(e,i))}(r,e,t,i,a)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===N.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===N.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function te(e,t,i,a){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!1),"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!0,t.useMetallnessFromMetallicTextureBlue=!0),"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!0,t.subSurface.refractionIntensity=i.refractionIntensity||1),t[e]=a}function ie(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class ae{constructor(){ie(this,"materialVariantMap",new Map),ie(this,"keysThatRemovedBaseModel",[]),ie(this,"loadedContainerForKey",new Map)}async applyMaterial(e,t,i,a,r){return new Promise((n=>{const s=e.materials.filter((e=>e.name===t)),o=this.materialVariantMap.get(t);if(this.materialVariantMap.set(t,{...o,...i}),0===s.length)return void n(void 0);const c=new(0,C.AssetsManager)(e);c.useDefaultLoadingScreen=!1,s.forEach((e=>ee(i,e,c,r))),c.onProgress=(e,t,i)=>{a&&a(e/t*100,100,i.name)},c.onFinish=e=>{e.forEach((e=>{const t=e;a&&a(100,100,e.name),s.forEach((a=>te(e.name,a,i,t.texture)))})),n(void 0)},c.loadAsync()}))}async applyModel(e,t,i,a,r){if(a&&i&&!this.keysThatRemovedBaseModel.includes(t)&&this.keysThatRemovedBaseModel.push(t),!a){const i=this.keysThatRemovedBaseModel.includes(t);return this.loadedContainerForKey.get(t)?.removeAllFromScene(),e&&i&&await oe(e.metadata.baseModel,e),Promise.resolve()}const n=await V(a,e,r);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),i){(await V(e.metadata.baseModel,e)).removeAllFromScene()}n.addAllToScene(),this.loadedContainerForKey.set(t,n);const s=[];this.materialVariantMap.forEach((async(t,i)=>{s.push(this.applyMaterial(e,i,t))})),await Promise.all(s)}}var re=async(e,t)=>{const i=await t.createDefaultXRExperienceAsync({uiOptions:{sessionMode:"immersive-ar",referenceSpaceType:"local-floor",onError:e=>{console.log(e)}}}),a=i.baseExperience.featuresManager.enableFeature(A.WebXRHitTest.Name,"latest",{disablePermanentHitTest:!0,enableTransientHitTest:!0,useReferenceSpace:!0});let r=null;a.onHitTestResultObservable.add((e=>{r=e.length?e[0]:void 0})),t.onPointerDown=()=>{if(r&&i.baseExperience.state===L.WebXRState.IN_XR){const e=t.getNodeByName("__root__");r.transformationMatrix.decompose(void 0,e.rotationQuaternion,e.position)}}};function ne(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class se{constructor(e,t){ne(this,"engine",void 0),ne(this,"scene",void 0),ne(this,"configuration",void 0),ne(this,"loadProgress",new Map([["initialScene",0]])),ne(this,"materialReadyToLoadCallbacks",new Map),ne(this,"modelReadyToLoadCallbacks",new Map),ne(this,"queuedModelAnimation",void 0),ne(this,"queuedCameraAnimation",void 0),ne(this,"focusLostNotified",!1),ne(this,"loadObservable",new(0,f.Observable)),ne(this,"focusLostObservable",new(0,f.Observable)),ne(this,"dynamicTextures",new Map),ne(this,"highlightLayer",void 0),ne(this,"variantManager",new ae),this.configuration=new H(t);p.DracoCompression.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_decoder_gltf.js"}},e&&(e.getContext("webgl2")||e.getContext("webgl"));const i=console.log;console.log=()=>{};const a=e?new(0,c.Engine)(e,!0,{premultipliedAlpha:!1,preserveDrawingBuffer:!!t?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new(0,l.NullEngine);console.log=i,a.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=a,this.scene=new(0,v.Scene)(a)}registerFocusLostListener(e){this.focusLostObservable.add(e)}unregisterFocusLostListener(e){this.focusLostObservable.removeCallback(e)}registerLoadProgressListener(e){this.loadObservable.add(e),e(this.getLoadListenerEvent())}unregisterLoadProgressListener(e){this.loadObservable.removeCallback(e)}registerView(e){const t=e.height,i=e.width;this.engine.registerView(e),e.setAttribute("height",t.toString()),e.setAttribute("width",i.toString()),this.orbitEnabled()||this.setCameraState(q.Pan)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e),this.engine.inputElement=null}shutdown(){this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(e,t){if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.metadata={baseModel:e},this.scene.environmentTexture=d.CubeTexture.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),e){const t=99;await oe(e,this.scene,(e=>{this.loadProgress.set("initialScene",e.loaded*t/e.total),this.notifyLoadHandlers()}))}this.configuration.highlights.enabled&&this.scene.meshes.forEach((e=>{"targetcube_t"!==e.name&&"backgroundShell"!==e.name&&(e.isPickable=!0,e.actionManager||(e.actionManager=new(0,s.ActionManager)(this.scene)),e.actionManager.registerAction(new(0,o.ExecuteCodeAction)(s.ActionManager.OnPointerOutTrigger,(()=>{this.setHighlights([])}))),e.actionManager.registerAction(new(0,o.ExecuteCodeAction)(s.ActionManager.OnPointerOverTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&this.setHighlights([t])}}))))}));const i=Q.create(this.scene,this.configuration),a=t?.getAll()||new Map;U(this.scene,a,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new(0,h.GlowLayer)("GlowLayer",this.scene).intensity=.5}K(this.scene),this.engine.runRenderLoop((()=>{if(!this.engine.views)return;const e=this.engine.views[0],t=this.engine.inputElement;(!t||e&&t&&t.id!==e.target.id)&&this.reattachControls(e.target),a.forEach(((e,t)=>{const i=this.dynamicTextures.get(t);i&&e.getStaticContextDirty()&&i.isReady()&&(i.update(!1),e.setStaticContextDirty(!1))})),this.configuration.scene.transparentBackground&&this.engine.views.forEach((e=>{const t=this.engine.getRenderingCanvas();e.target.getContext("2d").clearRect(0,0,t.width,t.height)})),this.scene.render(),100!==this.getSceneInitializationProgress()&&(this.loadProgress.set("initialScene",100),this.materialReadyToLoadCallbacks.forEach(((e,t)=>{e.forEach(((e,i)=>{this.applyMaterialVariant(t,i,e)}))})),this.materialReadyToLoadCallbacks.clear(),this.modelReadyToLoadCallbacks.forEach((e=>{e(this.scene)})),this.modelReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeModelAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0),this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0),this.notifyLoadHandlers()),i.target.equalsWithEpsilon(i.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0)}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?G(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?X(this.scene,this.scene.activeCamera,e):this.queuedCameraAnimation=e}getCameraPose(){if(this.scene){const e=this.scene.activeCamera;if(e)return{lonDeg:Math.round(180*e.alpha/Math.PI),latDeg:Math.round(180*e.beta/Math.PI),radius:Math.round(1e4*(e.radius+Number.EPSILON))/1e4,target:{x:e.target.x,y:e.target.y,z:e.target.z}}}}setCameraPose(e){if(this.scene){const t=this.scene.activeCamera;t&&(t.target=new(0,b.Vector3)(e.target.x,e.target.y,e.target.z),t.radius=e.radius,t.alpha=e.latDeg,t.beta=e.lonDeg)}}async applyMaterialVariant(e,t,i,a){if(100===this.getSceneInitializationProgress())await this.variantManager.applyMaterial(this.scene,e,i,((e,t,i)=>{this.loadProgress.set(`key_${i}`,e/t*100),this.notifyLoadHandlers()}),a);else if(this.materialReadyToLoadCallbacks.has(e)){this.materialReadyToLoadCallbacks.get(e)?.set(t,i)}else{this.materialReadyToLoadCallbacks.set(e,new Map);this.materialReadyToLoadCallbacks.get(e)?.set(t,i)}}async applyModelVariant(e,i,a){100===this.getSceneInitializationProgress()?(await this.variantManager.applyModel(this.scene,e,a||!1,i.model,(t=>{this.loadProgress.set(e,100*t.loaded/t.total),this.notifyLoadHandlers()})),this.scene.materials.forEach((e=>{if(e&&0===e.getBindedMeshes().length){const i=e instanceof t.PBRMaterial&&!(e.albedoTexture instanceof m.DynamicTexture);e.dispose(!1,i)}})),U(this.scene,i.contextService.getAll(),this.dynamicTextures),K(this.scene)):this.modelReadyToLoadCallbacks.set(e,(()=>{this.applyModelVariant(e,i,a)}))}setCameraState(e){if(!this.engine?.views||!this.engine?.views[0])throw new Error("No views attached, camera state requires a view to attach controls onto.");e===q.Orbit?this.reattachControls(this.engine.views[0].target,2):this.reattachControls(this.engine.views[0].target,0)}animateToLastCameraFocus(){return new Promise((e=>{const t=this.scene.activeCamera,i=this.configuration;t.rerunFramingBehavior((()=>{this.focusLostNotified=!1,i.camera.limits.min.radius&&(t.lowerRadiusLimit=i.camera.limits.min.radius),i.camera.limits.max.radius&&(t.upperRadiusLimit=i.camera.limits.max.radius),e()}))}))}setAutoRotation(e){const t=this.scene.activeCamera;this.configuration.camera.autoRotation.enabled&&t&&(e?t.enableAutoRotationBehavior(this.configuration.camera.autoRotation.idleTimeMs):t.disableAutoRotationBehavior())}getCurrentConfiguration(){return this.configuration.options}async renderSceneScreenshot(e,t){const i=this.scene.activeCamera;if(!i)throw new Error("Missing product camera, cannot render screenshot!");var a;(a=i).getScene().stopAnimation(a),a.animations=[];const r=i.alpha,n=i.beta,s=i.radius,o=t.latDeg*Math.PI/180,c=t.lonDeg*Math.PI/180;i.alpha=c,i.beta=o,i.radius=t.radius||i.radius;const l=await y.Tools.CreateScreenshotUsingRenderTargetAsync(this.engine,i,e,"image/png",2,!0);return i.alpha=r,i.beta=n,i.radius=s,l}orbitEnabled(){const e=this.configuration;if(!e)return!0;const t=e.camera.limits.min.alpha,i=e.camera.limits.max.alpha,a=e.camera.limits.min.beta,r=e.camera.limits.max.beta;if(void 0===t||void 0===i||void 0===a||void 0===r)return!0;const n=[a,r],s=[t,i].every((e=>e===t)),o=n.every((e=>e===a));return!s&&!o}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}onMaterialSelected(e){this.scene.meshes.forEach((t=>{"targetcube_t"!==t.name&&"backgroundShell"!==t.name&&(t.actionManager||(t.actionManager=new(0,s.ActionManager)(this.scene)),t.actionManager.registerAction(new(0,o.ExecuteCodeAction)(s.ActionManager.OnPickDownTrigger,(t=>{if(t.meshUnderPointer){const i=t.meshUnderPointer.material;i&&e({id:i.id,name:i.name})}}))))}))}listMaterials(){const e=this.scene?.materials;return e?e.map((e=>({id:e.id,name:e.name}))):[]}setHighlights(e,t){0===e.length&&(this.highlightLayer?.dispose(),this.highlightLayer=void 0),this.highlightLayer||(this.highlightLayer=new(0,u.HighlightLayer)("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const i=t?new(0,g.Color3)(t[0],t[1],t[2]).toLinearSpace():void 0;e.forEach((e=>{const t=this.scene.materials.find((t=>t.name===e.name&&t.id===e.id));t&&t.getBindedMeshes().forEach((e=>this.highlightLayer?.addMesh(e,i||g.Color3.FromHexString("#fcba03"))))}))}initXRExperience(e){re(0,this.scene)}reattachControls(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;this.scene.detachControl(),this.engine.inputElement=e;const i=this.scene.activeCamera;if(i){i.attachControl(!0,!1,t);i.inputs.attached.pointers.multiTouchPanning=!1}this.scene.attachControl(!0,!0,!0)}getLoadListenerEvent(){const e=Array.from(this.loadProgress.values()).filter((e=>e<100)),t=e.reduce(((e,t)=>e+t),0)/e.length||0;return{loadValue:0===e.length?100:t,sceneInitialized:100===this.getSceneInitializationProgress()}}notifyLoadHandlers(){this.loadObservable.notifyObservers(this.getLoadListenerEvent())}}async function oe(e,t,i){(await V(e,t,i)).addAllToScene()}R(module.exports,F),R(module.exports,k),R(module.exports,O);
2
2
  //# sourceMappingURL=main.js.map
package/dist/module.js CHANGED
@@ -1,2 +1,2 @@
1
- import"@babylonjs/core/Engines/Extensions/engine.views";import"@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader";import"@babylonjs/core/Materials/Textures/Loaders/envTextureLoader";import"@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader";import"@babylonjs/core/Misc/screenshotTools";import"@babylonjs/core/Rendering/boundingBoxRenderer";import"@babylonjs/loaders/glTF/2.0";import"@babylonjs/core/Debug/debugLayer";import"@babylonjs/core/Helpers/sceneHelpers";import{SceneLoader as e}from"@babylonjs/core/Loading/sceneLoader";import{PBRMaterial as t}from"@babylonjs/core/Materials/PBR/pbrMaterial";import{MirrorTexture as a}from"@babylonjs/core/Materials/Textures/mirrorTexture";import{Color3 as i,Vector3 as r,Plane as s}from"@babylonjs/core/Maths/math";import{ReflectionProbe as o}from"@babylonjs/core/Probes/reflectionProbe";import{GLTF2 as n}from"@babylonjs/loaders/glTF";import{ActionManager as c}from"@babylonjs/core/Actions/actionManager";import{ExecuteCodeAction as l}from"@babylonjs/core/Actions/directActions";import{Engine as h}from"@babylonjs/core/Engines/engine";import{NullEngine as m}from"@babylonjs/core/Engines/nullEngine";import{GlowLayer as u}from"@babylonjs/core/Layers/glowLayer";import{HighlightLayer as d}from"@babylonjs/core/Layers/highlightLayer";import{CubeTexture as g}from"@babylonjs/core/Materials/Textures/cubeTexture";import{DynamicTexture as p}from"@babylonjs/core/Materials/Textures/dynamicTexture";import{Color3 as f,Color4 as b}from"@babylonjs/core/Maths/math.color";import{Vector3 as y}from"@babylonjs/core/Maths/math.vector";import{DracoCompression as v}from"@babylonjs/core/Meshes/Compression/dracoCompression";import{Observable as w}from"@babylonjs/core/Misc/observable";import{Tools as x}from"@babylonjs/core/Misc/tools";import{Scene as M}from"@babylonjs/core/scene";import{Texture as T}from"@babylonjs/core/Materials/Textures/texture";import{Animation as R}from"@babylonjs/core/Animations/animation";import{QuadraticEase as L,EasingFunction as C}from"@babylonjs/core/Animations/easing";import{ArcRotateCamera as A}from"@babylonjs/core/Cameras/arcRotateCamera";import{AssetsManager as P}from"@babylonjs/core/Misc/assetsManager";import{WebXRHitTest as E}from"@babylonjs/core/XR/features/WebXRHitTest";import{WebXRState as O}from"@babylonjs/core/XR/webXRTypes";function S(e,t,a,i){Object.defineProperty(e,t,{get:a,set:i,enumerable:!0,configurable:!0})}var I={};S(I,"RenderingConfiguration",(()=>B)),S(I,"REFLECTION_PROBE_RESOLUTION",(()=>F));class B{static getDynamicTextureResolution(){return this.getIsMobile()||!B.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}static shouldMipMap(){return!0}static offscreenRenderingSupported(){return!navigator.userAgent.includes("SamsungBrowser")&&(!!window.Worker&&!!window.OffscreenCanvas)}static getMirrorTextureResolution(){return this.getIsMobile()?512:1024}static getIsMobile(){return window.innerWidth<=480}}const F=128;n.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new N(e)})),e.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){const t=e;t.useRangeRequests=!0,t.transparencyAsCoverage=!0}}));class N{constructor(e){this.name="glbPostProcessor",this.enabled=!0,this.loader=e}onReady(){this.applyReflections(this.loader.babylonScene)}loadNodeAsync(e,t,a){return this.loader.loadNodeAsync(e,t,(function(e){t.extras&&Object.keys(t.extras).forEach((a=>{const i=t.extras[a];e.metadata[a]=i})),a(e)}))}loadMaterialPropertiesAsync(e,t,a){return this.enableMaterialExtrasIfRequired(t,a),this.loader.loadMaterialPropertiesAsync(e,t,a)}dispose(){}enableMaterialExtrasIfRequired(e,a){if(e.extras&&a instanceof t){if(e.extras.sheen){const t=a;t.sheen.isEnabled=!0,t.sheen.intensity=e.extras.sheen}if(e.extras.translucency){const t=a;t.subSurface.isTranslucencyEnabled=!0,t.subSurface.translucencyIntensity=e.extras.translucency,e.extras.translucencyR&&e.extras.translucencyG&&e.extras.translucencyB&&(t.subSurface.tintColor=new i(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.useDepthPrePass){const e=a;e.needDepthPrePass=!0,e.forceIrradianceInFragment=!0}if(e.extras.useParallax){const t=a;t.useParallax=!0,t.useParallaxOcclusion=!0,t.parallaxScaleBias=e.extras.useParallax}}}applyReflections(e){function t(e){const t=[];return e.transformNodes.forEach((e=>{e.metadata&&e.metadata.reflective&&t.push(...e.getChildMeshes())})),e.meshes.forEach((e=>{e.metadata&&e.metadata.reflective&&!t.includes(e)&&t.push(e)})),t}e.meshes.forEach((i=>{const n=i.metadata;n&&(n.mirrorTexture&&function(i,o=1){const n=i.material;if(!n)return;const c=new a("mirror",B.getMirrorTextureResolution(),e,!0);c.renderList=t(e);const l=i.getVerticesData("normal");if(!l)throw new Error("Mirror attribute specified on: "+i.name+"But no normals exist to generate a mirror from!");i.computeWorldMatrix(!0);const h=i.getWorldMatrix(),m=r.TransformNormal(new r(l[0],l[1],l[2]),h).normalize(),u=s.FromPositionAndNormal(i.position,m.scale(-1));c.mirrorPlane=u,c.level=o,n.reflectionTexture=c}(i,n.mirrorTexture),n.reflectionProbe&&function(a){const i=a.material,r=new o("probe-"+i.name,F,e);r.attachToMesh(a),r.renderList&&r.renderList.push(...t(e)),i.reflectionTexture=r.cubeTexture}(i))}))}}var j={};let D;var k;let _;var z;S(j,"ProductCameraRig",(()=>D)),S(j,"MaterialEffectMode",(()=>_)),(k=D||(D={}))[k.Orbit=0]="Orbit",k[k.Pan=1]="Pan",(z=_||(_={})).None="None",z.RemoveWhenSelected="RemoveWhenSelected",z.ApplyWhenSelected="ApplyWhenSelected";var V={};S(V,"SpiffCommerce3DPreviewService",(()=>se)),S(V,"createBaseModel",(()=>oe));const H=new Map;async function U(t,a,i){return new Promise(((r,s)=>{const o=H.get(t);if(o&&o.scene.uid===a.uid)return r(o);e.LoadAssetContainerAsync(t,void 0,a,i).then((e=>{H.set(t,e),r(e)})).catch(s)}))}class W{constructor(e){this.customOptions=e}get options(){return this.customOptions}get scene(){return{clearColor:this.getSceneClearColor(),transparentBackground:this.customOptions?.backgroundImage,environmentFile:this.customOptions?.environmentFile??"assets/model-viewer/default.env"}}get camera(){return{autoOrientation:this.customOptions?.disableAutomaticOrientation??!0,autoRotation:{enabled:this.customOptions?.autoRotation??!1,idleTimeMs:this.customOptions?.idleTimeBeforeRotation??5e3},limits:{min:{alpha:this.customOptions?.lowerAlphaLimitDeg?this.customOptions?.lowerAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.lowerBetaLimitDeg?this.customOptions?.lowerBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.minZoomOverride},max:{alpha:this.customOptions?.upperAlphaLimitDeg?this.customOptions?.upperAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.upperBetaLimitDeg?this.customOptions?.upperBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.maxZoomOverride}}}}get highlights(){return{enabled:this.customOptions?.highlightOnMaterialHover??!1,color:this.highlightColorFromConfig()}}getSceneClearColor=()=>{const e=this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions.backgroundImage)return new b(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=f.FromHexString(this.customOptions.backgroundColor);return new b(t.r,t.g,t.b,e).toLinearSpace()}return new b(.98,.98,.98,e).toLinearSpace()};highlightColorFromConfig=()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new b(.98,.98,.98,1).toLinearSpace();hexToColor4=(e,t=1)=>{const a=f.FromHexString(e);return new b(a.r,a.g,a.b,t).toLinearSpace()}}function G(e,t,a){t.forEach((t=>{const i=t.getID(),r=t.getName(),s=B.getDynamicTextureResolution();e.materials.filter((e=>e.name===r)).forEach((o=>{const n=a.get(i);if(n)q(o,n),n.update(false);else{const n=function(e,t,a,i){const r=new p(e,{width:a,height:i},t,B.shouldMipMap(),T.TRILINEAR_SAMPLINGMODE,h.TEXTUREFORMAT_RGBA),s=r.getContext();s&&(s.fillStyle="#f5f5f5",s.fillRect(0,0,a,i),r.update());return r}(r,e,s.width,s.height);a.set(i,n),t.setStaticContext(n.getContext()),q(o,n),n.onLoadObservable.addOnce((()=>{n.update(false)}))}}))}))}function q(e,a){if(e instanceof t){const t=e,i=t.albedoTexture;i?(a.wrapU=i.wrapU,a.wrapV=i.wrapV):(a.wrapU=1,a.wrapV=1),t.albedoTexture=a}else{const t=e,i=t.diffuseTexture;i&&(a.wrapU=i.wrapU,a.wrapV=i.wrapV),t.diffuseTexture=a}}function K(e,t,a,i){const r=e.animationGroups,s=e=>e.targetedAnimations.map((e=>e.animation.framePerSecond)).reduce(((e,t)=>e+t),0)/e.targetedAnimations.length||0;void 0===i||void 0===a||i!==a?r.forEach((e=>{e.stop();const r=s(e);e.start(t,1,i*r,a*r)})):r.forEach((e=>{e.stop();const a=s(e),r=i*a;e.start(t,1,r,r)}))}function X(e){e.animationGroups.forEach((e=>{e.stop()}))}function Z(e,t,a){var i,r,s;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(i=t.alpha,r=0,s=2*Math.PI,i<r?s-(r-i)%(s-r):r+(i-r)%(s-r)));const o=[],n=a.target,c=n?1:0;if(a.target&&o.push(Q("cameraTargetLerp","target",(new y).copyFrom(t.target),new y(a.target.x,a.target.y,a.target.z),R.ANIMATIONTYPE_VECTOR3,0)),o.push(Q("cameraAlphaLerp","alpha",t.alpha,Y(a.lonDeg),R.ANIMATIONTYPE_FLOAT,c)),o.push(Q("cameraBetaLerp","beta",t.beta,Y(a.latDeg),R.ANIMATIONTYPE_FLOAT,c)),void 0!==a.radius){const e=Math.max(.01,a.radius);o.push(Q("cameraRadiusLerp","radius",t.radius,e,R.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...o);const l=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,n?120:60,!1,1,(()=>{t.animations=[],l&&t.enableAutoRotationBehavior()}))}function Y(e){return e*Math.PI/180}function Q(e,t,a,i,r,s=0,o=R.ANIMATIONLOOPMODE_CONSTANT){const n=new L;n.setEasingMode(C.EASINGMODE_EASEINOUT);const c=new R(e,t,60,r,o),l=[];return s>0&&l.push({frame:0,value:a}),l.push({frame:60*s,value:a}),l.push({frame:60*(s+1),value:i}),c.setKeys(l),c.setEasingFunction(n),c}class $ extends A{constructor(e,t,a,i,r,s,o,n){super(e,t,a,i,r,s,n),this.minZ=.01,this.maxZ=1e3*this.radius,this.lowerRadiusLimit=.01*this.radius,this.enableFramingBehavior(),this.upperRadiusLimit=1.5*this.radius,this.wheelPrecision=100/this.radius,this.pinchPrecision=300/this.radius,this.wheelDeltaPercentage=.01,this.pinchDeltaPercentage=.005,this.useNaturalPinchZoom=!0,o.camera.autoOrientation&&(this.alpha+=Math.PI),o&&(o.camera.limits.min.beta&&(this.lowerBetaLimit=o.camera.limits.min.beta),o.camera.limits.max.beta&&(this.upperBetaLimit=o.camera.limits.max.beta),o.camera.limits.min.alpha&&(this.lowerAlphaLimit=o.camera.limits.min.alpha),o.camera.limits.max.alpha&&(this.upperAlphaLimit=o.camera.limits.max.alpha),o.camera.limits.min.radius&&(this.lowerRadiusLimit=o.camera.limits.min.radius),o.camera.limits.max.radius&&(this.upperRadiusLimit=o.camera.limits.max.radius),o.camera.autoRotation.enabled&&this.enableAutoRotationBehavior(o.camera.autoRotation.idleTimeMs))}lastFocus=new y(0,0,0);getFramingBehavior(){return this.getBehaviorByName("Framing")}getAutoRotationBehavior(){const e=this.getBehaviorByName("AutoRotation");return e||void 0}enableFramingBehavior(){this.useFramingBehavior=!0;const e=this.getFramingBehavior();e.attach(this),e.framingTime=0,e.elevationReturnTime=-1,e.zoomStopsAnimation=!1,this.lowerRadiusLimit=null;const t=J(this._scene);return e.zoomOnBoundingInfo(t.min,t.max),this.wheelPrecision=100/this.radius,null===this.lowerRadiusLimit&&(this.lowerRadiusLimit=.1),this.lastFocus.copyFrom(this.target),e}rerunFramingBehavior(e){const t=this.getFramingBehavior();t.framingTime=800;const a=J(this._scene);t.zoomOnBoundingInfo(a.min,a.max,void 0,(()=>{e()})),t.framingTime=0}enableAutoRotationBehavior(e=5e3){this.useAutoRotationBehavior=!0;const t=this.getAutoRotationBehavior();t&&(t.idleRotationWaitTime=e)}disableAutoRotationBehavior(){this.useAutoRotationBehavior=!1}static create(e,t){e.activeCamera&&(e.activeCamera.dispose(),e.activeCamera=null);const a=J(e),i=a.max.subtract(a.min),r=a.min.add(i.scale(.5)),s=new $("ProductCamera",-Math.PI/2,Math.PI/2,1.5*i.length(),r,e,t);return s.panningInertia=0,s.panningOriginTarget.copyFrom(r),s.onAfterCheckInputsObservable.add((()=>{s.panningSensibility=1e3/i.length()})),e.activeCamera=s,s}}function J(e){const t=e.meshes.filter((e=>e.name.toLowerCase().endsWith("_t")||e.name.toLowerCase().includes("_t_")));return e.getWorldExtends((e=>e.isVisible&&e.isEnabled()&&(0===t.length||t.includes(e))))}const ee={albedoTexture:"albedoMapKey",bumpTexture:"normalMapKey",ambientTexture:"ambientMapKey",emissiveTexture:"emissionMapKey",opacityTexture:"alphaMapKey",metallicTexture:"metallicMapKey",refractionTexture:"refractionMapKey"};function te(e,t,a,i){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((r=>{!function(e,t,a,i,r){const s=ee[e];if(!s)throw new Error("Unexpected texture name encountered.");const o=t[s];o?i.addTextureTask(e,o,!1,!1):r&&a[e]&&(a[e]&&a[e].dispose(),a[e]=null,function(e,t){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!0);"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!1,t.useMetallnessFromMetallicTextureBlue=!1);"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!1,t.subSurface.refractionIntensity=1)}(e,a))}(r,e,t,a,i)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===_.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===_.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function ae(e,t,a,i){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!1),"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!0,t.useMetallnessFromMetallicTextureBlue=!0),"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!0,t.subSurface.refractionIntensity=a.refractionIntensity||1),t[e]=i}class ie{materialVariantMap=new Map;keysThatRemovedBaseModel=[];loadedContainerForKey=new Map;async applyMaterial(e,t,a,i,r){return new Promise((s=>{const o=e.materials.filter((e=>e.name===t)),n=this.materialVariantMap.get(t);if(this.materialVariantMap.set(t,{...n,...a}),0===o.length)return void s(void 0);const c=new P(e);c.useDefaultLoadingScreen=!1,o.forEach((e=>te(a,e,c,r))),c.onProgress=(e,t,a)=>{i&&i(e/t*100,100,a.name)},c.onFinish=e=>{e.forEach((e=>{const t=e;i&&i(100,100,e.name),o.forEach((i=>ae(e.name,i,a,t.texture)))})),s(void 0)},c.loadAsync()}))}async applyModel(e,t,a,i,r){if(i&&a&&!this.keysThatRemovedBaseModel.includes(t)&&this.keysThatRemovedBaseModel.push(t),!i){const a=this.keysThatRemovedBaseModel.includes(t);return this.loadedContainerForKey.get(t)?.removeAllFromScene(),e&&a&&await oe(e.metadata.baseModel,e),Promise.resolve()}const s=await U(i,e,r);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),a){(await U(e.metadata.baseModel,e)).removeAllFromScene()}s.addAllToScene(),this.loadedContainerForKey.set(t,s);const o=[];this.materialVariantMap.forEach((async(t,a)=>{o.push(this.applyMaterial(e,a,t))})),await Promise.all(o)}}var re=async(e,t)=>{const a=await t.createDefaultXRExperienceAsync({uiOptions:{sessionMode:"immersive-ar",referenceSpaceType:"local-floor",onError:e=>{console.log(e)}}}),i=a.baseExperience.featuresManager.enableFeature(E.Name,"latest",{disablePermanentHitTest:!0,enableTransientHitTest:!0,useReferenceSpace:!0});let r=null;i.onHitTestResultObservable.add((e=>{r=e.length?e[0]:void 0})),t.onPointerDown=()=>{if(r&&a.baseExperience.state===O.IN_XR){const e=t.getNodeByName("__root__");r.transformationMatrix.decompose(void 0,e.rotationQuaternion,e.position)}}};class se{loadProgress=new Map([["initialScene",0]]);materialReadyToLoadCallbacks=new Map;modelReadyToLoadCallbacks=new Map;focusLostNotified=!1;loadObservable=new w;focusLostObservable=new w;dynamicTextures=new Map;variantManager=new ie;constructor(e,t){this.configuration=new W(t);v.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_decoder_gltf.js"}},e&&(e.getContext("webgl2")||e.getContext("webgl"));const a=console.log;console.log=()=>{};const i=e?new h(e,!0,{premultipliedAlpha:!1,preserveDrawingBuffer:!!t?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new m;console.log=a,i.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=i,this.scene=new M(i)}registerFocusLostListener(e){this.focusLostObservable.add(e)}unregisterFocusLostListener(e){this.focusLostObservable.removeCallback(e)}registerLoadProgressListener(e){this.loadObservable.add(e),e(this.getLoadListenerEvent())}unregisterLoadProgressListener(e){this.loadObservable.removeCallback(e)}registerView(e){const t=e.height,a=e.width;this.engine.registerView(e),e.setAttribute("height",t.toString()),e.setAttribute("width",a.toString()),this.orbitEnabled()||this.setCameraState(D.Pan)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e),this.engine.inputElement=null}shutdown(){this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(e,t){if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.metadata={baseModel:e},this.scene.environmentTexture=g.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),e){const t=99;await oe(e,this.scene,(e=>{this.loadProgress.set("initialScene",e.loaded*t/e.total),this.notifyLoadHandlers()}))}this.configuration.highlights.enabled&&this.scene.meshes.forEach((e=>{"targetcube_t"!==e.name&&"backgroundShell"!==e.name&&(e.isPickable=!0,e.actionManager||(e.actionManager=new c(this.scene)),e.actionManager.registerAction(new l(c.OnPointerOutTrigger,(()=>{this.setHighlights([])}))),e.actionManager.registerAction(new l(c.OnPointerOverTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&this.setHighlights([t])}}))))}));const a=$.create(this.scene,this.configuration),i=t?.getAll()||new Map;G(this.scene,i,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new u("GlowLayer",this.scene).intensity=.5}X(this.scene),this.engine.runRenderLoop((()=>{if(!this.engine.views)return;const e=this.engine.views[0],t=this.engine.inputElement;(!t||e&&t&&t.id!==e.target.id)&&this.reattachControls(e.target),i.forEach(((e,t)=>{const a=this.dynamicTextures.get(t);a&&e.getStaticContextDirty()&&a.isReady()&&(a.update(!1),e.setStaticContextDirty(!1))})),this.configuration.scene.transparentBackground&&this.engine.views.forEach((e=>{const t=this.engine.getRenderingCanvas();e.target.getContext("2d").clearRect(0,0,t.width,t.height)})),this.scene.render(),100!==this.getSceneInitializationProgress()&&(this.loadProgress.set("initialScene",100),this.materialReadyToLoadCallbacks.forEach(((e,t)=>{e.forEach(((e,a)=>{this.applyMaterialVariant(t,a,e)}))})),this.materialReadyToLoadCallbacks.clear(),this.modelReadyToLoadCallbacks.forEach((e=>{e(this.scene)})),this.modelReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeModelAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0),this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0),this.notifyLoadHandlers()),a.target.equalsWithEpsilon(a.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0)}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?K(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?Z(this.scene,this.scene.activeCamera,e):this.queuedCameraAnimation=e}getCameraPose(){if(this.scene){const e=this.scene.activeCamera;if(e)return{lonDeg:Math.round(180*e.alpha/Math.PI),latDeg:Math.round(180*e.beta/Math.PI),radius:Math.round(1e4*(e.radius+Number.EPSILON))/1e4,target:{x:e.target.x,y:e.target.y,z:e.target.z}}}}setCameraPose(e){if(this.scene){const t=this.scene.activeCamera;t&&(t.target=new y(e.target.x,e.target.y,e.target.z),t.radius=e.radius,t.alpha=e.latDeg,t.beta=e.lonDeg)}}async applyMaterialVariant(e,t,a,i){if(100===this.getSceneInitializationProgress())await this.variantManager.applyMaterial(this.scene,e,a,((e,t,a)=>{this.loadProgress.set(`key_${a}`,e/t*100),this.notifyLoadHandlers()}),i);else if(this.materialReadyToLoadCallbacks.has(e)){this.materialReadyToLoadCallbacks.get(e)?.set(t,a)}else{this.materialReadyToLoadCallbacks.set(e,new Map);this.materialReadyToLoadCallbacks.get(e)?.set(t,a)}}async applyModelVariant(e,a,i){100===this.getSceneInitializationProgress()?(await this.variantManager.applyModel(this.scene,e,i||!1,a.model,(t=>{this.loadProgress.set(e,100*t.loaded/t.total),this.notifyLoadHandlers()})),this.scene.materials.forEach((e=>{if(e&&0===e.getBindedMeshes().length){const a=e instanceof t&&!(e.albedoTexture instanceof p);e.dispose(!1,a)}})),G(this.scene,a.contextService.getAll(),this.dynamicTextures),X(this.scene)):this.modelReadyToLoadCallbacks.set(e,(()=>{this.applyModelVariant(e,a,i)}))}setCameraState(e){if(!this.engine?.views||!this.engine?.views[0])throw new Error("No views attached, camera state requires a view to attach controls onto.");e===D.Orbit?this.reattachControls(this.engine.views[0].target,2):this.reattachControls(this.engine.views[0].target,0)}animateToLastCameraFocus(){return new Promise((e=>{const t=this.scene.activeCamera,a=this.configuration;t.rerunFramingBehavior((()=>{this.focusLostNotified=!1,a.camera.limits.min.radius&&(t.lowerRadiusLimit=a.camera.limits.min.radius),a.camera.limits.max.radius&&(t.upperRadiusLimit=a.camera.limits.max.radius),e()}))}))}setAutoRotation(e){const t=this.scene.activeCamera;this.configuration.camera.autoRotation.enabled&&t&&(e?t.enableAutoRotationBehavior(this.configuration.camera.autoRotation.idleTimeMs):t.disableAutoRotationBehavior())}getCurrentConfiguration(){return this.configuration.options}async renderSceneScreenshot(e,t){const a=this.scene.activeCamera;if(!a)throw new Error("Missing product camera, cannot render screenshot!");var i;(i=a).getScene().stopAnimation(i),i.animations=[];const r=a.alpha,s=a.beta,o=a.radius,n=t.latDeg*Math.PI/180,c=t.lonDeg*Math.PI/180;a.alpha=c,a.beta=n,a.radius=t.radius||a.radius;const l=await x.CreateScreenshotUsingRenderTargetAsync(this.engine,a,e,"image/png",2,!0);return a.alpha=r,a.beta=s,a.radius=o,l}orbitEnabled(){const e=this.configuration;if(!e)return!0;const t=e.camera.limits.min.alpha,a=e.camera.limits.max.alpha,i=e.camera.limits.min.beta,r=e.camera.limits.max.beta;if(void 0===t||void 0===a||void 0===i||void 0===r)return!0;const s=[i,r],o=[t,a].every((e=>e===t)),n=s.every((e=>e===i));return!o&&!n}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}onMaterialSelected(e){this.scene.meshes.forEach((t=>{"targetcube_t"!==t.name&&"backgroundShell"!==t.name&&(t.actionManager||(t.actionManager=new c(this.scene)),t.actionManager.registerAction(new l(c.OnPickDownTrigger,(t=>{if(t.meshUnderPointer){const a=t.meshUnderPointer.material;a&&e({id:a.id,name:a.name})}}))))}))}listMaterials(){const e=this.scene?.materials;return e?e.map((e=>({id:e.id,name:e.name}))):[]}setHighlights(e,t){0===e.length&&(this.highlightLayer?.dispose(),this.highlightLayer=void 0),this.highlightLayer||(this.highlightLayer=new d("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const a=t?new f(t[0],t[1],t[2]).toLinearSpace():void 0;e.forEach((e=>{const t=this.scene.materials.find((t=>t.name===e.name&&t.id===e.id));t&&t.getBindedMeshes().forEach((e=>this.highlightLayer?.addMesh(e,a||f.FromHexString("#fcba03"))))}))}initXRExperience(e){re(0,this.scene)}reattachControls(e,t=2){this.scene.detachControl(),this.engine.inputElement=e;const a=this.scene.activeCamera;if(a){a.attachControl(!0,!1,t);a.inputs.attached.pointers.multiTouchPanning=!1}this.scene.attachControl(!0,!0,!0)}getLoadListenerEvent(){const e=Array.from(this.loadProgress.values()).filter((e=>e<100)),t=e.reduce(((e,t)=>e+t),0)/e.length||0;return{loadValue:0===e.length?100:t,sceneInitialized:100===this.getSceneInitializationProgress()}}notifyLoadHandlers(){this.loadObservable.notifyObservers(this.getLoadListenerEvent())}}async function oe(e,t,a){(await U(e,t,a)).addAllToScene()}export{D as ProductCameraRig,_ as MaterialEffectMode,se as SpiffCommerce3DPreviewService,oe as createBaseModel,B as RenderingConfiguration,F as REFLECTION_PROBE_RESOLUTION};
1
+ import"@babylonjs/core/Engines/Extensions/engine.views";import"@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader";import"@babylonjs/core/Materials/Textures/Loaders/envTextureLoader";import"@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader";import"@babylonjs/core/Misc/screenshotTools";import"@babylonjs/core/Rendering/boundingBoxRenderer";import"@babylonjs/loaders/glTF/2.0";import"@babylonjs/core/Debug/debugLayer";import"@babylonjs/core/Helpers/sceneHelpers";import{SceneLoader as e}from"@babylonjs/core/Loading/sceneLoader";import{PBRMaterial as t}from"@babylonjs/core/Materials/PBR/pbrMaterial";import{MirrorTexture as a}from"@babylonjs/core/Materials/Textures/mirrorTexture";import{Color3 as i,Vector3 as r,Plane as s}from"@babylonjs/core/Maths/math";import{ReflectionProbe as o}from"@babylonjs/core/Probes/reflectionProbe";import{GLTF2 as n}from"@babylonjs/loaders/glTF";import{ActionManager as c}from"@babylonjs/core/Actions/actionManager";import{ExecuteCodeAction as l}from"@babylonjs/core/Actions/directActions";import{Engine as h}from"@babylonjs/core/Engines/engine";import{NullEngine as u}from"@babylonjs/core/Engines/nullEngine";import{GlowLayer as m}from"@babylonjs/core/Layers/glowLayer";import{HighlightLayer as d}from"@babylonjs/core/Layers/highlightLayer";import{CubeTexture as g}from"@babylonjs/core/Materials/Textures/cubeTexture";import{DynamicTexture as p}from"@babylonjs/core/Materials/Textures/dynamicTexture";import{Color3 as f,Color4 as b}from"@babylonjs/core/Maths/math.color";import{Vector3 as v}from"@babylonjs/core/Maths/math.vector";import{DracoCompression as y}from"@babylonjs/core/Meshes/Compression/dracoCompression";import{Observable as w}from"@babylonjs/core/Misc/observable";import{Tools as x}from"@babylonjs/core/Misc/tools";import{Scene as M}from"@babylonjs/core/scene";import{Texture as T}from"@babylonjs/core/Materials/Textures/texture";import{Animation as L}from"@babylonjs/core/Animations/animation";import{QuadraticEase as R,EasingFunction as C}from"@babylonjs/core/Animations/easing";import{ArcRotateCamera as A}from"@babylonjs/core/Cameras/arcRotateCamera";import{AssetsManager as P}from"@babylonjs/core/Misc/assetsManager";import{WebXRHitTest as O}from"@babylonjs/core/XR/features/WebXRHitTest";import{WebXRState as E}from"@babylonjs/core/XR/webXRTypes";function S(e,t,a,i){Object.defineProperty(e,t,{get:a,set:i,enumerable:!0,configurable:!0})}var I={};S(I,"RenderingConfiguration",(()=>B)),S(I,"REFLECTION_PROBE_RESOLUTION",(()=>F));class B{static getDynamicTextureResolution(){return this.getIsMobile()||!B.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}static shouldMipMap(){return!0}static offscreenRenderingSupported(){return!navigator.userAgent.includes("SamsungBrowser")&&(!!window.Worker&&!!window.OffscreenCanvas)}static getMirrorTextureResolution(){return this.getIsMobile()?512:1024}static getIsMobile(){return window.innerWidth<=480}}const F=128;function j(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}n.GLTFLoader.RegisterExtension("glbPostProcessor",(function(e){return new N(e)})),e.OnPluginActivatedObservable.add((e=>{if("gltf"===e.name){const t=e;t.useRangeRequests=!0,t.transparencyAsCoverage=!0}}));class N{constructor(e){j(this,"name",void 0),j(this,"enabled",void 0),j(this,"loader",void 0),this.name="glbPostProcessor",this.enabled=!0,this.loader=e}onReady(){this.applyReflections(this.loader.babylonScene)}loadNodeAsync(e,t,a){return this.loader.loadNodeAsync(e,t,(function(e){t.extras&&Object.keys(t.extras).forEach((a=>{const i=t.extras[a];e.metadata[a]=i})),a(e)}))}loadMaterialPropertiesAsync(e,t,a){return this.enableMaterialExtrasIfRequired(t,a),this.loader.loadMaterialPropertiesAsync(e,t,a)}dispose(){}enableMaterialExtrasIfRequired(e,a){if(e.extras&&a instanceof t){if(e.extras.sheen){const t=a;t.sheen.isEnabled=!0,t.sheen.intensity=e.extras.sheen}if(e.extras.translucency){const t=a;t.subSurface.isTranslucencyEnabled=!0,t.subSurface.translucencyIntensity=e.extras.translucency,e.extras.translucencyR&&e.extras.translucencyG&&e.extras.translucencyB&&(t.subSurface.tintColor=new i(e.extras.translucencyR,e.extras.translucencyG,e.extras.translucencyB))}if(e.extras.useDepthPrePass){const e=a;e.needDepthPrePass=!0,e.forceIrradianceInFragment=!0}if(e.extras.useParallax){const t=a;t.useParallax=!0,t.useParallaxOcclusion=!0,t.parallaxScaleBias=e.extras.useParallax}}}applyReflections(e){function t(e){const t=[];return e.transformNodes.forEach((e=>{e.metadata&&e.metadata.reflective&&t.push(...e.getChildMeshes())})),e.meshes.forEach((e=>{e.metadata&&e.metadata.reflective&&!t.includes(e)&&t.push(e)})),t}e.meshes.forEach((i=>{const n=i.metadata;n&&(n.mirrorTexture&&function(i){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const n=i.material;if(!n)return;const c=new a("mirror",B.getMirrorTextureResolution(),e,!0);c.renderList=t(e);const l=i.getVerticesData("normal");if(!l)throw new Error("Mirror attribute specified on: "+i.name+"But no normals exist to generate a mirror from!");i.computeWorldMatrix(!0);const h=i.getWorldMatrix(),u=r.TransformNormal(new r(l[0],l[1],l[2]),h).normalize(),m=s.FromPositionAndNormal(i.position,u.scale(-1));c.mirrorPlane=m,c.level=o,n.reflectionTexture=c}(i,n.mirrorTexture),n.reflectionProbe&&function(a){const i=a.material,r=new o("probe-"+i.name,F,e);r.attachToMesh(a),r.renderList&&r.renderList.push(...t(e)),i.reflectionTexture=r.cubeTexture}(i))}))}}var D={};let k;var _;let z;var V;S(D,"ProductCameraRig",(()=>k)),S(D,"MaterialEffectMode",(()=>z)),(_=k||(k={}))[_.Orbit=0]="Orbit",_[_.Pan=1]="Pan",(V=z||(z={})).None="None",V.RemoveWhenSelected="RemoveWhenSelected",V.ApplyWhenSelected="ApplyWhenSelected";var H={};S(H,"SpiffCommerce3DPreviewService",(()=>le)),S(H,"createBaseModel",(()=>he));const U=new Map;async function W(t,a,i){return new Promise(((r,s)=>{const o=U.get(t);if(o&&o.scene.uid===a.uid)return r(o);e.LoadAssetContainerAsync(t,void 0,a,i).then((e=>{U.set(t,e),r(e)})).catch(s)}))}function G(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class q{constructor(e){G(this,"customOptions",void 0),G(this,"getSceneClearColor",(()=>{const e=this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions.backgroundImage)return new b(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=f.FromHexString(this.customOptions.backgroundColor);return new b(t.r,t.g,t.b,e).toLinearSpace()}return new b(.98,.98,.98,e).toLinearSpace()})),G(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new b(.98,.98,.98,1).toLinearSpace())),G(this,"hexToColor4",(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const a=f.FromHexString(e);return new b(a.r,a.g,a.b,t).toLinearSpace()})),this.customOptions=e}get options(){return this.customOptions}get scene(){return{clearColor:this.getSceneClearColor(),transparentBackground:this.customOptions?.backgroundImage,environmentFile:this.customOptions?.environmentFile??"assets/model-viewer/default.env"}}get camera(){return{autoOrientation:this.customOptions?.disableAutomaticOrientation??!0,autoRotation:{enabled:this.customOptions?.autoRotation??!1,idleTimeMs:this.customOptions?.idleTimeBeforeRotation??5e3},limits:{min:{alpha:this.customOptions?.lowerAlphaLimitDeg?this.customOptions?.lowerAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.lowerBetaLimitDeg?this.customOptions?.lowerBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.minZoomOverride},max:{alpha:this.customOptions?.upperAlphaLimitDeg?this.customOptions?.upperAlphaLimitDeg*Math.PI/180:void 0,beta:this.customOptions?.upperBetaLimitDeg?this.customOptions?.upperBetaLimitDeg*Math.PI/180:void 0,radius:this.customOptions?.maxZoomOverride}}}}get highlights(){return{enabled:this.customOptions?.highlightOnMaterialHover??!1,color:this.highlightColorFromConfig()}}}function K(e,t,a){t.forEach((t=>{const i=t.getID(),r=t.getName(),s=B.getDynamicTextureResolution();e.materials.filter((e=>e.name===r)).forEach((o=>{const n=a.get(i);if(n)X(o,n),n.update(false);else{const n=function(e,t,a,i){const r=new p(e,{width:a,height:i},t,B.shouldMipMap(),T.TRILINEAR_SAMPLINGMODE,h.TEXTUREFORMAT_RGBA),s=r.getContext();s&&(s.fillStyle="#f5f5f5",s.fillRect(0,0,a,i),r.update());return r}(r,e,s.width,s.height);a.set(i,n),t.setStaticContext(n.getContext()),X(o,n),n.onLoadObservable.addOnce((()=>{n.update(false)}))}}))}))}function X(e,a){if(e instanceof t){const t=e,i=t.albedoTexture;i?(a.wrapU=i.wrapU,a.wrapV=i.wrapV):(a.wrapU=1,a.wrapV=1),t.albedoTexture=a}else{const t=e,i=t.diffuseTexture;i&&(a.wrapU=i.wrapU,a.wrapV=i.wrapV),t.diffuseTexture=a}}function Z(e,t,a,i){const r=e.animationGroups,s=e=>e.targetedAnimations.map((e=>e.animation.framePerSecond)).reduce(((e,t)=>e+t),0)/e.targetedAnimations.length||0;void 0===i||void 0===a||i!==a?r.forEach((e=>{e.stop();const r=s(e);e.start(t,1,i*r,a*r)})):r.forEach((e=>{e.stop();const a=s(e),r=i*a;e.start(t,1,r,r)}))}function Y(e){e.animationGroups.forEach((e=>{e.stop()}))}function Q(e,t,a){var i,r,s;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(i=t.alpha,r=0,s=2*Math.PI,i<r?s-(r-i)%(s-r):r+(i-r)%(s-r)));const o=[],n=a.target,c=n?1:0;if(a.target&&o.push(J("cameraTargetLerp","target",(new v).copyFrom(t.target),new v(a.target.x,a.target.y,a.target.z),L.ANIMATIONTYPE_VECTOR3,0)),o.push(J("cameraAlphaLerp","alpha",t.alpha,$(a.lonDeg),L.ANIMATIONTYPE_FLOAT,c)),o.push(J("cameraBetaLerp","beta",t.beta,$(a.latDeg),L.ANIMATIONTYPE_FLOAT,c)),void 0!==a.radius){const e=Math.max(.01,a.radius);o.push(J("cameraRadiusLerp","radius",t.radius,e,L.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...o);const l=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,n?120:60,!1,1,(()=>{t.animations=[],l&&t.enableAutoRotationBehavior()}))}function $(e){return e*Math.PI/180}function J(e,t,a,i,r){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:L.ANIMATIONLOOPMODE_CONSTANT;const n=new R;n.setEasingMode(C.EASINGMODE_EASEINOUT);const c=new L(e,t,60,r,o),l=[];return s>0&&l.push({frame:0,value:a}),l.push({frame:60*s,value:a}),l.push({frame:60*(s+1),value:i}),c.setKeys(l),c.setEasingFunction(n),c}class ee extends A{constructor(e,t,a,i,r,s,o,n){var c,l,h;super(e,t,a,i,r,s,n),c=this,l="lastFocus",h=new v(0,0,0),l in c?Object.defineProperty(c,l,{value:h,enumerable:!0,configurable:!0,writable:!0}):c[l]=h,this.minZ=.01,this.maxZ=1e3*this.radius,this.lowerRadiusLimit=.01*this.radius,this.enableFramingBehavior(),this.upperRadiusLimit=1.5*this.radius,this.wheelPrecision=100/this.radius,this.pinchPrecision=300/this.radius,this.wheelDeltaPercentage=.01,this.pinchDeltaPercentage=.005,this.useNaturalPinchZoom=!0,o.camera.autoOrientation&&(this.alpha+=Math.PI),o&&(o.camera.limits.min.beta&&(this.lowerBetaLimit=o.camera.limits.min.beta),o.camera.limits.max.beta&&(this.upperBetaLimit=o.camera.limits.max.beta),o.camera.limits.min.alpha&&(this.lowerAlphaLimit=o.camera.limits.min.alpha),o.camera.limits.max.alpha&&(this.upperAlphaLimit=o.camera.limits.max.alpha),o.camera.limits.min.radius&&(this.lowerRadiusLimit=o.camera.limits.min.radius),o.camera.limits.max.radius&&(this.upperRadiusLimit=o.camera.limits.max.radius),o.camera.autoRotation.enabled&&this.enableAutoRotationBehavior(o.camera.autoRotation.idleTimeMs))}getFramingBehavior(){return this.getBehaviorByName("Framing")}getAutoRotationBehavior(){const e=this.getBehaviorByName("AutoRotation");return e||void 0}enableFramingBehavior(){this.useFramingBehavior=!0;const e=this.getFramingBehavior();e.attach(this),e.framingTime=0,e.elevationReturnTime=-1,e.zoomStopsAnimation=!1,this.lowerRadiusLimit=null;const t=te(this._scene);return e.zoomOnBoundingInfo(t.min,t.max),this.wheelPrecision=100/this.radius,null===this.lowerRadiusLimit&&(this.lowerRadiusLimit=.1),this.lastFocus.copyFrom(this.target),e}rerunFramingBehavior(e){const t=this.getFramingBehavior();t.framingTime=800;const a=te(this._scene);t.zoomOnBoundingInfo(a.min,a.max,void 0,(()=>{e()})),t.framingTime=0}enableAutoRotationBehavior(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e3;this.useAutoRotationBehavior=!0;const t=this.getAutoRotationBehavior();t&&(t.idleRotationWaitTime=e)}disableAutoRotationBehavior(){this.useAutoRotationBehavior=!1}static create(e,t){e.activeCamera&&(e.activeCamera.dispose(),e.activeCamera=null);const a=te(e),i=a.max.subtract(a.min),r=a.min.add(i.scale(.5)),s=new ee("ProductCamera",-Math.PI/2,Math.PI/2,1.5*i.length(),r,e,t);return s.panningInertia=0,s.panningOriginTarget.copyFrom(r),s.onAfterCheckInputsObservable.add((()=>{s.panningSensibility=1e3/i.length()})),e.activeCamera=s,s}}function te(e){const t=e.meshes.filter((e=>e.name.toLowerCase().endsWith("_t")||e.name.toLowerCase().includes("_t_")));return e.getWorldExtends((e=>e.isVisible&&e.isEnabled()&&(0===t.length||t.includes(e))))}const ae={albedoTexture:"albedoMapKey",bumpTexture:"normalMapKey",ambientTexture:"ambientMapKey",emissiveTexture:"emissionMapKey",opacityTexture:"alphaMapKey",metallicTexture:"metallicMapKey",refractionTexture:"refractionMapKey"};function ie(e,t,a,i){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((r=>{!function(e,t,a,i,r){const s=ae[e];if(!s)throw new Error("Unexpected texture name encountered.");const o=t[s];o?i.addTextureTask(e,o,!1,!1):r&&a[e]&&(a[e]&&a[e].dispose(),a[e]=null,function(e,t){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!0);"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!1,t.useMetallnessFromMetallicTextureBlue=!1);"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!1,t.subSurface.refractionIntensity=1)}(e,a))}(r,e,t,a,i)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===z.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===z.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function re(e,t,a,i){"opacityTexture"===e&&(t.useAlphaFromAlbedoTexture=!1),"metallicTexture"===e&&(t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!0,t.useMetallnessFromMetallicTextureBlue=!0),"refractionTexture"===e&&(t.subSurface.isRefractionEnabled=!0,t.subSurface.refractionIntensity=a.refractionIntensity||1),t[e]=i}function se(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class oe{constructor(){se(this,"materialVariantMap",new Map),se(this,"keysThatRemovedBaseModel",[]),se(this,"loadedContainerForKey",new Map)}async applyMaterial(e,t,a,i,r){return new Promise((s=>{const o=e.materials.filter((e=>e.name===t)),n=this.materialVariantMap.get(t);if(this.materialVariantMap.set(t,{...n,...a}),0===o.length)return void s(void 0);const c=new P(e);c.useDefaultLoadingScreen=!1,o.forEach((e=>ie(a,e,c,r))),c.onProgress=(e,t,a)=>{i&&i(e/t*100,100,a.name)},c.onFinish=e=>{e.forEach((e=>{const t=e;i&&i(100,100,e.name),o.forEach((i=>re(e.name,i,a,t.texture)))})),s(void 0)},c.loadAsync()}))}async applyModel(e,t,a,i,r){if(i&&a&&!this.keysThatRemovedBaseModel.includes(t)&&this.keysThatRemovedBaseModel.push(t),!i){const a=this.keysThatRemovedBaseModel.includes(t);return this.loadedContainerForKey.get(t)?.removeAllFromScene(),e&&a&&await he(e.metadata.baseModel,e),Promise.resolve()}const s=await W(i,e,r);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),a){(await W(e.metadata.baseModel,e)).removeAllFromScene()}s.addAllToScene(),this.loadedContainerForKey.set(t,s);const o=[];this.materialVariantMap.forEach((async(t,a)=>{o.push(this.applyMaterial(e,a,t))})),await Promise.all(o)}}var ne=async(e,t)=>{const a=await t.createDefaultXRExperienceAsync({uiOptions:{sessionMode:"immersive-ar",referenceSpaceType:"local-floor",onError:e=>{console.log(e)}}}),i=a.baseExperience.featuresManager.enableFeature(O.Name,"latest",{disablePermanentHitTest:!0,enableTransientHitTest:!0,useReferenceSpace:!0});let r=null;i.onHitTestResultObservable.add((e=>{r=e.length?e[0]:void 0})),t.onPointerDown=()=>{if(r&&a.baseExperience.state===E.IN_XR){const e=t.getNodeByName("__root__");r.transformationMatrix.decompose(void 0,e.rotationQuaternion,e.position)}}};function ce(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class le{constructor(e,t){ce(this,"engine",void 0),ce(this,"scene",void 0),ce(this,"configuration",void 0),ce(this,"loadProgress",new Map([["initialScene",0]])),ce(this,"materialReadyToLoadCallbacks",new Map),ce(this,"modelReadyToLoadCallbacks",new Map),ce(this,"queuedModelAnimation",void 0),ce(this,"queuedCameraAnimation",void 0),ce(this,"focusLostNotified",!1),ce(this,"loadObservable",new w),ce(this,"focusLostObservable",new w),ce(this,"dynamicTextures",new Map),ce(this,"highlightLayer",void 0),ce(this,"variantManager",new oe),this.configuration=new q(t);y.Configuration={decoder:{wasmUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_decoder_gltf.wasm",fallbackUrl:"https://www.gstatic.com/draco/versioned/decoders/1.5.3/draco_decoder_gltf.js"}},e&&(e.getContext("webgl2")||e.getContext("webgl"));const a=console.log;console.log=()=>{};const i=e?new h(e,!0,{premultipliedAlpha:!1,preserveDrawingBuffer:!!t?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new u;console.log=a,i.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=i,this.scene=new M(i)}registerFocusLostListener(e){this.focusLostObservable.add(e)}unregisterFocusLostListener(e){this.focusLostObservable.removeCallback(e)}registerLoadProgressListener(e){this.loadObservable.add(e),e(this.getLoadListenerEvent())}unregisterLoadProgressListener(e){this.loadObservable.removeCallback(e)}registerView(e){const t=e.height,a=e.width;this.engine.registerView(e),e.setAttribute("height",t.toString()),e.setAttribute("width",a.toString()),this.orbitEnabled()||this.setCameraState(k.Pan)}getNumViewports(){return this.engine.views?.length||0}unregisterView(e){this.engine.unRegisterView(e),this.engine.inputElement=null}shutdown(){this.engine&&this.engine.dispose(),window.removeEventListener("resize",this.fireResizeEvent)}getSceneInitializationProgress(){return this.loadProgress.get("initialScene")}async initialize(e,t){if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.metadata={baseModel:e},this.scene.environmentTexture=g.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),e){const t=99;await he(e,this.scene,(e=>{this.loadProgress.set("initialScene",e.loaded*t/e.total),this.notifyLoadHandlers()}))}this.configuration.highlights.enabled&&this.scene.meshes.forEach((e=>{"targetcube_t"!==e.name&&"backgroundShell"!==e.name&&(e.isPickable=!0,e.actionManager||(e.actionManager=new c(this.scene)),e.actionManager.registerAction(new l(c.OnPointerOutTrigger,(()=>{this.setHighlights([])}))),e.actionManager.registerAction(new l(c.OnPointerOverTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&this.setHighlights([t])}}))))}));const a=ee.create(this.scene,this.configuration),i=t?.getAll()||new Map;K(this.scene,i,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new m("GlowLayer",this.scene).intensity=.5}Y(this.scene),this.engine.runRenderLoop((()=>{if(!this.engine.views)return;const e=this.engine.views[0],t=this.engine.inputElement;(!t||e&&t&&t.id!==e.target.id)&&this.reattachControls(e.target),i.forEach(((e,t)=>{const a=this.dynamicTextures.get(t);a&&e.getStaticContextDirty()&&a.isReady()&&(a.update(!1),e.setStaticContextDirty(!1))})),this.configuration.scene.transparentBackground&&this.engine.views.forEach((e=>{const t=this.engine.getRenderingCanvas();e.target.getContext("2d").clearRect(0,0,t.width,t.height)})),this.scene.render(),100!==this.getSceneInitializationProgress()&&(this.loadProgress.set("initialScene",100),this.materialReadyToLoadCallbacks.forEach(((e,t)=>{e.forEach(((e,a)=>{this.applyMaterialVariant(t,a,e)}))})),this.materialReadyToLoadCallbacks.clear(),this.modelReadyToLoadCallbacks.forEach((e=>{e(this.scene)})),this.modelReadyToLoadCallbacks.clear(),this.queuedModelAnimation&&(this.executeModelAnimation(this.queuedModelAnimation),this.queuedModelAnimation=void 0),this.queuedCameraAnimation&&(this.executeCameraAnimation(this.queuedCameraAnimation),this.queuedCameraAnimation=void 0),this.notifyLoadHandlers()),a.target.equalsWithEpsilon(a.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0)}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?Z(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?Q(this.scene,this.scene.activeCamera,e):this.queuedCameraAnimation=e}getCameraPose(){if(this.scene){const e=this.scene.activeCamera;if(e)return{lonDeg:Math.round(180*e.alpha/Math.PI),latDeg:Math.round(180*e.beta/Math.PI),radius:Math.round(1e4*(e.radius+Number.EPSILON))/1e4,target:{x:e.target.x,y:e.target.y,z:e.target.z}}}}setCameraPose(e){if(this.scene){const t=this.scene.activeCamera;t&&(t.target=new v(e.target.x,e.target.y,e.target.z),t.radius=e.radius,t.alpha=e.latDeg,t.beta=e.lonDeg)}}async applyMaterialVariant(e,t,a,i){if(100===this.getSceneInitializationProgress())await this.variantManager.applyMaterial(this.scene,e,a,((e,t,a)=>{this.loadProgress.set(`key_${a}`,e/t*100),this.notifyLoadHandlers()}),i);else if(this.materialReadyToLoadCallbacks.has(e)){this.materialReadyToLoadCallbacks.get(e)?.set(t,a)}else{this.materialReadyToLoadCallbacks.set(e,new Map);this.materialReadyToLoadCallbacks.get(e)?.set(t,a)}}async applyModelVariant(e,a,i){100===this.getSceneInitializationProgress()?(await this.variantManager.applyModel(this.scene,e,i||!1,a.model,(t=>{this.loadProgress.set(e,100*t.loaded/t.total),this.notifyLoadHandlers()})),this.scene.materials.forEach((e=>{if(e&&0===e.getBindedMeshes().length){const a=e instanceof t&&!(e.albedoTexture instanceof p);e.dispose(!1,a)}})),K(this.scene,a.contextService.getAll(),this.dynamicTextures),Y(this.scene)):this.modelReadyToLoadCallbacks.set(e,(()=>{this.applyModelVariant(e,a,i)}))}setCameraState(e){if(!this.engine?.views||!this.engine?.views[0])throw new Error("No views attached, camera state requires a view to attach controls onto.");e===k.Orbit?this.reattachControls(this.engine.views[0].target,2):this.reattachControls(this.engine.views[0].target,0)}animateToLastCameraFocus(){return new Promise((e=>{const t=this.scene.activeCamera,a=this.configuration;t.rerunFramingBehavior((()=>{this.focusLostNotified=!1,a.camera.limits.min.radius&&(t.lowerRadiusLimit=a.camera.limits.min.radius),a.camera.limits.max.radius&&(t.upperRadiusLimit=a.camera.limits.max.radius),e()}))}))}setAutoRotation(e){const t=this.scene.activeCamera;this.configuration.camera.autoRotation.enabled&&t&&(e?t.enableAutoRotationBehavior(this.configuration.camera.autoRotation.idleTimeMs):t.disableAutoRotationBehavior())}getCurrentConfiguration(){return this.configuration.options}async renderSceneScreenshot(e,t){const a=this.scene.activeCamera;if(!a)throw new Error("Missing product camera, cannot render screenshot!");var i;(i=a).getScene().stopAnimation(i),i.animations=[];const r=a.alpha,s=a.beta,o=a.radius,n=t.latDeg*Math.PI/180,c=t.lonDeg*Math.PI/180;a.alpha=c,a.beta=n,a.radius=t.radius||a.radius;const l=await x.CreateScreenshotUsingRenderTargetAsync(this.engine,a,e,"image/png",2,!0);return a.alpha=r,a.beta=s,a.radius=o,l}orbitEnabled(){const e=this.configuration;if(!e)return!0;const t=e.camera.limits.min.alpha,a=e.camera.limits.max.alpha,i=e.camera.limits.min.beta,r=e.camera.limits.max.beta;if(void 0===t||void 0===a||void 0===i||void 0===r)return!0;const s=[i,r],o=[t,a].every((e=>e===t)),n=s.every((e=>e===i));return!o&&!n}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}onMaterialSelected(e){this.scene.meshes.forEach((t=>{"targetcube_t"!==t.name&&"backgroundShell"!==t.name&&(t.actionManager||(t.actionManager=new c(this.scene)),t.actionManager.registerAction(new l(c.OnPickDownTrigger,(t=>{if(t.meshUnderPointer){const a=t.meshUnderPointer.material;a&&e({id:a.id,name:a.name})}}))))}))}listMaterials(){const e=this.scene?.materials;return e?e.map((e=>({id:e.id,name:e.name}))):[]}setHighlights(e,t){0===e.length&&(this.highlightLayer?.dispose(),this.highlightLayer=void 0),this.highlightLayer||(this.highlightLayer=new d("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const a=t?new f(t[0],t[1],t[2]).toLinearSpace():void 0;e.forEach((e=>{const t=this.scene.materials.find((t=>t.name===e.name&&t.id===e.id));t&&t.getBindedMeshes().forEach((e=>this.highlightLayer?.addMesh(e,a||f.FromHexString("#fcba03"))))}))}initXRExperience(e){ne(0,this.scene)}reattachControls(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;this.scene.detachControl(),this.engine.inputElement=e;const a=this.scene.activeCamera;if(a){a.attachControl(!0,!1,t);a.inputs.attached.pointers.multiTouchPanning=!1}this.scene.attachControl(!0,!0,!0)}getLoadListenerEvent(){const e=Array.from(this.loadProgress.values()).filter((e=>e<100)),t=e.reduce(((e,t)=>e+t),0)/e.length||0;return{loadValue:0===e.length?100:t,sceneInitialized:100===this.getSceneInitializationProgress()}}notifyLoadHandlers(){this.loadObservable.notifyObservers(this.getLoadListenerEvent())}}async function he(e,t,a){(await W(e,t,a)).addAllToScene()}export{k as ProductCameraRig,z as MaterialEffectMode,le as SpiffCommerce3DPreviewService,he as createBaseModel,B as RenderingConfiguration,F as REFLECTION_PROBE_RESOLUTION};
2
2
  //# sourceMappingURL=module.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spiffcommerce/preview",
3
- "version": "2.0.0",
3
+ "version": "2.0.2",
4
4
  "description": "An internal implementation of the ThreeDPreviewService interface used by Spiff Commerce",
5
5
  "source": "src/index.ts",
6
6
  "main": "dist/main.js",
@@ -20,6 +20,8 @@
20
20
  "babylonjs-gltf2interface": "^5.26.1"
21
21
  },
22
22
  "devDependencies": {
23
+ "@babel/plugin-proposal-class-properties": "^7.18.6",
24
+ "@parcel/babel-preset-env": "^2.7.0",
23
25
  "@parcel/packager-ts": "2.7.0",
24
26
  "@parcel/transformer-typescript-tsc": "^2.7.0",
25
27
  "@parcel/transformer-typescript-types": "^2.7.0",