babylon.glTFLoader.ts 81 KB

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