babylon.glTFLoader.ts 79 KB

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