glTFLoader.ts 100 KB

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