UNPKG

@babylonjs/viewer

Version:

The Babylon Viewer aims to simplify a specific but common Babylon.js use case: loading, viewing, and interacting with a 3D model.

3 lines (2 loc) 31.2 kB
import{a as t,A as e,ao as n,aZ as i,V as o,M as s,bR as a,O as r,y as l,bb as u,ba as d,aY as c,aQ as h,bo as p,bp as _}from"./index-BPURObVq.esm.min.js";import{_ as m,d as f}from"./spatialWebAudio-Cxs0XdBX.esm.min.js";import{_WebAudioSoundSource as g}from"./webAudioSoundSource-CbegW_An.esm.min.js";import{_WebAudioStaticSound as A}from"./webAudioStaticSound-MIX2pABC.esm.min.js";import{_WebAudioStreamingSound as y}from"./webAudioStreamingSound-G95NHMdc.esm.min.js";import{A as T,b as C}from"./glTFLoader.pure-Bdyl6AcK.esm.min.js";import"./webAudioBaseSubGraph-Ww7puCo8.esm.min.js";import"./spatialWebAudioUpdaterComponent-LOlF6N8J.esm.min.js";import"./abstractSoundSource-C5k4Xume.esm.min.js";import"./abstractSoundInstance-CT5dRXOE.esm.min.js";import"./morphTargetManager-CdEb1BHc.esm.min.js";import"./bone.pure-BcPT5kCP.esm.min.js";import"./skeleton-DinTjF3y.esm.min.js";import"./assetContainer-CAncviZo.esm.min.js";import"./objectModelMapping-ClgDmo5Q.esm.min.js";import"./spotLight.pure-5s2DDDIt.esm.min.js";class b{constructor(t,e,n){this.frame=t,this.action=e,this.onlyOnce=n,this.isDone=!1}_clone(){return new b(this.frame,this.action,this.onlyOnce)}}class V{constructor(e,n={}){this.id=-1,this._isInitialized=!1,(e=e||t.LastCreatedScene)&&(this._scene=e,this.soundCollection=[],this._options=n,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){e.audioEngine?.canUseWebAudio&&e.audioEngine.audioContext&&(this._outputAudioNode=e.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(e.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(e.audioEngine&&e.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(t){this._isInitialized||this._initializeSoundTrackAudioGraph(),e.audioEngine?.canUseWebAudio&&this._outputAudioNode&&t.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==t.soundTrackId&&(-1===t.soundTrackId?this._scene.mainSoundTrack.removeSound(t):this._scene.soundTracks&&this._scene.soundTracks[t.soundTrackId].removeSound(t)),this.soundCollection.push(t),t.soundTrackId=this.id}removeSound(t){const e=this.soundCollection.indexOf(t);-1!==e&&this.soundCollection.splice(e,1)}setVolume(t){e.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=t)}switchPanningModelToHRTF(){if(e.audioEngine?.canUseWebAudio)for(let t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToHRTF()}switchPanningModelToEqualPower(){if(e.audioEngine?.canUseWebAudio)for(let t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToEqualPower()}connectToAnalyser(t){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=t,e.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,e.audioEngine.masterGain))}}class P{get audioEnabled(){return this._audioEnabled}get headphone(){return this._headphone}constructor(e){this.name=i.NAME_AUDIO,this._audioEnabled=!0,this._headphone=!1,this.audioPositioningRefreshRate=500,this.audioListenerPositionProvider=null,this.audioListenerRotationProvider=null,this._cachedCameraDirection=new o,this._cachedCameraPosition=new o,this._lastCheck=0,this._invertMatrixTemp=new s,this._cameraDirectionTemp=new o,(e=e||t.LastCreatedScene)&&(this.scene=e,e.soundTracks=[],e.sounds=[])}register(){this.scene._afterRenderStage.registerStep(i.STEP_AFTERRENDER_AUDIO,this,this._afterRender)}rebuild(){}serialize(t){if(t.sounds=[],this.scene.soundTracks)for(let e=0;e<this.scene.soundTracks.length;e++){const n=this.scene.soundTracks[e];for(let e=0;e<n.soundCollection.length;e++)t.sounds.push(n.soundCollection[e].serialize())}}addFromContainer(t){if(t.sounds)for(const e of t.sounds)e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}removeFromContainer(t,e=!1){if(t.sounds)for(const n of t.sounds)n.stop(),n.autoplay=!1,this.scene.mainSoundTrack.removeSound(n),e&&n.dispose()}dispose(){const t=this.scene;if(t._mainSoundTrack&&t.mainSoundTrack.dispose(),t.soundTracks)for(let e=0;e<t.soundTracks.length;e++)t.soundTracks[e].dispose()}disableAudio(){const t=this.scene;let n;for(this._audioEnabled=!1,e.audioEngine&&e.audioEngine.audioContext&&e.audioEngine.audioContext.suspend(),n=0;n<t.mainSoundTrack.soundCollection.length;n++)t.mainSoundTrack.soundCollection[n].pause();if(t.soundTracks)for(n=0;n<t.soundTracks.length;n++)for(let e=0;e<t.soundTracks[n].soundCollection.length;e++)t.soundTracks[n].soundCollection[e].pause()}enableAudio(){const t=this.scene;let n;for(this._audioEnabled=!0,e.audioEngine&&e.audioEngine.audioContext&&e.audioEngine.audioContext.resume(),n=0;n<t.mainSoundTrack.soundCollection.length;n++)t.mainSoundTrack.soundCollection[n].isPaused&&t.mainSoundTrack.soundCollection[n].play();if(t.soundTracks)for(n=0;n<t.soundTracks.length;n++)for(let e=0;e<t.soundTracks[n].soundCollection.length;e++)t.soundTracks[n].soundCollection[e].isPaused&&t.soundTracks[n].soundCollection[e].play()}switchAudioModeForHeadphones(){const t=this.scene;if(this._headphone=!0,t.mainSoundTrack.switchPanningModelToHRTF(),t.soundTracks)for(let e=0;e<t.soundTracks.length;e++)t.soundTracks[e].switchPanningModelToHRTF()}switchAudioModeForNormalSpeakers(){const t=this.scene;if(this._headphone=!1,t.mainSoundTrack.switchPanningModelToEqualPower(),t.soundTracks)for(let e=0;e<t.soundTracks.length;e++)t.soundTracks[e].switchPanningModelToEqualPower()}_afterRender(){const t=a.Now;if(this._lastCheck&&t-this._lastCheck<this.audioPositioningRefreshRate)return;this._lastCheck=t;const n=this.scene;if(!this._audioEnabled||!n._mainSoundTrack||!n.soundTracks||0===n._mainSoundTrack.soundCollection.length&&1===n.soundTracks.length)return;const i=e.audioEngine;if(i&&i.audioContext){let t,e=n.activeCamera;if(n.activeCameras&&n.activeCameras.length>0&&(e=n.activeCameras[0]),this.audioListenerPositionProvider){const t=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(t.x||0,t.y||0,t.z||0)}else e?this._cachedCameraPosition.equals(e.globalPosition)||(this._cachedCameraPosition.copyFrom(e.globalPosition),i.audioContext.listener.setPosition(e.globalPosition.x,e.globalPosition.y,e.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const t=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(t.x||0,t.y||0,t.z||0,0,1,0)}else e?(e.rigCameras&&e.rigCameras.length>0&&(e=e.rigCameras[0]),e.getViewMatrix().invertToRef(this._invertMatrixTemp),o.TransformNormalToRef(P._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(t=0;t<n.mainSoundTrack.soundCollection.length;t++){const e=n.mainSoundTrack.soundCollection[t];e.useCustomAttenuation&&e.updateDistanceFromListener()}if(n.soundTracks)for(t=0;t<n.soundTracks.length;t++)for(let e=0;e<n.soundTracks[t].soundCollection.length;e++){const i=n.soundTracks[t].soundCollection[e];i.useCustomAttenuation&&i.updateDistanceFromListener()}}}}P._CameraDirection=new o(0,0,-1);let D=!1;function S(t){D||(D=!0,Object.defineProperty(n.prototype,"mainSoundTrack",{get:function(){let t=this._getComponent(i.NAME_AUDIO);return t||(t=new P(this),this._addComponent(t)),this._mainSoundTrack||(this._mainSoundTrack=new V(this,{mainTrack:!0})),this._mainSoundTrack},enumerable:!0,configurable:!0}),n.prototype.getSoundByName=function(t){let e;for(e=0;e<this.mainSoundTrack.soundCollection.length;e++)if(this.mainSoundTrack.soundCollection[e].name===t)return this.mainSoundTrack.soundCollection[e];if(this.soundTracks)for(let n=0;n<this.soundTracks.length;n++)for(e=0;e<this.soundTracks[n].soundCollection.length;e++)if(this.soundTracks[n].soundCollection[e].name===t)return this.soundTracks[n].soundCollection[e];return null},Object.defineProperty(n.prototype,"audioEnabled",{get:function(){let t=this._getComponent(i.NAME_AUDIO);return t||(t=new P(this),this._addComponent(t)),t.audioEnabled},set:function(t){let e=this._getComponent(i.NAME_AUDIO);e||(e=new P(this),this._addComponent(e)),t?e.enableAudio():e.disableAudio()},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"headphone",{get:function(){let t=this._getComponent(i.NAME_AUDIO);return t||(t=new P(this),this._addComponent(t)),t.headphone},set:function(t){let e=this._getComponent(i.NAME_AUDIO);e||(e=new P(this),this._addComponent(e)),t?e.switchAudioModeForHeadphones():e.switchAudioModeForNormalSpeakers()},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"audioListenerPositionProvider",{get:function(){let t=this._getComponent(i.NAME_AUDIO);return t||(t=new P(this),this._addComponent(t)),t.audioListenerPositionProvider},set:function(t){let e=this._getComponent(i.NAME_AUDIO);if(e||(e=new P(this),this._addComponent(e)),t&&"function"!=typeof t)throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");e.audioListenerPositionProvider=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"audioListenerRotationProvider",{get:function(){let t=this._getComponent(i.NAME_AUDIO);return t||(t=new P(this),this._addComponent(t)),t.audioListenerRotationProvider},set:function(t){let e=this._getComponent(i.NAME_AUDIO);if(e||(e=new P(this),this._addComponent(e)),t&&"function"!=typeof t)throw new Error("The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3");e.audioListenerRotationProvider=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"audioPositioningRefreshRate",{get:function(){let t=this._getComponent(i.NAME_AUDIO);return t||(t=new P(this),this._addComponent(t)),t.audioPositioningRefreshRate},set:function(t){let e=this._getComponent(i.NAME_AUDIO);e||(e=new P(this),this._addComponent(e)),e.audioPositioningRefreshRate=t},enumerable:!0,configurable:!0}),t._SceneComponentInitialization=t=>{let e=t._getComponent(i.NAME_AUDIO);e||(e=new P(t),t._addComponent(e))})}const v={duration:0,shape:"linear"},M={duration:0,startOffset:0,waitTime:0},k={waitTime:0};function w(t){return t*Math.PI/180}function E(t){return 180*t/Math.PI}class O{get name(){return this._soundV2.name}set name(t){this._soundV2.name=t}get autoplay(){return this._soundV2 instanceof g||this._optionsV2.autoplay}set autoplay(t){this._optionsV2.autoplay=t}get loop(){return this._soundV2 instanceof g||this._soundV2.loop}set loop(t){this._soundV2 instanceof g||this._soundV2&&(this._soundV2.loop=t)}get isPlaying(){return this._soundV2 instanceof g||(3===this._soundV2?.state||!this.isReady()&&this._optionsV2.autoplay)}get isPaused(){return!(this._soundV2 instanceof g)&&5===this._soundV2.state}get maxDistance(){return this._optionsV2.spatialMaxDistance||100}set maxDistance(t){this._optionsV2.spatialMaxDistance=t,this.useCustomAttenuation||this._soundV2&&(this._initSpatial(),this._soundV2.spatial.maxDistance=t)}get distanceModel(){return this._optionsV2.spatialDistanceModel||"linear"}set distanceModel(t){this._optionsV2.spatialDistanceModel=t,this._soundV2&&(this._initSpatial(),this._soundV2.spatial.distanceModel=t)}get currentTime(){return this._soundV2 instanceof g?this._soundV2.engine.currentTime:this._soundV2.currentTime}get spatialSound(){return this._soundV2?._isSpatial??!1}set spatialSound(t){this._soundV2&&(t?this._initSpatial():this._soundV2._isSpatial=!1)}get _onReady(){return this._onReadyObservable||(this._onReadyObservable=new r),this._onReadyObservable}constructor(n,i,s,a=null,u){if(this.useCustomAttenuation=!1,this.soundTrackId=-1,this.refDistance=1,this.rolloffFactor=1,this.metadata=null,this.onEndedObservable=new r,this._localDirection=new o(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._isOutputConnected=!1,this._url=null,this._onReadyObservable=null,this._onReadyToPlay=()=>{this._scene.mainSoundTrack.addSound(this),this._isReadyToPlay=!0,this._readyToPlayCallback(),this._onReadyObservable&&this._onReadyObservable.notifyObservers(),this._optionsV2.autoplay&&this.play()},this._onended=()=>{this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)},!(s=s||t.LastCreatedScene))return;this._scene=s,S(O),O._SceneComponentInitialization(s),this._readyToPlayCallback=a||(()=>{}),this._customAttenuationFunction=(t,e,n,i,o)=>e<n?t*(1-e/n):0;const d={analyzerEnabled:!1,autoplay:!1,duration:(u=u||{}).length||0,loop:u.loop||!1,loopEnd:0,loopStart:0,outBus:null,outBusAutoDefault:!1,playbackRate:u.playbackRate||1,pitch:0,skipCodecCheck:u.skipCodecCheck||!1,spatialDistanceModel:u.distanceModel,spatialEnabled:u.spatialSound,spatialMaxDistance:u.maxDistance,spatialMinDistance:u.refDistance,spatialRolloffFactor:u.rolloffFactor,stereoEnabled:!1,startOffset:u.offset||0,volume:u.volume??1};this._volume=u.volume??1,m(d)&&(d.spatialAutoUpdate=!1,d.spatialConeInnerAngle=f.coneInnerAngle,d.spatialConeOuterAngle=f.coneOuterAngle,d.spatialConeOuterVolume=f.coneOuterVolume,d.spatialMinUpdateTime=0,d.spatialOrientation=f.orientation.clone(),d.spatialPanningModel=this._scene.headphone?"HRTF":"equalpower",d.spatialPosition=f.position.clone(),d.spatialRotation=f.rotation.clone(),d.spatialRotationQuaternion=f.rotationQuaternion.clone(),void 0===d.spatialMaxDistance&&(d.spatialMaxDistance=100)),this._optionsV2={...d},this._optionsV2.autoplay=u.autoplay||!1,this.useCustomAttenuation=u.useCustomAttenuation??!1,this.useCustomAttenuation&&(d.spatialMaxDistance=Number.MAX_VALUE,d.volume=0);let c=u?.streaming||!1;if(!e.audioEngine)return;const h=e.audioEngine._v2,p=()=>{if(c){const t={preloadCount:0,...d},e=new y(n,h,t);return e._initAsync(i,d).then(()=>{e.preloadInstancesAsync(1).then(this._onReadyToPlay)}),e}{const t=new A(n,h,d);return t._initAsync(i,d).then(this._onReadyToPlay),t}};if(i)if("string"==typeof i)this._url=i,this._soundV2=p();else if(i instanceof ArrayBuffer)c=!1,this._soundV2=p();else if(i instanceof HTMLMediaElement)c=!0,this._soundV2=p();else if(i instanceof MediaStream){const t=new MediaStreamAudioSourceNode(h._audioContext,{mediaStream:i});this._soundV2=new g(n,t,h,d),this._soundV2._initAsync(d).then(this._onReadyToPlay)}else i instanceof AudioBuffer?(c=!1,this._soundV2=p()):Array.isArray(i)&&(this._soundV2=p());else this._soundV2=new A(n,h,d);this._soundV2?this._soundV2 instanceof g||this._soundV2.onEndedObservable.add(this._onended):l.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}dispose(){this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._soundV2.dispose()}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}setAudioBuffer(t){this._isReadyToPlay||this._soundV2 instanceof A&&this._soundV2._initAsync(t,this._optionsV2).then(this._onReadyToPlay)}updateOptions(t){if(t){if(this.loop=t.loop??this.loop,this.maxDistance=t.maxDistance??this.maxDistance,this.useCustomAttenuation=t.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=t.rolloffFactor??this.rolloffFactor,this.refDistance=t.refDistance??this.refDistance,this.distanceModel=t.distanceModel??this.distanceModel,void 0!==t.playbackRate&&this.setPlaybackRate(t.playbackRate),void 0!==t.spatialSound&&(this.spatialSound=t.spatialSound),void 0!==t.volume&&this.setVolume(t.volume),this._soundV2 instanceof A){let e=!1;void 0!==t.offset&&(this._optionsV2.startOffset=t.offset,e=!0),void 0!==t.length&&(this._soundV2.duration=t.length,e=!0),e&&this.isPaused&&this.stop()}this._updateSpatialParameters()}}_updateSpatialParameters(){if(!this.spatialSound)return;const t=this._soundV2.spatial;this.useCustomAttenuation?(t.distanceModel="linear",t.minDistance=1,t.maxDistance=Number.MAX_VALUE,t.rolloffFactor=1,t.panningModel="equalpower"):(t.distanceModel=this.distanceModel,t.minDistance=this.refDistance,t.maxDistance=this.maxDistance,t.rolloffFactor=this.rolloffFactor,t.panningModel=this._optionsV2.spatialPanningModel||"equalpower")}switchPanningModelToHRTF(){this.spatialSound&&(this._initSpatial(),this._soundV2.spatial.panningModel="HRTF")}switchPanningModelToEqualPower(){this.spatialSound&&(this._initSpatial(),this._soundV2.spatial.panningModel="equalpower")}connectToSoundTrackAudioNode(t){const e=this._soundV2._outNode;e&&(this._isOutputConnected&&e.disconnect(),e.connect(t),this._isOutputConnected=!0)}setDirectionalCone(t,e,n){e<t?l.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."):(this._optionsV2.spatialConeInnerAngle=w(t),this._optionsV2.spatialConeOuterAngle=w(e),this._optionsV2.spatialConeOuterVolume=n,this._initSpatial(),this._soundV2.spatial.coneInnerAngle=this._optionsV2.spatialConeInnerAngle,this._soundV2.spatial.coneOuterAngle=this._optionsV2.spatialConeOuterAngle,this._soundV2.spatial.coneOuterVolume=n,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._optionsV2.startOffset,this._optionsV2.duration)))}get directionalConeInnerAngle(){return E("number"==typeof this._optionsV2.spatialConeInnerAngle?this._optionsV2.spatialConeInnerAngle:f.coneInnerAngle)}set directionalConeInnerAngle(t){if((t=w(t))!=this._optionsV2.spatialConeInnerAngle){if(this.directionalConeOuterAngle<t)return void l.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._optionsV2.spatialConeInnerAngle=t,this.spatialSound&&(this._initSpatial(),this._soundV2.spatial.coneInnerAngle=t)}}get directionalConeOuterAngle(){return E("number"==typeof this._optionsV2.spatialConeOuterAngle?this._optionsV2.spatialConeOuterAngle:f.coneOuterAngle)}set directionalConeOuterAngle(t){if((t=w(t))!=this._optionsV2.spatialConeOuterAngle){if(t<this.directionalConeInnerAngle)return void l.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._optionsV2.spatialConeOuterAngle=t,this.spatialSound&&(this._initSpatial(),this._soundV2.spatial.coneOuterAngle=t)}}setPosition(t){this._optionsV2.spatialPosition&&t.equals(this._optionsV2.spatialPosition)||(this._optionsV2.spatialPosition||(this._optionsV2.spatialPosition=o.Zero()),this._optionsV2.spatialPosition.copyFrom(t),!this.spatialSound||isNaN(t.x)||isNaN(t.y)||isNaN(t.z)||(this._initSpatial(),this._soundV2.spatial.position=t))}setLocalDirectionToMesh(t){this._localDirection=t,this._connectedTransformNode&&this.isPlaying&&this._updateDirection()}_updateDirection(){if(!this._connectedTransformNode||!this.spatialSound)return;const t=this._connectedTransformNode.getWorldMatrix(),e=o.TransformNormal(this._localDirection,t);e.normalize(),this._initSpatial(),this._soundV2.spatial.orientation=e}_initSpatial(){this._soundV2._isSpatial=!0,void 0===this._optionsV2.spatialDistanceModel&&(this._optionsV2.spatialDistanceModel="linear",this._soundV2.spatial.distanceModel="linear"),void 0===this._optionsV2.spatialMaxDistance&&(this._optionsV2.spatialMaxDistance=100,this._soundV2.spatial.maxDistance=100)}updateDistanceFromListener(){if(this._soundV2._outNode&&this._connectedTransformNode&&this.useCustomAttenuation&&this._scene.activeCamera){const t=this._scene.audioListenerPositionProvider?this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length():this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundV2.volume=this._customAttenuationFunction(this._volume,t,this.maxDistance,this.refDistance,this.rolloffFactor)}}setAttenuationFunction(t){this._customAttenuationFunction=t}play(t,n,i){const o=e.audioEngine;if(o?.unlock(),!(this._soundV2 instanceof g)&&this._isReadyToPlay&&this._scene.audioEnabled){5!==this._soundV2.state||void 0===t&&void 0===n&&void 0===i||this._soundV2.stop();try{M.duration=i||0,M.startOffset=void 0!==n&&n||this._optionsV2.startOffset,M.waitTime=t||0,M.loop=void 0,M.loopStart=void 0,M.loopEnd=void 0,M.volume=void 0,o?.unlocked?this._soundV2.play(M):setTimeout(()=>{this._soundV2.play(M)},500)}catch(t){l.Error("Error while trying to play audio: "+this.name+", "+t.message)}}}stop(t){this._soundV2&&(this._soundV2 instanceof g||(k.waitTime=t||0,this._soundV2.stop(k)))}pause(){this._soundV2&&(this._soundV2 instanceof g||this._soundV2.pause())}setVolume(t,e){this.isReady()?(v.duration=e||0,this._soundV2.setVolume(t,v),this._volume=t):this._onReady.addOnce(()=>{this.setVolume(t,e)})}setPlaybackRate(t){this._soundV2 instanceof A&&(this._soundV2.playbackRate=t)}getPlaybackRate(){return this._soundV2 instanceof A?this._soundV2.playbackRate:1}getVolume(){return this._volume}attachToMesh(t){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=t,this.spatialSound||(this.spatialSound=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._optionsV2.startOffset,this._optionsV2.duration))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=t=>this._onRegisterAfterWorldMatrixUpdate(t),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(t){if(t.getBoundingInfo){const e=t.getBoundingInfo();this.setPosition(e.boundingSphere.centerWorld)}else this.setPosition(t.absolutePosition);this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(!(this._soundV2 instanceof A))return null;const t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},e=new O(this.name+"_cloned",this._soundV2.buffer,this._scene,null,t);return e._optionsV2=this._optionsV2,this.useCustomAttenuation&&e.setAttenuationFunction(this._customAttenuationFunction),e}getAudioBuffer(){return this._soundV2 instanceof A?this._soundV2.buffer._audioBuffer:null}getSoundSource(){return null}getSoundGain(){return this._soundV2._outNode}serialize(){const t={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this.getPlaybackRate(),panningModel:this._soundV2.spatial.panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this.spatialSound&&(this._connectedTransformNode&&(t.connectedMeshId=this._connectedTransformNode.id),t.position=this._soundV2.spatial.position.asArray(),t.refDistance=this.refDistance,t.distanceModel=this.distanceModel,t.isDirectional=this._isDirectional,t.localDirectionToMesh=this._localDirection.asArray(),t.coneInnerAngle=this.directionalConeInnerAngle,t.coneOuterAngle=this.directionalConeOuterAngle,t.coneOuterGain=this._soundV2.spatial.coneOuterVolume),t}static Parse(t,e,n,i){const s=t.name;let a;a=t.url?n+t.url:n+s;const r={autoplay:t.autoplay,loop:t.loop,volume:t.volume,spatialSound:t.spatialSound,maxDistance:t.maxDistance,rolloffFactor:t.rolloffFactor,refDistance:t.refDistance,distanceModel:t.distanceModel,playbackRate:t.playbackRate};let l;if(i){const t=()=>{u(()=>i._isReadyToPlay,()=>{const t=i.getAudioBuffer();t&&l.setAudioBuffer(t),l._isReadyToPlay=!0,l.autoplay&&l.play(0,i._optionsV2.startOffset,i._optionsV2.duration)},void 0,300)};l=new O(s,new ArrayBuffer(0),e,null,r),t()}else l=new O(s,a,e,()=>{e.removePendingData(l)},r),e.addPendingData(l);if(t.position){const e=o.FromArray(t.position);l.setPosition(e)}if(t.isDirectional&&(l.setDirectionalCone(t.coneInnerAngle||360,t.coneOuterAngle||360,t.coneOuterGain||0),t.localDirectionToMesh)){const e=o.FromArray(t.localDirectionToMesh);l.setLocalDirectionToMesh(e)}if(t.connectedMeshId){const n=e.getMeshById(t.connectedMeshId);n&&l.attachToMesh(n)}return t.metadata&&(l.metadata=t.metadata),l}}O._SceneComponentInitialization=t=>{throw d("AudioSceneComponent")};class x{constructor(t,e,n){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],e.length!==n.length)throw new Error("Sounds length does not equal weights length");this.loop=t,this._weights=n;let i=0;for(const t of n)i+=t;const o=i>0?1/i:0;for(let t=0;t<this._weights.length;t++)this._weights[t]*=o;this._sounds=e;for(const t of this._sounds)t.onEndedObservable.add(()=>{this._onended()})}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(t){if(t!==this._coneInnerAngle){if(this._coneOuterAngle<t)return void l.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=t;for(const e of this._sounds)e.directionalConeInnerAngle=t}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(t){if(t!==this._coneOuterAngle){if(t<this._coneInnerAngle)return void l.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=t;for(const e of this._sounds)e.directionalConeOuterAngle=t}}get volume(){return this._volume}set volume(t){if(t!==this._volume)for(const e of this._sounds)e.setVolume(t)}_onended(){void 0!==this._currentIndex&&(this._sounds[this._currentIndex].autoplay=!1),this.loop&&this.isPlaying?this.play():this.isPlaying=!1}pause(){this.isPlaying&&(this.isPaused=!0,void 0!==this._currentIndex&&this._sounds[this._currentIndex].pause())}stop(){this.isPlaying=!1,void 0!==this._currentIndex&&this._sounds[this._currentIndex].stop()}play(t){if(!this.isPaused){this.stop();const t=Math.random();let e=0;for(let n=0;n<this._weights.length;n++)if(e+=this._weights[n],t<=e){this._currentIndex=n;break}}const e=this._sounds[this._currentIndex??0];e.isReady()?e.play(0,this.isPaused?void 0:t):e.autoplay=!0,this.isPlaying=!0,this.isPaused=!1}}const R="MSFT_audio_emitter";class I{constructor(t){this.name=R,this._loader=t,this.enabled=this._loader.isExtensionUsed(R)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const t=this._loader.gltf.extensions;if(t&&t[this.name]){const e=t[this.name];this._clips=e.clips,this._emitters=e.emitters,T.Assign(this._clips),T.Assign(this._emitters)}}loadSceneAsync(t,e){return C.LoadExtensionAsync(t,e,this.name,async(n,i)=>{const o=new Array;o.push(this._loader.loadSceneAsync(t,e));for(const t of i.emitters){const e=T.Get(`${n}/emitters`,this._emitters,t);if(null!=e.refDistance||null!=e.maxDistance||null!=e.rolloffFactor||null!=e.distanceModel||null!=e.innerAngle||null!=e.outerAngle)throw new Error(`${n}: Direction or Distance properties are not allowed on emitters attached to a scene`);o.push(this._loadEmitterAsync(`${n}/emitters/${e.index}`,e))}await Promise.all(o)})}loadNodeAsync(t,e,n){return C.LoadExtensionAsync(t,e,this.name,async(t,i)=>{const s=new Array,a=await this._loader.loadNodeAsync(t,e,e=>{for(const n of i.emitters){const i=T.Get(`${t}/emitters`,this._emitters,n);s.push(this._loadEmitterAsync(`${t}/emitters/${i.index}`,i).then(()=>{for(const t of i._babylonSounds)t.attachToMesh(e),null==i.innerAngle&&null==i.outerAngle||(t.setLocalDirectionToMesh(o.Forward()),t.setDirectionalCone(2*c.ToDegrees(null==i.innerAngle?Math.PI:i.innerAngle),2*c.ToDegrees(null==i.outerAngle?Math.PI:i.outerAngle),0))}))}n(e)});return await Promise.all(s),a})}loadAnimationAsync(t,e){return C.LoadExtensionAsync(t,e,this.name,async(n,i)=>{const o=await this._loader.loadAnimationAsync(t,e),s=new Array;T.Assign(i.events);for(const a of i.events)s.push(this._loadAnimationEventAsync(`${n}/events/${a.index}`,t,e,a,o));return await Promise.all(s),o})}_loadClipAsync(t,e){if(e._objectURL)return e._objectURL;let n;if(e.uri)n=this._loader.loadUriAsync(t,e,e.uri);else{const i=T.Get(`${t}/bufferView`,this._loader.gltf.bufferViews,e.bufferView);n=this._loader.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}return e._objectURL=n.then(t=>{const n=h(t);return URL.createObjectURL(new Blob([n],{type:e.mimeType}))}),e._objectURL}_loadEmitterAsync(t,e){if(e._babylonSounds=e._babylonSounds||[],!e._babylonData){const t=new Array,n=e.name||`emitter${e.index}`,i={loop:!1,autoplay:!1,volume:null==e.volume?1:e.volume};for(let o=0;o<e.clips.length;o++){const s=`/extensions/${this.name}/clips`,a=T.Get(s,this._clips,e.clips[o].clip);t.push(this._loadClipAsync(`${s}/${e.clips[o].clip}`,a).then(t=>{const s=e._babylonSounds[o]=new O(n,t,this._loader.babylonScene,null,i);s.refDistance=e.refDistance||1,s.maxDistance=e.maxDistance||256,s.rolloffFactor=e.rolloffFactor||1,s.distanceModel=e.distanceModel||"exponential"}))}const o=Promise.all(t).then(()=>{const t=e.clips.map(t=>t.weight||1),n=new x(e.loop||!1,e._babylonSounds,t);e.innerAngle&&(n.directionalConeInnerAngle=2*c.ToDegrees(e.innerAngle)),e.outerAngle&&(n.directionalConeOuterAngle=2*c.ToDegrees(e.outerAngle)),e.volume&&(n.volume=e.volume),e._babylonData.sound=n});e._babylonData={loaded:o}}return e._babylonData.loaded}_getEventAction(t,e,n,i,o){switch(n){case"play":return t=>{const n=(o||0)+(t-i);e.play(n)};case"stop":return()=>{e.stop()};case"pause":return()=>{e.pause()};default:throw new Error(`${t}: Unsupported action ${n}`)}}_loadAnimationEventAsync(t,e,n,i,o){if(0==o.targetedAnimations.length)return Promise.resolve();const s=o.targetedAnimations[0],a=i.emitter,r=T.Get(`/extensions/${this.name}/emitters`,this._emitters,a);return this._loadEmitterAsync(t,r).then(()=>{const e=r._babylonData.sound;if(e){const n=new b(i.time,this._getEventAction(t,e,i.action,i.time,i.startOffset));s.animation.addEvent(n),o.onAnimationGroupEndObservable.add(()=>{e.stop()}),o.onAnimationGroupPauseObservable.add(()=>{e.pause()})}})}}let N=!1;function F(){N||(N=!0,p(R),_(R,!0,t=>new I(t)))}S(O),F();export{I as MSFT_audio_emitter,F as RegisterMSFT_audio_emitter}; //# sourceMappingURL=MSFT_audio_emitter-fekfPLUc.esm.min.js.map