MSFT_audio_emitter.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import { Nullable } from "babylonjs/types";
  2. import { Vector3 } from "babylonjs/Maths/math";
  3. import { Tools } from "babylonjs/Misc/tools";
  4. import { AnimationGroup } from "babylonjs/Animations/animationGroup";
  5. import { AnimationEvent } from "babylonjs/Animations/animationEvent";
  6. import { TransformNode } from "babylonjs/Meshes/transformNode";
  7. import { Sound } from "babylonjs/Audio/sound";
  8. import { WeightedSound } from "babylonjs/Audio/weightedsound";
  9. import { IArrayItem, IScene, INode, IAnimation } from "../glTFLoaderInterfaces";
  10. import { IGLTFLoaderExtension } from "../glTFLoaderExtension";
  11. import { GLTFLoader, ArrayItem } from "../glTFLoader";
  12. import { IProperty } from 'babylonjs-gltf2interface';
  13. const NAME = "MSFT_audio_emitter";
  14. interface IClipReference {
  15. clip: number;
  16. weight?: number;
  17. }
  18. interface IEmittersReference {
  19. emitters: number[];
  20. }
  21. const enum DistanceModel {
  22. linear = "linear",
  23. inverse = "inverse",
  24. exponential = "exponential",
  25. }
  26. interface IEmitter {
  27. name?: string;
  28. distanceModel?: DistanceModel;
  29. refDistance?: number;
  30. maxDistance?: number;
  31. rolloffFactor?: number;
  32. innerAngle?: number;
  33. outerAngle?: number;
  34. loop?: boolean;
  35. volume?: number;
  36. clips: IClipReference[];
  37. }
  38. const enum AudioMimeType {
  39. WAV = "audio/wav",
  40. }
  41. interface IClip extends IProperty {
  42. uri?: string;
  43. bufferView?: number;
  44. mimeType?: AudioMimeType;
  45. }
  46. interface ILoaderClip extends IClip, IArrayItem {
  47. _objectURL?: Promise<string>;
  48. }
  49. interface ILoaderEmitter extends IEmitter, IArrayItem {
  50. _babylonData?: {
  51. sound?: WeightedSound;
  52. loaded: Promise<void>;
  53. };
  54. _babylonSounds: Sound[];
  55. }
  56. interface IMSFTAudioEmitter {
  57. clips: ILoaderClip[];
  58. emitters: ILoaderEmitter[];
  59. }
  60. const enum AnimationEventAction {
  61. play = "play",
  62. pause = "pause",
  63. stop = "stop",
  64. }
  65. interface IAnimationEvent {
  66. action: AnimationEventAction;
  67. emitter: number;
  68. time: number;
  69. startOffset?: number;
  70. }
  71. interface ILoaderAnimationEvent extends IAnimationEvent, IArrayItem {
  72. }
  73. interface ILoaderAnimationEvents {
  74. events: ILoaderAnimationEvent[];
  75. }
  76. /**
  77. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  78. */
  79. export class MSFT_audio_emitter implements IGLTFLoaderExtension {
  80. /** The name of this extension. */
  81. public readonly name = NAME;
  82. /** Defines whether this extension is enabled. */
  83. public enabled = true;
  84. private _loader: GLTFLoader;
  85. private _clips: Array<ILoaderClip>;
  86. private _emitters: Array<ILoaderEmitter>;
  87. /** @hidden */
  88. constructor(loader: GLTFLoader) {
  89. this._loader = loader;
  90. }
  91. /** @hidden */
  92. public dispose() {
  93. delete this._loader;
  94. delete this._clips;
  95. delete this._emitters;
  96. }
  97. /** @hidden */
  98. public onLoading(): void {
  99. const extensions = this._loader.gltf.extensions;
  100. if (extensions && extensions[this.name]) {
  101. const extension = extensions[this.name] as IMSFTAudioEmitter;
  102. this._clips = extension.clips;
  103. this._emitters = extension.emitters;
  104. ArrayItem.Assign(this._clips);
  105. ArrayItem.Assign(this._emitters);
  106. }
  107. }
  108. /** @hidden */
  109. public loadSceneAsync(context: string, scene: IScene): Nullable<Promise<void>> {
  110. return GLTFLoader.LoadExtensionAsync<IEmittersReference>(context, scene, this.name, (extensionContext, extension) => {
  111. const promises = new Array<Promise<any>>();
  112. promises.push(this._loader.loadSceneAsync(context, scene));
  113. for (const emitterIndex of extension.emitters) {
  114. const emitter = ArrayItem.Get(`${extensionContext}/emitters`, this._emitters, emitterIndex);
  115. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  116. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  117. throw new Error(`${extensionContext}: Direction or Distance properties are not allowed on emitters attached to a scene`);
  118. }
  119. promises.push(this._loadEmitterAsync(`${extensionContext}/emitters/${emitter.index}`, emitter));
  120. }
  121. return Promise.all(promises).then(() => { });
  122. });
  123. }
  124. /** @hidden */
  125. public loadNodeAsync(context: string, node: INode, assign: (babylonTransformNode: TransformNode) => void): Nullable<Promise<TransformNode>> {
  126. return GLTFLoader.LoadExtensionAsync<IEmittersReference, TransformNode>(context, node, this.name, (extensionContext, extension) => {
  127. const promises = new Array<Promise<any>>();
  128. return this._loader.loadNodeAsync(extensionContext, node, (babylonMesh) => {
  129. for (const emitterIndex of extension.emitters) {
  130. const emitter = ArrayItem.Get(`${extensionContext}/emitters`, this._emitters, emitterIndex);
  131. promises.push(this._loadEmitterAsync(`${extensionContext}/emitters/${emitter.index}`, emitter).then(() => {
  132. for (const sound of emitter._babylonSounds) {
  133. sound.attachToMesh(babylonMesh);
  134. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  135. sound.setLocalDirectionToMesh(Vector3.Forward());
  136. sound.setDirectionalCone(
  137. 2 * Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle),
  138. 2 * Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle),
  139. 0);
  140. }
  141. }
  142. }));
  143. }
  144. assign(babylonMesh);
  145. }).then((babylonMesh) => {
  146. return Promise.all(promises).then(() => {
  147. return babylonMesh;
  148. });
  149. });
  150. });
  151. }
  152. /** @hidden */
  153. public loadAnimationAsync(context: string, animation: IAnimation): Nullable<Promise<AnimationGroup>> {
  154. return GLTFLoader.LoadExtensionAsync<ILoaderAnimationEvents, AnimationGroup>(context, animation, this.name, (extensionContext, extension) => {
  155. return this._loader.loadAnimationAsync(context, animation).then((babylonAnimationGroup) => {
  156. const promises = new Array<Promise<any>>();
  157. ArrayItem.Assign(extension.events);
  158. for (const event of extension.events) {
  159. promises.push(this._loadAnimationEventAsync(`${extensionContext}/events/${event.index}`, context, animation, event, babylonAnimationGroup));
  160. }
  161. return Promise.all(promises).then(() => {
  162. return babylonAnimationGroup;
  163. });
  164. });
  165. });
  166. }
  167. private _loadClipAsync(context: string, clip: ILoaderClip): Promise<string> {
  168. if (clip._objectURL) {
  169. return clip._objectURL;
  170. }
  171. let promise: Promise<ArrayBufferView>;
  172. if (clip.uri) {
  173. promise = this._loader.loadUriAsync(context, clip, clip.uri);
  174. }
  175. else {
  176. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._loader.gltf.bufferViews, clip.bufferView);
  177. promise = this._loader.loadBufferViewAsync(`#/bufferViews/${bufferView.index}`, bufferView);
  178. }
  179. clip._objectURL = promise.then((data) => {
  180. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  181. });
  182. return clip._objectURL;
  183. }
  184. private _loadEmitterAsync(context: string, emitter: ILoaderEmitter): Promise<void> {
  185. emitter._babylonSounds = emitter._babylonSounds || [];
  186. if (!emitter._babylonData) {
  187. const clipPromises = new Array<Promise<any>>();
  188. const name = emitter.name || `emitter${emitter.index}`;
  189. const options = {
  190. loop: false,
  191. autoplay: false,
  192. volume: emitter.volume == undefined ? 1 : emitter.volume,
  193. };
  194. for (let i = 0; i < emitter.clips.length; i++) {
  195. const clipContext = `#/extensions/${this.name}/clips`;
  196. const clip = ArrayItem.Get(clipContext, this._clips, emitter.clips[i].clip);
  197. clipPromises.push(this._loadClipAsync(`${clipContext}/${emitter.clips[i].clip}`, clip).then((objectURL: string) => {
  198. const sound = emitter._babylonSounds[i] = new Sound(name, objectURL, this._loader.babylonScene, null, options);
  199. sound.refDistance = emitter.refDistance || 1;
  200. sound.maxDistance = emitter.maxDistance || 256;
  201. sound.rolloffFactor = emitter.rolloffFactor || 1;
  202. sound.distanceModel = emitter.distanceModel || 'exponential';
  203. sound._positionInEmitterSpace = true;
  204. }));
  205. }
  206. const promise = Promise.all(clipPromises).then(() => {
  207. const weights = emitter.clips.map((clip) => { return clip.weight || 1; });
  208. const weightedSound = new WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  209. if (emitter.innerAngle) { weightedSound.directionalConeInnerAngle = 2 * Tools.ToDegrees(emitter.innerAngle); }
  210. if (emitter.outerAngle) { weightedSound.directionalConeOuterAngle = 2 * Tools.ToDegrees(emitter.outerAngle); }
  211. if (emitter.volume) { weightedSound.volume = emitter.volume; }
  212. emitter._babylonData!.sound = weightedSound;
  213. });
  214. emitter._babylonData = {
  215. loaded: promise
  216. };
  217. }
  218. return emitter._babylonData.loaded;
  219. }
  220. private _getEventAction(context: string, sound: WeightedSound, action: AnimationEventAction, time: number, startOffset?: number): (currentFrame: number) => void {
  221. switch (action) {
  222. case AnimationEventAction.play: {
  223. return (currentFrame: number) => {
  224. const frameOffset = (startOffset || 0) + (currentFrame - time);
  225. sound.play(frameOffset);
  226. };
  227. }
  228. case AnimationEventAction.stop: {
  229. return (currentFrame: number) => {
  230. sound.stop();
  231. };
  232. }
  233. case AnimationEventAction.pause: {
  234. return (currentFrame: number) => {
  235. sound.pause();
  236. };
  237. }
  238. default: {
  239. throw new Error(`${context}: Unsupported action ${action}`);
  240. }
  241. }
  242. }
  243. private _loadAnimationEventAsync(context: string, animationContext: string, animation: IAnimation, event: ILoaderAnimationEvent, babylonAnimationGroup: AnimationGroup): Promise<void> {
  244. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  245. return Promise.resolve();
  246. }
  247. const babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  248. const emitterIndex = event.emitter;
  249. const emitter = ArrayItem.Get(`#/extensions/${this.name}/emitters`, this._emitters, emitterIndex);
  250. return this._loadEmitterAsync(context, emitter).then(() => {
  251. const sound = emitter._babylonData!.sound;
  252. if (sound) {
  253. var babylonAnimationEvent = new AnimationEvent(event.time, this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  254. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  255. // Make sure all started audio stops when this animation is terminated.
  256. babylonAnimationGroup.onAnimationGroupEndObservable.add(() => {
  257. sound.stop();
  258. });
  259. babylonAnimationGroup.onAnimationGroupPauseObservable.add(() => {
  260. sound.pause();
  261. });
  262. }
  263. });
  264. }
  265. }
  266. GLTFLoader.RegisterExtension(NAME, (loader) => new MSFT_audio_emitter(loader));