babylon.glTFLoader.ts 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF2 {
  3. class GLTFLoaderTracker {
  4. private _pendingCount = 0;
  5. private _callback: () => void;
  6. constructor(onComplete: () => void) {
  7. this._callback = onComplete;
  8. }
  9. public _addPendingData(data: any): void {
  10. this._pendingCount++;
  11. }
  12. public _removePendingData(data: any): void {
  13. if (--this._pendingCount === 0) {
  14. this._callback();
  15. }
  16. }
  17. }
  18. interface TypedArray extends ArrayBufferView {
  19. [index: number]: number;
  20. }
  21. interface TypedArrayConstructor<T extends TypedArray> {
  22. readonly prototype: T;
  23. new(length: number): T;
  24. new(array: ArrayLike<number>): T;
  25. new(buffer: ArrayBuffer, byteOffset?: number, length?: number): T;
  26. readonly BYTES_PER_ELEMENT: number;
  27. }
  28. export class GLTFLoader implements IGLTFLoader, IDisposable {
  29. public _gltf: IGLTF;
  30. public _babylonScene: Scene;
  31. private _parent: GLTFFileLoader;
  32. private _rootUrl: string;
  33. private _defaultMaterial: PBRMaterial;
  34. private _rootNode: IGLTFNode;
  35. private _successCallback: () => void;
  36. private _progressCallback: (event: ProgressEvent) => void;
  37. private _errorCallback: (message: string) => void;
  38. private _renderReady = false;
  39. private _disposed = false;
  40. private _renderReadyObservable = new Observable<GLTFLoader>();
  41. // Count of pending work that needs to complete before the asset is rendered.
  42. private _renderPendingCount = 0;
  43. // Count of pending work that needs to complete before the loader is disposed.
  44. private _loaderPendingCount = 0;
  45. private _loaderTrackers = new Array<GLTFLoaderTracker>();
  46. public static Extensions: { [name: string]: GLTFLoaderExtension } = {};
  47. public static RegisterExtension(extension: GLTFLoaderExtension): void {
  48. if (GLTFLoader.Extensions[extension.name]) {
  49. Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  50. return;
  51. }
  52. GLTFLoader.Extensions[extension.name] = extension;
  53. // Keep the order of registration so that extensions registered first are called first.
  54. GLTFLoaderExtension._Extensions.push(extension);
  55. }
  56. public constructor(parent: GLTFFileLoader) {
  57. this._parent = parent;
  58. }
  59. public dispose(): void {
  60. if (this._disposed) {
  61. return;
  62. }
  63. this._disposed = true;
  64. // Revoke object urls created during load
  65. if (this._gltf.textures) {
  66. this._gltf.textures.forEach(texture => {
  67. if (texture.url) {
  68. URL.revokeObjectURL(texture.url);
  69. }
  70. });
  71. }
  72. this._gltf = undefined;
  73. this._babylonScene = undefined;
  74. this._rootUrl = undefined;
  75. this._defaultMaterial = undefined;
  76. this._successCallback = undefined;
  77. this._errorCallback = undefined;
  78. this._renderReady = false;
  79. this._renderReadyObservable.clear();
  80. this._renderPendingCount = 0;
  81. this._loaderPendingCount = 0;
  82. }
  83. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress: (event: ProgressEvent) => void, onError: (message: string) => void): void {
  84. this._loadAsync(meshesNames, scene, data, rootUrl, () => {
  85. onSuccess(this._getMeshes(), null, this._getSkeletons());
  86. }, onProgress, onError);
  87. }
  88. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: ProgressEvent) => void, onError: (message: string) => void): void {
  89. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  90. }
  91. private _loadAsync(nodeNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: ProgressEvent) => void, onError: (message: string) => void): void {
  92. this._tryCatchOnError(() => {
  93. this._loadData(data);
  94. this._babylonScene = scene;
  95. this._rootUrl = rootUrl;
  96. this._successCallback = onSuccess;
  97. this._progressCallback = onProgress;
  98. this._errorCallback = onError;
  99. GLTFUtils.AssignIndices(this._gltf.accessors);
  100. GLTFUtils.AssignIndices(this._gltf.animations);
  101. GLTFUtils.AssignIndices(this._gltf.buffers);
  102. GLTFUtils.AssignIndices(this._gltf.bufferViews);
  103. GLTFUtils.AssignIndices(this._gltf.images);
  104. GLTFUtils.AssignIndices(this._gltf.materials);
  105. GLTFUtils.AssignIndices(this._gltf.meshes);
  106. GLTFUtils.AssignIndices(this._gltf.nodes);
  107. GLTFUtils.AssignIndices(this._gltf.scenes);
  108. GLTFUtils.AssignIndices(this._gltf.skins);
  109. GLTFUtils.AssignIndices(this._gltf.textures);
  110. this._addPendingData(this);
  111. this._loadDefaultScene(nodeNames);
  112. this._loadAnimations();
  113. this._removePendingData(this);
  114. });
  115. }
  116. private _onError(message: string): void {
  117. if (this._disposed) {
  118. return;
  119. }
  120. Tools.Error("glTF Loader: " + message);
  121. if (this._errorCallback) {
  122. this._errorCallback(message);
  123. }
  124. this.dispose();
  125. }
  126. private _onProgress(event: ProgressEvent): void {
  127. if (this._disposed) {
  128. return;
  129. }
  130. if (this._progressCallback) {
  131. this._progressCallback(event);
  132. }
  133. }
  134. public _executeWhenRenderReady(func: () => void): void {
  135. if (this._renderReady) {
  136. func();
  137. }
  138. else {
  139. this._renderReadyObservable.add(func);
  140. }
  141. }
  142. private _onRenderReady(): void {
  143. this._rootNode.babylonMesh.setEnabled(true);
  144. this._startAnimations();
  145. this._successCallback();
  146. this._renderReadyObservable.notifyObservers(this);
  147. if (this._parent.onReady) {
  148. this._parent.onReady();
  149. }
  150. }
  151. private _onComplete(): void {
  152. if (this._parent.onComplete) {
  153. this._parent.onComplete();
  154. }
  155. this.dispose();
  156. }
  157. private _loadData(data: IGLTFLoaderData): void {
  158. this._gltf = <IGLTF>data.json;
  159. if (data.bin) {
  160. var buffers = this._gltf.buffers;
  161. if (buffers && buffers[0] && !buffers[0].uri) {
  162. var binaryBuffer = buffers[0];
  163. if (binaryBuffer.byteLength != data.bin.byteLength) {
  164. Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  165. }
  166. binaryBuffer.loadedData = data.bin;
  167. }
  168. else {
  169. Tools.Warn("Unexpected BIN chunk");
  170. }
  171. }
  172. }
  173. private _getMeshes(): Mesh[] {
  174. var meshes = [this._rootNode.babylonMesh];
  175. var nodes = this._gltf.nodes;
  176. if (nodes) {
  177. nodes.forEach(node => {
  178. if (node.babylonMesh) {
  179. meshes.push(node.babylonMesh);
  180. }
  181. });
  182. }
  183. return meshes;
  184. }
  185. private _getSkeletons(): Skeleton[] {
  186. var skeletons = new Array<Skeleton>();
  187. var skins = this._gltf.skins;
  188. if (skins) {
  189. skins.forEach(skin => {
  190. if (skin.babylonSkeleton instanceof Skeleton) {
  191. skeletons.push(skin.babylonSkeleton);
  192. }
  193. });
  194. }
  195. return skeletons;
  196. }
  197. private _getAnimationTargets(): any[] {
  198. var targets = new Array();
  199. var animations = this._gltf.animations;
  200. if (animations) {
  201. animations.forEach(animation => {
  202. targets.push(...animation.targets);
  203. });
  204. }
  205. return targets;
  206. }
  207. private _startAnimations(): void {
  208. this._getAnimationTargets().forEach(target => this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true));
  209. }
  210. private _loadDefaultScene(nodeNames: any): void {
  211. var scene = GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  212. if (!scene) {
  213. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  214. }
  215. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  216. }
  217. private _loadScene(context: string, scene: IGLTFScene, nodeNames: any): void {
  218. this._rootNode = { babylonMesh: new Mesh("__root__", this._babylonScene) };
  219. switch (this._parent.coordinateSystemMode) {
  220. case GLTFLoaderCoordinateSystemMode.AUTO:
  221. if (!this._babylonScene.useRightHandedSystem) {
  222. this._rootNode.babylonMesh.rotation = new Vector3(0, Math.PI, 0);
  223. this._rootNode.babylonMesh.scaling = new Vector3(1, 1, -1);
  224. }
  225. break;
  226. case GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  227. // do nothing
  228. break;
  229. case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  230. this._babylonScene.useRightHandedSystem = true;
  231. break;
  232. default:
  233. Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  234. return;
  235. }
  236. var nodeIndices = scene.nodes;
  237. this._traverseNodes(context, nodeIndices, (node, parentNode) => {
  238. node.parent = parentNode;
  239. return true;
  240. }, this._rootNode);
  241. if (nodeNames) {
  242. if (!(nodeNames instanceof Array)) {
  243. nodeNames = [nodeNames];
  244. }
  245. var filteredNodeIndices = new Array<number>();
  246. this._traverseNodes(context, nodeIndices, node => {
  247. if (nodeNames.indexOf(node.name) !== -1) {
  248. filteredNodeIndices.push(node.index);
  249. return false;
  250. }
  251. return true;
  252. }, this._rootNode);
  253. nodeIndices = filteredNodeIndices;
  254. }
  255. for (var i = 0; i < nodeIndices.length; i++) {
  256. var node = GLTFUtils.GetArrayItem(this._gltf.nodes, nodeIndices[i]);
  257. if (!node) {
  258. throw new Error(context + ": Failed to find node " + nodeIndices[i]);
  259. }
  260. this._loadNode("#/nodes/" + nodeIndices[i], node);
  261. }
  262. // Disable the root mesh until the asset is ready to render.
  263. this._rootNode.babylonMesh.setEnabled(false);
  264. }
  265. public _loadNode(context: string, node: IGLTFNode): void {
  266. if (GLTFLoaderExtension.LoadNode(this, context, node)) {
  267. return;
  268. }
  269. node.babylonMesh = new Mesh(node.name || "mesh" + node.index, this._babylonScene);
  270. this._loadTransform(node);
  271. if (node.mesh != null) {
  272. var mesh = GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  273. if (!mesh) {
  274. throw new Error(context + ": Failed to find mesh " + node.mesh);
  275. }
  276. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  277. }
  278. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  279. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  280. node.babylonAnimationTargets.push(node.babylonMesh);
  281. if (node.skin != null) {
  282. var skin = GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  283. if (!skin) {
  284. throw new Error(context + ": Failed to find skin " + node.skin);
  285. }
  286. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  287. }
  288. if (node.camera != null) {
  289. // TODO: handle cameras
  290. }
  291. if (node.children) {
  292. for (var i = 0; i < node.children.length; i++) {
  293. var childNode = GLTFUtils.GetArrayItem(this._gltf.nodes, node.children[i]);
  294. if (!childNode) {
  295. throw new Error(context + ": Failed to find child node " + node.children[i]);
  296. }
  297. this._loadNode("#/nodes/" + node.children[i], childNode);
  298. }
  299. }
  300. }
  301. private _loadMesh(context: string, node: IGLTFNode, mesh: IGLTFMesh): void {
  302. node.babylonMesh.name = node.babylonMesh.name || mesh.name;
  303. if (!mesh.primitives || mesh.primitives.length === 0) {
  304. throw new Error(context + ": Primitives are missing");
  305. }
  306. this._createMorphTargets(context, node, mesh);
  307. this._loadAllVertexDataAsync(context, mesh, () => {
  308. this._loadMorphTargets(context, node, mesh);
  309. var primitives = mesh.primitives;
  310. var vertexData = new VertexData();
  311. for (var primitive of primitives) {
  312. vertexData.merge(primitive.vertexData);
  313. }
  314. new Geometry(node.babylonMesh.name, this._babylonScene, vertexData, false, node.babylonMesh);
  315. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  316. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  317. node.babylonMesh.subMeshes = [];
  318. var verticesStart = 0;
  319. var indicesStart = 0;
  320. for (var index = 0; index < primitives.length; index++) {
  321. var vertexData = primitives[index].vertexData;
  322. var verticesCount = vertexData.positions.length;
  323. var indicesCount = vertexData.indices.length;
  324. SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  325. verticesStart += verticesCount;
  326. indicesStart += indicesCount;
  327. };
  328. var multiMaterial = new MultiMaterial(node.babylonMesh.name, this._babylonScene);
  329. node.babylonMesh.material = multiMaterial;
  330. var subMaterials = multiMaterial.subMaterials;
  331. for (var index = 0; index < primitives.length; index++) {
  332. var primitive = primitives[index];
  333. if (primitive.material == null) {
  334. subMaterials[index] = this._getDefaultMaterial();
  335. }
  336. else {
  337. var material = GLTFUtils.GetArrayItem(this._gltf.materials, primitive.material);
  338. if (!material) {
  339. throw new Error(context + ": Failed to find material " + primitive.material);
  340. }
  341. this._loadMaterial("#/materials/" + material.index, material, (babylonMaterial, isNew) => {
  342. if (isNew && this._parent.onMaterialLoaded) {
  343. this._parent.onMaterialLoaded(babylonMaterial);
  344. }
  345. if (this._parent.onBeforeMaterialReadyAsync) {
  346. this._addLoaderPendingData(material);
  347. this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, () => {
  348. subMaterials[index] = babylonMaterial;
  349. this._removeLoaderPendingData(material);
  350. });
  351. } else {
  352. subMaterials[index] = babylonMaterial;
  353. }
  354. });
  355. }
  356. };
  357. });
  358. }
  359. private _loadAllVertexDataAsync(context: string, mesh: IGLTFMesh, onSuccess: () => void): void {
  360. var primitives = mesh.primitives;
  361. var numRemainingPrimitives = primitives.length;
  362. for (var index = 0; index < primitives.length; index++) {
  363. let primitive = primitives[index];
  364. this._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, vertexData => {
  365. primitive.vertexData = vertexData;
  366. if (--numRemainingPrimitives === 0) {
  367. onSuccess();
  368. }
  369. });
  370. }
  371. }
  372. private _loadVertexDataAsync(context: string, mesh: IGLTFMesh, primitive: IGLTFMeshPrimitive, onSuccess: (vertexData: VertexData) => void): void {
  373. var attributes = primitive.attributes;
  374. if (!attributes) {
  375. throw new Error(context + ": Attributes are missing");
  376. }
  377. if (primitive.mode && primitive.mode !== EMeshPrimitiveMode.TRIANGLES) {
  378. // TODO: handle other primitive modes
  379. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  380. }
  381. var vertexData = new VertexData();
  382. var numRemainingAttributes = Object.keys(attributes).length;
  383. for (let attribute in attributes) {
  384. var accessor = GLTFUtils.GetArrayItem(this._gltf.accessors, attributes[attribute]);
  385. if (!accessor) {
  386. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  387. }
  388. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, data => {
  389. switch (attribute) {
  390. case "NORMAL":
  391. vertexData.normals = <Float32Array>data;
  392. break;
  393. case "POSITION":
  394. vertexData.positions = <Float32Array>data;
  395. break;
  396. case "TANGENT":
  397. vertexData.tangents = <Float32Array>data;
  398. break;
  399. case "TEXCOORD_0":
  400. vertexData.uvs = <Float32Array>data;
  401. break;
  402. case "TEXCOORD_1":
  403. vertexData.uvs2 = <Float32Array>data;
  404. break;
  405. case "JOINTS_0":
  406. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  407. break;
  408. case "WEIGHTS_0":
  409. vertexData.matricesWeights = <Float32Array>data;
  410. break;
  411. case "COLOR_0":
  412. vertexData.colors = <Float32Array>data;
  413. break;
  414. default:
  415. Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  416. break;
  417. }
  418. if (--numRemainingAttributes === 0) {
  419. if (primitive.indices == null) {
  420. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  421. vertexData.indices.forEach((v, i) => vertexData.indices[i] = i);
  422. onSuccess(vertexData);
  423. }
  424. else {
  425. var indicesAccessor = GLTFUtils.GetArrayItem(this._gltf.accessors, primitive.indices);
  426. if (!indicesAccessor) {
  427. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  428. }
  429. this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, data => {
  430. vertexData.indices = <IndicesArray>data;
  431. onSuccess(vertexData);
  432. });
  433. }
  434. }
  435. });
  436. }
  437. }
  438. private _createMorphTargets(context: string, node: IGLTFNode, mesh: IGLTFMesh): void {
  439. var primitives = mesh.primitives;
  440. var targets = primitives[0].targets;
  441. if (!targets) {
  442. return;
  443. }
  444. for (var primitive of primitives) {
  445. if (!primitive.targets || primitive.targets.length != targets.length) {
  446. throw new Error(context + ": All primitives are required to list the same number of targets");
  447. }
  448. }
  449. var morphTargetManager = new MorphTargetManager();
  450. node.babylonMesh.morphTargetManager = morphTargetManager;
  451. for (var index = 0; index < targets.length; index++) {
  452. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  453. morphTargetManager.addTarget(new MorphTarget("morphTarget" + index, weight));
  454. }
  455. }
  456. private _loadMorphTargets(context: string, node: IGLTFNode, mesh: IGLTFMesh): void {
  457. var morphTargetManager = node.babylonMesh.morphTargetManager;
  458. if (!morphTargetManager) {
  459. return;
  460. }
  461. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, () => {
  462. var numTargets = morphTargetManager.numTargets;
  463. for (var index = 0; index < numTargets; index++) {
  464. var vertexData = new VertexData();
  465. for (var primitive of mesh.primitives) {
  466. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  467. }
  468. var target = morphTargetManager.getTarget(index);
  469. target.setNormals(vertexData.normals);
  470. target.setPositions(vertexData.positions);
  471. target.setTangents(vertexData.tangents);
  472. }
  473. });
  474. }
  475. private _loadAllMorphTargetVertexDataAsync(context: string, node: IGLTFNode, mesh: IGLTFMesh, onSuccess: () => void): void {
  476. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  477. for (var primitive of mesh.primitives) {
  478. var targets = primitive.targets;
  479. primitive.targetsVertexData = new Array<VertexData>(targets.length);
  480. for (let index = 0; index < targets.length; index++) {
  481. this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], vertexData => {
  482. primitive.targetsVertexData[index] = vertexData;
  483. if (--numRemainingTargets === 0) {
  484. onSuccess();
  485. }
  486. });
  487. }
  488. }
  489. }
  490. private _loadMorphTargetVertexDataAsync(context: string, vertexData: VertexData, attributes: { [name: string]: number }, onSuccess: (vertexData: VertexData) => void): void {
  491. var targetVertexData = new VertexData();
  492. var numRemainingAttributes = Object.keys(attributes).length;
  493. for (let attribute in attributes) {
  494. var accessor = GLTFUtils.GetArrayItem(this._gltf.accessors, attributes[attribute]);
  495. if (!accessor) {
  496. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  497. }
  498. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, data => {
  499. // glTF stores morph target information as deltas while babylon.js expects the final data.
  500. // As a result we have to add the original data to the delta to calculate the final data.
  501. var values = <Float32Array>data;
  502. switch (attribute) {
  503. case "NORMAL":
  504. for (var i = 0; i < values.length; i++) {
  505. values[i] += vertexData.normals[i];
  506. }
  507. targetVertexData.normals = values;
  508. break;
  509. case "POSITION":
  510. for (var i = 0; i < values.length; i++) {
  511. values[i] += vertexData.positions[i];
  512. }
  513. targetVertexData.positions = values;
  514. break;
  515. case "TANGENT":
  516. // Tangent data for morph targets is stored as xyz delta.
  517. // The vertexData.tangent is stored as xyzw.
  518. // So we need to skip every fourth vertexData.tangent.
  519. for (var i = 0, j = 0; i < values.length; i++, j++) {
  520. values[i] += vertexData.tangents[j];
  521. if ((i + 1) % 3 == 0) {
  522. j++;
  523. }
  524. }
  525. targetVertexData.tangents = values;
  526. break;
  527. default:
  528. Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  529. break;
  530. }
  531. if (--numRemainingAttributes === 0) {
  532. onSuccess(targetVertexData);
  533. }
  534. });
  535. }
  536. }
  537. private _loadTransform(node: IGLTFNode): void {
  538. var position: Vector3 = Vector3.Zero();
  539. var rotation: Quaternion = Quaternion.Identity();
  540. var scaling: Vector3 = Vector3.One();
  541. if (node.matrix) {
  542. var mat = Matrix.FromArray(node.matrix);
  543. mat.decompose(scaling, rotation, position);
  544. }
  545. else {
  546. if (node.translation) position = Vector3.FromArray(node.translation);
  547. if (node.rotation) rotation = Quaternion.FromArray(node.rotation);
  548. if (node.scale) scaling = Vector3.FromArray(node.scale);
  549. }
  550. node.babylonMesh.position = position;
  551. node.babylonMesh.rotationQuaternion = rotation;
  552. node.babylonMesh.scaling = scaling;
  553. }
  554. private _loadSkin(context: string, skin: IGLTFSkin): Skeleton {
  555. var skeletonId = "skeleton" + skin.index;
  556. skin.babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  557. if (skin.inverseBindMatrices == null) {
  558. this._loadBones(context, skin, null);
  559. }
  560. else {
  561. var accessor = GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  562. if (!accessor) {
  563. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  564. }
  565. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, data => {
  566. this._loadBones(context, skin, <Float32Array>data);
  567. });
  568. }
  569. return skin.babylonSkeleton;
  570. }
  571. private _createBone(node: IGLTFNode, skin: IGLTFSkin, parent: Bone, localMatrix: Matrix, baseMatrix: Matrix, index: number): Bone {
  572. var babylonBone = new Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  573. node.babylonBones = node.babylonBones || {};
  574. node.babylonBones[skin.index] = babylonBone;
  575. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  576. node.babylonAnimationTargets.push(babylonBone);
  577. return babylonBone;
  578. }
  579. private _loadBones(context: string, skin: IGLTFSkin, inverseBindMatrixData: Float32Array): void {
  580. var babylonBones: { [index: number]: Bone } = {};
  581. for (var i = 0; i < skin.joints.length; i++) {
  582. var node = GLTFUtils.GetArrayItem(this._gltf.nodes, skin.joints[i]);
  583. if (!node) {
  584. throw new Error(context + ": Failed to find joint " + skin.joints[i]);
  585. }
  586. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  587. }
  588. }
  589. private _loadBone(node: IGLTFNode, skin: IGLTFSkin, inverseBindMatrixData: Float32Array, babylonBones: { [index: number]: Bone }): Bone {
  590. var babylonBone = babylonBones[node.index];
  591. if (babylonBone) {
  592. return babylonBone;
  593. }
  594. var boneIndex = skin.joints.indexOf(node.index);
  595. var baseMatrix = Matrix.Identity();
  596. if (inverseBindMatrixData && boneIndex !== -1) {
  597. baseMatrix = Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  598. baseMatrix.invertToRef(baseMatrix);
  599. }
  600. var babylonParentBone: Bone;
  601. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  602. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  603. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  604. }
  605. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  606. babylonBones[node.index] = babylonBone;
  607. return babylonBone;
  608. }
  609. private _getNodeMatrix(node: IGLTFNode): Matrix {
  610. return node.matrix ?
  611. Matrix.FromArray(node.matrix) :
  612. Matrix.Compose(
  613. node.scale ? Vector3.FromArray(node.scale) : Vector3.One(),
  614. node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(),
  615. node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());
  616. }
  617. private _traverseNodes(context: string, indices: number[], action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode = null): void {
  618. for (var i = 0; i < indices.length; i++) {
  619. var node = GLTFUtils.GetArrayItem(this._gltf.nodes, indices[i]);
  620. if (!node) {
  621. throw new Error(context + ": Failed to find node " + indices[i]);
  622. }
  623. this._traverseNode(context, node, action, parentNode);
  624. }
  625. }
  626. public _traverseNode(context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode = null): void {
  627. if (GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  628. return;
  629. }
  630. if (!action(node, parentNode)) {
  631. return;
  632. }
  633. if (node.children) {
  634. this._traverseNodes(context, node.children, action, node);
  635. }
  636. }
  637. private _loadAnimations(): void {
  638. var animations = this._gltf.animations;
  639. if (!animations) {
  640. return;
  641. }
  642. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  643. var animation = animations[animationIndex];
  644. var context = "#/animations/" + animationIndex;
  645. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  646. var channel = GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  647. if (!channel) {
  648. throw new Error(context + ": Failed to find channel " + channelIndex);
  649. }
  650. var sampler = GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  651. if (!sampler) {
  652. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  653. }
  654. this._loadAnimationChannel(animation,
  655. context + "/channels/" + channelIndex, channel,
  656. context + "/samplers/" + channel.sampler, sampler);
  657. }
  658. }
  659. }
  660. private _loadAnimationChannel(animation: IGLTFAnimation, channelContext: string, channel: IGLTFAnimationChannel, samplerContext: string, sampler: IGLTFAnimationSampler): void {
  661. var targetNode = GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  662. if (!targetNode) {
  663. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  664. }
  665. var targetPath: string;
  666. var animationType: number;
  667. switch (channel.target.path) {
  668. case "translation":
  669. targetPath = "position";
  670. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  671. break;
  672. case "rotation":
  673. targetPath = "rotationQuaternion";
  674. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  675. break;
  676. case "scale":
  677. targetPath = "scaling";
  678. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  679. break;
  680. case "weights":
  681. targetPath = "influence";
  682. animationType = Animation.ANIMATIONTYPE_FLOAT;
  683. break;
  684. default:
  685. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  686. }
  687. var inputData: Float32Array;
  688. var outputData: Float32Array;
  689. var checkSuccess = () => {
  690. if (!inputData || !outputData) {
  691. return;
  692. }
  693. var outputBufferOffset = 0;
  694. var getNextOutputValue: () => any;
  695. switch (targetPath) {
  696. case "position":
  697. getNextOutputValue = () => {
  698. var value = Vector3.FromArray(outputData, outputBufferOffset);
  699. outputBufferOffset += 3;
  700. return value;
  701. };
  702. break;
  703. case "rotationQuaternion":
  704. getNextOutputValue = () => {
  705. var value = Quaternion.FromArray(outputData, outputBufferOffset);
  706. outputBufferOffset += 4;
  707. return value;
  708. };
  709. break;
  710. case "scaling":
  711. getNextOutputValue = () => {
  712. var value = Vector3.FromArray(outputData, outputBufferOffset);
  713. outputBufferOffset += 3;
  714. return value;
  715. };
  716. break;
  717. case "influence":
  718. getNextOutputValue = () => {
  719. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  720. var value = new Array<number>(numTargets);
  721. for (var i = 0; i < numTargets; i++) {
  722. value[i] = outputData[outputBufferOffset++];
  723. }
  724. return value;
  725. };
  726. break;
  727. }
  728. var getNextKey: (frameIndex: number) => any;
  729. switch (sampler.interpolation) {
  730. case "LINEAR":
  731. getNextKey = frameIndex => ({
  732. frame: inputData[frameIndex],
  733. value: getNextOutputValue()
  734. });
  735. break;
  736. case "CUBICSPLINE":
  737. getNextKey = frameIndex => ({
  738. frame: inputData[frameIndex],
  739. inTangent: getNextOutputValue(),
  740. value: getNextOutputValue(),
  741. outTangent: getNextOutputValue()
  742. });
  743. break;
  744. default:
  745. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  746. };
  747. var keys = new Array(inputData.length);
  748. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  749. keys[frameIndex] = getNextKey(frameIndex);
  750. }
  751. animation.targets = animation.targets || [];
  752. if (targetPath === "influence") {
  753. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  754. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  755. var morphTarget = morphTargetManager.getTarget(targetIndex);
  756. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  757. var babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  758. babylonAnimation.setKeys(keys.map(key => ({
  759. frame: key.frame,
  760. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  761. value: key.value[targetIndex],
  762. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  763. })));
  764. morphTarget.animations.push(babylonAnimation);
  765. animation.targets.push(morphTarget);
  766. }
  767. }
  768. else {
  769. var animationName = animation.name || "anim" + animation.index;
  770. var babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  771. babylonAnimation.setKeys(keys);
  772. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  773. var target = targetNode.babylonAnimationTargets[i];
  774. target.animations.push(babylonAnimation.clone());
  775. animation.targets.push(target);
  776. }
  777. }
  778. };
  779. var inputAccessor = GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  780. if (!inputAccessor) {
  781. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  782. }
  783. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, data => {
  784. inputData = <Float32Array>data;
  785. checkSuccess();
  786. });
  787. var outputAccessor = GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  788. if (!outputAccessor) {
  789. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  790. }
  791. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, data => {
  792. outputData = <Float32Array>data;
  793. checkSuccess();
  794. });
  795. }
  796. private _loadBufferAsync(context: string, buffer: IGLTFBuffer, onSuccess: (data: ArrayBufferView) => void): void {
  797. this._addPendingData(buffer);
  798. if (buffer.loadedData) {
  799. onSuccess(buffer.loadedData);
  800. this._removePendingData(buffer);
  801. }
  802. else if (buffer.loadedObservable) {
  803. buffer.loadedObservable.add(buffer => {
  804. onSuccess(buffer.loadedData);
  805. this._removePendingData(buffer);
  806. });
  807. }
  808. else {
  809. if (!buffer.uri) {
  810. throw new Error(context + ": Uri is missing");
  811. }
  812. if (GLTFUtils.IsBase64(buffer.uri)) {
  813. var data = GLTFUtils.DecodeBase64(buffer.uri);
  814. buffer.loadedData = new Uint8Array(data);
  815. onSuccess(buffer.loadedData);
  816. this._removePendingData(buffer);
  817. }
  818. else {
  819. if (!GLTFUtils.ValidateUri(buffer.uri)) {
  820. throw new Error(context + ": Uri '" + buffer.uri + "' is invalid");
  821. }
  822. buffer.loadedObservable = new Observable<IGLTFBuffer>();
  823. buffer.loadedObservable.add(buffer => {
  824. onSuccess(buffer.loadedData);
  825. this._removePendingData(buffer);
  826. });
  827. Tools.LoadFile(this._rootUrl + buffer.uri, data => {
  828. this._tryCatchOnError(() => {
  829. buffer.loadedData = new Uint8Array(data);
  830. buffer.loadedObservable.notifyObservers(buffer);
  831. buffer.loadedObservable = null;
  832. });
  833. }, event => {
  834. this._tryCatchOnError(() => {
  835. this._onProgress(event);
  836. });
  837. }, this._babylonScene.database, true, request => {
  838. this._tryCatchOnError(() => {
  839. throw new Error(context + ": Failed to load '" + buffer.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  840. });
  841. });
  842. }
  843. }
  844. }
  845. private _loadBufferViewAsync(context: string, bufferView: IGLTFBufferView, onSuccess: (data: ArrayBufferView) => void): void {
  846. var buffer = GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  847. if (!buffer) {
  848. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  849. }
  850. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, bufferData => {
  851. if (this._disposed) {
  852. return;
  853. }
  854. try {
  855. var data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  856. }
  857. catch (e) {
  858. throw new Error(context + ": " + e.message);
  859. }
  860. onSuccess(data);
  861. });
  862. }
  863. private _loadAccessorAsync(context: string, accessor: IGLTFAccessor, onSuccess: (data: ArrayBufferView) => void): void {
  864. if (accessor.sparse) {
  865. throw new Error(context + ": Sparse accessors are not currently supported");
  866. }
  867. if (accessor.normalized) {
  868. throw new Error(context + ": Normalized accessors are not currently supported");
  869. }
  870. var bufferView = GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  871. if (!bufferView) {
  872. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  873. }
  874. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, bufferViewData => {
  875. var numComponents = this._getNumComponentsOfType(accessor.type);
  876. if (numComponents === 0) {
  877. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  878. }
  879. var data: ArrayBufferView;
  880. switch (accessor.componentType) {
  881. case EComponentType.BYTE:
  882. data = this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  883. break;
  884. case EComponentType.UNSIGNED_BYTE:
  885. data = this._buildArrayBuffer(Uint8Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  886. break;
  887. case EComponentType.SHORT:
  888. data = this._buildArrayBuffer(Int16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  889. break;
  890. case EComponentType.UNSIGNED_SHORT:
  891. data = this._buildArrayBuffer(Uint16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  892. break;
  893. case EComponentType.UNSIGNED_INT:
  894. data = this._buildArrayBuffer(Uint32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  895. break;
  896. case EComponentType.FLOAT:
  897. data = this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  898. break;
  899. default:
  900. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  901. }
  902. onSuccess(data);
  903. });
  904. }
  905. private _getNumComponentsOfType(type: string): number {
  906. switch (type) {
  907. case "SCALAR": return 1;
  908. case "VEC2": return 2;
  909. case "VEC3": return 3;
  910. case "VEC4": return 4;
  911. case "MAT2": return 4;
  912. case "MAT3": return 9;
  913. case "MAT4": return 16;
  914. }
  915. return 0;
  916. }
  917. private _buildArrayBuffer<T extends TypedArray>(typedArray: TypedArrayConstructor<T>, context: string, data: ArrayBufferView, byteOffset: number, count: number, numComponents: number, byteStride: number): T {
  918. try {
  919. var byteOffset = data.byteOffset + (byteOffset || 0);
  920. var targetLength = count * numComponents;
  921. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  922. return new typedArray(data.buffer, byteOffset, targetLength);
  923. }
  924. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  925. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  926. var targetBuffer = new typedArray(targetLength);
  927. var sourceIndex = 0;
  928. var targetIndex = 0;
  929. while (targetIndex < targetLength) {
  930. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  931. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  932. targetIndex++;
  933. }
  934. sourceIndex += elementStride;
  935. }
  936. return targetBuffer;
  937. }
  938. catch (e) {
  939. throw new Error(context + ": " + e);
  940. }
  941. }
  942. public _addPendingData(data: any): void {
  943. if (!this._renderReady) {
  944. this._renderPendingCount++;
  945. }
  946. this._addLoaderPendingData(data);
  947. }
  948. public _removePendingData(data: any): void {
  949. if (!this._renderReady) {
  950. if (--this._renderPendingCount === 0) {
  951. this._renderReady = true;
  952. this._onRenderReady();
  953. }
  954. }
  955. this._removeLoaderPendingData(data);
  956. }
  957. public _addLoaderPendingData(data: any): void {
  958. this._loaderPendingCount++;
  959. this._loaderTrackers.forEach(tracker => tracker._addPendingData(data));
  960. }
  961. public _removeLoaderPendingData(data: any): void {
  962. this._loaderTrackers.forEach(tracker => tracker._removePendingData(data));
  963. if (--this._loaderPendingCount === 0) {
  964. this._onComplete();
  965. }
  966. }
  967. public _whenAction(action: () => void, onComplete: () => void): void {
  968. var tracker = new GLTFLoaderTracker(() => {
  969. this._loaderTrackers.splice(this._loaderTrackers.indexOf(tracker));
  970. onComplete();
  971. });
  972. this._loaderTrackers.push(tracker);
  973. this._addLoaderPendingData(tracker);
  974. action();
  975. this._removeLoaderPendingData(tracker);
  976. }
  977. private _getDefaultMaterial(): Material {
  978. if (!this._defaultMaterial) {
  979. var id = "__gltf_default";
  980. var material = <PBRMaterial>this._babylonScene.getMaterialByName(id);
  981. if (!material) {
  982. material = new PBRMaterial(id, this._babylonScene);
  983. material.sideOrientation = Material.CounterClockWiseSideOrientation;
  984. material.metallic = 1;
  985. material.roughness = 1;
  986. }
  987. this._defaultMaterial = material;
  988. }
  989. return this._defaultMaterial;
  990. }
  991. private _loadMaterialMetallicRoughnessProperties(context: string, material: IGLTFMaterial): void {
  992. var babylonMaterial = material.babylonMaterial as PBRMaterial;
  993. // Ensure metallic workflow
  994. babylonMaterial.metallic = 1;
  995. babylonMaterial.roughness = 1;
  996. var properties = material.pbrMetallicRoughness;
  997. if (!properties) {
  998. return;
  999. }
  1000. babylonMaterial.albedoColor = properties.baseColorFactor ? Color3.FromArray(properties.baseColorFactor) : new Color3(1, 1, 1);
  1001. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  1002. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  1003. if (properties.baseColorTexture) {
  1004. var texture = GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  1005. if (!texture) {
  1006. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  1007. }
  1008. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  1009. }
  1010. if (properties.metallicRoughnessTexture) {
  1011. var texture = GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  1012. if (!texture) {
  1013. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  1014. }
  1015. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  1016. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1017. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1018. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1019. }
  1020. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  1021. }
  1022. public _loadMaterial(context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): void {
  1023. if (material.babylonMaterial) {
  1024. assign(material.babylonMaterial, false);
  1025. return;
  1026. }
  1027. if (GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  1028. return;
  1029. }
  1030. this._createPbrMaterial(material);
  1031. this._loadMaterialBaseProperties(context, material);
  1032. this._loadMaterialMetallicRoughnessProperties(context, material);
  1033. assign(material.babylonMaterial, true);
  1034. }
  1035. public _createPbrMaterial(material: IGLTFMaterial): void {
  1036. var babylonMaterial = new PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1037. babylonMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  1038. material.babylonMaterial = babylonMaterial;
  1039. }
  1040. public _loadMaterialBaseProperties(context: string, material: IGLTFMaterial): void {
  1041. var babylonMaterial = material.babylonMaterial as PBRMaterial;
  1042. babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  1043. if (material.doubleSided) {
  1044. babylonMaterial.backFaceCulling = false;
  1045. babylonMaterial.twoSidedLighting = true;
  1046. }
  1047. if (material.normalTexture) {
  1048. var texture = GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  1049. if (!texture) {
  1050. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  1051. }
  1052. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  1053. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1054. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1055. if (material.normalTexture.scale != null) {
  1056. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1057. }
  1058. }
  1059. if (material.occlusionTexture) {
  1060. var texture = GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  1061. if (!texture) {
  1062. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  1063. }
  1064. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  1065. babylonMaterial.useAmbientInGrayScale = true;
  1066. if (material.occlusionTexture.strength != null) {
  1067. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1068. }
  1069. }
  1070. if (material.emissiveTexture) {
  1071. var texture = GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  1072. if (!texture) {
  1073. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  1074. }
  1075. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  1076. }
  1077. }
  1078. public _loadMaterialAlphaProperties(context: string, material: IGLTFMaterial, colorFactor: number[]): void {
  1079. var babylonMaterial = material.babylonMaterial as PBRMaterial;
  1080. var alphaMode = material.alphaMode || "OPAQUE";
  1081. switch (alphaMode) {
  1082. case "OPAQUE":
  1083. // default is opaque
  1084. break;
  1085. case "MASK":
  1086. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  1087. if (colorFactor) {
  1088. if (colorFactor[3] == 0) {
  1089. babylonMaterial.alphaCutOff = 1;
  1090. }
  1091. else {
  1092. babylonMaterial.alphaCutOff /= colorFactor[3];
  1093. }
  1094. }
  1095. if (babylonMaterial.albedoTexture) {
  1096. babylonMaterial.albedoTexture.hasAlpha = true;
  1097. }
  1098. break;
  1099. case "BLEND":
  1100. if (colorFactor) {
  1101. babylonMaterial.alpha = colorFactor[3];
  1102. }
  1103. if (babylonMaterial.albedoTexture) {
  1104. babylonMaterial.albedoTexture.hasAlpha = true;
  1105. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1106. }
  1107. break;
  1108. default:
  1109. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  1110. }
  1111. }
  1112. public _loadTexture(context: string, texture: IGLTFTexture, coordinatesIndex: number): Texture {
  1113. var sampler = (texture.sampler == null ? <IGLTFSampler>{} : GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  1114. if (!sampler) {
  1115. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  1116. }
  1117. var noMipMaps = (sampler.minFilter === ETextureMinFilter.NEAREST || sampler.minFilter === ETextureMinFilter.LINEAR);
  1118. var samplingMode = GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  1119. this._addPendingData(texture);
  1120. var babylonTexture = new Texture(null, this._babylonScene, noMipMaps, false, samplingMode, () => {
  1121. this._tryCatchOnError(() => {
  1122. this._removePendingData(texture);
  1123. });
  1124. }, message => {
  1125. this._tryCatchOnError(() => {
  1126. throw new Error(context + ": " + message);
  1127. });
  1128. });
  1129. if (texture.url) {
  1130. babylonTexture.updateURL(texture.url);
  1131. }
  1132. else if (texture.dataReadyObservable) {
  1133. texture.dataReadyObservable.add(texture => {
  1134. babylonTexture.updateURL(texture.url);
  1135. });
  1136. }
  1137. else {
  1138. texture.dataReadyObservable = new Observable<IGLTFTexture>();
  1139. texture.dataReadyObservable.add(texture => {
  1140. babylonTexture.updateURL(texture.url);
  1141. });
  1142. var image = GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  1143. if (!image) {
  1144. throw new Error(context + ": Failed to find source " + texture.source);
  1145. }
  1146. this._loadImage("#/images/" + image.index, image, data => {
  1147. texture.url = URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  1148. texture.dataReadyObservable.notifyObservers(texture);
  1149. });
  1150. }
  1151. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  1152. babylonTexture.wrapU = GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  1153. babylonTexture.wrapV = GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  1154. babylonTexture.name = texture.name || "texture" + texture.index;
  1155. if (this._parent.onTextureLoaded) {
  1156. this._parent.onTextureLoaded(babylonTexture);
  1157. }
  1158. return babylonTexture;
  1159. }
  1160. private _loadImage(context: string, image: IGLTFImage, onSuccess: (data: ArrayBufferView) => void): void {
  1161. if (image.uri) {
  1162. if (!GLTFUtils.ValidateUri(image.uri)) {
  1163. throw new Error(context + ": Uri '" + image.uri + "' is invalid");
  1164. }
  1165. if (GLTFUtils.IsBase64(image.uri)) {
  1166. onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(image.uri)));
  1167. }
  1168. else {
  1169. Tools.LoadFile(this._rootUrl + image.uri, data => {
  1170. this._tryCatchOnError(() => {
  1171. onSuccess(data);
  1172. });
  1173. }, event => {
  1174. this._tryCatchOnError(() => {
  1175. this._onProgress(event);
  1176. });
  1177. }, this._babylonScene.database, true, request => {
  1178. this._tryCatchOnError(() => {
  1179. throw new Error(context + ": Failed to load '" + image.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  1180. });
  1181. });
  1182. }
  1183. }
  1184. else {
  1185. var bufferView = GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  1186. if (!bufferView) {
  1187. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  1188. }
  1189. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  1190. }
  1191. }
  1192. public _tryCatchOnError(handler: () => void) {
  1193. try {
  1194. handler();
  1195. }
  1196. catch (e) {
  1197. this._onError(e.message);
  1198. }
  1199. }
  1200. }
  1201. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = parent => new GLTFLoader(parent);
  1202. }