babylon.glTFLoader.ts 60 KB

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