glTFLoader.ts 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306
  1. import { IndicesArray, Nullable } from "babylonjs/types";
  2. import { Deferred } from "babylonjs/Misc/deferred";
  3. import { Quaternion, Color3, Vector3, Matrix } from "babylonjs/Maths/math";
  4. import { LoadFileError, IFileRequest, IAnimatable, Tools } from "babylonjs/Misc/tools";
  5. import { Camera } from "babylonjs/Cameras/camera";
  6. import { FreeCamera } from "babylonjs/Cameras/freeCamera";
  7. import { AnimationGroup } from "babylonjs/Animations/animationGroup";
  8. import { Animation } from "babylonjs/Animations/animation";
  9. import { Bone } from "babylonjs/Bones/bone";
  10. import { Skeleton } from "babylonjs/Bones/skeleton";
  11. import { IParticleSystem } from "babylonjs/Particles/IParticleSystem";
  12. import { Material } from "babylonjs/Materials/material";
  13. import { PBRMaterial } from "babylonjs/Materials/PBR/pbrMaterial";
  14. import { BaseTexture } from "babylonjs/Materials/Textures/baseTexture";
  15. import { Texture } from "babylonjs/Materials/Textures/texture";
  16. import { TransformNode } from "babylonjs/Meshes/transformNode";
  17. import { Buffer, VertexBuffer } from "babylonjs/Meshes/buffer";
  18. import { Geometry } from "babylonjs/Meshes/geometry";
  19. import { AbstractMesh } from "babylonjs/Meshes/abstractMesh";
  20. import { Mesh } from "babylonjs/Meshes/mesh";
  21. import { MorphTarget } from "babylonjs/Morph/morphTarget";
  22. import { MorphTargetManager } from "babylonjs/Morph/morphTargetManager";
  23. import { SceneLoaderProgressEvent } from "babylonjs/Loading/sceneLoader";
  24. import { Scene } from "babylonjs/scene";
  25. import { IProperty, AccessorType, CameraType, AnimationChannelTargetPath, AnimationSamplerInterpolation, AccessorComponentType, MaterialAlphaMode, TextureMinFilter, TextureWrapMode, TextureMagFilter, MeshPrimitiveMode } from "babylonjs-gltf2interface";
  26. import { _IAnimationSamplerData, IGLTF, ISampler, INode, IScene, IMesh, IAccessor, ISkin, ICamera, IAnimation, IAnimationChannel, IAnimationSampler, IBuffer, IBufferView, IMaterialPbrMetallicRoughness, IMaterial, ITextureInfo, ITexture, IImage, IMeshPrimitive, IArrayItem as IArrItem, _ISamplerData } from "./glTFLoaderInterfaces";
  27. import { IGLTFLoaderExtension } from "./glTFLoaderExtension";
  28. import { IGLTFLoader, GLTFFileLoader, GLTFLoaderState, IGLTFLoaderData, GLTFLoaderCoordinateSystemMode, GLTFLoaderAnimationStartMode } from "../glTFFileLoader";
  29. import { IAnimationKey, AnimationKeyInterpolation } from 'babylonjs/Animations/animationKey';
  30. interface IFileRequestInfo extends IFileRequest {
  31. _lengthComputable?: boolean;
  32. _loaded?: number;
  33. _total?: number;
  34. }
  35. interface ILoaderProperty extends IProperty {
  36. _activeLoaderExtensionFunctions: {
  37. [id: string]: boolean
  38. };
  39. }
  40. /**
  41. * Helper class for working with arrays when loading the glTF asset
  42. */
  43. export class ArrayItem {
  44. /**
  45. * Gets an item from the given array.
  46. * @param context The context when loading the asset
  47. * @param array The array to get the item from
  48. * @param index The index to the array
  49. * @returns The array item
  50. */
  51. public static Get<T>(context: string, array: ArrayLike<T> | undefined, index: number | undefined): T {
  52. if (!array || index == undefined || !array[index]) {
  53. throw new Error(`${context}: Failed to find index (${index})`);
  54. }
  55. return array[index];
  56. }
  57. /**
  58. * Assign an `index` field to each item of the given array.
  59. * @param array The array of items
  60. */
  61. public static Assign(array?: IArrItem[]): void {
  62. if (array) {
  63. for (let index = 0; index < array.length; index++) {
  64. array[index].index = index;
  65. }
  66. }
  67. }
  68. }
  69. /**
  70. * The glTF 2.0 loader
  71. */
  72. export class GLTFLoader implements IGLTFLoader {
  73. /** @hidden */
  74. public _completePromises = new Array<Promise<any>>();
  75. private _disposed = false;
  76. private _parent: GLTFFileLoader;
  77. private _state: Nullable<GLTFLoaderState> = null;
  78. private _extensions: { [name: string]: IGLTFLoaderExtension } = {};
  79. private _rootUrl: string;
  80. private _fileName: string;
  81. private _uniqueRootUrl: string;
  82. private _gltf: IGLTF;
  83. private _babylonScene: Scene;
  84. private _rootBabylonMesh: Mesh;
  85. private _defaultBabylonMaterialData: { [drawMode: number]: Material } = {};
  86. private _progressCallback?: (event: SceneLoaderProgressEvent) => void;
  87. private _requests = new Array<IFileRequestInfo>();
  88. private static readonly _DefaultSampler: ISampler = { index: -1 };
  89. private static _ExtensionNames = new Array<string>();
  90. private static _ExtensionFactories: { [name: string]: (loader: GLTFLoader) => IGLTFLoaderExtension } = {};
  91. /**
  92. * Registers a loader extension.
  93. * @param name The name of the loader extension.
  94. * @param factory The factory function that creates the loader extension.
  95. */
  96. public static RegisterExtension(name: string, factory: (loader: GLTFLoader) => IGLTFLoaderExtension): void {
  97. if (GLTFLoader.UnregisterExtension(name)) {
  98. Tools.Warn(`Extension with the name '${name}' already exists`);
  99. }
  100. GLTFLoader._ExtensionFactories[name] = factory;
  101. // Keep the order of registration so that extensions registered first are called first.
  102. GLTFLoader._ExtensionNames.push(name);
  103. }
  104. /**
  105. * Unregisters a loader extension.
  106. * @param name The name of the loader extenion.
  107. * @returns A boolean indicating whether the extension has been unregistered
  108. */
  109. public static UnregisterExtension(name: string): boolean {
  110. if (!GLTFLoader._ExtensionFactories[name]) {
  111. return false;
  112. }
  113. delete GLTFLoader._ExtensionFactories[name];
  114. const index = GLTFLoader._ExtensionNames.indexOf(name);
  115. if (index !== -1) {
  116. GLTFLoader._ExtensionNames.splice(index, 1);
  117. }
  118. return true;
  119. }
  120. /**
  121. * Gets the loader state.
  122. */
  123. public get state(): Nullable<GLTFLoaderState> {
  124. return this._state;
  125. }
  126. /**
  127. * The glTF object parsed from the JSON.
  128. */
  129. public get gltf(): IGLTF {
  130. return this._gltf;
  131. }
  132. /**
  133. * The Babylon scene when loading the asset.
  134. */
  135. public get babylonScene(): Scene {
  136. return this._babylonScene;
  137. }
  138. /**
  139. * The root Babylon mesh when loading the asset.
  140. */
  141. public get rootBabylonMesh(): Mesh {
  142. return this._rootBabylonMesh;
  143. }
  144. /** @hidden */
  145. constructor(parent: GLTFFileLoader) {
  146. this._parent = parent;
  147. }
  148. /** @hidden */
  149. public dispose(): void {
  150. if (this._disposed) {
  151. return;
  152. }
  153. this._disposed = true;
  154. for (const request of this._requests) {
  155. request.abort();
  156. }
  157. this._requests.length = 0;
  158. this._completePromises.length = 0;
  159. for (const name in this._extensions) {
  160. const extension = this._extensions[name];
  161. if (extension.dispose) {
  162. this._extensions[name].dispose();
  163. }
  164. }
  165. this._extensions = {};
  166. delete this._gltf;
  167. delete this._babylonScene;
  168. delete this._rootBabylonMesh;
  169. delete this._progressCallback;
  170. this._parent._clear();
  171. }
  172. /** @hidden */
  173. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<{ meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }> {
  174. return Promise.resolve().then(() => {
  175. this._babylonScene = scene;
  176. this._rootUrl = rootUrl;
  177. this._fileName = fileName || "scene";
  178. this._progressCallback = onProgress;
  179. this._loadData(data);
  180. let nodes: Nullable<Array<number>> = null;
  181. if (meshesNames) {
  182. const nodeMap: { [name: string]: number } = {};
  183. if (this._gltf.nodes) {
  184. for (const node of this._gltf.nodes) {
  185. if (node.name) {
  186. nodeMap[node.name] = node.index;
  187. }
  188. }
  189. }
  190. const names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  191. nodes = names.map((name) => {
  192. const node = nodeMap[name];
  193. if (node === undefined) {
  194. throw new Error(`Failed to find node '${name}'`);
  195. }
  196. return node;
  197. });
  198. }
  199. return this._loadAsync(nodes, () => {
  200. return {
  201. meshes: this._getMeshes(),
  202. particleSystems: [],
  203. skeletons: this._getSkeletons(),
  204. animationGroups: this._getAnimationGroups()
  205. };
  206. });
  207. });
  208. }
  209. /** @hidden */
  210. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<void> {
  211. return Promise.resolve().then(() => {
  212. this._babylonScene = scene;
  213. this._rootUrl = rootUrl;
  214. this._fileName = fileName || "scene";
  215. this._progressCallback = onProgress;
  216. this._loadData(data);
  217. return this._loadAsync(null, () => undefined);
  218. });
  219. }
  220. private _loadAsync<T>(nodes: Nullable<Array<number>>, resultFunc: () => T): Promise<T> {
  221. return Promise.resolve().then(() => {
  222. this._uniqueRootUrl = (this._rootUrl.indexOf("file:") === -1 && this._fileName) ? this._rootUrl : `${this._rootUrl}${Date.now()}/`;
  223. this._loadExtensions();
  224. this._checkExtensions();
  225. const loadingToReadyCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.READY]}`;
  226. const loadingToCompleteCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.COMPLETE]}`;
  227. this._parent._startPerformanceCounter(loadingToReadyCounterName);
  228. this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  229. this._setState(GLTFLoaderState.LOADING);
  230. this._extensionsOnLoading();
  231. const promises = new Array<Promise<any>>();
  232. // Block the marking of materials dirty until the scene is loaded.
  233. const oldBlockMaterialDirtyMechanism = this._babylonScene.blockMaterialDirtyMechanism;
  234. this._babylonScene.blockMaterialDirtyMechanism = true;
  235. if (nodes) {
  236. promises.push(this.loadSceneAsync("/nodes", { nodes: nodes, index: -1 }));
  237. }
  238. else if (this._gltf.scene != undefined || (this._gltf.scenes && this._gltf.scenes[0])) {
  239. const scene = ArrayItem.Get(`/scene`, this._gltf.scenes, this._gltf.scene || 0);
  240. promises.push(this.loadSceneAsync(`/scenes/${scene.index}`, scene));
  241. }
  242. // Restore the blocking of material dirty.
  243. this._babylonScene.blockMaterialDirtyMechanism = oldBlockMaterialDirtyMechanism;
  244. if (this._parent.compileMaterials) {
  245. promises.push(this._compileMaterialsAsync());
  246. }
  247. if (this._parent.compileShadowGenerators) {
  248. promises.push(this._compileShadowGeneratorsAsync());
  249. }
  250. const resultPromise = Promise.all(promises).then(() => {
  251. if (this._rootBabylonMesh) {
  252. this._rootBabylonMesh.setEnabled(true);
  253. }
  254. this._setState(GLTFLoaderState.READY);
  255. this._extensionsOnReady();
  256. this._startAnimations();
  257. return resultFunc();
  258. });
  259. resultPromise.then(() => {
  260. this._parent._endPerformanceCounter(loadingToReadyCounterName);
  261. Tools.SetImmediate(() => {
  262. if (!this._disposed) {
  263. Promise.all(this._completePromises).then(() => {
  264. this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  265. this._setState(GLTFLoaderState.COMPLETE);
  266. this._parent.onCompleteObservable.notifyObservers(undefined);
  267. this._parent.onCompleteObservable.clear();
  268. this.dispose();
  269. }, (error) => {
  270. this._parent.onErrorObservable.notifyObservers(error);
  271. this._parent.onErrorObservable.clear();
  272. this.dispose();
  273. });
  274. }
  275. });
  276. });
  277. return resultPromise;
  278. }, (error) => {
  279. if (!this._disposed) {
  280. this._parent.onErrorObservable.notifyObservers(error);
  281. this._parent.onErrorObservable.clear();
  282. this.dispose();
  283. }
  284. throw error;
  285. });
  286. }
  287. private _loadData(data: IGLTFLoaderData): void {
  288. this._gltf = data.json as IGLTF;
  289. this._setupData();
  290. if (data.bin) {
  291. const buffers = this._gltf.buffers;
  292. if (buffers && buffers[0] && !buffers[0].uri) {
  293. const binaryBuffer = buffers[0];
  294. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  295. Tools.Warn(`Binary buffer length (${binaryBuffer.byteLength}) from JSON does not match chunk length (${data.bin.byteLength})`);
  296. }
  297. binaryBuffer._data = Promise.resolve(data.bin);
  298. }
  299. else {
  300. Tools.Warn("Unexpected BIN chunk");
  301. }
  302. }
  303. }
  304. private _setupData(): void {
  305. ArrayItem.Assign(this._gltf.accessors);
  306. ArrayItem.Assign(this._gltf.animations);
  307. ArrayItem.Assign(this._gltf.buffers);
  308. ArrayItem.Assign(this._gltf.bufferViews);
  309. ArrayItem.Assign(this._gltf.cameras);
  310. ArrayItem.Assign(this._gltf.images);
  311. ArrayItem.Assign(this._gltf.materials);
  312. ArrayItem.Assign(this._gltf.meshes);
  313. ArrayItem.Assign(this._gltf.nodes);
  314. ArrayItem.Assign(this._gltf.samplers);
  315. ArrayItem.Assign(this._gltf.scenes);
  316. ArrayItem.Assign(this._gltf.skins);
  317. ArrayItem.Assign(this._gltf.textures);
  318. if (this._gltf.nodes) {
  319. const nodeParents: { [index: number]: number } = {};
  320. for (const node of this._gltf.nodes) {
  321. if (node.children) {
  322. for (const index of node.children) {
  323. nodeParents[index] = node.index;
  324. }
  325. }
  326. }
  327. const rootNode = this._createRootNode();
  328. for (const node of this._gltf.nodes) {
  329. const parentIndex = nodeParents[node.index];
  330. node.parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  331. }
  332. }
  333. }
  334. private _loadExtensions(): void {
  335. for (const name of GLTFLoader._ExtensionNames) {
  336. const extension = GLTFLoader._ExtensionFactories[name](this);
  337. this._extensions[name] = extension;
  338. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  339. }
  340. this._parent.onExtensionLoadedObservable.clear();
  341. }
  342. private _checkExtensions(): void {
  343. if (this._gltf.extensionsRequired) {
  344. for (const name of this._gltf.extensionsRequired) {
  345. const extension = this._extensions[name];
  346. if (!extension || !extension.enabled) {
  347. throw new Error(`Require extension ${name} is not available`);
  348. }
  349. }
  350. }
  351. }
  352. private _setState(state: GLTFLoaderState): void {
  353. this._state = state;
  354. this.log(GLTFLoaderState[this._state]);
  355. }
  356. private _createRootNode(): INode {
  357. this._rootBabylonMesh = new Mesh("__root__", this._babylonScene);
  358. this._rootBabylonMesh.setEnabled(false);
  359. const rootNode: INode = {
  360. _babylonTransformNode: this._rootBabylonMesh,
  361. index: -1
  362. };
  363. switch (this._parent.coordinateSystemMode) {
  364. case GLTFLoaderCoordinateSystemMode.AUTO: {
  365. if (!this._babylonScene.useRightHandedSystem) {
  366. rootNode.rotation = [0, 1, 0, 0];
  367. rootNode.scale = [1, 1, -1];
  368. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  369. }
  370. break;
  371. }
  372. case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  373. this._babylonScene.useRightHandedSystem = true;
  374. break;
  375. }
  376. default: {
  377. throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`);
  378. }
  379. }
  380. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  381. return rootNode;
  382. }
  383. /**
  384. * Loads a glTF scene.
  385. * @param context The context when loading the asset
  386. * @param scene The glTF scene property
  387. * @returns A promise that resolves when the load is complete
  388. */
  389. public loadSceneAsync(context: string, scene: IScene): Promise<void> {
  390. const extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  391. if (extensionPromise) {
  392. return extensionPromise;
  393. }
  394. const promises = new Array<Promise<any>>();
  395. this.logOpen(`${context} ${scene.name || ""}`);
  396. if (scene.nodes) {
  397. for (let index of scene.nodes) {
  398. const node = ArrayItem.Get(`${context}/nodes/${index}`, this._gltf.nodes, index);
  399. promises.push(this.loadNodeAsync(`/nodes/${node.index}`, node, (babylonMesh) => {
  400. babylonMesh.parent = this._rootBabylonMesh;
  401. }));
  402. }
  403. }
  404. // Link all Babylon bones for each glTF node with the corresponding Babylon transform node.
  405. // A glTF joint is a pointer to a glTF node in the glTF node hierarchy similar to Unity3D.
  406. if (this._gltf.nodes) {
  407. for (const node of this._gltf.nodes) {
  408. if (node._babylonTransformNode && node._babylonBones) {
  409. for (const babylonBone of node._babylonBones) {
  410. babylonBone.linkTransformNode(node._babylonTransformNode);
  411. }
  412. }
  413. }
  414. }
  415. promises.push(this._loadAnimationsAsync());
  416. this.logClose();
  417. return Promise.all(promises).then(() => { });
  418. }
  419. private _forEachPrimitive(node: INode, callback: (babylonMesh: AbstractMesh) => void): void {
  420. if (node._primitiveBabylonMeshes) {
  421. for (const babylonMesh of node._primitiveBabylonMeshes) {
  422. callback(babylonMesh);
  423. }
  424. }
  425. }
  426. private _getMeshes(): AbstractMesh[] {
  427. const meshes = new Array<AbstractMesh>();
  428. // Root mesh is always first.
  429. meshes.push(this._rootBabylonMesh);
  430. const nodes = this._gltf.nodes;
  431. if (nodes) {
  432. for (const node of nodes) {
  433. this._forEachPrimitive(node, (babylonMesh) => {
  434. meshes.push(babylonMesh);
  435. });
  436. }
  437. }
  438. return meshes;
  439. }
  440. private _getSkeletons(): Skeleton[] {
  441. const skeletons = new Array<Skeleton>();
  442. const skins = this._gltf.skins;
  443. if (skins) {
  444. for (const skin of skins) {
  445. if (skin._data) {
  446. skeletons.push(skin._data.babylonSkeleton);
  447. }
  448. }
  449. }
  450. return skeletons;
  451. }
  452. private _getAnimationGroups(): AnimationGroup[] {
  453. const animationGroups = new Array<AnimationGroup>();
  454. const animations = this._gltf.animations;
  455. if (animations) {
  456. for (const animation of animations) {
  457. if (animation._babylonAnimationGroup) {
  458. animationGroups.push(animation._babylonAnimationGroup);
  459. }
  460. }
  461. }
  462. return animationGroups;
  463. }
  464. private _startAnimations(): void {
  465. switch (this._parent.animationStartMode) {
  466. case GLTFLoaderAnimationStartMode.NONE: {
  467. // do nothing
  468. break;
  469. }
  470. case GLTFLoaderAnimationStartMode.FIRST: {
  471. const babylonAnimationGroups = this._getAnimationGroups();
  472. if (babylonAnimationGroups.length !== 0) {
  473. babylonAnimationGroups[0].start(true);
  474. }
  475. break;
  476. }
  477. case GLTFLoaderAnimationStartMode.ALL: {
  478. const babylonAnimationGroups = this._getAnimationGroups();
  479. for (const babylonAnimationGroup of babylonAnimationGroups) {
  480. babylonAnimationGroup.start(true);
  481. }
  482. break;
  483. }
  484. default: {
  485. Tools.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);
  486. return;
  487. }
  488. }
  489. }
  490. /**
  491. * Loads a glTF node.
  492. * @param context The context when loading the asset
  493. * @param node The glTF node property
  494. * @param assign A function called synchronously after parsing the glTF properties
  495. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  496. */
  497. public loadNodeAsync(context: string, node: INode, assign: (babylonTransformNode: TransformNode) => void = () => { }): Promise<TransformNode> {
  498. const extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  499. if (extensionPromise) {
  500. return extensionPromise;
  501. }
  502. if (node._babylonTransformNode) {
  503. throw new Error(`${context}: Invalid recursive node hierarchy`);
  504. }
  505. const promises = new Array<Promise<any>>();
  506. this.logOpen(`${context} ${node.name || ""}`);
  507. const loadNode = (babylonTransformNode: TransformNode) => {
  508. GLTFLoader.AddPointerMetadata(babylonTransformNode, context);
  509. GLTFLoader._LoadTransform(node, babylonTransformNode);
  510. if (node.camera != undefined) {
  511. const camera = ArrayItem.Get(`${context}/camera`, this._gltf.cameras, node.camera);
  512. promises.push(this.loadCameraAsync(`/cameras/${camera.index}`, camera, (babylonCamera) => {
  513. babylonCamera.parent = babylonTransformNode;
  514. }));
  515. }
  516. if (node.children) {
  517. for (const index of node.children) {
  518. const childNode = ArrayItem.Get(`${context}/children/${index}`, this._gltf.nodes, index);
  519. promises.push(this.loadNodeAsync(`/nodes/${childNode.index}`, childNode, (childBabylonMesh) => {
  520. childBabylonMesh.parent = babylonTransformNode;
  521. }));
  522. }
  523. }
  524. assign(babylonTransformNode);
  525. };
  526. if (node.mesh == undefined) {
  527. const nodeName = node.name || `node${node.index}`;
  528. node._babylonTransformNode = new TransformNode(nodeName, this._babylonScene);
  529. loadNode(node._babylonTransformNode);
  530. }
  531. else {
  532. const mesh = ArrayItem.Get(`${context}/mesh`, this._gltf.meshes, node.mesh);
  533. promises.push(this._loadMeshAsync(`/meshes/${mesh.index}`, node, mesh, loadNode));
  534. }
  535. this.logClose();
  536. return Promise.all(promises).then(() => {
  537. this._forEachPrimitive(node, (babylonMesh) => {
  538. babylonMesh.refreshBoundingInfo(true);
  539. });
  540. return node._babylonTransformNode!;
  541. });
  542. }
  543. private _loadMeshAsync(context: string, node: INode, mesh: IMesh, assign: (babylonTransformNode: TransformNode) => void): Promise<TransformNode> {
  544. const primitives = mesh.primitives;
  545. if (!primitives || !primitives.length) {
  546. throw new Error(`${context}: Primitives are missing`);
  547. }
  548. if (primitives[0].index == undefined) {
  549. ArrayItem.Assign(primitives);
  550. }
  551. const promises = new Array<Promise<any>>();
  552. this.logOpen(`${context} ${mesh.name || ""}`);
  553. const name = node.name || `node${node.index}`;
  554. if (primitives.length === 1) {
  555. const primitive = mesh.primitives[0];
  556. promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, name, node, mesh, primitive, (babylonMesh) => {
  557. node._babylonTransformNode = babylonMesh;
  558. node._primitiveBabylonMeshes = [babylonMesh];
  559. }));
  560. }
  561. else {
  562. node._babylonTransformNode = new TransformNode(name, this._babylonScene);
  563. node._primitiveBabylonMeshes = [];
  564. for (const primitive of primitives) {
  565. promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, `${name}_primitive${primitive.index}`, node, mesh, primitive, (babylonMesh) => {
  566. babylonMesh.parent = node._babylonTransformNode!;
  567. node._primitiveBabylonMeshes!.push(babylonMesh);
  568. }));
  569. }
  570. }
  571. if (node.skin != undefined) {
  572. const skin = ArrayItem.Get(`${context}/skin`, this._gltf.skins, node.skin);
  573. promises.push(this._loadSkinAsync(`/skins/${skin.index}`, node, skin));
  574. }
  575. assign(node._babylonTransformNode!);
  576. this.logClose();
  577. return Promise.all(promises).then(() => {
  578. return node._babylonTransformNode!;
  579. });
  580. }
  581. /**
  582. * @hidden Define this method to modify the default behavior when loading data for mesh primitives.
  583. * @param context The context when loading the asset
  584. * @param name The mesh name when loading the asset
  585. * @param node The glTF node when loading the asset
  586. * @param mesh The glTF mesh when loading the asset
  587. * @param primitive The glTF mesh primitive property
  588. * @param assign A function called synchronously after parsing the glTF properties
  589. * @returns A promise that resolves with the loaded mesh when the load is complete or null if not handled
  590. */
  591. public _loadMeshPrimitiveAsync(context: string, name: string, node: INode, mesh: IMesh, primitive: IMeshPrimitive, assign: (babylonMesh: AbstractMesh) => void): Promise<AbstractMesh> {
  592. const extensionPromise = this._extensionsLoadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign);
  593. if (extensionPromise) {
  594. return extensionPromise;
  595. }
  596. this.logOpen(`${context}`);
  597. const canInstance = (node.skin == undefined && !mesh.primitives[0].targets);
  598. let babylonAbstractMesh: AbstractMesh;
  599. let promise: Promise<any>;
  600. const instanceData = primitive._instanceData;
  601. if (canInstance && instanceData) {
  602. babylonAbstractMesh = instanceData.babylonSourceMesh.createInstance(name);
  603. promise = instanceData.promise;
  604. }
  605. else {
  606. const promises = new Array<Promise<any>>();
  607. const babylonMesh = new Mesh(name, this._babylonScene);
  608. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  609. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then((babylonGeometry) => {
  610. return this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(() => {
  611. babylonGeometry.applyToMesh(babylonMesh);
  612. });
  613. }));
  614. const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  615. if (primitive.material == undefined) {
  616. let babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  617. if (!babylonMaterial) {
  618. babylonMaterial = this._createDefaultMaterial("__GLTFLoader._default", babylonDrawMode);
  619. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  620. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  621. }
  622. babylonMesh.material = babylonMaterial;
  623. }
  624. else {
  625. const material = ArrayItem.Get(`${context}/material`, this._gltf.materials, primitive.material);
  626. promises.push(this._loadMaterialAsync(`/materials/${material.index}`, material, babylonMesh, babylonDrawMode, (babylonMaterial) => {
  627. babylonMesh.material = babylonMaterial;
  628. }));
  629. }
  630. promise = Promise.all(promises);
  631. if (canInstance) {
  632. primitive._instanceData = {
  633. babylonSourceMesh: babylonMesh,
  634. promise: promise
  635. };
  636. }
  637. babylonAbstractMesh = babylonMesh;
  638. }
  639. GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context);
  640. this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh);
  641. assign(babylonAbstractMesh);
  642. this.logClose();
  643. return promise.then(() => {
  644. return babylonAbstractMesh;
  645. });
  646. }
  647. private _loadVertexDataAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh): Promise<Geometry> {
  648. const extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  649. if (extensionPromise) {
  650. return extensionPromise;
  651. }
  652. const attributes = primitive.attributes;
  653. if (!attributes) {
  654. throw new Error(`${context}: Attributes are missing`);
  655. }
  656. const promises = new Array<Promise<any>>();
  657. const babylonGeometry = new Geometry(babylonMesh.name, this._babylonScene);
  658. if (primitive.indices == undefined) {
  659. babylonMesh.isUnIndexed = true;
  660. }
  661. else {
  662. const accessor = ArrayItem.Get(`${context}/indices`, this._gltf.accessors, primitive.indices);
  663. promises.push(this._loadIndicesAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  664. babylonGeometry.setIndices(data);
  665. }));
  666. }
  667. const loadAttribute = (attribute: string, kind: string, callback?: (accessor: IAccessor) => void) => {
  668. if (attributes[attribute] == undefined) {
  669. return;
  670. }
  671. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  672. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  673. babylonMesh._delayInfo.push(kind);
  674. }
  675. const accessor = ArrayItem.Get(`${context}/attributes/${attribute}`, this._gltf.accessors, attributes[attribute]);
  676. promises.push(this._loadVertexAccessorAsync(`/accessors/${accessor.index}`, accessor, kind).then((babylonVertexBuffer) => {
  677. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  678. }));
  679. if (callback) {
  680. callback(accessor);
  681. }
  682. };
  683. loadAttribute("POSITION", VertexBuffer.PositionKind);
  684. loadAttribute("NORMAL", VertexBuffer.NormalKind);
  685. loadAttribute("TANGENT", VertexBuffer.TangentKind);
  686. loadAttribute("TEXCOORD_0", VertexBuffer.UVKind);
  687. loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind);
  688. loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind);
  689. loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind);
  690. loadAttribute("COLOR_0", VertexBuffer.ColorKind, (accessor) => {
  691. if (accessor.type === AccessorType.VEC4) {
  692. babylonMesh.hasVertexAlpha = true;
  693. }
  694. });
  695. return Promise.all(promises).then(() => {
  696. return babylonGeometry;
  697. });
  698. }
  699. private _createMorphTargets(context: string, node: INode, mesh: IMesh, primitive: IMeshPrimitive, babylonMesh: Mesh): void {
  700. if (!primitive.targets) {
  701. return;
  702. }
  703. if (node._numMorphTargets == undefined) {
  704. node._numMorphTargets = primitive.targets.length;
  705. }
  706. else if (primitive.targets.length !== node._numMorphTargets) {
  707. throw new Error(`${context}: Primitives do not have the same number of targets`);
  708. }
  709. babylonMesh.morphTargetManager = new MorphTargetManager(babylonMesh.getScene());
  710. for (let index = 0; index < primitive.targets.length; index++) {
  711. const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  712. babylonMesh.morphTargetManager.addTarget(new MorphTarget(`morphTarget${index}`, weight, babylonMesh.getScene()));
  713. // TODO: tell the target whether it has positions, normals, tangents
  714. }
  715. }
  716. private _loadMorphTargetsAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh, babylonGeometry: Geometry): Promise<void> {
  717. if (!primitive.targets) {
  718. return Promise.resolve();
  719. }
  720. const promises = new Array<Promise<any>>();
  721. const morphTargetManager = babylonMesh.morphTargetManager!;
  722. for (let index = 0; index < morphTargetManager.numTargets; index++) {
  723. const babylonMorphTarget = morphTargetManager.getTarget(index);
  724. promises.push(this._loadMorphTargetVertexDataAsync(`${context}/targets/${index}`, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  725. }
  726. return Promise.all(promises).then(() => { });
  727. }
  728. private _loadMorphTargetVertexDataAsync(context: string, babylonGeometry: Geometry, attributes: { [name: string]: number }, babylonMorphTarget: MorphTarget): Promise<void> {
  729. const promises = new Array<Promise<any>>();
  730. const loadAttribute = (attribute: string, kind: string, setData: (babylonVertexBuffer: VertexBuffer, data: Float32Array) => void) => {
  731. if (attributes[attribute] == undefined) {
  732. return;
  733. }
  734. const babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  735. if (!babylonVertexBuffer) {
  736. return;
  737. }
  738. const accessor = ArrayItem.Get(`${context}/${attribute}`, this._gltf.accessors, attributes[attribute]);
  739. promises.push(this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  740. setData(babylonVertexBuffer, data);
  741. }));
  742. };
  743. loadAttribute("POSITION", VertexBuffer.PositionKind, (babylonVertexBuffer, data) => {
  744. const positions = new Float32Array(data.length);
  745. babylonVertexBuffer.forEach(data.length, (value, index) => {
  746. positions[index] = data[index] + value;
  747. });
  748. babylonMorphTarget.setPositions(positions);
  749. });
  750. loadAttribute("NORMAL", VertexBuffer.NormalKind, (babylonVertexBuffer, data) => {
  751. const normals = new Float32Array(data.length);
  752. babylonVertexBuffer.forEach(normals.length, (value, index) => {
  753. normals[index] = data[index] + value;
  754. });
  755. babylonMorphTarget.setNormals(normals);
  756. });
  757. loadAttribute("TANGENT", VertexBuffer.TangentKind, (babylonVertexBuffer, data) => {
  758. const tangents = new Float32Array(data.length / 3 * 4);
  759. let dataIndex = 0;
  760. babylonVertexBuffer.forEach(data.length / 3 * 4, (value, index) => {
  761. // Tangent data for morph targets is stored as xyz delta.
  762. // The vertexData.tangent is stored as xyzw.
  763. // So we need to skip every fourth vertexData.tangent.
  764. if (((index + 1) % 4) !== 0) {
  765. tangents[dataIndex] = data[dataIndex] + value;
  766. dataIndex++;
  767. }
  768. });
  769. babylonMorphTarget.setTangents(tangents);
  770. });
  771. return Promise.all(promises).then(() => { });
  772. }
  773. private static _LoadTransform(node: INode, babylonNode: TransformNode): void {
  774. // Ignore the TRS of skinned nodes.
  775. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  776. if (node.skin != undefined) {
  777. return;
  778. }
  779. let position = Vector3.Zero();
  780. let rotation = Quaternion.Identity();
  781. let scaling = Vector3.One();
  782. if (node.matrix) {
  783. const matrix = Matrix.FromArray(node.matrix);
  784. matrix.decompose(scaling, rotation, position);
  785. }
  786. else {
  787. if (node.translation) { position = Vector3.FromArray(node.translation); }
  788. if (node.rotation) { rotation = Quaternion.FromArray(node.rotation); }
  789. if (node.scale) { scaling = Vector3.FromArray(node.scale); }
  790. }
  791. babylonNode.position = position;
  792. babylonNode.rotationQuaternion = rotation;
  793. babylonNode.scaling = scaling;
  794. }
  795. private _loadSkinAsync(context: string, node: INode, skin: ISkin): Promise<void> {
  796. const extensionPromise = this._extensionsLoadSkinAsync(context, node, skin);
  797. if (extensionPromise) {
  798. return extensionPromise;
  799. }
  800. const assignSkeleton = (skeleton: Skeleton) => {
  801. this._forEachPrimitive(node, (babylonMesh) => {
  802. babylonMesh.skeleton = skeleton;
  803. });
  804. };
  805. if (skin._data) {
  806. assignSkeleton(skin._data.babylonSkeleton);
  807. return skin._data.promise;
  808. }
  809. const skeletonId = `skeleton${skin.index}`;
  810. const babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  811. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  812. babylonSkeleton.overrideMesh = this._rootBabylonMesh;
  813. this._loadBones(context, skin, babylonSkeleton);
  814. assignSkeleton(babylonSkeleton);
  815. const promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then((inverseBindMatricesData) => {
  816. this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  817. });
  818. skin._data = {
  819. babylonSkeleton: babylonSkeleton,
  820. promise: promise
  821. };
  822. return promise;
  823. }
  824. private _loadBones(context: string, skin: ISkin, babylonSkeleton: Skeleton): void {
  825. const babylonBones: { [index: number]: Bone } = {};
  826. for (const index of skin.joints) {
  827. const node = ArrayItem.Get(`${context}/joints/${index}`, this._gltf.nodes, index);
  828. this._loadBone(node, skin, babylonSkeleton, babylonBones);
  829. }
  830. }
  831. private _loadBone(node: INode, skin: ISkin, babylonSkeleton: Skeleton, babylonBones: { [index: number]: Bone }): Bone {
  832. let babylonBone = babylonBones[node.index];
  833. if (babylonBone) {
  834. return babylonBone;
  835. }
  836. let babylonParentBone: Nullable<Bone> = null;
  837. if (node.parent && node.parent._babylonTransformNode !== this._rootBabylonMesh) {
  838. babylonParentBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones);
  839. }
  840. const boneIndex = skin.joints.indexOf(node.index);
  841. babylonBone = new Bone(node.name || `joint${node.index}`, babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  842. babylonBones[node.index] = babylonBone;
  843. node._babylonBones = node._babylonBones || [];
  844. node._babylonBones.push(babylonBone);
  845. return babylonBone;
  846. }
  847. private _loadSkinInverseBindMatricesDataAsync(context: string, skin: ISkin): Promise<Nullable<Float32Array>> {
  848. if (skin.inverseBindMatrices == undefined) {
  849. return Promise.resolve(null);
  850. }
  851. const accessor = ArrayItem.Get(`${context}/inverseBindMatrices`, this._gltf.accessors, skin.inverseBindMatrices);
  852. return this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor);
  853. }
  854. private _updateBoneMatrices(babylonSkeleton: Skeleton, inverseBindMatricesData: Nullable<Float32Array>): void {
  855. for (const babylonBone of babylonSkeleton.bones) {
  856. let baseMatrix = Matrix.Identity();
  857. const boneIndex = babylonBone._index!;
  858. if (inverseBindMatricesData && boneIndex !== -1) {
  859. Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  860. baseMatrix.invertToRef(baseMatrix);
  861. }
  862. const babylonParentBone = babylonBone.getParent();
  863. if (babylonParentBone) {
  864. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  865. }
  866. babylonBone.updateMatrix(baseMatrix, false, false);
  867. babylonBone._updateDifferenceMatrix(undefined, false);
  868. }
  869. }
  870. private _getNodeMatrix(node: INode): Matrix {
  871. return node.matrix ?
  872. Matrix.FromArray(node.matrix) :
  873. Matrix.Compose(
  874. node.scale ? Vector3.FromArray(node.scale) : Vector3.One(),
  875. node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(),
  876. node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());
  877. }
  878. /**
  879. * Loads a glTF camera.
  880. * @param context The context when loading the asset
  881. * @param camera The glTF camera property
  882. * @param assign A function called synchronously after parsing the glTF properties
  883. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  884. */
  885. public loadCameraAsync(context: string, camera: ICamera, assign: (babylonCamera: Camera) => void = () => { }): Promise<Camera> {
  886. const extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  887. if (extensionPromise) {
  888. return extensionPromise;
  889. }
  890. const promises = new Array<Promise<any>>();
  891. this.logOpen(`${context} ${camera.name || ""}`);
  892. const babylonCamera = new FreeCamera(camera.name || `camera${camera.index}`, Vector3.Zero(), this._babylonScene, false);
  893. babylonCamera.rotation = new Vector3(0, Math.PI, 0);
  894. switch (camera.type) {
  895. case CameraType.PERSPECTIVE: {
  896. const perspective = camera.perspective;
  897. if (!perspective) {
  898. throw new Error(`${context}: Camera perspective properties are missing`);
  899. }
  900. babylonCamera.fov = perspective.yfov;
  901. babylonCamera.minZ = perspective.znear;
  902. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  903. break;
  904. }
  905. case CameraType.ORTHOGRAPHIC: {
  906. if (!camera.orthographic) {
  907. throw new Error(`${context}: Camera orthographic properties are missing`);
  908. }
  909. babylonCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  910. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  911. babylonCamera.orthoRight = camera.orthographic.xmag;
  912. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  913. babylonCamera.orthoTop = camera.orthographic.ymag;
  914. babylonCamera.minZ = camera.orthographic.znear;
  915. babylonCamera.maxZ = camera.orthographic.zfar;
  916. break;
  917. }
  918. default: {
  919. throw new Error(`${context}: Invalid camera type (${camera.type})`);
  920. }
  921. }
  922. GLTFLoader.AddPointerMetadata(babylonCamera, context);
  923. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  924. assign(babylonCamera);
  925. return Promise.all(promises).then(() => {
  926. return babylonCamera;
  927. });
  928. }
  929. private _loadAnimationsAsync(): Promise<void> {
  930. const animations = this._gltf.animations;
  931. if (!animations) {
  932. return Promise.resolve();
  933. }
  934. const promises = new Array<Promise<any>>();
  935. for (let index = 0; index < animations.length; index++) {
  936. const animation = animations[index];
  937. promises.push(this.loadAnimationAsync(`/animations/${animation.index}`, animation));
  938. }
  939. return Promise.all(promises).then(() => { });
  940. }
  941. /**
  942. * Loads a glTF animation.
  943. * @param context The context when loading the asset
  944. * @param animation The glTF animation property
  945. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  946. */
  947. public loadAnimationAsync(context: string, animation: IAnimation): Promise<AnimationGroup> {
  948. const promise = this._extensionsLoadAnimationAsync(context, animation);
  949. if (promise) {
  950. return promise;
  951. }
  952. const babylonAnimationGroup = new AnimationGroup(animation.name || `animation${animation.index}`, this._babylonScene);
  953. animation._babylonAnimationGroup = babylonAnimationGroup;
  954. const promises = new Array<Promise<any>>();
  955. ArrayItem.Assign(animation.channels);
  956. ArrayItem.Assign(animation.samplers);
  957. for (const channel of animation.channels) {
  958. promises.push(this._loadAnimationChannelAsync(`${context}/channels/${channel.index}`, context, animation, channel, babylonAnimationGroup));
  959. }
  960. return Promise.all(promises).then(() => {
  961. babylonAnimationGroup.normalize(0);
  962. return babylonAnimationGroup;
  963. });
  964. }
  965. /**
  966. * @hidden Loads a glTF animation channel.
  967. * @param context The context when loading the asset
  968. * @param animationContext The context of the animation when loading the asset
  969. * @param animation The glTF animation property
  970. * @param channel The glTF animation channel property
  971. * @param babylonAnimationGroup The babylon animation group property
  972. * @param animationTargetOverride The babylon animation channel target override property. My be null.
  973. * @returns A void promise when the channel load is complete
  974. */
  975. public _loadAnimationChannelAsync(context: string, animationContext: string, animation: IAnimation, channel: IAnimationChannel, babylonAnimationGroup: AnimationGroup, animationTargetOverride: Nullable<IAnimatable> = null): Promise<void> {
  976. if (channel.target.node == undefined) {
  977. return Promise.resolve();
  978. }
  979. const targetNode = ArrayItem.Get(`${context}/target/node`, this._gltf.nodes, channel.target.node);
  980. // Ignore animations that have no animation targets.
  981. if ((channel.target.path === AnimationChannelTargetPath.WEIGHTS && !targetNode._numMorphTargets) ||
  982. (channel.target.path !== AnimationChannelTargetPath.WEIGHTS && !targetNode._babylonTransformNode)) {
  983. return Promise.resolve();
  984. }
  985. const sampler = ArrayItem.Get(`${context}/sampler`, animation.samplers, channel.sampler);
  986. return this._loadAnimationSamplerAsync(`${animationContext}/samplers/${channel.sampler}`, sampler).then((data) => {
  987. let targetPath: string;
  988. let animationType: number;
  989. switch (channel.target.path) {
  990. case AnimationChannelTargetPath.TRANSLATION: {
  991. targetPath = "position";
  992. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  993. break;
  994. }
  995. case AnimationChannelTargetPath.ROTATION: {
  996. targetPath = "rotationQuaternion";
  997. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  998. break;
  999. }
  1000. case AnimationChannelTargetPath.SCALE: {
  1001. targetPath = "scaling";
  1002. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  1003. break;
  1004. }
  1005. case AnimationChannelTargetPath.WEIGHTS: {
  1006. targetPath = "influence";
  1007. animationType = Animation.ANIMATIONTYPE_FLOAT;
  1008. break;
  1009. }
  1010. default: {
  1011. throw new Error(`${context}/target/path: Invalid value (${channel.target.path})`);
  1012. }
  1013. }
  1014. let outputBufferOffset = 0;
  1015. let getNextOutputValue: () => Vector3 | Quaternion | Array<number>;
  1016. switch (targetPath) {
  1017. case "position": {
  1018. getNextOutputValue = () => {
  1019. const value = Vector3.FromArray(data.output, outputBufferOffset);
  1020. outputBufferOffset += 3;
  1021. return value;
  1022. };
  1023. break;
  1024. }
  1025. case "rotationQuaternion": {
  1026. getNextOutputValue = () => {
  1027. const value = Quaternion.FromArray(data.output, outputBufferOffset);
  1028. outputBufferOffset += 4;
  1029. return value;
  1030. };
  1031. break;
  1032. }
  1033. case "scaling": {
  1034. getNextOutputValue = () => {
  1035. const value = Vector3.FromArray(data.output, outputBufferOffset);
  1036. outputBufferOffset += 3;
  1037. return value;
  1038. };
  1039. break;
  1040. }
  1041. case "influence": {
  1042. getNextOutputValue = () => {
  1043. const value = new Array<number>(targetNode._numMorphTargets!);
  1044. for (let i = 0; i < targetNode._numMorphTargets!; i++) {
  1045. value[i] = data.output[outputBufferOffset++];
  1046. }
  1047. return value;
  1048. };
  1049. break;
  1050. }
  1051. }
  1052. let getNextKey: (frameIndex: number) => IAnimationKey;
  1053. switch (data.interpolation) {
  1054. case AnimationSamplerInterpolation.STEP: {
  1055. getNextKey = (frameIndex) => ({
  1056. frame: data.input[frameIndex],
  1057. value: getNextOutputValue(),
  1058. interpolation: AnimationKeyInterpolation.STEP
  1059. });
  1060. break;
  1061. }
  1062. case AnimationSamplerInterpolation.LINEAR: {
  1063. getNextKey = (frameIndex) => ({
  1064. frame: data.input[frameIndex],
  1065. value: getNextOutputValue()
  1066. });
  1067. break;
  1068. }
  1069. case AnimationSamplerInterpolation.CUBICSPLINE: {
  1070. getNextKey = (frameIndex) => ({
  1071. frame: data.input[frameIndex],
  1072. inTangent: getNextOutputValue(),
  1073. value: getNextOutputValue(),
  1074. outTangent: getNextOutputValue()
  1075. });
  1076. break;
  1077. }
  1078. }
  1079. const keys = new Array(data.input.length);
  1080. for (let frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  1081. keys[frameIndex] = getNextKey!(frameIndex);
  1082. }
  1083. if (targetPath === "influence") {
  1084. for (let targetIndex = 0; targetIndex < targetNode._numMorphTargets!; targetIndex++) {
  1085. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  1086. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  1087. babylonAnimation.setKeys(keys.map((key) => ({
  1088. frame: key.frame,
  1089. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1090. value: key.value[targetIndex],
  1091. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1092. })));
  1093. this._forEachPrimitive(targetNode, (babylonAbstractMesh: AbstractMesh) => {
  1094. const babylonMesh = babylonAbstractMesh as Mesh;
  1095. const morphTarget = babylonMesh.morphTargetManager!.getTarget(targetIndex);
  1096. const babylonAnimationClone = babylonAnimation.clone();
  1097. morphTarget.animations.push(babylonAnimationClone);
  1098. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  1099. });
  1100. }
  1101. }
  1102. else {
  1103. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  1104. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  1105. babylonAnimation.setKeys(keys);
  1106. if (animationTargetOverride != null && animationTargetOverride.animations != null) {
  1107. animationTargetOverride.animations.push(babylonAnimation);
  1108. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, animationTargetOverride);
  1109. } else {
  1110. targetNode._babylonTransformNode!.animations.push(babylonAnimation);
  1111. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonTransformNode!);
  1112. }
  1113. }
  1114. });
  1115. }
  1116. private _loadAnimationSamplerAsync(context: string, sampler: IAnimationSampler): Promise<_IAnimationSamplerData> {
  1117. if (sampler._data) {
  1118. return sampler._data;
  1119. }
  1120. const interpolation = sampler.interpolation || AnimationSamplerInterpolation.LINEAR;
  1121. switch (interpolation) {
  1122. case AnimationSamplerInterpolation.STEP:
  1123. case AnimationSamplerInterpolation.LINEAR:
  1124. case AnimationSamplerInterpolation.CUBICSPLINE: {
  1125. break;
  1126. }
  1127. default: {
  1128. throw new Error(`${context}/interpolation: Invalid value (${sampler.interpolation})`);
  1129. }
  1130. }
  1131. const inputAccessor = ArrayItem.Get(`${context}/input`, this._gltf.accessors, sampler.input);
  1132. const outputAccessor = ArrayItem.Get(`${context}/output`, this._gltf.accessors, sampler.output);
  1133. sampler._data = Promise.all([
  1134. this._loadFloatAccessorAsync(`/accessors/${inputAccessor.index}`, inputAccessor),
  1135. this._loadFloatAccessorAsync(`/accessors/${outputAccessor.index}`, outputAccessor)
  1136. ]).then(([inputData, outputData]) => {
  1137. return {
  1138. input: inputData,
  1139. interpolation: interpolation,
  1140. output: outputData,
  1141. };
  1142. });
  1143. return sampler._data;
  1144. }
  1145. private _loadBufferAsync(context: string, buffer: IBuffer): Promise<ArrayBufferView> {
  1146. if (buffer._data) {
  1147. return buffer._data;
  1148. }
  1149. if (!buffer.uri) {
  1150. throw new Error(`${context}/uri: Value is missing`);
  1151. }
  1152. buffer._data = this.loadUriAsync(`${context}/uri`, buffer, buffer.uri);
  1153. return buffer._data;
  1154. }
  1155. /**
  1156. * Loads a glTF buffer view.
  1157. * @param context The context when loading the asset
  1158. * @param bufferView The glTF buffer view property
  1159. * @returns A promise that resolves with the loaded data when the load is complete
  1160. */
  1161. public loadBufferViewAsync(context: string, bufferView: IBufferView): Promise<ArrayBufferView> {
  1162. if (bufferView._data) {
  1163. return bufferView._data;
  1164. }
  1165. const buffer = ArrayItem.Get(`${context}/buffer`, this._gltf.buffers, bufferView.buffer);
  1166. bufferView._data = this._loadBufferAsync(`/buffers/${buffer.index}`, buffer).then((data) => {
  1167. try {
  1168. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1169. }
  1170. catch (e) {
  1171. throw new Error(`${context}: ${e.message}`);
  1172. }
  1173. });
  1174. return bufferView._data;
  1175. }
  1176. private _loadIndicesAccessorAsync(context: string, accessor: IAccessor): Promise<IndicesArray> {
  1177. if (accessor.type !== AccessorType.SCALAR) {
  1178. throw new Error(`${context}/type: Invalid value ${accessor.type}`);
  1179. }
  1180. if (accessor.componentType !== AccessorComponentType.UNSIGNED_BYTE &&
  1181. accessor.componentType !== AccessorComponentType.UNSIGNED_SHORT &&
  1182. accessor.componentType !== AccessorComponentType.UNSIGNED_INT) {
  1183. throw new Error(`${context}/componentType: Invalid value ${accessor.componentType}`);
  1184. }
  1185. if (accessor._data) {
  1186. return accessor._data as Promise<IndicesArray>;
  1187. }
  1188. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  1189. accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
  1190. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  1191. });
  1192. return accessor._data as Promise<IndicesArray>;
  1193. }
  1194. private _loadFloatAccessorAsync(context: string, accessor: IAccessor): Promise<Float32Array> {
  1195. // TODO: support normalized and stride
  1196. if (accessor.componentType !== AccessorComponentType.FLOAT) {
  1197. throw new Error(`Invalid component type ${accessor.componentType}`);
  1198. }
  1199. if (accessor._data) {
  1200. return accessor._data as Promise<Float32Array>;
  1201. }
  1202. const numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1203. const length = numComponents * accessor.count;
  1204. if (accessor.bufferView == undefined) {
  1205. accessor._data = Promise.resolve(new Float32Array(length));
  1206. }
  1207. else {
  1208. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  1209. accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
  1210. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  1211. });
  1212. }
  1213. if (accessor.sparse) {
  1214. const sparse = accessor.sparse;
  1215. accessor._data = accessor._data.then((view: ArrayBufferView) => {
  1216. const data = view as Float32Array;
  1217. const indicesBufferView = ArrayItem.Get(`${context}/sparse/indices/bufferView`, this._gltf.bufferViews, sparse.indices.bufferView);
  1218. const valuesBufferView = ArrayItem.Get(`${context}/sparse/values/bufferView`, this._gltf.bufferViews, sparse.values.bufferView);
  1219. return Promise.all([
  1220. this.loadBufferViewAsync(`/bufferViews/${indicesBufferView.index}`, indicesBufferView),
  1221. this.loadBufferViewAsync(`/bufferViews/${valuesBufferView.index}`, valuesBufferView)
  1222. ]).then(([indicesData, valuesData]) => {
  1223. const indices = GLTFLoader._GetTypedArray(`${context}/sparse/indices`, sparse.indices.componentType, indicesData, sparse.indices.byteOffset, sparse.count) as IndicesArray;
  1224. const values = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, numComponents * sparse.count) as Float32Array;
  1225. let valuesIndex = 0;
  1226. for (let indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  1227. let dataIndex = indices[indicesIndex] * numComponents;
  1228. for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1229. data[dataIndex++] = values[valuesIndex++];
  1230. }
  1231. }
  1232. return data;
  1233. });
  1234. });
  1235. }
  1236. return accessor._data as Promise<Float32Array>;
  1237. }
  1238. private _loadVertexBufferViewAsync(bufferView: IBufferView, kind: string): Promise<Buffer> {
  1239. if (bufferView._babylonBuffer) {
  1240. return bufferView._babylonBuffer;
  1241. }
  1242. bufferView._babylonBuffer = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
  1243. return new Buffer(this._babylonScene.getEngine(), data, false);
  1244. });
  1245. return bufferView._babylonBuffer;
  1246. }
  1247. private _loadVertexAccessorAsync(context: string, accessor: IAccessor, kind: string): Promise<VertexBuffer> {
  1248. if (accessor._babylonVertexBuffer) {
  1249. return accessor._babylonVertexBuffer;
  1250. }
  1251. if (accessor.sparse) {
  1252. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  1253. return new VertexBuffer(this._babylonScene.getEngine(), data, kind, false);
  1254. });
  1255. }
  1256. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  1257. else if (accessor.byteOffset && accessor.byteOffset % VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  1258. Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  1259. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  1260. return new VertexBuffer(this._babylonScene.getEngine(), data, kind, false);
  1261. });
  1262. }
  1263. else {
  1264. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  1265. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView, kind).then((babylonBuffer) => {
  1266. const size = GLTFLoader._GetNumComponents(context, accessor.type);
  1267. return new VertexBuffer(this._babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView.byteStride,
  1268. false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  1269. });
  1270. }
  1271. return accessor._babylonVertexBuffer;
  1272. }
  1273. private _loadMaterialMetallicRoughnessPropertiesAsync(context: string, properties: IMaterialPbrMetallicRoughness, babylonMaterial: Material): Promise<void> {
  1274. if (!(babylonMaterial instanceof PBRMaterial)) {
  1275. throw new Error(`${context}: Material type not supported`);
  1276. }
  1277. const promises = new Array<Promise<any>>();
  1278. if (properties) {
  1279. if (properties.baseColorFactor) {
  1280. babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);
  1281. babylonMaterial.alpha = properties.baseColorFactor[3];
  1282. }
  1283. else {
  1284. babylonMaterial.albedoColor = Color3.White();
  1285. }
  1286. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1287. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1288. if (properties.baseColorTexture) {
  1289. promises.push(this.loadTextureInfoAsync(`${context}/baseColorTexture`, properties.baseColorTexture, (texture) => {
  1290. texture.name = `${babylonMaterial.name} (Base Color)`;
  1291. babylonMaterial.albedoTexture = texture;
  1292. }));
  1293. }
  1294. if (properties.metallicRoughnessTexture) {
  1295. promises.push(this.loadTextureInfoAsync(`${context}/metallicRoughnessTexture`, properties.metallicRoughnessTexture, (texture) => {
  1296. texture.name = `${babylonMaterial.name} (Metallic Roughness)`;
  1297. babylonMaterial.metallicTexture = texture;
  1298. }));
  1299. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1300. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1301. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1302. }
  1303. }
  1304. return Promise.all(promises).then(() => { });
  1305. }
  1306. /** @hidden */
  1307. public _loadMaterialAsync(context: string, material: IMaterial, babylonMesh: Mesh, babylonDrawMode: number, assign: (babylonMaterial: Material) => void = () => { }): Promise<Material> {
  1308. const extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  1309. if (extensionPromise) {
  1310. return extensionPromise;
  1311. }
  1312. material._data = material._data || {};
  1313. let babylonData = material._data[babylonDrawMode];
  1314. if (!babylonData) {
  1315. this.logOpen(`${context} ${material.name || ""}`);
  1316. const babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  1317. babylonData = {
  1318. babylonMaterial: babylonMaterial,
  1319. babylonMeshes: [],
  1320. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  1321. };
  1322. material._data[babylonDrawMode] = babylonData;
  1323. GLTFLoader.AddPointerMetadata(babylonMaterial, context);
  1324. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1325. this.logClose();
  1326. }
  1327. babylonData.babylonMeshes.push(babylonMesh);
  1328. babylonMesh.onDisposeObservable.addOnce(() => {
  1329. const index = babylonData.babylonMeshes.indexOf(babylonMesh);
  1330. if (index !== -1) {
  1331. babylonData.babylonMeshes.splice(index, 1);
  1332. }
  1333. });
  1334. assign(babylonData.babylonMaterial);
  1335. return babylonData.promise.then(() => {
  1336. return babylonData.babylonMaterial;
  1337. });
  1338. }
  1339. private _createDefaultMaterial(name: string, babylonDrawMode: number): Material {
  1340. const babylonMaterial = new PBRMaterial(name, this._babylonScene);
  1341. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
  1342. babylonMaterial.fillMode = babylonDrawMode;
  1343. babylonMaterial.enableSpecularAntiAliasing = true;
  1344. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  1345. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  1346. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1347. babylonMaterial.metallic = 1;
  1348. babylonMaterial.roughness = 1;
  1349. return babylonMaterial;
  1350. }
  1351. /**
  1352. * Creates a Babylon material from a glTF material.
  1353. * @param context The context when loading the asset
  1354. * @param material The glTF material property
  1355. * @param babylonDrawMode The draw mode for the Babylon material
  1356. * @returns The Babylon material
  1357. */
  1358. public createMaterial(context: string, material: IMaterial, babylonDrawMode: number): Material {
  1359. const extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  1360. if (extensionPromise) {
  1361. return extensionPromise;
  1362. }
  1363. const name = material.name || `material${material.index}`;
  1364. const babylonMaterial = this._createDefaultMaterial(name, babylonDrawMode);
  1365. return babylonMaterial;
  1366. }
  1367. /**
  1368. * Loads properties from a glTF material into a Babylon material.
  1369. * @param context The context when loading the asset
  1370. * @param material The glTF material property
  1371. * @param babylonMaterial The Babylon material
  1372. * @returns A promise that resolves when the load is complete
  1373. */
  1374. public loadMaterialPropertiesAsync(context: string, material: IMaterial, babylonMaterial: Material): Promise<void> {
  1375. const extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  1376. if (extensionPromise) {
  1377. return extensionPromise;
  1378. }
  1379. const promises = new Array<Promise<any>>();
  1380. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  1381. if (material.pbrMetallicRoughness) {
  1382. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${context}/pbrMetallicRoughness`, material.pbrMetallicRoughness, babylonMaterial));
  1383. }
  1384. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  1385. return Promise.all(promises).then(() => { });
  1386. }
  1387. /**
  1388. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  1389. * @param context The context when loading the asset
  1390. * @param material The glTF material property
  1391. * @param babylonMaterial The Babylon material
  1392. * @returns A promise that resolves when the load is complete
  1393. */
  1394. public loadMaterialBasePropertiesAsync(context: string, material: IMaterial, babylonMaterial: Material): Promise<void> {
  1395. if (!(babylonMaterial instanceof PBRMaterial)) {
  1396. throw new Error(`${context}: Material type not supported`);
  1397. }
  1398. const promises = new Array<Promise<any>>();
  1399. babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  1400. if (material.doubleSided) {
  1401. babylonMaterial.backFaceCulling = false;
  1402. babylonMaterial.twoSidedLighting = true;
  1403. }
  1404. if (material.normalTexture) {
  1405. promises.push(this.loadTextureInfoAsync(`${context}/normalTexture`, material.normalTexture, (texture) => {
  1406. texture.name = `${babylonMaterial.name} (Normal)`;
  1407. babylonMaterial.bumpTexture = texture;
  1408. }));
  1409. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1410. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1411. if (material.normalTexture.scale != undefined) {
  1412. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1413. }
  1414. babylonMaterial.forceIrradianceInFragment = true;
  1415. }
  1416. if (material.occlusionTexture) {
  1417. promises.push(this.loadTextureInfoAsync(`${context}/occlusionTexture`, material.occlusionTexture, (texture) => {
  1418. texture.name = `${babylonMaterial.name} (Occlusion)`;
  1419. babylonMaterial.ambientTexture = texture;
  1420. }));
  1421. babylonMaterial.useAmbientInGrayScale = true;
  1422. if (material.occlusionTexture.strength != undefined) {
  1423. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1424. }
  1425. }
  1426. if (material.emissiveTexture) {
  1427. promises.push(this.loadTextureInfoAsync(`${context}/emissiveTexture`, material.emissiveTexture, (texture) => {
  1428. texture.name = `${babylonMaterial.name} (Emissive)`;
  1429. babylonMaterial.emissiveTexture = texture;
  1430. }));
  1431. }
  1432. return Promise.all(promises).then(() => { });
  1433. }
  1434. /**
  1435. * Loads the alpha properties from a glTF material into a Babylon material.
  1436. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  1437. * @param context The context when loading the asset
  1438. * @param material The glTF material property
  1439. * @param babylonMaterial The Babylon material
  1440. */
  1441. public loadMaterialAlphaProperties(context: string, material: IMaterial, babylonMaterial: Material): void {
  1442. if (!(babylonMaterial instanceof PBRMaterial)) {
  1443. throw new Error(`${context}: Material type not supported`);
  1444. }
  1445. const alphaMode = material.alphaMode || MaterialAlphaMode.OPAQUE;
  1446. switch (alphaMode) {
  1447. case MaterialAlphaMode.OPAQUE: {
  1448. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1449. break;
  1450. }
  1451. case MaterialAlphaMode.MASK: {
  1452. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;
  1453. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  1454. if (babylonMaterial.albedoTexture) {
  1455. babylonMaterial.albedoTexture.hasAlpha = true;
  1456. }
  1457. break;
  1458. }
  1459. case MaterialAlphaMode.BLEND: {
  1460. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1461. if (babylonMaterial.albedoTexture) {
  1462. babylonMaterial.albedoTexture.hasAlpha = true;
  1463. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1464. }
  1465. break;
  1466. }
  1467. default: {
  1468. throw new Error(`${context}/alphaMode: Invalid value (${material.alphaMode})`);
  1469. }
  1470. }
  1471. }
  1472. /**
  1473. * Loads a glTF texture info.
  1474. * @param context The context when loading the asset
  1475. * @param textureInfo The glTF texture info property
  1476. * @param assign A function called synchronously after parsing the glTF properties
  1477. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  1478. */
  1479. public loadTextureInfoAsync(context: string, textureInfo: ITextureInfo, assign: (babylonTexture: BaseTexture) => void = () => { }): Promise<BaseTexture> {
  1480. const extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  1481. if (extensionPromise) {
  1482. return extensionPromise;
  1483. }
  1484. this.logOpen(`${context}`);
  1485. const texture = ArrayItem.Get(`${context}/index`, this._gltf.textures, textureInfo.index);
  1486. const promise = this._loadTextureAsync(`/textures/${textureInfo.index}`, texture, (babylonTexture) => {
  1487. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  1488. GLTFLoader.AddPointerMetadata(babylonTexture, context);
  1489. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1490. assign(babylonTexture);
  1491. });
  1492. this.logClose();
  1493. return promise;
  1494. }
  1495. private _loadTextureAsync(context: string, texture: ITexture, assign: (babylonTexture: BaseTexture) => void = () => { }): Promise<BaseTexture> {
  1496. const promises = new Array<Promise<any>>();
  1497. this.logOpen(`${context} ${texture.name || ""}`);
  1498. const sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._gltf.samplers, texture.sampler));
  1499. const samplerData = this._loadSampler(`/samplers/${sampler.index}`, sampler);
  1500. const image = ArrayItem.Get(`${context}/source`, this._gltf.images, texture.source);
  1501. let url: Nullable<string> = null;
  1502. if (image.uri) {
  1503. if (Tools.IsBase64(image.uri)) {
  1504. url = image.uri;
  1505. }
  1506. else if (this._babylonScene.getEngine().textureFormatInUse) {
  1507. // If an image uri and a texture format is set like (eg. KTX) load from url instead of blob to support texture format and fallback
  1508. url = this._rootUrl + image.uri;
  1509. }
  1510. }
  1511. const deferred = new Deferred<void>();
  1512. const babylonTexture = new Texture(url, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, () => {
  1513. if (!this._disposed) {
  1514. deferred.resolve();
  1515. }
  1516. }, (message, exception) => {
  1517. if (!this._disposed) {
  1518. deferred.reject(new Error(`${context}: ${(exception && exception.message) ? exception.message : message || "Failed to load texture"}`));
  1519. }
  1520. });
  1521. promises.push(deferred.promise);
  1522. if (!url) {
  1523. promises.push(this.loadImageAsync(`/images/${image.index}`, image).then((data) => {
  1524. const name = image.uri || `${this._fileName}#image${image.index}`;
  1525. const dataUrl = `data:${this._uniqueRootUrl}${name}`;
  1526. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  1527. }));
  1528. }
  1529. babylonTexture.wrapU = samplerData.wrapU;
  1530. babylonTexture.wrapV = samplerData.wrapV;
  1531. assign(babylonTexture);
  1532. this.logClose();
  1533. return Promise.all(promises).then(() => {
  1534. return babylonTexture;
  1535. });
  1536. }
  1537. private _loadSampler(context: string, sampler: ISampler): _ISamplerData {
  1538. if (!sampler._data) {
  1539. sampler._data = {
  1540. noMipMaps: (sampler.minFilter === TextureMinFilter.NEAREST || sampler.minFilter === TextureMinFilter.LINEAR),
  1541. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  1542. wrapU: GLTFLoader._GetTextureWrapMode(`${context}/wrapS`, sampler.wrapS),
  1543. wrapV: GLTFLoader._GetTextureWrapMode(`${context}/wrapT`, sampler.wrapT)
  1544. };
  1545. }
  1546. return sampler._data;
  1547. }
  1548. /**
  1549. * Loads a glTF image.
  1550. * @param context The context when loading the asset
  1551. * @param image The glTF image property
  1552. * @returns A promise that resolves with the loaded data when the load is complete
  1553. */
  1554. public loadImageAsync(context: string, image: IImage): Promise<ArrayBufferView> {
  1555. if (!image._data) {
  1556. this.logOpen(`${context} ${image.name || ""}`);
  1557. if (image.uri) {
  1558. image._data = this.loadUriAsync(`${context}/uri`, image, image.uri);
  1559. }
  1560. else {
  1561. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, image.bufferView);
  1562. image._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView);
  1563. }
  1564. this.logClose();
  1565. }
  1566. return image._data;
  1567. }
  1568. /**
  1569. * Loads a glTF uri.
  1570. * @param context The context when loading the asset
  1571. * @param property The glTF property associated with the uri
  1572. * @param uri The base64 or relative uri
  1573. * @returns A promise that resolves with the loaded data when the load is complete
  1574. */
  1575. public loadUriAsync(context: string, property: IProperty, uri: string): Promise<ArrayBufferView> {
  1576. const extensionPromise = this._extensionsLoadUriAsync(context, property, uri);
  1577. if (extensionPromise) {
  1578. return extensionPromise;
  1579. }
  1580. if (!GLTFLoader._ValidateUri(uri)) {
  1581. throw new Error(`${context}: '${uri}' is invalid`);
  1582. }
  1583. if (Tools.IsBase64(uri)) {
  1584. const data = new Uint8Array(Tools.DecodeBase64(uri));
  1585. this.log(`Decoded ${uri.substr(0, 64)}... (${data.length} bytes)`);
  1586. return Promise.resolve(data);
  1587. }
  1588. this.log(`Loading ${uri}`);
  1589. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then((url) => {
  1590. return new Promise<ArrayBufferView>((resolve, reject) => {
  1591. if (!this._disposed) {
  1592. const request = Tools.LoadFile(url, (fileData) => {
  1593. if (!this._disposed) {
  1594. const data = new Uint8Array(fileData as ArrayBuffer);
  1595. this.log(`Loaded ${uri} (${data.length} bytes)`);
  1596. resolve(data);
  1597. }
  1598. }, (event) => {
  1599. if (!this._disposed) {
  1600. if (request) {
  1601. request._lengthComputable = event.lengthComputable;
  1602. request._loaded = event.loaded;
  1603. request._total = event.total;
  1604. }
  1605. if (this._state === GLTFLoaderState.LOADING) {
  1606. try {
  1607. this._onProgress();
  1608. }
  1609. catch (e) {
  1610. reject(e);
  1611. }
  1612. }
  1613. }
  1614. }, this._babylonScene.offlineProvider, true, (request, exception) => {
  1615. if (!this._disposed) {
  1616. reject(new LoadFileError(`${context}: Failed to load '${uri}'${request ? ": " + request.status + " " + request.statusText : ""}`, request));
  1617. }
  1618. }) as IFileRequestInfo;
  1619. this._requests.push(request);
  1620. }
  1621. });
  1622. });
  1623. }
  1624. private _onProgress(): void {
  1625. if (!this._progressCallback) {
  1626. return;
  1627. }
  1628. let lengthComputable = true;
  1629. let loaded = 0;
  1630. let total = 0;
  1631. for (let request of this._requests) {
  1632. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  1633. return;
  1634. }
  1635. lengthComputable = lengthComputable && request._lengthComputable;
  1636. loaded += request._loaded;
  1637. total += request._total;
  1638. }
  1639. this._progressCallback(new SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  1640. }
  1641. /**
  1642. * Adds a JSON pointer to the metadata of the Babylon object at `<object>.metadata.gltf.pointers`.
  1643. * @param babylonObject the Babylon object with metadata
  1644. * @param pointer the JSON pointer
  1645. */
  1646. public static AddPointerMetadata(babylonObject: { metadata: any }, pointer: string): void {
  1647. const metadata = (babylonObject.metadata = babylonObject.metadata || {});
  1648. const gltf = (metadata.gltf = metadata.gltf || {});
  1649. const pointers = (gltf.pointers = gltf.pointers || []);
  1650. pointers.push(pointer);
  1651. }
  1652. private static _GetTextureWrapMode(context: string, mode: TextureWrapMode | undefined): number {
  1653. // Set defaults if undefined
  1654. mode = mode == undefined ? TextureWrapMode.REPEAT : mode;
  1655. switch (mode) {
  1656. case TextureWrapMode.CLAMP_TO_EDGE: return Texture.CLAMP_ADDRESSMODE;
  1657. case TextureWrapMode.MIRRORED_REPEAT: return Texture.MIRROR_ADDRESSMODE;
  1658. case TextureWrapMode.REPEAT: return Texture.WRAP_ADDRESSMODE;
  1659. default:
  1660. Tools.Warn(`${context}: Invalid value (${mode})`);
  1661. return Texture.WRAP_ADDRESSMODE;
  1662. }
  1663. }
  1664. private static _GetTextureSamplingMode(context: string, sampler: ISampler): number {
  1665. // Set defaults if undefined
  1666. const magFilter = sampler.magFilter == undefined ? TextureMagFilter.LINEAR : sampler.magFilter;
  1667. const minFilter = sampler.minFilter == undefined ? TextureMinFilter.LINEAR_MIPMAP_LINEAR : sampler.minFilter;
  1668. if (magFilter === TextureMagFilter.LINEAR) {
  1669. switch (minFilter) {
  1670. case TextureMinFilter.NEAREST: return Texture.LINEAR_NEAREST;
  1671. case TextureMinFilter.LINEAR: return Texture.LINEAR_LINEAR;
  1672. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.LINEAR_NEAREST_MIPNEAREST;
  1673. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.LINEAR_LINEAR_MIPNEAREST;
  1674. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.LINEAR_NEAREST_MIPLINEAR;
  1675. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.LINEAR_LINEAR_MIPLINEAR;
  1676. default:
  1677. Tools.Warn(`${context}/minFilter: Invalid value (${minFilter})`);
  1678. return Texture.LINEAR_LINEAR_MIPLINEAR;
  1679. }
  1680. }
  1681. else {
  1682. if (magFilter !== TextureMagFilter.NEAREST) {
  1683. Tools.Warn(`${context}/magFilter: Invalid value (${magFilter})`);
  1684. }
  1685. switch (minFilter) {
  1686. case TextureMinFilter.NEAREST: return Texture.NEAREST_NEAREST;
  1687. case TextureMinFilter.LINEAR: return Texture.NEAREST_LINEAR;
  1688. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.NEAREST_NEAREST_MIPNEAREST;
  1689. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.NEAREST_LINEAR_MIPNEAREST;
  1690. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.NEAREST_NEAREST_MIPLINEAR;
  1691. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.NEAREST_LINEAR_MIPLINEAR;
  1692. default:
  1693. Tools.Warn(`${context}/minFilter: Invalid value (${minFilter})`);
  1694. return Texture.NEAREST_NEAREST_MIPNEAREST;
  1695. }
  1696. }
  1697. }
  1698. private static _GetTypedArray(context: string, componentType: AccessorComponentType, bufferView: ArrayBufferView, byteOffset: number | undefined, length: number): ArrayBufferView {
  1699. const buffer = bufferView.buffer;
  1700. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  1701. try {
  1702. switch (componentType) {
  1703. case AccessorComponentType.BYTE: return new Int8Array(buffer, byteOffset, length);
  1704. case AccessorComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, length);
  1705. case AccessorComponentType.SHORT: return new Int16Array(buffer, byteOffset, length);
  1706. case AccessorComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, length);
  1707. case AccessorComponentType.UNSIGNED_INT: return new Uint32Array(buffer, byteOffset, length);
  1708. case AccessorComponentType.FLOAT: return new Float32Array(buffer, byteOffset, length);
  1709. default: throw new Error(`Invalid component type ${componentType}`);
  1710. }
  1711. }
  1712. catch (e) {
  1713. throw new Error(`${context}: ${e}`);
  1714. }
  1715. }
  1716. private static _GetNumComponents(context: string, type: string): number {
  1717. switch (type) {
  1718. case "SCALAR": return 1;
  1719. case "VEC2": return 2;
  1720. case "VEC3": return 3;
  1721. case "VEC4": return 4;
  1722. case "MAT2": return 4;
  1723. case "MAT3": return 9;
  1724. case "MAT4": return 16;
  1725. }
  1726. throw new Error(`${context}: Invalid type (${type})`);
  1727. }
  1728. private static _ValidateUri(uri: string): boolean {
  1729. return (Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  1730. }
  1731. private static _GetDrawMode(context: string, mode: number | undefined): number {
  1732. if (mode == undefined) {
  1733. mode = MeshPrimitiveMode.TRIANGLES;
  1734. }
  1735. switch (mode) {
  1736. case MeshPrimitiveMode.POINTS: return Material.PointListDrawMode;
  1737. case MeshPrimitiveMode.LINES: return Material.LineListDrawMode;
  1738. case MeshPrimitiveMode.LINE_LOOP: return Material.LineLoopDrawMode;
  1739. case MeshPrimitiveMode.LINE_STRIP: return Material.LineStripDrawMode;
  1740. case MeshPrimitiveMode.TRIANGLES: return Material.TriangleFillMode;
  1741. case MeshPrimitiveMode.TRIANGLE_STRIP: return Material.TriangleStripDrawMode;
  1742. case MeshPrimitiveMode.TRIANGLE_FAN: return Material.TriangleFanDrawMode;
  1743. }
  1744. throw new Error(`${context}: Invalid mesh primitive mode (${mode})`);
  1745. }
  1746. private _compileMaterialsAsync(): Promise<void> {
  1747. this._parent._startPerformanceCounter("Compile materials");
  1748. const promises = new Array<Promise<any>>();
  1749. if (this._gltf.materials) {
  1750. for (const material of this._gltf.materials) {
  1751. if (material._data) {
  1752. for (const babylonDrawMode in material._data) {
  1753. const babylonData = material._data[babylonDrawMode];
  1754. for (const babylonMesh of babylonData.babylonMeshes) {
  1755. // Ensure nonUniformScaling is set if necessary.
  1756. babylonMesh.computeWorldMatrix(true);
  1757. const babylonMaterial = babylonData.babylonMaterial;
  1758. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  1759. if (this._parent.useClipPlane) {
  1760. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  1761. }
  1762. }
  1763. }
  1764. }
  1765. }
  1766. }
  1767. return Promise.all(promises).then(() => {
  1768. this._parent._endPerformanceCounter("Compile materials");
  1769. });
  1770. }
  1771. private _compileShadowGeneratorsAsync(): Promise<void> {
  1772. this._parent._startPerformanceCounter("Compile shadow generators");
  1773. const promises = new Array<Promise<any>>();
  1774. const lights = this._babylonScene.lights;
  1775. for (let light of lights) {
  1776. let generator = light.getShadowGenerator();
  1777. if (generator) {
  1778. promises.push(generator.forceCompilationAsync());
  1779. }
  1780. }
  1781. return Promise.all(promises).then(() => {
  1782. this._parent._endPerformanceCounter("Compile shadow generators");
  1783. });
  1784. }
  1785. private _forEachExtensions(action: (extension: IGLTFLoaderExtension) => void): void {
  1786. for (const name of GLTFLoader._ExtensionNames) {
  1787. const extension = this._extensions[name];
  1788. if (extension.enabled) {
  1789. action(extension);
  1790. }
  1791. }
  1792. }
  1793. private _applyExtensions<T>(property: IProperty, functionName: string, actionAsync: (extension: IGLTFLoaderExtension) => Nullable<T> | undefined): Nullable<T> {
  1794. for (const name of GLTFLoader._ExtensionNames) {
  1795. const extension = this._extensions[name];
  1796. if (extension.enabled) {
  1797. const id = `${name}.${functionName}`;
  1798. const loaderProperty = property as ILoaderProperty;
  1799. loaderProperty._activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions || {};
  1800. const activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions;
  1801. if (!activeLoaderExtensionFunctions[id]) {
  1802. activeLoaderExtensionFunctions[id] = true;
  1803. try {
  1804. const result = actionAsync(extension);
  1805. if (result) {
  1806. return result;
  1807. }
  1808. }
  1809. finally {
  1810. delete activeLoaderExtensionFunctions[id];
  1811. }
  1812. }
  1813. }
  1814. }
  1815. return null;
  1816. }
  1817. private _extensionsOnLoading(): void {
  1818. this._forEachExtensions((extension) => extension.onLoading && extension.onLoading());
  1819. }
  1820. private _extensionsOnReady(): void {
  1821. this._forEachExtensions((extension) => extension.onReady && extension.onReady());
  1822. }
  1823. private _extensionsLoadSceneAsync(context: string, scene: IScene): Nullable<Promise<void>> {
  1824. return this._applyExtensions(scene, "loadScene", (extension) => extension.loadSceneAsync && extension.loadSceneAsync(context, scene));
  1825. }
  1826. private _extensionsLoadNodeAsync(context: string, node: INode, assign: (babylonTransformNode: TransformNode) => void): Nullable<Promise<TransformNode>> {
  1827. return this._applyExtensions(node, "loadNode", (extension) => extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign));
  1828. }
  1829. private _extensionsLoadCameraAsync(context: string, camera: ICamera, assign: (babylonCamera: Camera) => void): Nullable<Promise<Camera>> {
  1830. return this._applyExtensions(camera, "loadCamera", (extension) => extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign));
  1831. }
  1832. private _extensionsLoadVertexDataAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh): Nullable<Promise<Geometry>> {
  1833. return this._applyExtensions(primitive, "loadVertexData", (extension) => extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh));
  1834. }
  1835. private _extensionsLoadMeshPrimitiveAsync(context: string, name: string, node: INode, mesh: IMesh, primitive: IMeshPrimitive, assign: (babylonMesh: AbstractMesh) => void): Nullable<Promise<AbstractMesh>> {
  1836. return this._applyExtensions(primitive, "loadMeshPrimitive", (extension) => extension._loadMeshPrimitiveAsync && extension._loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign));
  1837. }
  1838. private _extensionsLoadMaterialAsync(context: string, material: IMaterial, babylonMesh: Mesh, babylonDrawMode: number, assign: (babylonMaterial: Material) => void): Nullable<Promise<Material>> {
  1839. return this._applyExtensions(material, "loadMaterial", (extension) => extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign));
  1840. }
  1841. private _extensionsCreateMaterial(context: string, material: IMaterial, babylonDrawMode: number): Nullable<Material> {
  1842. return this._applyExtensions(material, "createMaterial", (extension) => extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode));
  1843. }
  1844. private _extensionsLoadMaterialPropertiesAsync(context: string, material: IMaterial, babylonMaterial: Material): Nullable<Promise<void>> {
  1845. return this._applyExtensions(material, "loadMaterialProperties", (extension) => extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial));
  1846. }
  1847. private _extensionsLoadTextureInfoAsync(context: string, textureInfo: ITextureInfo, assign: (babylonTexture: BaseTexture) => void): Nullable<Promise<BaseTexture>> {
  1848. return this._applyExtensions(textureInfo, "loadTextureInfo", (extension) => extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign));
  1849. }
  1850. private _extensionsLoadAnimationAsync(context: string, animation: IAnimation): Nullable<Promise<AnimationGroup>> {
  1851. return this._applyExtensions(animation, "loadAnimation", (extension) => extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation));
  1852. }
  1853. private _extensionsLoadSkinAsync(context: string, node: INode, skin: ISkin): Nullable<Promise<void>> {
  1854. return this._applyExtensions(skin, "loadSkin", (extension) => extension._loadSkinAsync && extension._loadSkinAsync(context, node, skin));
  1855. }
  1856. private _extensionsLoadUriAsync(context: string, property: IProperty, uri: string): Nullable<Promise<ArrayBufferView>> {
  1857. return this._applyExtensions(property, "loadUri", (extension) => extension._loadUriAsync && extension._loadUriAsync(context, property, uri));
  1858. }
  1859. /**
  1860. * Helper method called by a loader extension to load an glTF extension.
  1861. * @param context The context when loading the asset
  1862. * @param property The glTF property to load the extension from
  1863. * @param extensionName The name of the extension to load
  1864. * @param actionAsync The action to run
  1865. * @returns The promise returned by actionAsync or null if the extension does not exist
  1866. */
  1867. public static LoadExtensionAsync<TExtension = any, TResult = void>(context: string, property: IProperty, extensionName: string, actionAsync: (extensionContext: string, extension: TExtension) => Nullable<Promise<TResult>>): Nullable<Promise<TResult>> {
  1868. if (!property.extensions) {
  1869. return null;
  1870. }
  1871. const extensions = property.extensions;
  1872. const extension = extensions[extensionName] as TExtension;
  1873. if (!extension) {
  1874. return null;
  1875. }
  1876. return actionAsync(`${context}/extensions/${extensionName}`, extension);
  1877. }
  1878. /**
  1879. * Helper method called by a loader extension to load a glTF extra.
  1880. * @param context The context when loading the asset
  1881. * @param property The glTF property to load the extra from
  1882. * @param extensionName The name of the extension to load
  1883. * @param actionAsync The action to run
  1884. * @returns The promise returned by actionAsync or null if the extra does not exist
  1885. */
  1886. public static LoadExtraAsync<TExtra = any, TResult = void>(context: string, property: IProperty, extensionName: string, actionAsync: (extraContext: string, extra: TExtra) => Nullable<Promise<TResult>>): Nullable<Promise<TResult>> {
  1887. if (!property.extras) {
  1888. return null;
  1889. }
  1890. const extras = property.extras;
  1891. const extra = extras[extensionName] as TExtra;
  1892. if (!extra) {
  1893. return null;
  1894. }
  1895. return actionAsync(`${context}/extras/${extensionName}`, extra);
  1896. }
  1897. /**
  1898. * Increments the indentation level and logs a message.
  1899. * @param message The message to log
  1900. */
  1901. public logOpen(message: string): void {
  1902. this._parent._logOpen(message);
  1903. }
  1904. /**
  1905. * Decrements the indentation level.
  1906. */
  1907. public logClose(): void {
  1908. this._parent._logClose();
  1909. }
  1910. /**
  1911. * Logs a message
  1912. * @param message The message to log
  1913. */
  1914. public log(message: string): void {
  1915. this._parent._log(message);
  1916. }
  1917. /**
  1918. * Starts a performance counter.
  1919. * @param counterName The name of the performance counter
  1920. */
  1921. public startPerformanceCounter(counterName: string): void {
  1922. this._parent._startPerformanceCounter(counterName);
  1923. }
  1924. /**
  1925. * Ends a performance counter.
  1926. * @param counterName The name of the performance counter
  1927. */
  1928. public endPerformanceCounter(counterName: string): void {
  1929. this._parent._endPerformanceCounter(counterName);
  1930. }
  1931. }
  1932. GLTFFileLoader._CreateGLTF2Loader = (parent) => new GLTFLoader(parent);