@spiffcommerce/preview 2.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2019 Liam Parker
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Liam Parker
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # spiff-preview
2
-
3
- A library allowing for 3D product visualization, used in tandem with the Spiff 3D suite of e-commerce plugins.
1
+ # spiff-preview
2
+
3
+ A library allowing for 3D product visualization, used in tandem with the Spiff 3D suite of e-commerce plugins.
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 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};
1
+ import{ActionManager as e}from"@babylonjs/core/Actions/actionManager";import{ExecuteCodeAction as t}from"@babylonjs/core/Actions/directActions";import{Engine as i}from"@babylonjs/core/Engines/engine";import{NullEngine as a}from"@babylonjs/core/Engines/nullEngine";import{GlowLayer as s}from"@babylonjs/core/Layers/glowLayer";import{HighlightLayer as n}from"@babylonjs/core/Layers/highlightLayer";import{PBRMaterial as o}from"@babylonjs/core/Materials/PBR/pbrMaterial";import{CubeTexture as r}from"@babylonjs/core/Materials/Textures/cubeTexture";import{DynamicTexture as c}from"@babylonjs/core/Materials/Textures/dynamicTexture";import{Color3 as l,Color4 as h}from"@babylonjs/core/Maths/math.color";import{Vector3 as m}from"@babylonjs/core/Maths/math.vector";import{DracoCompression as u}from"@babylonjs/core/Meshes/Compression/dracoCompression";import{Observable as d}from"@babylonjs/core/Misc/observable";import{Tools as g}from"@babylonjs/core/Misc/tools";import{Scene as p}from"@babylonjs/core/scene";import{SceneLoader as f}from"@babylonjs/core/Loading/sceneLoader";import{Texture as b}from"@babylonjs/core/Materials/Textures/texture";import{Animation as v}from"@babylonjs/core/Animations/animation";import{QuadraticEase as w,EasingFunction as y}from"@babylonjs/core/Animations/easing";import{ArcRotateCamera as M}from"@babylonjs/core/Cameras/arcRotateCamera";import{AssetsManager as T}from"@babylonjs/core/Misc/assetsManager";import{WebXRHitTest as C}from"@babylonjs/core/XR/features/WebXRHitTest";import{WebXRState as L}from"@babylonjs/core/XR/webXRTypes";function R(e,t,i,a){Object.defineProperty(e,t,{get:i,set:a,enumerable:!0,configurable:!0})}var x={};let A;var O;let E;var S;R(x,"ProductCameraRig",(()=>A)),R(x,"MaterialEffectMode",(()=>E)),(O=A||(A={}))[O.Orbit=0]="Orbit",O[O.Pan=1]="Pan",(S=E||(E={})).None="None",S.RemoveWhenSelected="RemoveWhenSelected",S.ApplyWhenSelected="ApplyWhenSelected";var P={};R(P,"SpiffCommerce3DPreviewService",(()=>te)),R(P,"createBaseModel",(()=>ie));const I=new Map;async function B(e,t,i){return new Promise(((a,s)=>{const n=I.get(e);if(n&&n.scene.uid===t.uid)return a(n);f.LoadAssetContainerAsync(e,void 0,t,i).then((t=>{I.set(e,t),a(t)})).catch(s)}))}function F(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class N{constructor(e){F(this,"customOptions",void 0),F(this,"getSceneClearColor",(()=>{const e=this.customOptions?.backgroundImage?0:1;if(this.customOptions&&this.customOptions.backgroundImage)return new h(0,0,0,e).toLinearSpace();if(this.customOptions&&this.customOptions.backgroundColor){const t=l.FromHexString(this.customOptions.backgroundColor);return new h(t.r,t.g,t.b,e).toLinearSpace()}return new h(.98,.98,.98,e).toLinearSpace()})),F(this,"highlightColorFromConfig",(()=>this.customOptions&&this.customOptions.highlightColor?this.hexToColor4(this.customOptions.highlightColor):new h(.98,.98,.98,1).toLinearSpace())),F(this,"hexToColor4",((e,t=1)=>{const i=l.FromHexString(e);return new h(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()}}}var D={};R(D,"RenderingConfiguration",(()=>k)),R(D,"REFLECTION_PROBE_RESOLUTION",(()=>_));class k{static getDynamicTextureResolution(){return this.getIsMobile()||!k.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 _=128;function j(e,t,a){t.forEach((t=>{const s=t.getID(),n=t.getName(),o=k.getDynamicTextureResolution();e.materials.filter((e=>e.name===n)).forEach((r=>{const l=a.get(s);if(l)z(r,l),l.update(false);else{const l=function(e,t,a,s){const n=new c(e,{width:a,height:s},t,k.shouldMipMap(),b.TRILINEAR_SAMPLINGMODE,i.TEXTUREFORMAT_RGBA),o=n.getContext();o&&(o.fillStyle="#f5f5f5",o.fillRect(0,0,a,s),n.update());return n}(n,e,o.width,o.height);a.set(s,l),t.setStaticContext(l.getContext()),z(r,l),l.onLoadObservable.addOnce((()=>{l.update(false)}))}}))}))}function z(e,t){if(e instanceof o){const i=e,a=i.albedoTexture;a?(t.wrapU=a.wrapU,t.wrapV=a.wrapV):(t.wrapU=1,t.wrapV=1),i.albedoTexture=t}else{const i=e,a=i.diffuseTexture;a&&(t.wrapU=a.wrapU,t.wrapV=a.wrapV),i.diffuseTexture=t}}function V(e,t,i,a){const s=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?s.forEach((e=>{e.stop();const s=n(e);e.start(t,1,a*s,i*s)})):s.forEach((e=>{e.stop();const i=n(e),s=a*i;e.start(t,1,s,s)}))}function H(e){e.animationGroups.forEach((e=>{e.stop()}))}function U(e,t,i){var a,s,n;e.stopAnimation(t),t.animations=[],Math.abs(t.alpha)>2*Math.PI&&(t.alpha=(a=t.alpha,s=0,n=2*Math.PI,a<s?n-(s-a)%(n-s):s+(a-s)%(n-s)));const o=[],r=i.target,c=r?1:0;if(i.target&&o.push(K("cameraTargetLerp","target",(new m).copyFrom(t.target),new m(i.target.x,i.target.y,i.target.z),v.ANIMATIONTYPE_VECTOR3,0)),o.push(K("cameraAlphaLerp","alpha",t.alpha,W(i.lonDeg),v.ANIMATIONTYPE_FLOAT,c)),o.push(K("cameraBetaLerp","beta",t.beta,W(i.latDeg),v.ANIMATIONTYPE_FLOAT,c)),void 0!==i.radius){const e=Math.max(.01,i.radius);o.push(K("cameraRadiusLerp","radius",t.radius,e,v.ANIMATIONTYPE_FLOAT,c))}t.animations.push(...o);const l=t.useAutoRotationBehavior;t.disableAutoRotationBehavior(),e.beginAnimation(t,0,r?120:60,!1,1,(()=>{t.animations=[],l&&t.enableAutoRotationBehavior()}))}function W(e){return e*Math.PI/180}function K(e,t,i,a,s,n=0,o=v.ANIMATIONLOOPMODE_CONSTANT){const r=new w;r.setEasingMode(y.EASINGMODE_EASEINOUT);const c=new v(e,t,60,s,o),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(r),c}class q extends M{constructor(e,t,i,a,s,n,o,r){var c,l,h;super(e,t,i,a,s,n,r),c=this,l="lastFocus",h=new m(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=G(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=G(this._scene);t.zoomOnBoundingInfo(i.min,i.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 i=G(e),a=i.max.subtract(i.min),s=i.min.add(a.scale(.5)),n=new q("ProductCamera",-Math.PI/2,Math.PI/2,1.5*a.length(),s,e,t);return n.panningInertia=0,n.panningOriginTarget.copyFrom(s),n.onAfterCheckInputsObservable.add((()=>{n.panningSensibility=1e3/a.length()})),e.activeCamera=n,n}}function G(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 X={albedoTexture:"albedoMapKey",bumpTexture:"normalMapKey",ambientTexture:"ambientMapKey",emissiveTexture:"emissionMapKey",opacityTexture:"alphaMapKey",metallicTexture:"metallicMapKey",refractionTexture:"refractionMapKey"};function Z(e,t,i,a){["albedoTexture","bumpTexture","ambientTexture","emissiveTexture","opacityTexture","metallicTexture","refractionTexture"].forEach((s=>{!function(e,t,i,a,s){const n=X[e];if(!n)throw new Error("Unexpected texture name encountered.");const o=t[n];o?a.addTextureTask(e,o,!1,!1):s&&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))}(s,e,t,i,a)})),function(e,t){if(!e.clearCoat)return;e.clearCoat===E.RemoveWhenSelected?(t.clearCoat.isEnabled=!1,t.clearCoat.indexOfRefraction=1.5):e.clearCoat===E.ApplyWhenSelected&&(t.clearCoat.isEnabled=!0,t.clearCoat.indexOfRefraction=e.clearCoatIOR||t.clearCoat.indexOfRefraction)}(e,t)}function Y(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 Q(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class ${constructor(){Q(this,"materialVariantMap",new Map),Q(this,"keysThatRemovedBaseModel",[]),Q(this,"loadedContainerForKey",new Map)}async applyMaterial(e,t,i,a,s){return new Promise((n=>{const o=e.materials.filter((e=>e.name===t)),r=this.materialVariantMap.get(t);if(this.materialVariantMap.set(t,{...r,...i}),0===o.length)return void n(void 0);const c=new T(e);c.useDefaultLoadingScreen=!1,o.forEach((e=>Z(i,e,c,s))),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),o.forEach((a=>Y(e.name,a,i,t.texture)))})),n(void 0)},c.loadAsync()}))}async applyModel(e,t,i,a,s){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 ie(e.metadata.baseModel,e),Promise.resolve()}const n=await B(a,e,s);if(this.loadedContainerForKey.has(t)&&this.loadedContainerForKey.get(t)?.removeAllFromScene(),i){(await B(e.metadata.baseModel,e)).removeAllFromScene()}n.addAllToScene(),this.loadedContainerForKey.set(t,n);const o=[];this.materialVariantMap.forEach((async(t,i)=>{o.push(this.applyMaterial(e,i,t))})),await Promise.all(o)}}var J=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(C.Name,"latest",{disablePermanentHitTest:!0,enableTransientHitTest:!0,useReferenceSpace:!0});let s=null;a.onHitTestResultObservable.add((e=>{s=e.length?e[0]:void 0})),t.onPointerDown=()=>{if(s&&i.baseExperience.state===L.IN_XR){const e=t.getNodeByName("__root__");s.transformationMatrix.decompose(void 0,e.rotationQuaternion,e.position)}}};function ee(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class te{constructor(e,t){ee(this,"engine",void 0),ee(this,"scene",void 0),ee(this,"configuration",void 0),ee(this,"loadProgress",new Map([["initialScene",0]])),ee(this,"materialReadyToLoadCallbacks",new Map),ee(this,"modelReadyToLoadCallbacks",new Map),ee(this,"queuedModelAnimation",void 0),ee(this,"queuedCameraAnimation",void 0),ee(this,"focusLostNotified",!1),ee(this,"loadObservable",new d),ee(this,"focusLostObservable",new d),ee(this,"dynamicTextures",new Map),ee(this,"highlightLayer",void 0),ee(this,"variantManager",new $),this.configuration=new N(t);u.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 s=console.log;console.log=()=>{};const n=e?new i(e,!0,{premultipliedAlpha:!1,preserveDrawingBuffer:!!t?.backgroundImage,audioEngine:!1,stencil:this.configuration.highlights.enabled,forceSRGBBufferSupportState:!0}):new a;console.log=s,n.hideLoadingUI(),window.addEventListener("resize",this.fireResizeEvent.bind(this)),this.engine=n,this.scene=new p(n)}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(A.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(i,a){if(this.scene.clearColor=this.configuration.scene.clearColor,this.scene.metadata={baseModel:i},this.scene.environmentTexture=r.CreateFromPrefilteredData(this.configuration.scene.environmentFile,this.scene),i){const e=99;await ie(i,this.scene,(t=>{this.loadProgress.set("initialScene",t.loaded*e/t.total),this.notifyLoadHandlers()}))}this.configuration.highlights.enabled&&this.scene.meshes.forEach((i=>{"targetcube_t"!==i.name&&"backgroundShell"!==i.name&&(i.isPickable=!0,i.actionManager||(i.actionManager=new e(this.scene)),i.actionManager.registerAction(new t(e.OnPointerOutTrigger,(()=>{this.setHighlights([])}))),i.actionManager.registerAction(new t(e.OnPointerOverTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&this.setHighlights([t])}}))))}));const n=q.create(this.scene,this.configuration),o=a?.getAll()||new Map;j(this.scene,o,this.dynamicTextures);if(this.scene.materials.some((e=>"emissiveTexture"in e&&null!==e.emissiveTexture))){new s("GlowLayer",this.scene).intensity=.5}H(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),o.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()),n.target.equalsWithEpsilon(n.lastFocus,.1)||this.focusLostNotified||(this.focusLostObservable.notifyObservers(void 0),this.focusLostNotified=!0)}))}executeModelAnimation(e){100===this.getSceneInitializationProgress()?V(this.scene,e.loop,e.to,e.from):this.queuedModelAnimation=e}executeCameraAnimation(e){100===this.getSceneInitializationProgress()&&this.scene.activeCamera?U(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 m(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,t,i){100===this.getSceneInitializationProgress()?(await this.variantManager.applyModel(this.scene,e,i||!1,t.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 t=e instanceof o&&!(e.albedoTexture instanceof c);e.dispose(!1,t)}})),j(this.scene,t.contextService.getAll(),this.dynamicTextures),H(this.scene)):this.modelReadyToLoadCallbacks.set(e,(()=>{this.applyModelVariant(e,t,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===A.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 s=i.alpha,n=i.beta,o=i.radius,r=t.latDeg*Math.PI/180,c=t.lonDeg*Math.PI/180;i.alpha=c,i.beta=r,i.radius=t.radius||i.radius;const l=await g.CreateScreenshotUsingRenderTargetAsync(this.engine,i,e,"image/png",2,!0);return i.alpha=s,i.beta=n,i.radius=o,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,s=e.camera.limits.max.beta;if(void 0===t||void 0===i||void 0===a||void 0===s)return!0;const n=[a,s],o=[t,i].every((e=>e===t)),r=n.every((e=>e===a));return!o&&!r}fireResizeEvent(){this.getNumViewports()>0&&this.engine.resize()}onMaterialSelected(i){this.scene.meshes.forEach((a=>{"targetcube_t"!==a.name&&"backgroundShell"!==a.name&&(a.actionManager||(a.actionManager=new e(this.scene)),a.actionManager.registerAction(new t(e.OnPickDownTrigger,(e=>{if(e.meshUnderPointer){const t=e.meshUnderPointer.material;t&&i({id:t.id,name:t.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 n("highlights",this.scene,{isStroke:!0,blurVerticalSize:.85,blurHorizontalSize:.85}),this.highlightLayer.innerGlow=!0,this.highlightLayer.outerGlow=!1),this.highlightLayer.removeAllMeshes();const i=t?new l(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||l.FromHexString("#fcba03"))))}))}initXRExperience(e){J(0,this.scene)}reattachControls(e,t=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 ie(e,t,i){(await B(e,t,i)).addAllToScene()}export{A as ProductCameraRig,E as MaterialEffectMode,te as SpiffCommerce3DPreviewService,ie as createBaseModel,k as RenderingConfiguration,_ as REFLECTION_PROBE_RESOLUTION};
2
2
  //# sourceMappingURL=module.js.map