babylon.glTFLoader.ts 81 KB

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