glTFLoader.ts 104 KB

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