babylon.glTFLoader.ts 81 KB

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