glTFLoader.ts 105 KB

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