glTFLoader.ts 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259
  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, 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. private _loadMeshPrimitiveAsync(context: string, name: string, node: INode, mesh: IMesh, primitive: IMeshPrimitive, assign: (babylonMesh: AbstractMesh) => void): Promise<AbstractMesh> {
  582. this.logOpen(`${context}`);
  583. const canInstance = (node.skin == undefined && !mesh.primitives[0].targets);
  584. let babylonAbstractMesh: AbstractMesh;
  585. let promise: Promise<any>;
  586. const instanceData = primitive._instanceData;
  587. if (canInstance && instanceData) {
  588. babylonAbstractMesh = instanceData.babylonSourceMesh.createInstance(name);
  589. promise = instanceData.promise;
  590. }
  591. else {
  592. const promises = new Array<Promise<any>>();
  593. const babylonMesh = new Mesh(name, this._babylonScene);
  594. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  595. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then((babylonGeometry) => {
  596. return this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(() => {
  597. babylonGeometry.applyToMesh(babylonMesh);
  598. });
  599. }));
  600. const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  601. if (primitive.material == undefined) {
  602. let babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  603. if (!babylonMaterial) {
  604. babylonMaterial = this._createDefaultMaterial("__GLTFLoader._default", babylonDrawMode);
  605. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  606. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  607. }
  608. babylonMesh.material = babylonMaterial;
  609. }
  610. else {
  611. const material = ArrayItem.Get(`${context}/material`, this._gltf.materials, primitive.material);
  612. promises.push(this._loadMaterialAsync(`/materials/${material.index}`, material, babylonMesh, babylonDrawMode, (babylonMaterial) => {
  613. babylonMesh.material = babylonMaterial;
  614. }));
  615. }
  616. promise = Promise.all(promises);
  617. if (canInstance) {
  618. primitive._instanceData = {
  619. babylonSourceMesh: babylonMesh,
  620. promise: promise
  621. };
  622. }
  623. babylonAbstractMesh = babylonMesh;
  624. }
  625. GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context);
  626. this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh);
  627. assign(babylonAbstractMesh);
  628. this.logClose();
  629. return promise.then(() => {
  630. return babylonAbstractMesh;
  631. });
  632. }
  633. private _loadVertexDataAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh): Promise<Geometry> {
  634. const extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  635. if (extensionPromise) {
  636. return extensionPromise;
  637. }
  638. const attributes = primitive.attributes;
  639. if (!attributes) {
  640. throw new Error(`${context}: Attributes are missing`);
  641. }
  642. const promises = new Array<Promise<any>>();
  643. const babylonGeometry = new Geometry(babylonMesh.name, this._babylonScene);
  644. if (primitive.indices == undefined) {
  645. babylonMesh.isUnIndexed = true;
  646. }
  647. else {
  648. const accessor = ArrayItem.Get(`${context}/indices`, this._gltf.accessors, primitive.indices);
  649. promises.push(this._loadIndicesAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  650. babylonGeometry.setIndices(data);
  651. }));
  652. }
  653. const loadAttribute = (attribute: string, kind: string, callback?: (accessor: IAccessor) => void) => {
  654. if (attributes[attribute] == undefined) {
  655. return;
  656. }
  657. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  658. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  659. babylonMesh._delayInfo.push(kind);
  660. }
  661. const accessor = ArrayItem.Get(`${context}/attributes/${attribute}`, this._gltf.accessors, attributes[attribute]);
  662. promises.push(this._loadVertexAccessorAsync(`/accessors/${accessor.index}`, accessor, kind).then((babylonVertexBuffer) => {
  663. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  664. }));
  665. if (callback) {
  666. callback(accessor);
  667. }
  668. };
  669. loadAttribute("POSITION", VertexBuffer.PositionKind);
  670. loadAttribute("NORMAL", VertexBuffer.NormalKind);
  671. loadAttribute("TANGENT", VertexBuffer.TangentKind);
  672. loadAttribute("TEXCOORD_0", VertexBuffer.UVKind);
  673. loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind);
  674. loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind);
  675. loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind);
  676. loadAttribute("COLOR_0", VertexBuffer.ColorKind, (accessor) => {
  677. if (accessor.type === AccessorType.VEC4) {
  678. babylonMesh.hasVertexAlpha = true;
  679. }
  680. });
  681. return Promise.all(promises).then(() => {
  682. return babylonGeometry;
  683. });
  684. }
  685. private _createMorphTargets(context: string, node: INode, mesh: IMesh, primitive: IMeshPrimitive, babylonMesh: Mesh): void {
  686. if (!primitive.targets) {
  687. return;
  688. }
  689. if (node._numMorphTargets == undefined) {
  690. node._numMorphTargets = primitive.targets.length;
  691. }
  692. else if (primitive.targets.length !== node._numMorphTargets) {
  693. throw new Error(`${context}: Primitives do not have the same number of targets`);
  694. }
  695. babylonMesh.morphTargetManager = new MorphTargetManager();
  696. for (let index = 0; index < primitive.targets.length; index++) {
  697. const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  698. babylonMesh.morphTargetManager.addTarget(new MorphTarget(`morphTarget${index}`, weight));
  699. // TODO: tell the target whether it has positions, normals, tangents
  700. }
  701. }
  702. private _loadMorphTargetsAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh, babylonGeometry: Geometry): Promise<void> {
  703. if (!primitive.targets) {
  704. return Promise.resolve();
  705. }
  706. const promises = new Array<Promise<any>>();
  707. const morphTargetManager = babylonMesh.morphTargetManager!;
  708. for (let index = 0; index < morphTargetManager.numTargets; index++) {
  709. const babylonMorphTarget = morphTargetManager.getTarget(index);
  710. promises.push(this._loadMorphTargetVertexDataAsync(`${context}/targets/${index}`, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  711. }
  712. return Promise.all(promises).then(() => { });
  713. }
  714. private _loadMorphTargetVertexDataAsync(context: string, babylonGeometry: Geometry, attributes: { [name: string]: number }, babylonMorphTarget: MorphTarget): Promise<void> {
  715. const promises = new Array<Promise<any>>();
  716. const loadAttribute = (attribute: string, kind: string, setData: (babylonVertexBuffer: VertexBuffer, data: Float32Array) => void) => {
  717. if (attributes[attribute] == undefined) {
  718. return;
  719. }
  720. const babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  721. if (!babylonVertexBuffer) {
  722. return;
  723. }
  724. const accessor = ArrayItem.Get(`${context}/${attribute}`, this._gltf.accessors, attributes[attribute]);
  725. promises.push(this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  726. setData(babylonVertexBuffer, data);
  727. }));
  728. };
  729. loadAttribute("POSITION", VertexBuffer.PositionKind, (babylonVertexBuffer, data) => {
  730. babylonVertexBuffer.forEach(data.length, (value, index) => {
  731. data[index] += value;
  732. });
  733. babylonMorphTarget.setPositions(data);
  734. });
  735. loadAttribute("NORMAL", VertexBuffer.NormalKind, (babylonVertexBuffer, data) => {
  736. babylonVertexBuffer.forEach(data.length, (value, index) => {
  737. data[index] += value;
  738. });
  739. babylonMorphTarget.setNormals(data);
  740. });
  741. loadAttribute("TANGENT", VertexBuffer.TangentKind, (babylonVertexBuffer, data) => {
  742. let dataIndex = 0;
  743. babylonVertexBuffer.forEach(data.length / 3 * 4, (value, index) => {
  744. // Tangent data for morph targets is stored as xyz delta.
  745. // The vertexData.tangent is stored as xyzw.
  746. // So we need to skip every fourth vertexData.tangent.
  747. if (((index + 1) % 4) !== 0) {
  748. data[dataIndex++] += value;
  749. }
  750. });
  751. babylonMorphTarget.setTangents(data);
  752. });
  753. return Promise.all(promises).then(() => { });
  754. }
  755. private static _LoadTransform(node: INode, babylonNode: TransformNode): void {
  756. // Ignore the TRS of skinned nodes.
  757. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  758. if (node.skin != undefined) {
  759. return;
  760. }
  761. let position = Vector3.Zero();
  762. let rotation = Quaternion.Identity();
  763. let scaling = Vector3.One();
  764. if (node.matrix) {
  765. const matrix = Matrix.FromArray(node.matrix);
  766. matrix.decompose(scaling, rotation, position);
  767. }
  768. else {
  769. if (node.translation) { position = Vector3.FromArray(node.translation); }
  770. if (node.rotation) { rotation = Quaternion.FromArray(node.rotation); }
  771. if (node.scale) { scaling = Vector3.FromArray(node.scale); }
  772. }
  773. babylonNode.position = position;
  774. babylonNode.rotationQuaternion = rotation;
  775. babylonNode.scaling = scaling;
  776. }
  777. private _loadSkinAsync(context: string, node: INode, skin: ISkin): Promise<void> {
  778. const assignSkeleton = (skeleton: Skeleton) => {
  779. this._forEachPrimitive(node, (babylonMesh) => {
  780. babylonMesh.skeleton = skeleton;
  781. });
  782. };
  783. if (skin._data) {
  784. assignSkeleton(skin._data.babylonSkeleton);
  785. return skin._data.promise;
  786. }
  787. const skeletonId = `skeleton${skin.index}`;
  788. const babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  789. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  790. babylonSkeleton.overrideMesh = this._rootBabylonMesh;
  791. this._loadBones(context, skin, babylonSkeleton);
  792. assignSkeleton(babylonSkeleton);
  793. const promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then((inverseBindMatricesData) => {
  794. this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  795. });
  796. skin._data = {
  797. babylonSkeleton: babylonSkeleton,
  798. promise: promise
  799. };
  800. return promise;
  801. }
  802. private _loadBones(context: string, skin: ISkin, babylonSkeleton: Skeleton): void {
  803. const babylonBones: { [index: number]: Bone } = {};
  804. for (const index of skin.joints) {
  805. const node = ArrayItem.Get(`${context}/joints/${index}`, this._gltf.nodes, index);
  806. this._loadBone(node, skin, babylonSkeleton, babylonBones);
  807. }
  808. }
  809. private _loadBone(node: INode, skin: ISkin, babylonSkeleton: Skeleton, babylonBones: { [index: number]: Bone }): Bone {
  810. let babylonBone = babylonBones[node.index];
  811. if (babylonBone) {
  812. return babylonBone;
  813. }
  814. let babylonParentBone: Nullable<Bone> = null;
  815. if (node.parent && node.parent._babylonTransformNode !== this._rootBabylonMesh) {
  816. babylonParentBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones);
  817. }
  818. const boneIndex = skin.joints.indexOf(node.index);
  819. babylonBone = new Bone(node.name || `joint${node.index}`, babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  820. babylonBones[node.index] = babylonBone;
  821. node._babylonBones = node._babylonBones || [];
  822. node._babylonBones.push(babylonBone);
  823. return babylonBone;
  824. }
  825. private _loadSkinInverseBindMatricesDataAsync(context: string, skin: ISkin): Promise<Nullable<Float32Array>> {
  826. if (skin.inverseBindMatrices == undefined) {
  827. return Promise.resolve(null);
  828. }
  829. const accessor = ArrayItem.Get(`${context}/inverseBindMatrices`, this._gltf.accessors, skin.inverseBindMatrices);
  830. return this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor);
  831. }
  832. private _updateBoneMatrices(babylonSkeleton: Skeleton, inverseBindMatricesData: Nullable<Float32Array>): void {
  833. for (const babylonBone of babylonSkeleton.bones) {
  834. let baseMatrix = Matrix.Identity();
  835. const boneIndex = babylonBone._index!;
  836. if (inverseBindMatricesData && boneIndex !== -1) {
  837. Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  838. baseMatrix.invertToRef(baseMatrix);
  839. }
  840. const babylonParentBone = babylonBone.getParent();
  841. if (babylonParentBone) {
  842. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  843. }
  844. babylonBone.updateMatrix(baseMatrix, false, false);
  845. babylonBone._updateDifferenceMatrix(undefined, false);
  846. }
  847. }
  848. private _getNodeMatrix(node: INode): Matrix {
  849. return node.matrix ?
  850. Matrix.FromArray(node.matrix) :
  851. Matrix.Compose(
  852. node.scale ? Vector3.FromArray(node.scale) : Vector3.One(),
  853. node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(),
  854. node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());
  855. }
  856. /**
  857. * Loads a glTF camera.
  858. * @param context The context when loading the asset
  859. * @param camera The glTF camera property
  860. * @param assign A function called synchronously after parsing the glTF properties
  861. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  862. */
  863. public loadCameraAsync(context: string, camera: ICamera, assign: (babylonCamera: Camera) => void = () => { }): Promise<Camera> {
  864. const extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  865. if (extensionPromise) {
  866. return extensionPromise;
  867. }
  868. const promises = new Array<Promise<any>>();
  869. this.logOpen(`${context} ${camera.name || ""}`);
  870. const babylonCamera = new FreeCamera(camera.name || `camera${camera.index}`, Vector3.Zero(), this._babylonScene, false);
  871. babylonCamera.rotation = new Vector3(0, Math.PI, 0);
  872. switch (camera.type) {
  873. case CameraType.PERSPECTIVE: {
  874. const perspective = camera.perspective;
  875. if (!perspective) {
  876. throw new Error(`${context}: Camera perspective properties are missing`);
  877. }
  878. babylonCamera.fov = perspective.yfov;
  879. babylonCamera.minZ = perspective.znear;
  880. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  881. break;
  882. }
  883. case CameraType.ORTHOGRAPHIC: {
  884. if (!camera.orthographic) {
  885. throw new Error(`${context}: Camera orthographic properties are missing`);
  886. }
  887. babylonCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  888. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  889. babylonCamera.orthoRight = camera.orthographic.xmag;
  890. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  891. babylonCamera.orthoTop = camera.orthographic.ymag;
  892. babylonCamera.minZ = camera.orthographic.znear;
  893. babylonCamera.maxZ = camera.orthographic.zfar;
  894. break;
  895. }
  896. default: {
  897. throw new Error(`${context}: Invalid camera type (${camera.type})`);
  898. }
  899. }
  900. GLTFLoader.AddPointerMetadata(babylonCamera, context);
  901. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  902. assign(babylonCamera);
  903. return Promise.all(promises).then(() => {
  904. return babylonCamera;
  905. });
  906. }
  907. private _loadAnimationsAsync(): Promise<void> {
  908. const animations = this._gltf.animations;
  909. if (!animations) {
  910. return Promise.resolve();
  911. }
  912. const promises = new Array<Promise<any>>();
  913. for (let index = 0; index < animations.length; index++) {
  914. const animation = animations[index];
  915. promises.push(this.loadAnimationAsync(`/animations/${animation.index}`, animation));
  916. }
  917. return Promise.all(promises).then(() => { });
  918. }
  919. /**
  920. * Loads a glTF animation.
  921. * @param context The context when loading the asset
  922. * @param animation The glTF animation property
  923. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  924. */
  925. public loadAnimationAsync(context: string, animation: IAnimation): Promise<AnimationGroup> {
  926. const promise = this._extensionsLoadAnimationAsync(context, animation);
  927. if (promise) {
  928. return promise;
  929. }
  930. const babylonAnimationGroup = new AnimationGroup(animation.name || `animation${animation.index}`, this._babylonScene);
  931. animation._babylonAnimationGroup = babylonAnimationGroup;
  932. const promises = new Array<Promise<any>>();
  933. ArrayItem.Assign(animation.channels);
  934. ArrayItem.Assign(animation.samplers);
  935. for (const channel of animation.channels) {
  936. promises.push(this._loadAnimationChannelAsync(`${context}/channels/${channel.index}`, context, animation, channel, babylonAnimationGroup));
  937. }
  938. return Promise.all(promises).then(() => {
  939. babylonAnimationGroup.normalize(0);
  940. return babylonAnimationGroup;
  941. });
  942. }
  943. private _loadAnimationChannelAsync(context: string, animationContext: string, animation: IAnimation, channel: IAnimationChannel, babylonAnimationGroup: AnimationGroup): Promise<void> {
  944. if (channel.target.node == undefined) {
  945. return Promise.resolve();
  946. }
  947. const targetNode = ArrayItem.Get(`${context}/target/node`, this._gltf.nodes, channel.target.node);
  948. // Ignore animations that have no animation targets.
  949. if ((channel.target.path === AnimationChannelTargetPath.WEIGHTS && !targetNode._numMorphTargets) ||
  950. (channel.target.path !== AnimationChannelTargetPath.WEIGHTS && !targetNode._babylonTransformNode)) {
  951. return Promise.resolve();
  952. }
  953. const sampler = ArrayItem.Get(`${context}/sampler`, animation.samplers, channel.sampler);
  954. return this._loadAnimationSamplerAsync(`${animationContext}/samplers/${channel.sampler}`, sampler).then((data) => {
  955. let targetPath: string;
  956. let animationType: number;
  957. switch (channel.target.path) {
  958. case AnimationChannelTargetPath.TRANSLATION: {
  959. targetPath = "position";
  960. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  961. break;
  962. }
  963. case AnimationChannelTargetPath.ROTATION: {
  964. targetPath = "rotationQuaternion";
  965. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  966. break;
  967. }
  968. case AnimationChannelTargetPath.SCALE: {
  969. targetPath = "scaling";
  970. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  971. break;
  972. }
  973. case AnimationChannelTargetPath.WEIGHTS: {
  974. targetPath = "influence";
  975. animationType = Animation.ANIMATIONTYPE_FLOAT;
  976. break;
  977. }
  978. default: {
  979. throw new Error(`${context}/target/path: Invalid value (${channel.target.path})`);
  980. }
  981. }
  982. let outputBufferOffset = 0;
  983. let getNextOutputValue: () => Vector3 | Quaternion | Array<number>;
  984. switch (targetPath) {
  985. case "position": {
  986. getNextOutputValue = () => {
  987. const value = Vector3.FromArray(data.output, outputBufferOffset);
  988. outputBufferOffset += 3;
  989. return value;
  990. };
  991. break;
  992. }
  993. case "rotationQuaternion": {
  994. getNextOutputValue = () => {
  995. const value = Quaternion.FromArray(data.output, outputBufferOffset);
  996. outputBufferOffset += 4;
  997. return value;
  998. };
  999. break;
  1000. }
  1001. case "scaling": {
  1002. getNextOutputValue = () => {
  1003. const value = Vector3.FromArray(data.output, outputBufferOffset);
  1004. outputBufferOffset += 3;
  1005. return value;
  1006. };
  1007. break;
  1008. }
  1009. case "influence": {
  1010. getNextOutputValue = () => {
  1011. const value = new Array<number>(targetNode._numMorphTargets!);
  1012. for (let i = 0; i < targetNode._numMorphTargets!; i++) {
  1013. value[i] = data.output[outputBufferOffset++];
  1014. }
  1015. return value;
  1016. };
  1017. break;
  1018. }
  1019. }
  1020. let getNextKey: (frameIndex: number) => IAnimationKey;
  1021. switch (data.interpolation) {
  1022. case AnimationSamplerInterpolation.STEP: {
  1023. getNextKey = (frameIndex) => ({
  1024. frame: data.input[frameIndex],
  1025. value: getNextOutputValue(),
  1026. interpolation: AnimationKeyInterpolation.STEP
  1027. });
  1028. break;
  1029. }
  1030. case AnimationSamplerInterpolation.LINEAR: {
  1031. getNextKey = (frameIndex) => ({
  1032. frame: data.input[frameIndex],
  1033. value: getNextOutputValue()
  1034. });
  1035. break;
  1036. }
  1037. case AnimationSamplerInterpolation.CUBICSPLINE: {
  1038. getNextKey = (frameIndex) => ({
  1039. frame: data.input[frameIndex],
  1040. inTangent: getNextOutputValue(),
  1041. value: getNextOutputValue(),
  1042. outTangent: getNextOutputValue()
  1043. });
  1044. break;
  1045. }
  1046. }
  1047. const keys = new Array(data.input.length);
  1048. for (let frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  1049. keys[frameIndex] = getNextKey!(frameIndex);
  1050. }
  1051. if (targetPath === "influence") {
  1052. for (let targetIndex = 0; targetIndex < targetNode._numMorphTargets!; targetIndex++) {
  1053. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  1054. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  1055. babylonAnimation.setKeys(keys.map((key) => ({
  1056. frame: key.frame,
  1057. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1058. value: key.value[targetIndex],
  1059. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1060. })));
  1061. this._forEachPrimitive(targetNode, (babylonAbstractMesh: AbstractMesh) => {
  1062. const babylonMesh = babylonAbstractMesh as Mesh;
  1063. const morphTarget = babylonMesh.morphTargetManager!.getTarget(targetIndex);
  1064. const babylonAnimationClone = babylonAnimation.clone();
  1065. morphTarget.animations.push(babylonAnimationClone);
  1066. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  1067. });
  1068. }
  1069. }
  1070. else {
  1071. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  1072. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  1073. babylonAnimation.setKeys(keys);
  1074. targetNode._babylonTransformNode!.animations.push(babylonAnimation);
  1075. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonTransformNode!);
  1076. }
  1077. });
  1078. }
  1079. private _loadAnimationSamplerAsync(context: string, sampler: IAnimationSampler): Promise<_IAnimationSamplerData> {
  1080. if (sampler._data) {
  1081. return sampler._data;
  1082. }
  1083. const interpolation = sampler.interpolation || AnimationSamplerInterpolation.LINEAR;
  1084. switch (interpolation) {
  1085. case AnimationSamplerInterpolation.STEP:
  1086. case AnimationSamplerInterpolation.LINEAR:
  1087. case AnimationSamplerInterpolation.CUBICSPLINE: {
  1088. break;
  1089. }
  1090. default: {
  1091. throw new Error(`${context}/interpolation: Invalid value (${sampler.interpolation})`);
  1092. }
  1093. }
  1094. const inputAccessor = ArrayItem.Get(`${context}/input`, this._gltf.accessors, sampler.input);
  1095. const outputAccessor = ArrayItem.Get(`${context}/output`, this._gltf.accessors, sampler.output);
  1096. sampler._data = Promise.all([
  1097. this._loadFloatAccessorAsync(`/accessors/${inputAccessor.index}`, inputAccessor),
  1098. this._loadFloatAccessorAsync(`/accessors/${outputAccessor.index}`, outputAccessor)
  1099. ]).then(([inputData, outputData]) => {
  1100. return {
  1101. input: inputData,
  1102. interpolation: interpolation,
  1103. output: outputData,
  1104. };
  1105. });
  1106. return sampler._data;
  1107. }
  1108. private _loadBufferAsync(context: string, buffer: IBuffer): Promise<ArrayBufferView> {
  1109. if (buffer._data) {
  1110. return buffer._data;
  1111. }
  1112. if (!buffer.uri) {
  1113. throw new Error(`${context}/uri: Value is missing`);
  1114. }
  1115. buffer._data = this.loadUriAsync(`${context}/uri`, buffer, buffer.uri);
  1116. return buffer._data;
  1117. }
  1118. /**
  1119. * Loads a glTF buffer view.
  1120. * @param context The context when loading the asset
  1121. * @param bufferView The glTF buffer view property
  1122. * @returns A promise that resolves with the loaded data when the load is complete
  1123. */
  1124. public loadBufferViewAsync(context: string, bufferView: IBufferView): Promise<ArrayBufferView> {
  1125. if (bufferView._data) {
  1126. return bufferView._data;
  1127. }
  1128. const buffer = ArrayItem.Get(`${context}/buffer`, this._gltf.buffers, bufferView.buffer);
  1129. bufferView._data = this._loadBufferAsync(`/buffers/${buffer.index}`, buffer).then((data) => {
  1130. try {
  1131. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1132. }
  1133. catch (e) {
  1134. throw new Error(`${context}: ${e.message}`);
  1135. }
  1136. });
  1137. return bufferView._data;
  1138. }
  1139. private _loadIndicesAccessorAsync(context: string, accessor: IAccessor): Promise<IndicesArray> {
  1140. if (accessor.type !== AccessorType.SCALAR) {
  1141. throw new Error(`${context}/type: Invalid value ${accessor.type}`);
  1142. }
  1143. if (accessor.componentType !== AccessorComponentType.UNSIGNED_BYTE &&
  1144. accessor.componentType !== AccessorComponentType.UNSIGNED_SHORT &&
  1145. accessor.componentType !== AccessorComponentType.UNSIGNED_INT) {
  1146. throw new Error(`${context}/componentType: Invalid value ${accessor.componentType}`);
  1147. }
  1148. if (accessor._data) {
  1149. return accessor._data as Promise<IndicesArray>;
  1150. }
  1151. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  1152. accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
  1153. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  1154. });
  1155. return accessor._data as Promise<IndicesArray>;
  1156. }
  1157. private _loadFloatAccessorAsync(context: string, accessor: IAccessor): Promise<Float32Array> {
  1158. // TODO: support normalized and stride
  1159. if (accessor.componentType !== AccessorComponentType.FLOAT) {
  1160. throw new Error(`Invalid component type ${accessor.componentType}`);
  1161. }
  1162. if (accessor._data) {
  1163. return accessor._data as Promise<Float32Array>;
  1164. }
  1165. const numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1166. const length = numComponents * accessor.count;
  1167. if (accessor.bufferView == undefined) {
  1168. accessor._data = Promise.resolve(new Float32Array(length));
  1169. }
  1170. else {
  1171. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  1172. accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
  1173. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  1174. });
  1175. }
  1176. if (accessor.sparse) {
  1177. const sparse = accessor.sparse;
  1178. accessor._data = accessor._data.then((view: ArrayBufferView) => {
  1179. const data = view as Float32Array;
  1180. const indicesBufferView = ArrayItem.Get(`${context}/sparse/indices/bufferView`, this._gltf.bufferViews, sparse.indices.bufferView);
  1181. const valuesBufferView = ArrayItem.Get(`${context}/sparse/values/bufferView`, this._gltf.bufferViews, sparse.values.bufferView);
  1182. return Promise.all([
  1183. this.loadBufferViewAsync(`/bufferViews/${indicesBufferView.index}`, indicesBufferView),
  1184. this.loadBufferViewAsync(`/bufferViews/${valuesBufferView.index}`, valuesBufferView)
  1185. ]).then(([indicesData, valuesData]) => {
  1186. const indices = GLTFLoader._GetTypedArray(`${context}/sparse/indices`, sparse.indices.componentType, indicesData, sparse.indices.byteOffset, sparse.count) as IndicesArray;
  1187. const values = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, numComponents * sparse.count) as Float32Array;
  1188. let valuesIndex = 0;
  1189. for (let indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  1190. let dataIndex = indices[indicesIndex] * numComponents;
  1191. for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1192. data[dataIndex++] = values[valuesIndex++];
  1193. }
  1194. }
  1195. return data;
  1196. });
  1197. });
  1198. }
  1199. return accessor._data as Promise<Float32Array>;
  1200. }
  1201. private _loadVertexBufferViewAsync(bufferView: IBufferView, kind: string): Promise<Buffer> {
  1202. if (bufferView._babylonBuffer) {
  1203. return bufferView._babylonBuffer;
  1204. }
  1205. bufferView._babylonBuffer = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
  1206. return new Buffer(this._babylonScene.getEngine(), data, false);
  1207. });
  1208. return bufferView._babylonBuffer;
  1209. }
  1210. private _loadVertexAccessorAsync(context: string, accessor: IAccessor, kind: string): Promise<VertexBuffer> {
  1211. if (accessor._babylonVertexBuffer) {
  1212. return accessor._babylonVertexBuffer;
  1213. }
  1214. if (accessor.sparse) {
  1215. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  1216. return new VertexBuffer(this._babylonScene.getEngine(), data, kind, false);
  1217. });
  1218. }
  1219. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  1220. else if (accessor.byteOffset && accessor.byteOffset % VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  1221. Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  1222. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  1223. return new VertexBuffer(this._babylonScene.getEngine(), data, kind, false);
  1224. });
  1225. }
  1226. else {
  1227. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  1228. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView, kind).then((babylonBuffer) => {
  1229. const size = GLTFLoader._GetNumComponents(context, accessor.type);
  1230. return new VertexBuffer(this._babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView.byteStride,
  1231. false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  1232. });
  1233. }
  1234. return accessor._babylonVertexBuffer;
  1235. }
  1236. private _loadMaterialMetallicRoughnessPropertiesAsync(context: string, properties: IMaterialPbrMetallicRoughness, babylonMaterial: Material): Promise<void> {
  1237. if (!(babylonMaterial instanceof PBRMaterial)) {
  1238. throw new Error(`${context}: Material type not supported`);
  1239. }
  1240. const promises = new Array<Promise<any>>();
  1241. if (properties) {
  1242. if (properties.baseColorFactor) {
  1243. babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);
  1244. babylonMaterial.alpha = properties.baseColorFactor[3];
  1245. }
  1246. else {
  1247. babylonMaterial.albedoColor = Color3.White();
  1248. }
  1249. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1250. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1251. if (properties.baseColorTexture) {
  1252. promises.push(this.loadTextureInfoAsync(`${context}/baseColorTexture`, properties.baseColorTexture, (texture) => {
  1253. texture.name = `${babylonMaterial.name} (Base Color)`;
  1254. babylonMaterial.albedoTexture = texture;
  1255. }));
  1256. }
  1257. if (properties.metallicRoughnessTexture) {
  1258. promises.push(this.loadTextureInfoAsync(`${context}/metallicRoughnessTexture`, properties.metallicRoughnessTexture, (texture) => {
  1259. texture.name = `${babylonMaterial.name} (Metallic Roughness)`;
  1260. babylonMaterial.metallicTexture = texture;
  1261. }));
  1262. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1263. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1264. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1265. }
  1266. }
  1267. return Promise.all(promises).then(() => { });
  1268. }
  1269. /** @hidden */
  1270. public _loadMaterialAsync(context: string, material: IMaterial, babylonMesh: Mesh, babylonDrawMode: number, assign: (babylonMaterial: Material) => void = () => { }): Promise<Material> {
  1271. const extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  1272. if (extensionPromise) {
  1273. return extensionPromise;
  1274. }
  1275. material._data = material._data || {};
  1276. let babylonData = material._data[babylonDrawMode];
  1277. if (!babylonData) {
  1278. this.logOpen(`${context} ${material.name || ""}`);
  1279. const babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  1280. babylonData = {
  1281. babylonMaterial: babylonMaterial,
  1282. babylonMeshes: [],
  1283. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  1284. };
  1285. material._data[babylonDrawMode] = babylonData;
  1286. GLTFLoader.AddPointerMetadata(babylonMaterial, context);
  1287. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1288. this.logClose();
  1289. }
  1290. babylonData.babylonMeshes.push(babylonMesh);
  1291. babylonMesh.onDisposeObservable.addOnce(() => {
  1292. const index = babylonData.babylonMeshes.indexOf(babylonMesh);
  1293. if (index !== -1) {
  1294. babylonData.babylonMeshes.splice(index, 1);
  1295. }
  1296. });
  1297. assign(babylonData.babylonMaterial);
  1298. return babylonData.promise.then(() => {
  1299. return babylonData.babylonMaterial;
  1300. });
  1301. }
  1302. private _createDefaultMaterial(name: string, babylonDrawMode: number): Material {
  1303. const babylonMaterial = new PBRMaterial(name, this._babylonScene);
  1304. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
  1305. babylonMaterial.fillMode = babylonDrawMode;
  1306. babylonMaterial.enableSpecularAntiAliasing = true;
  1307. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  1308. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  1309. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1310. babylonMaterial.metallic = 1;
  1311. babylonMaterial.roughness = 1;
  1312. return babylonMaterial;
  1313. }
  1314. /**
  1315. * Creates a Babylon material from a glTF material.
  1316. * @param context The context when loading the asset
  1317. * @param material The glTF material property
  1318. * @param babylonDrawMode The draw mode for the Babylon material
  1319. * @returns The Babylon material
  1320. */
  1321. public createMaterial(context: string, material: IMaterial, babylonDrawMode: number): Material {
  1322. const extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  1323. if (extensionPromise) {
  1324. return extensionPromise;
  1325. }
  1326. const name = material.name || `material${material.index}`;
  1327. const babylonMaterial = this._createDefaultMaterial(name, babylonDrawMode);
  1328. return babylonMaterial;
  1329. }
  1330. /**
  1331. * Loads properties from a glTF material into a Babylon material.
  1332. * @param context The context when loading the asset
  1333. * @param material The glTF material property
  1334. * @param babylonMaterial The Babylon material
  1335. * @returns A promise that resolves when the load is complete
  1336. */
  1337. public loadMaterialPropertiesAsync(context: string, material: IMaterial, babylonMaterial: Material): Promise<void> {
  1338. const extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  1339. if (extensionPromise) {
  1340. return extensionPromise;
  1341. }
  1342. const promises = new Array<Promise<any>>();
  1343. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  1344. if (material.pbrMetallicRoughness) {
  1345. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${context}/pbrMetallicRoughness`, material.pbrMetallicRoughness, babylonMaterial));
  1346. }
  1347. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  1348. return Promise.all(promises).then(() => { });
  1349. }
  1350. /**
  1351. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  1352. * @param context The context when loading the asset
  1353. * @param material The glTF material property
  1354. * @param babylonMaterial The Babylon material
  1355. * @returns A promise that resolves when the load is complete
  1356. */
  1357. public loadMaterialBasePropertiesAsync(context: string, material: IMaterial, babylonMaterial: Material): Promise<void> {
  1358. if (!(babylonMaterial instanceof PBRMaterial)) {
  1359. throw new Error(`${context}: Material type not supported`);
  1360. }
  1361. const promises = new Array<Promise<any>>();
  1362. babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  1363. if (material.doubleSided) {
  1364. babylonMaterial.backFaceCulling = false;
  1365. babylonMaterial.twoSidedLighting = true;
  1366. }
  1367. if (material.normalTexture) {
  1368. promises.push(this.loadTextureInfoAsync(`${context}/normalTexture`, material.normalTexture, (texture) => {
  1369. texture.name = `${babylonMaterial.name} (Normal)`;
  1370. babylonMaterial.bumpTexture = texture;
  1371. }));
  1372. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1373. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1374. if (material.normalTexture.scale != undefined) {
  1375. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1376. }
  1377. babylonMaterial.forceIrradianceInFragment = true;
  1378. }
  1379. if (material.occlusionTexture) {
  1380. promises.push(this.loadTextureInfoAsync(`${context}/occlusionTexture`, material.occlusionTexture, (texture) => {
  1381. texture.name = `${babylonMaterial.name} (Occlusion)`;
  1382. babylonMaterial.ambientTexture = texture;
  1383. }));
  1384. babylonMaterial.useAmbientInGrayScale = true;
  1385. if (material.occlusionTexture.strength != undefined) {
  1386. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1387. }
  1388. }
  1389. if (material.emissiveTexture) {
  1390. promises.push(this.loadTextureInfoAsync(`${context}/emissiveTexture`, material.emissiveTexture, (texture) => {
  1391. texture.name = `${babylonMaterial.name} (Emissive)`;
  1392. babylonMaterial.emissiveTexture = texture;
  1393. }));
  1394. }
  1395. return Promise.all(promises).then(() => { });
  1396. }
  1397. /**
  1398. * Loads the alpha properties from a glTF material into a Babylon material.
  1399. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  1400. * @param context The context when loading the asset
  1401. * @param material The glTF material property
  1402. * @param babylonMaterial The Babylon material
  1403. */
  1404. public loadMaterialAlphaProperties(context: string, material: IMaterial, babylonMaterial: Material): void {
  1405. if (!(babylonMaterial instanceof PBRMaterial)) {
  1406. throw new Error(`${context}: Material type not supported`);
  1407. }
  1408. const alphaMode = material.alphaMode || MaterialAlphaMode.OPAQUE;
  1409. switch (alphaMode) {
  1410. case MaterialAlphaMode.OPAQUE: {
  1411. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1412. break;
  1413. }
  1414. case MaterialAlphaMode.MASK: {
  1415. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;
  1416. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  1417. if (babylonMaterial.albedoTexture) {
  1418. babylonMaterial.albedoTexture.hasAlpha = true;
  1419. }
  1420. break;
  1421. }
  1422. case MaterialAlphaMode.BLEND: {
  1423. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1424. if (babylonMaterial.albedoTexture) {
  1425. babylonMaterial.albedoTexture.hasAlpha = true;
  1426. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1427. }
  1428. break;
  1429. }
  1430. default: {
  1431. throw new Error(`${context}/alphaMode: Invalid value (${material.alphaMode})`);
  1432. }
  1433. }
  1434. }
  1435. /**
  1436. * Loads a glTF texture info.
  1437. * @param context The context when loading the asset
  1438. * @param textureInfo The glTF texture info property
  1439. * @param assign A function called synchronously after parsing the glTF properties
  1440. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  1441. */
  1442. public loadTextureInfoAsync(context: string, textureInfo: ITextureInfo, assign: (babylonTexture: BaseTexture) => void = () => { }): Promise<BaseTexture> {
  1443. const extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  1444. if (extensionPromise) {
  1445. return extensionPromise;
  1446. }
  1447. this.logOpen(`${context}`);
  1448. const texture = ArrayItem.Get(`${context}/index`, this._gltf.textures, textureInfo.index);
  1449. const promise = this._loadTextureAsync(`/textures/${textureInfo.index}`, texture, (babylonTexture) => {
  1450. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  1451. GLTFLoader.AddPointerMetadata(babylonTexture, context);
  1452. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1453. assign(babylonTexture);
  1454. });
  1455. this.logClose();
  1456. return promise;
  1457. }
  1458. private _loadTextureAsync(context: string, texture: ITexture, assign: (babylonTexture: BaseTexture) => void = () => { }): Promise<BaseTexture> {
  1459. const promises = new Array<Promise<any>>();
  1460. this.logOpen(`${context} ${texture.name || ""}`);
  1461. const sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._gltf.samplers, texture.sampler));
  1462. const samplerData = this._loadSampler(`/samplers/${sampler.index}`, sampler);
  1463. const image = ArrayItem.Get(`${context}/source`, this._gltf.images, texture.source);
  1464. let url: Nullable<string> = null;
  1465. if (image.uri) {
  1466. if (Tools.IsBase64(image.uri)) {
  1467. url = image.uri;
  1468. }
  1469. else if (this._babylonScene.getEngine().textureFormatInUse) {
  1470. // 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
  1471. url = this._rootUrl + image.uri;
  1472. }
  1473. }
  1474. const deferred = new Deferred<void>();
  1475. const babylonTexture = new Texture(url, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, () => {
  1476. if (!this._disposed) {
  1477. deferred.resolve();
  1478. }
  1479. }, (message, exception) => {
  1480. if (!this._disposed) {
  1481. deferred.reject(new Error(`${context}: ${(exception && exception.message) ? exception.message : message || "Failed to load texture"}`));
  1482. }
  1483. });
  1484. promises.push(deferred.promise);
  1485. if (!url) {
  1486. promises.push(this.loadImageAsync(`/images/${image.index}`, image).then((data) => {
  1487. const name = image.uri || `${this._fileName}#image${image.index}`;
  1488. const dataUrl = `data:${this._uniqueRootUrl}${name}`;
  1489. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  1490. }));
  1491. }
  1492. babylonTexture.wrapU = samplerData.wrapU;
  1493. babylonTexture.wrapV = samplerData.wrapV;
  1494. assign(babylonTexture);
  1495. this.logClose();
  1496. return Promise.all(promises).then(() => {
  1497. return babylonTexture;
  1498. });
  1499. }
  1500. private _loadSampler(context: string, sampler: ISampler): _ISamplerData {
  1501. if (!sampler._data) {
  1502. sampler._data = {
  1503. noMipMaps: (sampler.minFilter === TextureMinFilter.NEAREST || sampler.minFilter === TextureMinFilter.LINEAR),
  1504. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  1505. wrapU: GLTFLoader._GetTextureWrapMode(`${context}/wrapS`, sampler.wrapS),
  1506. wrapV: GLTFLoader._GetTextureWrapMode(`${context}/wrapT`, sampler.wrapT)
  1507. };
  1508. }
  1509. return sampler._data;
  1510. }
  1511. /**
  1512. * Loads a glTF image.
  1513. * @param context The context when loading the asset
  1514. * @param image The glTF image property
  1515. * @returns A promise that resolves with the loaded data when the load is complete
  1516. */
  1517. public loadImageAsync(context: string, image: IImage): Promise<ArrayBufferView> {
  1518. if (!image._data) {
  1519. this.logOpen(`${context} ${image.name || ""}`);
  1520. if (image.uri) {
  1521. image._data = this.loadUriAsync(`${context}/uri`, image, image.uri);
  1522. }
  1523. else {
  1524. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, image.bufferView);
  1525. image._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView);
  1526. }
  1527. this.logClose();
  1528. }
  1529. return image._data;
  1530. }
  1531. /**
  1532. * Loads a glTF uri.
  1533. * @param context The context when loading the asset
  1534. * @param property The glTF property associated with the uri
  1535. * @param uri The base64 or relative uri
  1536. * @returns A promise that resolves with the loaded data when the load is complete
  1537. */
  1538. public loadUriAsync(context: string, property: IProperty, uri: string): Promise<ArrayBufferView> {
  1539. const extensionPromise = this._extensionsLoadUriAsync(context, property, uri);
  1540. if (extensionPromise) {
  1541. return extensionPromise;
  1542. }
  1543. if (!GLTFLoader._ValidateUri(uri)) {
  1544. throw new Error(`${context}: '${uri}' is invalid`);
  1545. }
  1546. if (Tools.IsBase64(uri)) {
  1547. const data = new Uint8Array(Tools.DecodeBase64(uri));
  1548. this.log(`Decoded ${uri.substr(0, 64)}... (${data.length} bytes)`);
  1549. return Promise.resolve(data);
  1550. }
  1551. this.log(`Loading ${uri}`);
  1552. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then((url) => {
  1553. return new Promise<ArrayBufferView>((resolve, reject) => {
  1554. if (!this._disposed) {
  1555. const request = Tools.LoadFile(url, (fileData) => {
  1556. if (!this._disposed) {
  1557. const data = new Uint8Array(fileData as ArrayBuffer);
  1558. this.log(`Loaded ${uri} (${data.length} bytes)`);
  1559. resolve(data);
  1560. }
  1561. }, (event) => {
  1562. if (!this._disposed) {
  1563. if (request) {
  1564. request._lengthComputable = event.lengthComputable;
  1565. request._loaded = event.loaded;
  1566. request._total = event.total;
  1567. }
  1568. if (this._state === GLTFLoaderState.LOADING) {
  1569. try {
  1570. this._onProgress();
  1571. }
  1572. catch (e) {
  1573. reject(e);
  1574. }
  1575. }
  1576. }
  1577. }, this._babylonScene.offlineProvider, true, (request, exception) => {
  1578. if (!this._disposed) {
  1579. reject(new LoadFileError(`${context}: Failed to load '${uri}'${request ? ": " + request.status + " " + request.statusText : ""}`, request));
  1580. }
  1581. }) as IFileRequestInfo;
  1582. this._requests.push(request);
  1583. }
  1584. });
  1585. });
  1586. }
  1587. private _onProgress(): void {
  1588. if (!this._progressCallback) {
  1589. return;
  1590. }
  1591. let lengthComputable = true;
  1592. let loaded = 0;
  1593. let total = 0;
  1594. for (let request of this._requests) {
  1595. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  1596. return;
  1597. }
  1598. lengthComputable = lengthComputable && request._lengthComputable;
  1599. loaded += request._loaded;
  1600. total += request._total;
  1601. }
  1602. this._progressCallback(new SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  1603. }
  1604. /**
  1605. * Adds a JSON pointer to the metadata of the Babylon object at `<object>.metadata.gltf.pointers`.
  1606. * @param babylonObject the Babylon object with metadata
  1607. * @param pointer the JSON pointer
  1608. */
  1609. public static AddPointerMetadata(babylonObject: { metadata: any }, pointer: string): void {
  1610. const metadata = (babylonObject.metadata = babylonObject.metadata || {});
  1611. const gltf = (metadata.gltf = metadata.gltf || {});
  1612. const pointers = (gltf.pointers = gltf.pointers || []);
  1613. pointers.push(pointer);
  1614. }
  1615. private static _GetTextureWrapMode(context: string, mode: TextureWrapMode | undefined): number {
  1616. // Set defaults if undefined
  1617. mode = mode == undefined ? TextureWrapMode.REPEAT : mode;
  1618. switch (mode) {
  1619. case TextureWrapMode.CLAMP_TO_EDGE: return Texture.CLAMP_ADDRESSMODE;
  1620. case TextureWrapMode.MIRRORED_REPEAT: return Texture.MIRROR_ADDRESSMODE;
  1621. case TextureWrapMode.REPEAT: return Texture.WRAP_ADDRESSMODE;
  1622. default:
  1623. Tools.Warn(`${context}: Invalid value (${mode})`);
  1624. return Texture.WRAP_ADDRESSMODE;
  1625. }
  1626. }
  1627. private static _GetTextureSamplingMode(context: string, sampler: ISampler): number {
  1628. // Set defaults if undefined
  1629. const magFilter = sampler.magFilter == undefined ? TextureMagFilter.LINEAR : sampler.magFilter;
  1630. const minFilter = sampler.minFilter == undefined ? TextureMinFilter.LINEAR_MIPMAP_LINEAR : sampler.minFilter;
  1631. if (magFilter === TextureMagFilter.LINEAR) {
  1632. switch (minFilter) {
  1633. case TextureMinFilter.NEAREST: return Texture.LINEAR_NEAREST;
  1634. case TextureMinFilter.LINEAR: return Texture.LINEAR_LINEAR;
  1635. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.LINEAR_NEAREST_MIPNEAREST;
  1636. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.LINEAR_LINEAR_MIPNEAREST;
  1637. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.LINEAR_NEAREST_MIPLINEAR;
  1638. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.LINEAR_LINEAR_MIPLINEAR;
  1639. default:
  1640. Tools.Warn(`${context}/minFilter: Invalid value (${minFilter})`);
  1641. return Texture.LINEAR_LINEAR_MIPLINEAR;
  1642. }
  1643. }
  1644. else {
  1645. if (magFilter !== TextureMagFilter.NEAREST) {
  1646. Tools.Warn(`${context}/magFilter: Invalid value (${magFilter})`);
  1647. }
  1648. switch (minFilter) {
  1649. case TextureMinFilter.NEAREST: return Texture.NEAREST_NEAREST;
  1650. case TextureMinFilter.LINEAR: return Texture.NEAREST_LINEAR;
  1651. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.NEAREST_NEAREST_MIPNEAREST;
  1652. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.NEAREST_LINEAR_MIPNEAREST;
  1653. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.NEAREST_NEAREST_MIPLINEAR;
  1654. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.NEAREST_LINEAR_MIPLINEAR;
  1655. default:
  1656. Tools.Warn(`${context}/minFilter: Invalid value (${minFilter})`);
  1657. return Texture.NEAREST_NEAREST_MIPNEAREST;
  1658. }
  1659. }
  1660. }
  1661. private static _GetTypedArray(context: string, componentType: AccessorComponentType, bufferView: ArrayBufferView, byteOffset: number | undefined, length: number): ArrayBufferView {
  1662. const buffer = bufferView.buffer;
  1663. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  1664. try {
  1665. switch (componentType) {
  1666. case AccessorComponentType.BYTE: return new Int8Array(buffer, byteOffset, length);
  1667. case AccessorComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, length);
  1668. case AccessorComponentType.SHORT: return new Int16Array(buffer, byteOffset, length);
  1669. case AccessorComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, length);
  1670. case AccessorComponentType.UNSIGNED_INT: return new Uint32Array(buffer, byteOffset, length);
  1671. case AccessorComponentType.FLOAT: return new Float32Array(buffer, byteOffset, length);
  1672. default: throw new Error(`Invalid component type ${componentType}`);
  1673. }
  1674. }
  1675. catch (e) {
  1676. throw new Error(`${context}: ${e}`);
  1677. }
  1678. }
  1679. private static _GetNumComponents(context: string, type: string): number {
  1680. switch (type) {
  1681. case "SCALAR": return 1;
  1682. case "VEC2": return 2;
  1683. case "VEC3": return 3;
  1684. case "VEC4": return 4;
  1685. case "MAT2": return 4;
  1686. case "MAT3": return 9;
  1687. case "MAT4": return 16;
  1688. }
  1689. throw new Error(`${context}: Invalid type (${type})`);
  1690. }
  1691. private static _ValidateUri(uri: string): boolean {
  1692. return (Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  1693. }
  1694. private static _GetDrawMode(context: string, mode: number | undefined): number {
  1695. if (mode == undefined) {
  1696. mode = MeshPrimitiveMode.TRIANGLES;
  1697. }
  1698. switch (mode) {
  1699. case MeshPrimitiveMode.POINTS: return Material.PointListDrawMode;
  1700. case MeshPrimitiveMode.LINES: return Material.LineListDrawMode;
  1701. case MeshPrimitiveMode.LINE_LOOP: return Material.LineLoopDrawMode;
  1702. case MeshPrimitiveMode.LINE_STRIP: return Material.LineStripDrawMode;
  1703. case MeshPrimitiveMode.TRIANGLES: return Material.TriangleFillMode;
  1704. case MeshPrimitiveMode.TRIANGLE_STRIP: return Material.TriangleStripDrawMode;
  1705. case MeshPrimitiveMode.TRIANGLE_FAN: return Material.TriangleFanDrawMode;
  1706. }
  1707. throw new Error(`${context}: Invalid mesh primitive mode (${mode})`);
  1708. }
  1709. private _compileMaterialsAsync(): Promise<void> {
  1710. this._parent._startPerformanceCounter("Compile materials");
  1711. const promises = new Array<Promise<any>>();
  1712. if (this._gltf.materials) {
  1713. for (const material of this._gltf.materials) {
  1714. if (material._data) {
  1715. for (const babylonDrawMode in material._data) {
  1716. const babylonData = material._data[babylonDrawMode];
  1717. for (const babylonMesh of babylonData.babylonMeshes) {
  1718. // Ensure nonUniformScaling is set if necessary.
  1719. babylonMesh.computeWorldMatrix(true);
  1720. const babylonMaterial = babylonData.babylonMaterial;
  1721. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  1722. if (this._parent.useClipPlane) {
  1723. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  1724. }
  1725. }
  1726. }
  1727. }
  1728. }
  1729. }
  1730. return Promise.all(promises).then(() => {
  1731. this._parent._endPerformanceCounter("Compile materials");
  1732. });
  1733. }
  1734. private _compileShadowGeneratorsAsync(): Promise<void> {
  1735. this._parent._startPerformanceCounter("Compile shadow generators");
  1736. const promises = new Array<Promise<any>>();
  1737. const lights = this._babylonScene.lights;
  1738. for (let light of lights) {
  1739. let generator = light.getShadowGenerator();
  1740. if (generator) {
  1741. promises.push(generator.forceCompilationAsync());
  1742. }
  1743. }
  1744. return Promise.all(promises).then(() => {
  1745. this._parent._endPerformanceCounter("Compile shadow generators");
  1746. });
  1747. }
  1748. private _forEachExtensions(action: (extension: IGLTFLoaderExtension) => void): void {
  1749. for (const name of GLTFLoader._ExtensionNames) {
  1750. const extension = this._extensions[name];
  1751. if (extension.enabled) {
  1752. action(extension);
  1753. }
  1754. }
  1755. }
  1756. private _applyExtensions<T>(property: IProperty, functionName: string, actionAsync: (extension: IGLTFLoaderExtension) => Nullable<T> | undefined): Nullable<T> {
  1757. for (const name of GLTFLoader._ExtensionNames) {
  1758. const extension = this._extensions[name];
  1759. if (extension.enabled) {
  1760. const id = `${name}.${functionName}`;
  1761. const loaderProperty = property as ILoaderProperty;
  1762. loaderProperty._activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions || {};
  1763. const activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions;
  1764. if (!activeLoaderExtensionFunctions[id]) {
  1765. activeLoaderExtensionFunctions[id] = true;
  1766. try {
  1767. const result = actionAsync(extension);
  1768. if (result) {
  1769. return result;
  1770. }
  1771. }
  1772. finally {
  1773. delete activeLoaderExtensionFunctions[id];
  1774. }
  1775. }
  1776. }
  1777. }
  1778. return null;
  1779. }
  1780. private _extensionsOnLoading(): void {
  1781. this._forEachExtensions((extension) => extension.onLoading && extension.onLoading());
  1782. }
  1783. private _extensionsOnReady(): void {
  1784. this._forEachExtensions((extension) => extension.onReady && extension.onReady());
  1785. }
  1786. private _extensionsLoadSceneAsync(context: string, scene: IScene): Nullable<Promise<void>> {
  1787. return this._applyExtensions(scene, "loadScene", (extension) => extension.loadSceneAsync && extension.loadSceneAsync(context, scene));
  1788. }
  1789. private _extensionsLoadNodeAsync(context: string, node: INode, assign: (babylonTransformNode: TransformNode) => void): Nullable<Promise<TransformNode>> {
  1790. return this._applyExtensions(node, "loadNode", (extension) => extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign));
  1791. }
  1792. private _extensionsLoadCameraAsync(context: string, camera: ICamera, assign: (babylonCamera: Camera) => void): Nullable<Promise<Camera>> {
  1793. return this._applyExtensions(camera, "loadCamera", (extension) => extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign));
  1794. }
  1795. private _extensionsLoadVertexDataAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh): Nullable<Promise<Geometry>> {
  1796. return this._applyExtensions(primitive, "loadVertexData", (extension) => extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh));
  1797. }
  1798. private _extensionsLoadMaterialAsync(context: string, material: IMaterial, babylonMesh: Mesh, babylonDrawMode: number, assign: (babylonMaterial: Material) => void): Nullable<Promise<Material>> {
  1799. return this._applyExtensions(material, "loadMaterial", (extension) => extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign));
  1800. }
  1801. private _extensionsCreateMaterial(context: string, material: IMaterial, babylonDrawMode: number): Nullable<Material> {
  1802. return this._applyExtensions(material, "createMaterial", (extension) => extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode));
  1803. }
  1804. private _extensionsLoadMaterialPropertiesAsync(context: string, material: IMaterial, babylonMaterial: Material): Nullable<Promise<void>> {
  1805. return this._applyExtensions(material, "loadMaterialProperties", (extension) => extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial));
  1806. }
  1807. private _extensionsLoadTextureInfoAsync(context: string, textureInfo: ITextureInfo, assign: (babylonTexture: BaseTexture) => void): Nullable<Promise<BaseTexture>> {
  1808. return this._applyExtensions(textureInfo, "loadTextureInfo", (extension) => extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign));
  1809. }
  1810. private _extensionsLoadAnimationAsync(context: string, animation: IAnimation): Nullable<Promise<AnimationGroup>> {
  1811. return this._applyExtensions(animation, "loadAnimation", (extension) => extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation));
  1812. }
  1813. private _extensionsLoadUriAsync(context: string, property: IProperty, uri: string): Nullable<Promise<ArrayBufferView>> {
  1814. return this._applyExtensions(property, "loadUri", (extension) => extension._loadUriAsync && extension._loadUriAsync(context, property, uri));
  1815. }
  1816. /**
  1817. * Helper method called by a loader extension to load an glTF extension.
  1818. * @param context The context when loading the asset
  1819. * @param property The glTF property to load the extension from
  1820. * @param extensionName The name of the extension to load
  1821. * @param actionAsync The action to run
  1822. * @returns The promise returned by actionAsync or null if the extension does not exist
  1823. */
  1824. public static LoadExtensionAsync<TExtension = any, TResult = void>(context: string, property: IProperty, extensionName: string, actionAsync: (extensionContext: string, extension: TExtension) => Nullable<Promise<TResult>>): Nullable<Promise<TResult>> {
  1825. if (!property.extensions) {
  1826. return null;
  1827. }
  1828. const extensions = property.extensions;
  1829. const extension = extensions[extensionName] as TExtension;
  1830. if (!extension) {
  1831. return null;
  1832. }
  1833. return actionAsync(`${context}/extensions/${extensionName}`, extension);
  1834. }
  1835. /**
  1836. * Helper method called by a loader extension to load a glTF extra.
  1837. * @param context The context when loading the asset
  1838. * @param property The glTF property to load the extra from
  1839. * @param extensionName The name of the extension to load
  1840. * @param actionAsync The action to run
  1841. * @returns The promise returned by actionAsync or null if the extra does not exist
  1842. */
  1843. public static LoadExtraAsync<TExtra = any, TResult = void>(context: string, property: IProperty, extensionName: string, actionAsync: (extraContext: string, extra: TExtra) => Nullable<Promise<TResult>>): Nullable<Promise<TResult>> {
  1844. if (!property.extras) {
  1845. return null;
  1846. }
  1847. const extras = property.extras;
  1848. const extra = extras[extensionName] as TExtra;
  1849. if (!extra) {
  1850. return null;
  1851. }
  1852. return actionAsync(`${context}/extras/${extensionName}`, extra);
  1853. }
  1854. /**
  1855. * Increments the indentation level and logs a message.
  1856. * @param message The message to log
  1857. */
  1858. public logOpen(message: string): void {
  1859. this._parent._logOpen(message);
  1860. }
  1861. /**
  1862. * Decrements the indentation level.
  1863. */
  1864. public logClose(): void {
  1865. this._parent._logClose();
  1866. }
  1867. /**
  1868. * Logs a message
  1869. * @param message The message to log
  1870. */
  1871. public log(message: string): void {
  1872. this._parent._log(message);
  1873. }
  1874. /**
  1875. * Starts a performance counter.
  1876. * @param counterName The name of the performance counter
  1877. */
  1878. public startPerformanceCounter(counterName: string): void {
  1879. this._parent._startPerformanceCounter(counterName);
  1880. }
  1881. /**
  1882. * Ends a performance counter.
  1883. * @param counterName The name of the performance counter
  1884. */
  1885. public endPerformanceCounter(counterName: string): void {
  1886. this._parent._endPerformanceCounter(counterName);
  1887. }
  1888. }
  1889. GLTFFileLoader._CreateGLTF2Loader = (parent) => new GLTFLoader(parent);