babylon.glTFLoader.ts 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. /**
  3. * Defines the module used to import/export glTF 2.0 assets
  4. */
  5. module BABYLON.GLTF2 {
  6. interface IFileRequestInfo extends IFileRequest {
  7. _lengthComputable?: boolean;
  8. _loaded?: number;
  9. _total?: number;
  10. }
  11. /**
  12. * Loader for loading a glTF 2.0 asset
  13. */
  14. export class GLTFLoader implements IGLTFLoader {
  15. /** @hidden */
  16. public _gltf: _ILoaderGLTF;
  17. /** @hidden */
  18. public _babylonScene: Scene;
  19. /** @hidden */
  20. public _completePromises = new Array<Promise<void>>();
  21. private _disposed = false;
  22. private _state: Nullable<GLTFLoaderState> = null;
  23. private _extensions: { [name: string]: GLTFLoaderExtension } = {};
  24. private _rootUrl: string;
  25. private _rootBabylonMesh: Mesh;
  26. private _defaultSampler = {} as _ILoaderSampler;
  27. private _defaultBabylonMaterials: { [drawMode: number]: PBRMaterial } = {};
  28. private _progressCallback?: (event: SceneLoaderProgressEvent) => void;
  29. private _requests = new Array<IFileRequestInfo>();
  30. private static _ExtensionNames = new Array<string>();
  31. private static _ExtensionFactories: { [name: string]: (loader: GLTFLoader) => GLTFLoaderExtension } = {};
  32. /** @hidden */
  33. public static _Register(name: string, factory: (loader: GLTFLoader) => GLTFLoaderExtension): void {
  34. if (GLTFLoader._ExtensionFactories[name]) {
  35. Tools.Error(`Extension with the name '${name}' already exists`);
  36. return;
  37. }
  38. GLTFLoader._ExtensionFactories[name] = factory;
  39. // Keep the order of registration so that extensions registered first are called first.
  40. GLTFLoader._ExtensionNames.push(name);
  41. }
  42. /**
  43. * Mode that determines the coordinate system to use.
  44. */
  45. public coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  46. /**
  47. * Mode that determines what animations will start.
  48. */
  49. public animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  50. /**
  51. * Defines if the loader should compile materials.
  52. */
  53. public compileMaterials = false;
  54. /**
  55. * Defines if the loader should also compile materials with clip planes.
  56. */
  57. public useClipPlane = false;
  58. /**
  59. * Defines if the loader should compile shadow generators.
  60. */
  61. public compileShadowGenerators = false;
  62. /**
  63. * Defines if the Alpha blended materials are only applied as coverage.
  64. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  65. * If true, no extra effects are applied to transparent pixels.
  66. */
  67. public transparencyAsCoverage = false;
  68. /**
  69. * Function called before loading a url referenced by the asset.
  70. */
  71. public preprocessUrlAsync = (url: string) => Promise.resolve(url);
  72. /**
  73. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  74. */
  75. public readonly onMeshLoadedObservable = new Observable<AbstractMesh>();
  76. /**
  77. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  78. */
  79. public readonly onTextureLoadedObservable = new Observable<BaseTexture>();
  80. /**
  81. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  82. */
  83. public readonly onMaterialLoadedObservable = new Observable<Material>();
  84. /**
  85. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  86. */
  87. public readonly onCameraLoadedObservable = new Observable<Camera>();
  88. /**
  89. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  90. * For assets with LODs, raised when all of the LODs are complete.
  91. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  92. */
  93. public readonly onCompleteObservable = new Observable<IGLTFLoader>();
  94. /**
  95. * Observable raised after the loader is disposed.
  96. */
  97. public readonly onDisposeObservable = new Observable<IGLTFLoader>();
  98. /**
  99. * Observable raised after a loader extension is created.
  100. * Set additional options for a loader extension in this event.
  101. */
  102. public readonly onExtensionLoadedObservable = new Observable<IGLTFLoaderExtension>();
  103. /**
  104. * Loader state or null if the loader is not active.
  105. */
  106. public get state(): Nullable<GLTFLoaderState> {
  107. return this._state;
  108. }
  109. /**
  110. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  111. */
  112. public dispose(): void {
  113. if (this._disposed) {
  114. return;
  115. }
  116. this._disposed = true;
  117. this.onDisposeObservable.notifyObservers(this);
  118. this.onDisposeObservable.clear();
  119. this._clear();
  120. }
  121. /**
  122. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  123. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  124. * @param scene the scene the meshes should be added to
  125. * @param data the glTF data to load
  126. * @param rootUrl root url to load from
  127. * @param onProgress event that fires when loading progress has occured
  128. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  129. */
  130. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }> {
  131. return Promise.resolve().then(() => {
  132. let nodes: Nullable<Array<_ILoaderNode>> = null;
  133. if (meshesNames) {
  134. const nodeMap: { [name: string]: _ILoaderNode } = {};
  135. if (this._gltf.nodes) {
  136. for (const node of this._gltf.nodes) {
  137. if (node.name) {
  138. nodeMap[node.name] = node;
  139. }
  140. }
  141. }
  142. const names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  143. nodes = names.map(name => {
  144. const node = nodeMap[name];
  145. if (!node) {
  146. throw new Error(`Failed to find node '${name}'`);
  147. }
  148. return node;
  149. });
  150. }
  151. return this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(() => {
  152. return {
  153. meshes: this._getMeshes(),
  154. particleSystems: [],
  155. skeletons: this._getSkeletons(),
  156. animationGroups: this._getAnimationGroups()
  157. };
  158. });
  159. });
  160. }
  161. /**
  162. * Imports all objects from the loaded glTF data and adds them to the scene
  163. * @param scene the scene the objects should be added to
  164. * @param data the glTF data to load
  165. * @param rootUrl root url to load from
  166. * @param onProgress event that fires when loading progress has occured
  167. * @returns a promise which completes when objects have been loaded to the scene
  168. */
  169. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void> {
  170. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  171. }
  172. private _loadAsync(nodes: Nullable<Array<_ILoaderNode>>, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void> {
  173. return Promise.resolve().then(() => {
  174. this._babylonScene = scene;
  175. this._rootUrl = rootUrl;
  176. this._progressCallback = onProgress;
  177. this._state = GLTFLoaderState.LOADING;
  178. this._loadData(data);
  179. this._loadExtensions();
  180. this._checkExtensions();
  181. const promises = new Array<Promise<void>>();
  182. if (nodes) {
  183. promises.push(this._loadNodesAsync(nodes));
  184. }
  185. else {
  186. const scene = GLTFLoader._GetProperty(`#/scene`, this._gltf.scenes, this._gltf.scene || 0);
  187. promises.push(this._loadSceneAsync(`#/scenes/${scene._index}`, scene));
  188. }
  189. if (this.compileMaterials) {
  190. promises.push(this._compileMaterialsAsync());
  191. }
  192. if (this.compileShadowGenerators) {
  193. promises.push(this._compileShadowGeneratorsAsync());
  194. }
  195. const resultPromise = Promise.all(promises).then(() => {
  196. this._state = GLTFLoaderState.READY;
  197. this._startAnimations();
  198. });
  199. resultPromise.then(() => {
  200. this._rootBabylonMesh.setEnabled(true);
  201. Tools.SetImmediate(() => {
  202. if (!this._disposed) {
  203. Promise.all(this._completePromises).then(() => {
  204. this._state = GLTFLoaderState.COMPLETE;
  205. this.onCompleteObservable.notifyObservers(this);
  206. this.onCompleteObservable.clear();
  207. this._clear();
  208. }).catch(error => {
  209. Tools.Error(`glTF Loader: ${error.message}`);
  210. this._clear();
  211. });
  212. }
  213. });
  214. });
  215. return resultPromise;
  216. }).catch(error => {
  217. if (!this._disposed) {
  218. Tools.Error(`glTF Loader: ${error.message}`);
  219. this._clear();
  220. throw error;
  221. }
  222. });
  223. }
  224. private _loadData(data: IGLTFLoaderData): void {
  225. this._gltf = data.json as _ILoaderGLTF;
  226. this._setupData();
  227. if (data.bin) {
  228. const buffers = this._gltf.buffers;
  229. if (buffers && buffers[0] && !buffers[0].uri) {
  230. const binaryBuffer = buffers[0];
  231. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  232. Tools.Warn(`Binary buffer length (${binaryBuffer.byteLength}) from JSON does not match chunk length (${data.bin.byteLength})`);
  233. }
  234. binaryBuffer._data = Promise.resolve(data.bin);
  235. }
  236. else {
  237. Tools.Warn("Unexpected BIN chunk");
  238. }
  239. }
  240. }
  241. private _setupData(): void {
  242. _ArrayItem.Assign(this._gltf.accessors);
  243. _ArrayItem.Assign(this._gltf.animations);
  244. _ArrayItem.Assign(this._gltf.buffers);
  245. _ArrayItem.Assign(this._gltf.bufferViews);
  246. _ArrayItem.Assign(this._gltf.cameras);
  247. _ArrayItem.Assign(this._gltf.images);
  248. _ArrayItem.Assign(this._gltf.materials);
  249. _ArrayItem.Assign(this._gltf.meshes);
  250. _ArrayItem.Assign(this._gltf.nodes);
  251. _ArrayItem.Assign(this._gltf.samplers);
  252. _ArrayItem.Assign(this._gltf.scenes);
  253. _ArrayItem.Assign(this._gltf.skins);
  254. _ArrayItem.Assign(this._gltf.textures);
  255. if (this._gltf.nodes) {
  256. const nodeParents: { [index: number]: number } = {};
  257. for (const node of this._gltf.nodes) {
  258. if (node.children) {
  259. for (const index of node.children) {
  260. nodeParents[index] = node._index;
  261. }
  262. }
  263. }
  264. const rootNode = this._createRootNode();
  265. for (const node of this._gltf.nodes) {
  266. const parentIndex = nodeParents[node._index];
  267. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  268. }
  269. }
  270. }
  271. private _loadExtensions(): void {
  272. for (const name of GLTFLoader._ExtensionNames) {
  273. const extension = GLTFLoader._ExtensionFactories[name](this);
  274. this._extensions[name] = extension;
  275. this.onExtensionLoadedObservable.notifyObservers(extension);
  276. }
  277. this.onExtensionLoadedObservable.clear();
  278. }
  279. private _checkExtensions(): void {
  280. if (this._gltf.extensionsRequired) {
  281. for (const name of this._gltf.extensionsRequired) {
  282. const extension = this._extensions[name];
  283. if (!extension || !extension.enabled) {
  284. throw new Error(`Require extension ${name} is not available`);
  285. }
  286. }
  287. }
  288. }
  289. private _createRootNode(): _ILoaderNode {
  290. this._rootBabylonMesh = new Mesh("__root__", this._babylonScene);
  291. this._rootBabylonMesh.setEnabled(false);
  292. const rootNode = { _babylonMesh: this._rootBabylonMesh } as _ILoaderNode;
  293. switch (this.coordinateSystemMode) {
  294. case GLTFLoaderCoordinateSystemMode.AUTO: {
  295. if (!this._babylonScene.useRightHandedSystem) {
  296. rootNode.rotation = [0, 1, 0, 0];
  297. rootNode.scale = [1, 1, -1];
  298. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  299. }
  300. break;
  301. }
  302. case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  303. this._babylonScene.useRightHandedSystem = true;
  304. break;
  305. }
  306. default: {
  307. throw new Error(`Invalid coordinate system mode (${this.coordinateSystemMode})`);
  308. }
  309. }
  310. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  311. return rootNode;
  312. }
  313. private _loadNodesAsync(nodes: _ILoaderNode[], ): Promise<void> {
  314. const promises = new Array<Promise<void>>();
  315. for (let node of nodes) {
  316. promises.push(this._loadNodeAsync(`#/nodes/${node._index}`, node));
  317. }
  318. promises.push(this._loadAnimationsAsync());
  319. return Promise.all(promises).then(() => {});
  320. }
  321. /** @hidden */
  322. public _loadSceneAsync(context: string, scene: _ILoaderScene): Promise<void> {
  323. const promise = GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  324. if (promise) {
  325. return promise;
  326. }
  327. const promises = new Array<Promise<void>>();
  328. for (let index of scene.nodes) {
  329. const node = GLTFLoader._GetProperty(`${context}/nodes/${index}`, this._gltf.nodes, index);
  330. promises.push(this._loadNodeAsync(`#/nodes/${node._index}`, node));
  331. }
  332. promises.push(this._loadAnimationsAsync());
  333. return Promise.all(promises).then(() => {});
  334. }
  335. private _forEachPrimitive(node: _ILoaderNode, callback: (babylonMesh: Mesh) => void): void {
  336. if (node._primitiveBabylonMeshes) {
  337. for (const babylonMesh of node._primitiveBabylonMeshes) {
  338. callback(babylonMesh);
  339. }
  340. }
  341. else {
  342. callback(node._babylonMesh!);
  343. }
  344. }
  345. private _getMeshes(): Mesh[] {
  346. const meshes = new Array<Mesh>();
  347. // Root mesh is always first.
  348. meshes.push(this._rootBabylonMesh);
  349. const nodes = this._gltf.nodes;
  350. if (nodes) {
  351. for (const node of nodes) {
  352. if (node._babylonMesh) {
  353. meshes.push(node._babylonMesh);
  354. }
  355. if (node._primitiveBabylonMeshes) {
  356. for (const babylonMesh of node._primitiveBabylonMeshes) {
  357. meshes.push(babylonMesh);
  358. }
  359. }
  360. }
  361. }
  362. return meshes;
  363. }
  364. private _getSkeletons(): Skeleton[] {
  365. const skeletons = new Array<Skeleton>();
  366. const skins = this._gltf.skins;
  367. if (skins) {
  368. for (const skin of skins) {
  369. if (skin._babylonSkeleton) {
  370. skeletons.push(skin._babylonSkeleton);
  371. }
  372. }
  373. }
  374. return skeletons;
  375. }
  376. private _getAnimationGroups(): AnimationGroup[] {
  377. const animationGroups = new Array<AnimationGroup>();
  378. const animations = this._gltf.animations;
  379. if (animations) {
  380. for (const animation of animations) {
  381. if (animation._babylonAnimationGroup) {
  382. animationGroups.push(animation._babylonAnimationGroup);
  383. }
  384. }
  385. }
  386. return animationGroups;
  387. }
  388. private _startAnimations(): void {
  389. switch (this.animationStartMode) {
  390. case GLTFLoaderAnimationStartMode.NONE: {
  391. // do nothing
  392. break;
  393. }
  394. case GLTFLoaderAnimationStartMode.FIRST: {
  395. const babylonAnimationGroups = this._getAnimationGroups();
  396. if (babylonAnimationGroups.length !== 0) {
  397. babylonAnimationGroups[0].start(true);
  398. }
  399. break;
  400. }
  401. case GLTFLoaderAnimationStartMode.ALL: {
  402. const babylonAnimationGroups = this._getAnimationGroups();
  403. for (const babylonAnimationGroup of babylonAnimationGroups) {
  404. babylonAnimationGroup.start(true);
  405. }
  406. break;
  407. }
  408. default: {
  409. Tools.Error(`Invalid animation start mode (${this.animationStartMode})`);
  410. return;
  411. }
  412. }
  413. }
  414. /** @hidden */
  415. public _loadNodeAsync(context: string, node: _ILoaderNode): Promise<void> {
  416. const promise = GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  417. if (promise) {
  418. return promise;
  419. }
  420. if (node._babylonMesh) {
  421. throw new Error(`${context}: Invalid recursive node hierarchy`);
  422. }
  423. const promises = new Array<Promise<void>>();
  424. const babylonMesh = new Mesh(node.name || `node${node._index}`, this._babylonScene, node._parent._babylonMesh);
  425. node._babylonMesh = babylonMesh;
  426. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  427. node._babylonAnimationTargets.push(babylonMesh);
  428. GLTFLoader._LoadTransform(node, babylonMesh);
  429. if (node.mesh != undefined) {
  430. const mesh = GLTFLoader._GetProperty(`${context}/mesh`, this._gltf.meshes, node.mesh);
  431. promises.push(this._loadMeshAsync(`#/meshes/${mesh._index}`, node, mesh, babylonMesh));
  432. }
  433. if (node.camera != undefined) {
  434. const camera = GLTFLoader._GetProperty(`${context}/camera`, this._gltf.cameras, node.camera);
  435. this._loadCamera(`#/cameras/${camera._index}`, camera, babylonMesh);
  436. }
  437. if (node.children) {
  438. for (const index of node.children) {
  439. const childNode = GLTFLoader._GetProperty(`${context}/children/${index}`, this._gltf.nodes, index);
  440. promises.push(this._loadNodeAsync(`#/nodes/${index}`, childNode));
  441. }
  442. }
  443. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  444. return Promise.all(promises).then(() => {});
  445. }
  446. private _loadMeshAsync(context: string, node: _ILoaderNode, mesh: _ILoaderMesh, babylonMesh: Mesh): Promise<void> {
  447. const promises = new Array<Promise<void>>();
  448. const primitives = mesh.primitives;
  449. if (!primitives || primitives.length === 0) {
  450. throw new Error(`${context}: Primitives are missing`);
  451. }
  452. _ArrayItem.Assign(primitives);
  453. if (primitives.length === 1) {
  454. const primitive = primitives[0];
  455. promises.push(this._loadPrimitiveAsync(`${context}/primitives/${primitive._index}`, node, mesh, primitive, babylonMesh));
  456. }
  457. else {
  458. node._primitiveBabylonMeshes = [];
  459. for (const primitive of primitives) {
  460. const primitiveBabylonMesh = new Mesh(`${mesh.name || babylonMesh.name}_${primitive._index}`, this._babylonScene, babylonMesh);
  461. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  462. promises.push(this._loadPrimitiveAsync(`${context}/primitives/${primitive._index}`, node, mesh, primitive, primitiveBabylonMesh));
  463. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  464. }
  465. }
  466. if (node.skin != undefined) {
  467. const skin = GLTFLoader._GetProperty(`${context}/skin`, this._gltf.skins, node.skin);
  468. promises.push(this._loadSkinAsync(`#/skins/${skin._index}`, node, mesh, skin));
  469. }
  470. return Promise.all(promises).then(() => {
  471. this._forEachPrimitive(node, babylonMesh => {
  472. babylonMesh._refreshBoundingInfo(true);
  473. });
  474. });
  475. }
  476. private _loadPrimitiveAsync(context: string, node: _ILoaderNode, mesh: _ILoaderMesh, primitive: _ILoaderMeshPrimitive, babylonMesh: Mesh): Promise<void> {
  477. const promises = new Array<Promise<void>>();
  478. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  479. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(babylonGeometry => {
  480. return this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(() => {
  481. babylonGeometry.applyToMesh(babylonMesh);
  482. });
  483. }));
  484. const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  485. if (primitive.material == undefined) {
  486. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  487. }
  488. else {
  489. const material = GLTFLoader._GetProperty(`${context}/material}`, this._gltf.materials, primitive.material);
  490. promises.push(this._loadMaterialAsync(`#/materials/${material._index}`, material, babylonMesh, babylonDrawMode, babylonMaterial => {
  491. babylonMesh.material = babylonMaterial;
  492. }));
  493. }
  494. return Promise.all(promises).then(() => {});
  495. }
  496. private _loadVertexDataAsync(context: string, primitive: _ILoaderMeshPrimitive, babylonMesh: Mesh): Promise<Geometry> {
  497. const promise = GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  498. if (promise) {
  499. return promise;
  500. }
  501. const attributes = primitive.attributes;
  502. if (!attributes) {
  503. throw new Error(`${context}: Attributes are missing`);
  504. }
  505. const promises = new Array<Promise<void>>();
  506. const babylonGeometry = new Geometry(babylonMesh.name, this._babylonScene);
  507. if (primitive.indices == undefined) {
  508. babylonMesh.isUnIndexed = true;
  509. }
  510. else {
  511. const accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  512. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(data => {
  513. babylonGeometry.setIndices(data);
  514. }));
  515. }
  516. const loadAttribute = (attribute: string, kind: string, callback?: (accessor: _ILoaderAccessor) => void) => {
  517. if (attributes[attribute] == undefined) {
  518. return;
  519. }
  520. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  521. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  522. babylonMesh._delayInfo.push(kind);
  523. }
  524. const accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, this._gltf.accessors, attributes[attribute]);
  525. promises.push(this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(babylonVertexBuffer => {
  526. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  527. }));
  528. if (callback) {
  529. callback(accessor);
  530. }
  531. };
  532. loadAttribute("POSITION", VertexBuffer.PositionKind);
  533. loadAttribute("NORMAL", VertexBuffer.NormalKind);
  534. loadAttribute("TANGENT", VertexBuffer.TangentKind);
  535. loadAttribute("TEXCOORD_0", VertexBuffer.UVKind);
  536. loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind);
  537. loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind);
  538. loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind);
  539. loadAttribute("COLOR_0", VertexBuffer.ColorKind, accessor => {
  540. if (accessor.type === AccessorType.VEC4) {
  541. babylonMesh.hasVertexAlpha = true;
  542. }
  543. });
  544. return Promise.all(promises).then(() => {
  545. return babylonGeometry;
  546. });
  547. }
  548. private _createMorphTargets(context: string, node: _ILoaderNode, mesh: _ILoaderMesh, primitive: IMeshPrimitive, babylonMesh: Mesh): void {
  549. if (!primitive.targets) {
  550. return;
  551. }
  552. if (node._numMorphTargets == undefined) {
  553. node._numMorphTargets = primitive.targets.length;
  554. }
  555. else if (primitive.targets.length !== node._numMorphTargets) {
  556. throw new Error(`${context}: Primitives do not have the same number of targets`);
  557. }
  558. babylonMesh.morphTargetManager = new MorphTargetManager();
  559. for (let index = 0; index < primitive.targets.length; index++) {
  560. const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  561. babylonMesh.morphTargetManager.addTarget(new MorphTarget(`morphTarget${index}`, weight));
  562. // TODO: tell the target whether it has positions, normals, tangents
  563. }
  564. }
  565. private _loadMorphTargetsAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh, babylonGeometry: Geometry): Promise<void> {
  566. if (!primitive.targets) {
  567. return Promise.resolve();
  568. }
  569. const promises = new Array<Promise<void>>();
  570. const morphTargetManager = babylonMesh.morphTargetManager!;
  571. for (let index = 0; index < morphTargetManager.numTargets; index++) {
  572. const babylonMorphTarget = morphTargetManager.getTarget(index);
  573. promises.push(this._loadMorphTargetVertexDataAsync(`${context}/targets/${index}`, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  574. }
  575. return Promise.all(promises).then(() => {});
  576. }
  577. private _loadMorphTargetVertexDataAsync(context: string, babylonGeometry: Geometry, attributes: { [name: string]: number }, babylonMorphTarget: MorphTarget): Promise<void> {
  578. const promises = new Array<Promise<void>>();
  579. const loadAttribute = (attribute: string, kind: string, setData: (babylonVertexBuffer: VertexBuffer, data: Float32Array) => void) => {
  580. if (attributes[attribute] == undefined) {
  581. return;
  582. }
  583. const babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  584. if (!babylonVertexBuffer) {
  585. return;
  586. }
  587. const accessor = GLTFLoader._GetProperty(`${context}/${attribute}`, this._gltf.accessors, attributes[attribute]);
  588. promises.push(this._loadFloatAccessorAsync(`#/accessors/${accessor._index}`, accessor).then(data => {
  589. setData(babylonVertexBuffer, data);
  590. }));
  591. };
  592. loadAttribute("POSITION", VertexBuffer.PositionKind, (babylonVertexBuffer, data) => {
  593. babylonVertexBuffer.forEach(data.length, (value, index) => {
  594. data[index] += value;
  595. });
  596. babylonMorphTarget.setPositions(data);
  597. });
  598. loadAttribute("NORMAL", VertexBuffer.NormalKind, (babylonVertexBuffer, data) => {
  599. babylonVertexBuffer.forEach(data.length, (value, index) => {
  600. data[index] += value;
  601. });
  602. babylonMorphTarget.setNormals(data);
  603. });
  604. loadAttribute("TANGENT", VertexBuffer.TangentKind, (babylonVertexBuffer, data) => {
  605. let dataIndex = 0;
  606. babylonVertexBuffer.forEach(data.length, (value, index) => {
  607. // Tangent data for morph targets is stored as xyz delta.
  608. // The vertexData.tangent is stored as xyzw.
  609. // So we need to skip every fourth vertexData.tangent.
  610. if (((index + 1) % 4) !== 0) {
  611. data[dataIndex++] += value;
  612. }
  613. });
  614. babylonMorphTarget.setTangents(data);
  615. });
  616. return Promise.all(promises).then(() => {});
  617. }
  618. private static _LoadTransform(node: _ILoaderNode, babylonNode: TransformNode): void {
  619. let position = Vector3.Zero();
  620. let rotation = Quaternion.Identity();
  621. let scaling = Vector3.One();
  622. if (node.matrix) {
  623. const matrix = Matrix.FromArray(node.matrix);
  624. matrix.decompose(scaling, rotation, position);
  625. }
  626. else {
  627. if (node.translation) position = Vector3.FromArray(node.translation);
  628. if (node.rotation) rotation = Quaternion.FromArray(node.rotation);
  629. if (node.scale) scaling = Vector3.FromArray(node.scale);
  630. }
  631. babylonNode.position = position;
  632. babylonNode.rotationQuaternion = rotation;
  633. babylonNode.scaling = scaling;
  634. }
  635. private _loadSkinAsync(context: string, node: _ILoaderNode, mesh: _ILoaderMesh, skin: _ILoaderSkin): Promise<void> {
  636. const assignSkeleton = (skeleton: Skeleton) => {
  637. this._forEachPrimitive(node, babylonMesh => {
  638. babylonMesh.skeleton = skeleton;
  639. });
  640. // Ignore the TRS of skinned nodes.
  641. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  642. node._babylonMesh!.parent = this._rootBabylonMesh;
  643. node._babylonMesh!.position = Vector3.Zero();
  644. node._babylonMesh!.rotationQuaternion = Quaternion.Identity();
  645. node._babylonMesh!.scaling = Vector3.One();
  646. };
  647. if (skin._loaded) {
  648. return skin._loaded.then(() => {
  649. assignSkeleton(skin._babylonSkeleton!);
  650. });
  651. }
  652. const skeletonId = `skeleton${skin._index}`;
  653. const babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  654. skin._babylonSkeleton = babylonSkeleton;
  655. this._loadBones(context, skin);
  656. assignSkeleton(babylonSkeleton);
  657. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(inverseBindMatricesData => {
  658. this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  659. }));
  660. }
  661. private _loadBones(context: string, skin: _ILoaderSkin): void {
  662. const babylonBones: { [index: number]: Bone } = {};
  663. for (const index of skin.joints) {
  664. const node = GLTFLoader._GetProperty(`${context}/joints/${index}`, this._gltf.nodes, index);
  665. this._loadBone(node, skin, babylonBones);
  666. }
  667. }
  668. private _loadBone(node: _ILoaderNode, skin: _ILoaderSkin, babylonBones: { [index: number]: Bone }): Bone {
  669. let babylonBone = babylonBones[node._index];
  670. if (babylonBone) {
  671. return babylonBone;
  672. }
  673. let babylonParentBone: Nullable<Bone> = null;
  674. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  675. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  676. }
  677. const boneIndex = skin.joints.indexOf(node._index);
  678. babylonBone = new Bone(node.name || `joint${node._index}`, skin._babylonSkeleton!, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  679. babylonBones[node._index] = babylonBone;
  680. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  681. node._babylonAnimationTargets.push(babylonBone);
  682. return babylonBone;
  683. }
  684. private _loadSkinInverseBindMatricesDataAsync(context: string, skin: _ILoaderSkin): Promise<Nullable<Float32Array>> {
  685. if (skin.inverseBindMatrices == undefined) {
  686. return Promise.resolve(null);
  687. }
  688. const accessor = GLTFLoader._GetProperty(`${context}/inverseBindMatrices`, this._gltf.accessors, skin.inverseBindMatrices);
  689. return this._loadFloatAccessorAsync(`#/accessors/${accessor._index}`, accessor);
  690. }
  691. private _updateBoneMatrices(babylonSkeleton: Skeleton, inverseBindMatricesData: Nullable<Float32Array>): void {
  692. for (const babylonBone of babylonSkeleton.bones) {
  693. let baseMatrix = Matrix.Identity();
  694. const boneIndex = babylonBone._index!;
  695. if (inverseBindMatricesData && boneIndex !== -1) {
  696. Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  697. baseMatrix.invertToRef(baseMatrix);
  698. }
  699. const babylonParentBone = babylonBone.getParent();
  700. if (babylonParentBone) {
  701. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  702. }
  703. babylonBone.updateMatrix(baseMatrix, false, false);
  704. babylonBone._updateDifferenceMatrix(undefined, false);
  705. }
  706. }
  707. private _getNodeMatrix(node: _ILoaderNode): Matrix {
  708. return node.matrix ?
  709. Matrix.FromArray(node.matrix) :
  710. Matrix.Compose(
  711. node.scale ? Vector3.FromArray(node.scale) : Vector3.One(),
  712. node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(),
  713. node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());
  714. }
  715. private _loadCamera(context: string, camera: _ILoaderCamera, babylonMesh: Mesh): void {
  716. const babylonCamera = new FreeCamera(camera.name || `camera${camera._index}`, Vector3.Zero(), this._babylonScene, false);
  717. babylonCamera.parent = babylonMesh;
  718. babylonCamera.rotation = new Vector3(0, Math.PI, 0);
  719. switch (camera.type) {
  720. case CameraType.PERSPECTIVE: {
  721. const perspective = camera.perspective;
  722. if (!perspective) {
  723. throw new Error(`${context}: Camera perspective properties are missing`);
  724. }
  725. babylonCamera.fov = perspective.yfov;
  726. babylonCamera.minZ = perspective.znear;
  727. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  728. break;
  729. }
  730. case CameraType.ORTHOGRAPHIC: {
  731. if (!camera.orthographic) {
  732. throw new Error(`${context}: Camera orthographic properties are missing`);
  733. }
  734. babylonCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  735. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  736. babylonCamera.orthoRight = camera.orthographic.xmag;
  737. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  738. babylonCamera.orthoTop = camera.orthographic.ymag;
  739. babylonCamera.minZ = camera.orthographic.znear;
  740. babylonCamera.maxZ = camera.orthographic.zfar;
  741. break;
  742. }
  743. default: {
  744. throw new Error(`${context}: Invalid camera type (${camera.type})`);
  745. }
  746. }
  747. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  748. }
  749. private _loadAnimationsAsync(): Promise<void> {
  750. const animations = this._gltf.animations;
  751. if (!animations) {
  752. return Promise.resolve();
  753. }
  754. const promises = new Array<Promise<void>>();
  755. for (let index = 0; index < animations.length; index++) {
  756. const animation = animations[index];
  757. promises.push(this._loadAnimationAsync(`#/animations/${index}`, animation));
  758. }
  759. return Promise.all(promises).then(() => {});
  760. }
  761. private _loadAnimationAsync(context: string, animation: _ILoaderAnimation): Promise<void> {
  762. const babylonAnimationGroup = new AnimationGroup(animation.name || `animation${animation._index}`, this._babylonScene);
  763. animation._babylonAnimationGroup = babylonAnimationGroup;
  764. const promises = new Array<Promise<void>>();
  765. _ArrayItem.Assign(animation.channels);
  766. _ArrayItem.Assign(animation.samplers);
  767. for (const channel of animation.channels) {
  768. promises.push(this._loadAnimationChannelAsync(`${context}/channels/${channel._index}`, context, animation, channel, babylonAnimationGroup));
  769. }
  770. return Promise.all(promises).then(() => {
  771. babylonAnimationGroup.normalize();
  772. });
  773. }
  774. private _loadAnimationChannelAsync(context: string, animationContext: string, animation: _ILoaderAnimation, channel: _ILoaderAnimationChannel, babylonAnimationGroup: AnimationGroup): Promise<void> {
  775. const targetNode = GLTFLoader._GetProperty(`${context}/target/node`, this._gltf.nodes, channel.target.node);
  776. // Ignore animations that have no animation targets.
  777. if ((channel.target.path === AnimationChannelTargetPath.WEIGHTS && !targetNode._numMorphTargets) ||
  778. (channel.target.path !== AnimationChannelTargetPath.WEIGHTS && !targetNode._babylonAnimationTargets)) {
  779. return Promise.resolve();
  780. }
  781. // Ignore animations targeting TRS of skinned nodes.
  782. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  783. if (targetNode.skin != undefined && channel.target.path !== AnimationChannelTargetPath.WEIGHTS) {
  784. return Promise.resolve();
  785. }
  786. const sampler = GLTFLoader._GetProperty(`${context}/sampler`, animation.samplers, channel.sampler);
  787. return this._loadAnimationSamplerAsync(`${animationContext}/samplers/${channel.sampler}`, sampler).then(data => {
  788. let targetPath: string;
  789. let animationType: number;
  790. switch (channel.target.path) {
  791. case AnimationChannelTargetPath.TRANSLATION: {
  792. targetPath = "position";
  793. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  794. break;
  795. }
  796. case AnimationChannelTargetPath.ROTATION: {
  797. targetPath = "rotationQuaternion";
  798. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  799. break;
  800. }
  801. case AnimationChannelTargetPath.SCALE: {
  802. targetPath = "scaling";
  803. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  804. break;
  805. }
  806. case AnimationChannelTargetPath.WEIGHTS: {
  807. targetPath = "influence";
  808. animationType = Animation.ANIMATIONTYPE_FLOAT;
  809. break;
  810. }
  811. default: {
  812. throw new Error(`${context}: Invalid target path (${channel.target.path})`);
  813. }
  814. }
  815. let outputBufferOffset = 0;
  816. let getNextOutputValue: () => Vector3 | Quaternion | Array<number>;
  817. switch (targetPath) {
  818. case "position": {
  819. getNextOutputValue = () => {
  820. const value = Vector3.FromArray(data.output, outputBufferOffset);
  821. outputBufferOffset += 3;
  822. return value;
  823. };
  824. break;
  825. }
  826. case "rotationQuaternion": {
  827. getNextOutputValue = () => {
  828. const value = Quaternion.FromArray(data.output, outputBufferOffset);
  829. outputBufferOffset += 4;
  830. return value;
  831. };
  832. break;
  833. }
  834. case "scaling": {
  835. getNextOutputValue = () => {
  836. const value = Vector3.FromArray(data.output, outputBufferOffset);
  837. outputBufferOffset += 3;
  838. return value;
  839. };
  840. break;
  841. }
  842. case "influence": {
  843. getNextOutputValue = () => {
  844. const value = new Array<number>(targetNode._numMorphTargets!);
  845. for (let i = 0; i < targetNode._numMorphTargets!; i++) {
  846. value[i] = data.output[outputBufferOffset++];
  847. }
  848. return value;
  849. };
  850. break;
  851. }
  852. }
  853. let getNextKey: (frameIndex: number) => IAnimationKey;
  854. switch (data.interpolation) {
  855. case AnimationSamplerInterpolation.STEP: {
  856. getNextKey = frameIndex => ({
  857. frame: data.input[frameIndex],
  858. value: getNextOutputValue(),
  859. interpolation: AnimationKeyInterpolation.STEP
  860. });
  861. break;
  862. }
  863. case AnimationSamplerInterpolation.LINEAR: {
  864. getNextKey = frameIndex => ({
  865. frame: data.input[frameIndex],
  866. value: getNextOutputValue()
  867. });
  868. break;
  869. }
  870. case AnimationSamplerInterpolation.CUBICSPLINE: {
  871. getNextKey = frameIndex => ({
  872. frame: data.input[frameIndex],
  873. inTangent: getNextOutputValue(),
  874. value: getNextOutputValue(),
  875. outTangent: getNextOutputValue()
  876. });
  877. break;
  878. }
  879. }
  880. const keys = new Array(data.input.length);
  881. for (let frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  882. keys[frameIndex] = getNextKey!(frameIndex);
  883. }
  884. if (targetPath === "influence") {
  885. for (let targetIndex = 0; targetIndex < targetNode._numMorphTargets!; targetIndex++) {
  886. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  887. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  888. babylonAnimation.setKeys(keys.map(key => ({
  889. frame: key.frame,
  890. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  891. value: key.value[targetIndex],
  892. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  893. })));
  894. const morphTargets = new Array<any>();
  895. this._forEachPrimitive(targetNode, babylonMesh => {
  896. const morphTarget = babylonMesh.morphTargetManager!.getTarget(targetIndex);
  897. morphTarget.animations.push(babylonAnimation);
  898. morphTargets.push(morphTarget);
  899. });
  900. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  901. }
  902. }
  903. else {
  904. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  905. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  906. babylonAnimation.setKeys(keys);
  907. if (targetNode._babylonAnimationTargets) {
  908. for (const babylonAnimationTarget of targetNode._babylonAnimationTargets) {
  909. babylonAnimationTarget.animations.push(babylonAnimation);
  910. }
  911. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  912. }
  913. }
  914. });
  915. }
  916. private _loadAnimationSamplerAsync(context: string, sampler: _ILoaderAnimationSampler): Promise<_ILoaderAnimationSamplerData> {
  917. if (sampler._data) {
  918. return sampler._data;
  919. }
  920. const interpolation = sampler.interpolation || AnimationSamplerInterpolation.LINEAR;
  921. switch (interpolation) {
  922. case AnimationSamplerInterpolation.STEP:
  923. case AnimationSamplerInterpolation.LINEAR:
  924. case AnimationSamplerInterpolation.CUBICSPLINE: {
  925. break;
  926. }
  927. default: {
  928. throw new Error(`${context}: Invalid interpolation (${sampler.interpolation})`);
  929. }
  930. }
  931. const inputAccessor = GLTFLoader._GetProperty(`${context}/input`, this._gltf.accessors, sampler.input);
  932. const outputAccessor = GLTFLoader._GetProperty(`${context}/output`, this._gltf.accessors, sampler.output);
  933. sampler._data = Promise.all([
  934. this._loadFloatAccessorAsync(`#/accessors/${inputAccessor._index}`, inputAccessor),
  935. this._loadFloatAccessorAsync(`#/accessors/${outputAccessor._index}`, outputAccessor)
  936. ]).then(([inputData, outputData]) => {
  937. return {
  938. input: inputData,
  939. interpolation: interpolation,
  940. output: outputData,
  941. };
  942. });
  943. return sampler._data;
  944. }
  945. private _loadBufferAsync(context: string, buffer: _ILoaderBuffer): Promise<ArrayBufferView> {
  946. if (buffer._data) {
  947. return buffer._data;
  948. }
  949. if (!buffer.uri) {
  950. throw new Error(`${context}: Uri is missing`);
  951. }
  952. buffer._data = this._loadUriAsync(context, buffer.uri);
  953. return buffer._data;
  954. }
  955. /** @hidden */
  956. public _loadBufferViewAsync(context: string, bufferView: _ILoaderBufferView): Promise<ArrayBufferView> {
  957. if (bufferView._data) {
  958. return bufferView._data;
  959. }
  960. const buffer = GLTFLoader._GetProperty(`${context}/buffer`, this._gltf.buffers, bufferView.buffer);
  961. bufferView._data = this._loadBufferAsync(`#/buffers/${buffer._index}`, buffer).then(data => {
  962. try {
  963. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  964. }
  965. catch (e) {
  966. throw new Error(`${context}: ${e.message}`);
  967. }
  968. });
  969. return bufferView._data;
  970. }
  971. private _loadIndicesAccessorAsync(context: string, accessor: _ILoaderAccessor): Promise<IndicesArray> {
  972. if (accessor.type !== AccessorType.SCALAR) {
  973. throw new Error(`${context}: Invalid type ${accessor.type}`);
  974. }
  975. if (accessor.componentType !== AccessorComponentType.UNSIGNED_BYTE &&
  976. accessor.componentType !== AccessorComponentType.UNSIGNED_SHORT &&
  977. accessor.componentType !== AccessorComponentType.UNSIGNED_INT) {
  978. throw new Error(`${context}: Invalid component type ${accessor.componentType}`);
  979. }
  980. if (accessor._data) {
  981. return accessor._data as Promise<IndicesArray>;
  982. }
  983. const bufferView = GLTFLoader._GetProperty(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  984. accessor._data = this._loadBufferViewAsync(`#/bufferViews/${bufferView._index}`, bufferView).then(data => {
  985. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  986. });
  987. return accessor._data as Promise<IndicesArray>;
  988. }
  989. private _loadFloatAccessorAsync(context: string, accessor: _ILoaderAccessor): Promise<Float32Array> {
  990. // TODO: support normalized and stride
  991. if (accessor.componentType !== AccessorComponentType.FLOAT) {
  992. throw new Error(`Invalid component type ${accessor.componentType}`);
  993. }
  994. if (accessor._data) {
  995. return accessor._data as Promise<Float32Array>;
  996. }
  997. const numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  998. const length = numComponents * accessor.count;
  999. if (accessor.bufferView == undefined) {
  1000. accessor._data = Promise.resolve(new Float32Array(length));
  1001. }
  1002. else {
  1003. const bufferView = GLTFLoader._GetProperty(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  1004. accessor._data = this._loadBufferViewAsync(`#/bufferViews/${bufferView._index}`, bufferView).then(data => {
  1005. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  1006. });
  1007. }
  1008. if (accessor.sparse) {
  1009. const sparse = accessor.sparse;
  1010. accessor._data = accessor._data.then((data: Float32Array) => {
  1011. const indicesBufferView = GLTFLoader._GetProperty(`${context}/sparse/indices/bufferView`, this._gltf.bufferViews, sparse.indices.bufferView);
  1012. const valuesBufferView = GLTFLoader._GetProperty(`${context}/sparse/values/bufferView`, this._gltf.bufferViews, sparse.values.bufferView);
  1013. return Promise.all([
  1014. this._loadBufferViewAsync(`#/bufferViews/${indicesBufferView._index}`, indicesBufferView),
  1015. this._loadBufferViewAsync(`#/bufferViews/${valuesBufferView._index}`, valuesBufferView)
  1016. ]).then(([indicesData, valuesData]) => {
  1017. const indices = GLTFLoader._GetTypedArray(`${context}/sparse/indices`, sparse.indices.componentType, indicesData, sparse.indices.byteOffset, sparse.count) as IndicesArray;
  1018. const values = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, numComponents * sparse.count) as Float32Array;
  1019. let valuesIndex = 0;
  1020. for (let indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  1021. let dataIndex = indices[indicesIndex] * numComponents;
  1022. for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1023. data[dataIndex++] = values[valuesIndex++];
  1024. }
  1025. }
  1026. return data;
  1027. });
  1028. });
  1029. }
  1030. return accessor._data as Promise<Float32Array>;
  1031. }
  1032. /** @hidden */
  1033. public _loadVertexBufferViewAsync(context: string, bufferView: _ILoaderBufferView, kind: string): Promise<Buffer> {
  1034. if (bufferView._babylonBuffer) {
  1035. return bufferView._babylonBuffer;
  1036. }
  1037. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(data => {
  1038. return new Buffer(this._babylonScene.getEngine(), data, false);
  1039. });
  1040. return bufferView._babylonBuffer;
  1041. }
  1042. private _loadVertexAccessorAsync(context: string, accessor: _ILoaderAccessor, kind: string): Promise<VertexBuffer> {
  1043. if (accessor._babylonVertexBuffer) {
  1044. return accessor._babylonVertexBuffer;
  1045. }
  1046. if (accessor.sparse) {
  1047. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(data => {
  1048. return new VertexBuffer(this._babylonScene.getEngine(), data, kind, false);
  1049. });
  1050. }
  1051. else {
  1052. const bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  1053. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(buffer => {
  1054. const size = GLTFLoader._GetNumComponents(context, accessor.type);
  1055. return new VertexBuffer(this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride,
  1056. false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  1057. });
  1058. }
  1059. return accessor._babylonVertexBuffer;
  1060. }
  1061. private _getDefaultMaterial(drawMode: number): Material {
  1062. let babylonMaterial = this._defaultBabylonMaterials[drawMode];
  1063. if (!babylonMaterial) {
  1064. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  1065. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1066. babylonMaterial.metallic = 1;
  1067. babylonMaterial.roughness = 1;
  1068. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1069. }
  1070. return babylonMaterial;
  1071. }
  1072. private _loadMaterialMetallicRoughnessPropertiesAsync(context: string, material: _ILoaderMaterial, babylonMaterial: PBRMaterial): Promise<void> {
  1073. const promises = new Array<Promise<void>>();
  1074. // Ensure metallic workflow
  1075. babylonMaterial.metallic = 1;
  1076. babylonMaterial.roughness = 1;
  1077. const properties = material.pbrMetallicRoughness;
  1078. if (properties) {
  1079. if (properties.baseColorFactor) {
  1080. babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);
  1081. babylonMaterial.alpha = properties.baseColorFactor[3];
  1082. }
  1083. else {
  1084. babylonMaterial.albedoColor = Color3.White();
  1085. }
  1086. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1087. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1088. if (properties.baseColorTexture) {
  1089. promises.push(this._loadTextureAsync(`${context}/baseColorTexture`, properties.baseColorTexture, texture => {
  1090. babylonMaterial.albedoTexture = texture;
  1091. }));
  1092. }
  1093. if (properties.metallicRoughnessTexture) {
  1094. promises.push(this._loadTextureAsync(`${context}/metallicRoughnessTexture`, properties.metallicRoughnessTexture, texture => {
  1095. babylonMaterial.metallicTexture = texture;
  1096. }));
  1097. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1098. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1099. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1100. }
  1101. }
  1102. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  1103. return Promise.all(promises).then(() => {});
  1104. }
  1105. /** @hidden */
  1106. public _loadMaterialAsync(context: string, material: _ILoaderMaterial, babylonMesh: Mesh, babylonDrawMode: number, assign: (babylonMaterial: Material) => void): Promise<void> {
  1107. const promise = GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  1108. if (promise) {
  1109. return promise;
  1110. }
  1111. material._babylonData = material._babylonData || {};
  1112. let babylonData = material._babylonData[babylonDrawMode];
  1113. if (!babylonData) {
  1114. const promises = new Array<Promise<void>>();
  1115. const name = material.name || `materialSG_${material._index}`;
  1116. const babylonMaterial = this._createMaterial(name, babylonDrawMode);
  1117. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  1118. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  1119. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1120. babylonData = {
  1121. material: babylonMaterial,
  1122. meshes: [],
  1123. loaded: Promise.all(promises).then(() => {})
  1124. };
  1125. material._babylonData[babylonDrawMode] = babylonData;
  1126. }
  1127. babylonData.meshes.push(babylonMesh);
  1128. assign(babylonData.material);
  1129. return babylonData.loaded;
  1130. }
  1131. /** @hidden */
  1132. public _createMaterial(name: string, drawMode: number): PBRMaterial {
  1133. const babylonMaterial = new PBRMaterial(name, this._babylonScene);
  1134. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
  1135. babylonMaterial.fillMode = drawMode;
  1136. babylonMaterial.enableSpecularAntiAliasing = true;
  1137. babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage;
  1138. babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage;
  1139. return babylonMaterial;
  1140. }
  1141. /** @hidden */
  1142. public _loadMaterialBasePropertiesAsync(context: string, material: _ILoaderMaterial, babylonMaterial: PBRMaterial): Promise<void> {
  1143. const promises = new Array<Promise<void>>();
  1144. babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  1145. if (material.doubleSided) {
  1146. babylonMaterial.backFaceCulling = false;
  1147. babylonMaterial.twoSidedLighting = true;
  1148. }
  1149. if (material.normalTexture) {
  1150. promises.push(this._loadTextureAsync(`${context}/normalTexture`, material.normalTexture, texture => {
  1151. babylonMaterial.bumpTexture = texture;
  1152. }));
  1153. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1154. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1155. if (material.normalTexture.scale != undefined) {
  1156. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1157. }
  1158. }
  1159. if (material.occlusionTexture) {
  1160. promises.push(this._loadTextureAsync(`${context}/occlusionTexture`, material.occlusionTexture, texture => {
  1161. babylonMaterial.ambientTexture = texture;
  1162. }));
  1163. babylonMaterial.useAmbientInGrayScale = true;
  1164. if (material.occlusionTexture.strength != undefined) {
  1165. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1166. }
  1167. }
  1168. if (material.emissiveTexture) {
  1169. promises.push(this._loadTextureAsync(`${context}/emissiveTexture`, material.emissiveTexture, texture => {
  1170. babylonMaterial.emissiveTexture = texture;
  1171. }));
  1172. }
  1173. return Promise.all(promises).then(() => {});
  1174. }
  1175. /** @hidden */
  1176. public _loadMaterialAlphaProperties(context: string, material: _ILoaderMaterial, babylonMaterial: PBRMaterial): void {
  1177. const alphaMode = material.alphaMode || MaterialAlphaMode.OPAQUE;
  1178. switch (alphaMode) {
  1179. case MaterialAlphaMode.OPAQUE: {
  1180. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1181. break;
  1182. }
  1183. case MaterialAlphaMode.MASK: {
  1184. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;
  1185. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  1186. if (babylonMaterial.albedoTexture) {
  1187. babylonMaterial.albedoTexture.hasAlpha = true;
  1188. }
  1189. break;
  1190. }
  1191. case MaterialAlphaMode.BLEND: {
  1192. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1193. if (babylonMaterial.albedoTexture) {
  1194. babylonMaterial.albedoTexture.hasAlpha = true;
  1195. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1196. }
  1197. break;
  1198. }
  1199. default: {
  1200. throw new Error(`${context}: Invalid alpha mode (${material.alphaMode})`);
  1201. }
  1202. }
  1203. }
  1204. /** @hidden */
  1205. public _loadTextureAsync(context: string, textureInfo: ITextureInfo, assign: (texture: Texture) => void): Promise<void> {
  1206. const texture = GLTFLoader._GetProperty(`${context}/index`, this._gltf.textures, textureInfo.index);
  1207. context = `#/textures/${textureInfo.index}`;
  1208. const promises = new Array<Promise<void>>();
  1209. const sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(`${context}/sampler`, this._gltf.samplers, texture.sampler));
  1210. const samplerData = this._loadSampler(`#/samplers/${sampler._index}`, sampler);
  1211. const deferred = new Deferred<void>();
  1212. const babylonTexture = new Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, () => {
  1213. if (!this._disposed) {
  1214. deferred.resolve();
  1215. }
  1216. }, (message, exception) => {
  1217. if (!this._disposed) {
  1218. deferred.reject(new Error(`${context}: ${(exception && exception.message) ? exception.message : message || "Failed to load texture"}`));
  1219. }
  1220. });
  1221. promises.push(deferred.promise);
  1222. babylonTexture.name = texture.name || `texture${texture._index}`;
  1223. babylonTexture.wrapU = samplerData.wrapU;
  1224. babylonTexture.wrapV = samplerData.wrapV;
  1225. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  1226. const image = GLTFLoader._GetProperty(`${context}/source`, this._gltf.images, texture.source);
  1227. promises.push(this._loadImageAsync(`#/images/${image._index}`, image).then(objectURL => {
  1228. babylonTexture.updateURL(objectURL);
  1229. }));
  1230. assign(babylonTexture);
  1231. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1232. return Promise.all(promises).then(() => {});
  1233. }
  1234. private _loadSampler(context: string, sampler: _ILoaderSampler): _ILoaderSamplerData {
  1235. if (!sampler._data) {
  1236. sampler._data = {
  1237. noMipMaps: (sampler.minFilter === TextureMinFilter.NEAREST || sampler.minFilter === TextureMinFilter.LINEAR),
  1238. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  1239. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  1240. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  1241. };
  1242. };
  1243. return sampler._data;
  1244. }
  1245. private _loadImageAsync(context: string, image: _ILoaderImage): Promise<string> {
  1246. if (image._objectURL) {
  1247. return image._objectURL;
  1248. }
  1249. let promise: Promise<ArrayBufferView>;
  1250. if (image.uri) {
  1251. promise = this._loadUriAsync(context, image.uri);
  1252. }
  1253. else {
  1254. const bufferView = GLTFLoader._GetProperty(`${context}/bufferView`, this._gltf.bufferViews, image.bufferView);
  1255. promise = this._loadBufferViewAsync(`#/bufferViews/${bufferView._index}`, bufferView);
  1256. }
  1257. image._objectURL = promise.then(data => {
  1258. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  1259. });
  1260. return image._objectURL;
  1261. }
  1262. /** @hidden */
  1263. public _loadUriAsync(context: string, uri: string): Promise<ArrayBufferView> {
  1264. const promise = GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  1265. if (promise) {
  1266. return promise;
  1267. }
  1268. if (!GLTFLoader._ValidateUri(uri)) {
  1269. throw new Error(`${context}: Uri '${uri}' is invalid`);
  1270. }
  1271. if (Tools.IsBase64(uri)) {
  1272. return Promise.resolve(new Uint8Array(Tools.DecodeBase64(uri)));
  1273. }
  1274. return this.preprocessUrlAsync(this._rootUrl + uri).then(url => {
  1275. return new Promise<ArrayBufferView>((resolve, reject) => {
  1276. if (!this._disposed) {
  1277. const request = Tools.LoadFile(url, data => {
  1278. if (!this._disposed) {
  1279. resolve(new Uint8Array(data as ArrayBuffer));
  1280. }
  1281. }, event => {
  1282. if (!this._disposed) {
  1283. try {
  1284. if (request && this._state === GLTFLoaderState.LOADING) {
  1285. request._lengthComputable = event.lengthComputable;
  1286. request._loaded = event.loaded;
  1287. request._total = event.total;
  1288. this._onProgress();
  1289. }
  1290. }
  1291. catch (e) {
  1292. reject(e);
  1293. }
  1294. }
  1295. }, this._babylonScene.database, true, (request, exception) => {
  1296. if (!this._disposed) {
  1297. reject(new LoadFileError(`${context}: Failed to load '${uri}'${request ? ": " + request.status + " " + request.statusText : ""}`, request));
  1298. }
  1299. }) as IFileRequestInfo;
  1300. this._requests.push(request);
  1301. }
  1302. });
  1303. });
  1304. }
  1305. private _onProgress(): void {
  1306. if (!this._progressCallback) {
  1307. return;
  1308. }
  1309. let lengthComputable = true;
  1310. let loaded = 0;
  1311. let total = 0;
  1312. for (let request of this._requests) {
  1313. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  1314. return;
  1315. }
  1316. lengthComputable = lengthComputable && request._lengthComputable;
  1317. loaded += request._loaded;
  1318. total += request._total;
  1319. }
  1320. this._progressCallback(new SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  1321. }
  1322. /** @hidden */
  1323. public static _GetProperty<T>(context: string, array: ArrayLike<T> | undefined, index: number | undefined): T {
  1324. if (!array || index == undefined || !array[index]) {
  1325. throw new Error(`${context}: Failed to find index (${index})`);
  1326. }
  1327. return array[index];
  1328. }
  1329. private static _GetTextureWrapMode(context: string, mode: TextureWrapMode | undefined): number {
  1330. // Set defaults if undefined
  1331. mode = mode == undefined ? TextureWrapMode.REPEAT : mode;
  1332. switch (mode) {
  1333. case TextureWrapMode.CLAMP_TO_EDGE: return Texture.CLAMP_ADDRESSMODE;
  1334. case TextureWrapMode.MIRRORED_REPEAT: return Texture.MIRROR_ADDRESSMODE;
  1335. case TextureWrapMode.REPEAT: return Texture.WRAP_ADDRESSMODE;
  1336. default:
  1337. Tools.Warn(`${context}: Invalid texture wrap mode (${mode})`);
  1338. return Texture.WRAP_ADDRESSMODE;
  1339. }
  1340. }
  1341. private static _GetTextureSamplingMode(context: string, magFilter?: TextureMagFilter, minFilter?: TextureMinFilter): number {
  1342. // Set defaults if undefined
  1343. magFilter = magFilter == undefined ? TextureMagFilter.LINEAR : magFilter;
  1344. minFilter = minFilter == undefined ? TextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  1345. if (magFilter === TextureMagFilter.LINEAR) {
  1346. switch (minFilter) {
  1347. case TextureMinFilter.NEAREST: return Texture.LINEAR_NEAREST;
  1348. case TextureMinFilter.LINEAR: return Texture.LINEAR_LINEAR;
  1349. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.LINEAR_NEAREST_MIPNEAREST;
  1350. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.LINEAR_LINEAR_MIPNEAREST;
  1351. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.LINEAR_NEAREST_MIPLINEAR;
  1352. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.LINEAR_LINEAR_MIPLINEAR;
  1353. default:
  1354. Tools.Warn(`${context}: Invalid texture minification filter (${minFilter})`);
  1355. return Texture.LINEAR_LINEAR_MIPLINEAR;
  1356. }
  1357. }
  1358. else {
  1359. if (magFilter !== TextureMagFilter.NEAREST) {
  1360. Tools.Warn(`${context}: Invalid texture magnification filter (${magFilter})`);
  1361. }
  1362. switch (minFilter) {
  1363. case TextureMinFilter.NEAREST: return Texture.NEAREST_NEAREST;
  1364. case TextureMinFilter.LINEAR: return Texture.NEAREST_LINEAR;
  1365. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.NEAREST_NEAREST_MIPNEAREST;
  1366. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.NEAREST_LINEAR_MIPNEAREST;
  1367. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.NEAREST_NEAREST_MIPLINEAR;
  1368. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.NEAREST_LINEAR_MIPLINEAR;
  1369. default:
  1370. Tools.Warn(`${context}: Invalid texture minification filter (${minFilter})`);
  1371. return Texture.NEAREST_NEAREST_MIPNEAREST;
  1372. }
  1373. }
  1374. }
  1375. private static _GetTypedArray(context: string, componentType: AccessorComponentType, bufferView: ArrayBufferView, byteOffset: number | undefined, length: number): ArrayBufferView {
  1376. const buffer = bufferView.buffer;
  1377. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  1378. try {
  1379. switch (componentType) {
  1380. case AccessorComponentType.BYTE: return new Int8Array(buffer, byteOffset, length);
  1381. case AccessorComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, length);
  1382. case AccessorComponentType.SHORT: return new Int16Array(buffer, byteOffset, length);
  1383. case AccessorComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, length);
  1384. case AccessorComponentType.UNSIGNED_INT: return new Uint32Array(buffer, byteOffset, length);
  1385. case AccessorComponentType.FLOAT: return new Float32Array(buffer, byteOffset, length);
  1386. default: throw new Error(`Invalid component type ${componentType}`);
  1387. }
  1388. }
  1389. catch (e) {
  1390. throw new Error(`${context}: ${e}`);
  1391. }
  1392. }
  1393. private static _GetNumComponents(context: string, type: string): number {
  1394. switch (type) {
  1395. case "SCALAR": return 1;
  1396. case "VEC2": return 2;
  1397. case "VEC3": return 3;
  1398. case "VEC4": return 4;
  1399. case "MAT2": return 4;
  1400. case "MAT3": return 9;
  1401. case "MAT4": return 16;
  1402. }
  1403. throw new Error(`${context}: Invalid type (${type})`);
  1404. }
  1405. private static _ValidateUri(uri: string): boolean {
  1406. return (Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  1407. }
  1408. private static _GetDrawMode(context: string, mode: number | undefined): number {
  1409. if (mode == undefined) {
  1410. mode = MeshPrimitiveMode.TRIANGLES;
  1411. }
  1412. switch (mode) {
  1413. case MeshPrimitiveMode.POINTS: return Material.PointListDrawMode;
  1414. case MeshPrimitiveMode.LINES: return Material.LineListDrawMode;
  1415. case MeshPrimitiveMode.LINE_LOOP: return Material.LineLoopDrawMode;
  1416. case MeshPrimitiveMode.LINE_STRIP: return Material.LineStripDrawMode;
  1417. case MeshPrimitiveMode.TRIANGLES: return Material.TriangleFillMode;
  1418. case MeshPrimitiveMode.TRIANGLE_STRIP: return Material.TriangleStripDrawMode;
  1419. case MeshPrimitiveMode.TRIANGLE_FAN: return Material.TriangleFanDrawMode;
  1420. }
  1421. throw new Error(`${context}: Invalid mesh primitive mode (${mode})`);
  1422. }
  1423. private _compileMaterialsAsync(): Promise<void> {
  1424. const promises = new Array<Promise<void>>();
  1425. if (this._gltf.materials) {
  1426. for (const material of this._gltf.materials) {
  1427. if (material._babylonData) {
  1428. for (const babylonDrawMode in material._babylonData) {
  1429. const babylonData = material._babylonData[babylonDrawMode];
  1430. for (const babylonMesh of babylonData.meshes) {
  1431. // Ensure nonUniformScaling is set if necessary.
  1432. babylonMesh.computeWorldMatrix(true);
  1433. const babylonMaterial = babylonData.material;
  1434. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  1435. if (this.useClipPlane) {
  1436. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  1437. }
  1438. }
  1439. }
  1440. }
  1441. }
  1442. }
  1443. return Promise.all(promises).then(() => {});
  1444. }
  1445. private _compileShadowGeneratorsAsync(): Promise<void> {
  1446. const promises = new Array<Promise<void>>();
  1447. const lights = this._babylonScene.lights;
  1448. for (let light of lights) {
  1449. let generator = light.getShadowGenerator();
  1450. if (generator) {
  1451. promises.push(generator.forceCompilationAsync());
  1452. }
  1453. }
  1454. return Promise.all(promises).then(() => {});
  1455. }
  1456. private _clear(): void {
  1457. for (const request of this._requests) {
  1458. request.abort();
  1459. }
  1460. this._requests.length = 0;
  1461. if (this._gltf && this._gltf.images) {
  1462. for (const image of this._gltf.images) {
  1463. if (image._objectURL) {
  1464. image._objectURL.then(value => {
  1465. URL.revokeObjectURL(value);
  1466. });
  1467. image._objectURL = undefined;
  1468. }
  1469. }
  1470. }
  1471. delete this._gltf;
  1472. delete this._babylonScene;
  1473. this._completePromises.length = 0;
  1474. for (const name in this._extensions) {
  1475. this._extensions[name].dispose();
  1476. }
  1477. this._extensions = {};
  1478. delete this._rootBabylonMesh;
  1479. delete this._progressCallback;
  1480. this.onMeshLoadedObservable.clear();
  1481. this.onTextureLoadedObservable.clear();
  1482. this.onMaterialLoadedObservable.clear();
  1483. this.onCameraLoadedObservable.clear();
  1484. }
  1485. /** @hidden */
  1486. public _applyExtensions<T>(actionAsync: (extension: GLTFLoaderExtension) => Nullable<Promise<T>>) {
  1487. for (const name of GLTFLoader._ExtensionNames) {
  1488. const extension = this._extensions[name];
  1489. if (extension.enabled) {
  1490. const promise = actionAsync(extension);
  1491. if (promise) {
  1492. return promise;
  1493. }
  1494. }
  1495. }
  1496. return null;
  1497. }
  1498. }
  1499. GLTFFileLoader.CreateGLTFLoaderV2 = () => new GLTFLoader();
  1500. }