babylon.glTFLoader.ts 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF2 {
  3. export class GLTFLoader implements IGLTFLoader {
  4. private _gltf: IGLTF;
  5. private _pendingCount: number;
  6. private _onLoaded: () => void;
  7. private _errors: string[];
  8. private _babylonScene: Scene;
  9. private _rootUrl: string;
  10. private _defaultMaterial: PBRMaterial;
  11. public static Extensions: { [name: string]: GLTFLoaderExtension } = {};
  12. public static RegisterExtension(extension: GLTFLoaderExtension): void {
  13. if (GLTFLoader.Extensions[extension.name]) {
  14. Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  15. return;
  16. }
  17. this.Extensions[extension.name] = extension;
  18. }
  19. public static LoadMaterial(index: number): IGLTFMaterial {
  20. return (<GLTFLoader>BABYLON.GLTFFileLoader.GLTFLoaderV2)._loadMaterial(index);
  21. }
  22. public static LoadCoreMaterial(index: number): Material {
  23. return (<GLTFLoader>BABYLON.GLTFFileLoader.GLTFLoaderV2)._loadCoreMaterial(index);
  24. }
  25. public static LoadCommonMaterialProperties(material: IGLTFMaterial): void {
  26. return (<GLTFLoader>BABYLON.GLTFFileLoader.GLTFLoaderV2)._loadCommonMaterialProperties(material);
  27. }
  28. public static LoadAlphaProperties(material: IGLTFMaterial): void {
  29. return (<GLTFLoader>BABYLON.GLTFFileLoader.GLTFLoaderV2)._loadAlphaProperties(material);
  30. }
  31. public static LoadTexture(textureInfo: IGLTFTextureInfo): Texture {
  32. return (<GLTFLoader>BABYLON.GLTFFileLoader.GLTFLoaderV2)._loadTexture(textureInfo);
  33. }
  34. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onError: () => void): void {
  35. this._loadAsync(meshesNames, scene, data, rootUrl, () => {
  36. var meshes = [];
  37. if (this._gltf.nodes) {
  38. for (var i = 0; i < this._gltf.nodes.length; i++) {
  39. var node = this._gltf.nodes[i];
  40. if (node.babylonNode instanceof AbstractMesh) {
  41. meshes.push(<AbstractMesh>node.babylonNode);
  42. }
  43. }
  44. }
  45. var skeletons = [];
  46. if (this._gltf.skins) {
  47. for (var i = 0; i < this._gltf.skins.length; i++) {
  48. var skin = this._gltf.skins[i];
  49. if (skin.babylonSkeleton instanceof Skeleton) {
  50. skeletons.push(skin.babylonSkeleton);
  51. }
  52. }
  53. }
  54. onSuccess(meshes, null, skeletons);
  55. }, onError);
  56. }
  57. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onError: () => void): void {
  58. this._loadAsync(null, scene, data, rootUrl, onSuccess, onError);
  59. }
  60. private _loadAsync(nodeNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onError: () => void): void {
  61. scene.useRightHandedSystem = true;
  62. this._clear();
  63. this._loadData(data);
  64. this._babylonScene = scene;
  65. this._rootUrl = rootUrl;
  66. this._onLoaded = () => {
  67. this._showMeshes();
  68. this._startFirstAnimation();
  69. if (this._errors.length === 0) {
  70. onSuccess();
  71. }
  72. else {
  73. this._errors.forEach(error => Tools.Error(error));
  74. onError();
  75. }
  76. this._clear();
  77. };
  78. this._addPendingData(this);
  79. this._loadScene(nodeNames);
  80. this._loadAnimations();
  81. this._removePendingData(this);
  82. }
  83. private _loadData(data: IGLTFLoaderData): void {
  84. this._gltf = <IGLTF>data.json;
  85. var binaryBuffer: IGLTFBuffer;
  86. var buffers = this._gltf.buffers;
  87. if (buffers.length > 0 && buffers[0].uri === undefined) {
  88. binaryBuffer = buffers[0];
  89. }
  90. if (data.bin) {
  91. if (binaryBuffer) {
  92. if (binaryBuffer.byteLength != data.bin.byteLength) {
  93. Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  94. }
  95. }
  96. else {
  97. Tools.Warn("Unexpected BIN chunk");
  98. }
  99. binaryBuffer.loadedData = data.bin;
  100. }
  101. }
  102. private _showMeshes(): void {
  103. var nodes = this._gltf.nodes;
  104. for (var i = 0; i < nodes.length; i++) {
  105. var node = nodes[i];
  106. if (node.babylonNode instanceof Mesh) {
  107. node.babylonNode.isVisible = true;
  108. }
  109. }
  110. }
  111. private _startFirstAnimation(): void {
  112. var animations = this._gltf.animations;
  113. if (!animations) {
  114. return;
  115. }
  116. var animation = animations[0];
  117. for (var i = 0; i < animation.targets.length; i++) {
  118. this._babylonScene.beginAnimation(animation.targets[i], 0, Number.MAX_VALUE, true);
  119. }
  120. }
  121. private _clear(): void {
  122. this._gltf = undefined;
  123. this._pendingCount = 0;
  124. this._onLoaded = undefined;
  125. this._errors = [];
  126. this._babylonScene = undefined;
  127. this._rootUrl = undefined;
  128. this._defaultMaterial = undefined;
  129. // Revoke object urls created during load
  130. if (this._gltf && this._gltf.textures) {
  131. for (var i = 0; i < this._gltf.textures.length; i++) {
  132. var texture = this._gltf.textures[i];
  133. if (texture.blobURL) {
  134. URL.revokeObjectURL(texture.blobURL);
  135. }
  136. }
  137. }
  138. }
  139. private _loadScene(nodeNames: any): void {
  140. nodeNames = (nodeNames === "") ? null : nodeNames;
  141. nodeNames = (nodeNames instanceof Array) ? nodeNames : [nodeNames];
  142. var scene = this._gltf.scenes[this._gltf.scene || 0];
  143. this._traverseScene(nodeNames, scene, node => this._loadSkin(node));
  144. this._traverseScene(nodeNames, scene, (node, parentNode) => this._loadMesh(node, parentNode));
  145. }
  146. private _loadSkin(node: IGLTFNode): boolean {
  147. if (node.babylonNode) {
  148. return false;
  149. }
  150. if (node.skin !== undefined) {
  151. var skin = this._gltf.skins[node.skin];
  152. var skeletonId = "skeleton" + node.skin;
  153. skin.babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  154. for (var i = 0; i < skin.joints.length; i++) {
  155. var jointIndex = skin.joints[i];
  156. var jointNode = this._gltf.nodes[jointIndex];
  157. jointNode.babylonNode = new Bone(jointNode.name || "bone" + jointIndex, skin.babylonSkeleton);
  158. }
  159. if (skin.skeleton === undefined) {
  160. // TODO: handle when skeleton is not defined
  161. throw new Error("Not implemented");
  162. }
  163. if (skin.inverseBindMatrices === undefined) {
  164. // TODO: handle when inverse bind matrices are not defined
  165. throw new Error("Not implemented");
  166. }
  167. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  168. this._loadAccessorAsync(accessor, data => {
  169. this._traverseNode(null, skin.skeleton, (node, parent) => this._updateBone(node, parent, skin, <Float32Array>data));
  170. });
  171. }
  172. return true;
  173. }
  174. private _updateBone(node: IGLTFNode, parentNode: IGLTFNode, skin: IGLTFSkin, inverseBindMatrixData: Float32Array): boolean {
  175. var jointIndex = skin.joints.indexOf(node.index);
  176. if (jointIndex === -1) {
  177. // TODO: handle non-joint in between two joints
  178. throw new Error("Not implemented");
  179. }
  180. var babylonBone = <Bone>node.babylonNode;
  181. // TODO: explain the math
  182. var matrix = Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  183. matrix.invertToRef(matrix);
  184. if (parentNode) {
  185. babylonBone.setParent(<Bone>parentNode.babylonNode, false);
  186. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  187. }
  188. babylonBone.updateMatrix(matrix);
  189. return true;
  190. }
  191. private _loadMesh(node: IGLTFNode, parentNode: IGLTFNode): boolean {
  192. if (node.babylonNode) {
  193. if (node.babylonNode instanceof Bone) {
  194. if (node.mesh !== undefined) {
  195. // TODO: handle mesh attached to bone
  196. throw new Error("Not implemented");
  197. }
  198. }
  199. return false;
  200. }
  201. var babylonMesh = new Mesh(node.name || "mesh" + node.index, this._babylonScene);
  202. babylonMesh.isVisible = false;
  203. this._loadTransform(node, babylonMesh);
  204. if (node.mesh !== undefined) {
  205. var mesh = this._gltf.meshes[node.mesh];
  206. this._loadMeshData(node, mesh, babylonMesh);
  207. }
  208. babylonMesh.parent = parentNode ? parentNode.babylonNode : null;
  209. node.babylonNode = babylonMesh;
  210. if (node.skin !== undefined) {
  211. var skin = this._gltf.skins[node.skin];
  212. babylonMesh.skeleton = skin.babylonSkeleton;
  213. }
  214. if (node.camera !== undefined) {
  215. // TODO: handle cameras
  216. }
  217. return true;
  218. }
  219. private _loadMeshData(node: IGLTFNode, mesh: IGLTFMesh, babylonMesh: Mesh): void {
  220. babylonMesh.name = mesh.name || babylonMesh.name;
  221. babylonMesh.subMeshes = [];
  222. var multiMaterial = new MultiMaterial(babylonMesh.name, this._babylonScene);
  223. babylonMesh.material = multiMaterial;
  224. var geometry = new Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  225. var vertexData = new VertexData();
  226. vertexData.positions = [];
  227. vertexData.indices = [];
  228. var primitivesLoaded = 0;
  229. var numPrimitives = mesh.primitives.length;
  230. for (var i = 0; i < numPrimitives; i++) {
  231. var primitive = mesh.primitives[i];
  232. if (primitive.mode && primitive.mode !== EMeshPrimitiveMode.TRIANGLES) {
  233. // TODO: handle other primitive modes
  234. throw new Error("Not implemented");
  235. }
  236. this._createMorphTargets(node, mesh, primitive, babylonMesh);
  237. this._loadVertexDataAsync(primitive, subVertexData => {
  238. this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  239. var subMesh = new SubMesh(multiMaterial.subMaterials.length, vertexData.positions.length, subVertexData.positions.length, vertexData.indices.length, subVertexData.indices.length, babylonMesh);
  240. var subMaterial = primitive.material === undefined ? this._getDefaultMaterial() : GLTFLoaderExtension.LoadMaterial(primitive.material);
  241. multiMaterial.subMaterials.push(subMaterial);
  242. vertexData.merge(subVertexData);
  243. if (++primitivesLoaded === numPrimitives) {
  244. geometry.setAllVerticesData(vertexData, false);
  245. }
  246. });
  247. }
  248. }
  249. private _loadVertexDataAsync(primitive: IGLTFMeshPrimitive, onSuccess: (vertexData: VertexData) => void): void {
  250. var attributes = primitive.attributes;
  251. if (!attributes) {
  252. this._errors.push("Primitive has no attributes");
  253. return;
  254. }
  255. var vertexData = new VertexData();
  256. var loadedAttributes = 0;
  257. var numAttributes = Object.keys(attributes).length;
  258. for (let semantic in attributes) {
  259. var accessor = this._gltf.accessors[attributes[semantic]];
  260. this._loadAccessorAsync(accessor, data => {
  261. switch (semantic) {
  262. case "NORMAL":
  263. vertexData.normals = <Float32Array>data;
  264. break;
  265. case "POSITION":
  266. vertexData.positions = <Float32Array>data;
  267. break;
  268. case "TANGENT":
  269. vertexData.tangents = <Float32Array>data;
  270. break;
  271. case "TEXCOORD_0":
  272. vertexData.uvs = <Float32Array>data;
  273. break;
  274. case "TEXCOORD_1":
  275. vertexData.uvs2 = <Float32Array>data;
  276. break;
  277. case "JOINTS_0":
  278. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  279. break;
  280. case "WEIGHTS_0":
  281. vertexData.matricesWeights = <Float32Array>data;
  282. break;
  283. case "COLOR_0":
  284. vertexData.colors = <Float32Array>data;
  285. break;
  286. default:
  287. Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  288. break;
  289. }
  290. if (++loadedAttributes === numAttributes) {
  291. var indicesAccessor = this._gltf.accessors[primitive.indices];
  292. if (indicesAccessor) {
  293. this._loadAccessorAsync(indicesAccessor, data => {
  294. vertexData.indices = <IndicesArray>data;
  295. onSuccess(vertexData);
  296. });
  297. }
  298. else {
  299. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  300. vertexData.indices.forEach((v, i) => vertexData.indices[i] = i);
  301. onSuccess(vertexData);
  302. }
  303. }
  304. });
  305. }
  306. }
  307. private _createMorphTargets(node: IGLTFNode, mesh: IGLTFMesh, primitive: IGLTFMeshPrimitive, babylonMesh: Mesh) {
  308. var targets = primitive.targets;
  309. if (!targets) {
  310. return;
  311. }
  312. if (!babylonMesh.morphTargetManager) {
  313. babylonMesh.morphTargetManager = new MorphTargetManager();
  314. }
  315. for (var index = 0; index < targets.length; index++) {
  316. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  317. babylonMesh.morphTargetManager.addTarget(new MorphTarget("morphTarget" + index, weight));
  318. }
  319. }
  320. private _loadMorphTargetsData(mesh: IGLTFMesh, primitive: IGLTFMeshPrimitive, vertexData: VertexData, babylonMesh: Mesh): void {
  321. var targets = primitive.targets;
  322. if (!targets) {
  323. return;
  324. }
  325. for (var index = 0; index < targets.length; index++) {
  326. let babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  327. var attributes = targets[index];
  328. for (let semantic in attributes) {
  329. var accessor = this._gltf.accessors[attributes[semantic]];
  330. this._loadAccessorAsync(accessor, data => {
  331. if (accessor.name) {
  332. babylonMorphTarget.name = accessor.name;
  333. }
  334. // glTF stores morph target information as deltas while babylon.js expects the final data.
  335. // As a result we have to add the original data to the delta to calculate the final data.
  336. var values = <Float32Array>data;
  337. switch (semantic) {
  338. case "NORMAL":
  339. values.forEach((v, i) => values[i] += vertexData.normals[i]);
  340. babylonMorphTarget.setNormals(values);
  341. break;
  342. case "POSITION":
  343. values.forEach((v, i) => values[i] += vertexData.positions[i]);
  344. babylonMorphTarget.setPositions(values);
  345. break;
  346. case "TANGENT":
  347. // Tangent data for morph targets is stored as xyz delta.
  348. // The vertexData.tangent is stored as xyzw.
  349. // So we need to skip every fourth vertexData.tangent.
  350. for (var i = 0, j = 0; i < values.length; i++, j++) {
  351. values[i] += vertexData.tangents[j];
  352. if ((i + 1) % 3 == 0) {
  353. j++;
  354. }
  355. }
  356. babylonMorphTarget.setTangents(values);
  357. break;
  358. default:
  359. Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  360. break;
  361. }
  362. });
  363. }
  364. }
  365. }
  366. private _loadTransform(node: IGLTFNode, babylonMesh: Mesh): void {
  367. var position: Vector3 = Vector3.Zero();
  368. var rotation: Quaternion = Quaternion.Identity();
  369. var scaling: Vector3 = Vector3.One();
  370. if (node.matrix) {
  371. var mat = Matrix.FromArray(node.matrix);
  372. mat.decompose(scaling, rotation, position);
  373. }
  374. else {
  375. if (node.translation) position = Vector3.FromArray(node.translation);
  376. if (node.rotation) rotation = Quaternion.FromArray(node.rotation);
  377. if (node.scale) scaling = Vector3.FromArray(node.scale);
  378. }
  379. babylonMesh.position = position;
  380. babylonMesh.rotationQuaternion = rotation;
  381. babylonMesh.scaling = scaling;
  382. }
  383. private _traverseScene(nodeNames: string[], scene: IGLTFScene, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean): void {
  384. var nodes = scene.nodes;
  385. if (nodes) {
  386. for (var i = 0; i < nodes.length; i++) {
  387. this._traverseNode(nodeNames, nodes[i], action);
  388. }
  389. }
  390. }
  391. private _traverseNode(nodeNames: string[], index: number, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode = null): void {
  392. var node = this._gltf.nodes[index];
  393. if (nodeNames) {
  394. if (nodeNames.indexOf(node.name)) {
  395. // load all children
  396. nodeNames = null;
  397. }
  398. else {
  399. // skip this node tree
  400. return;
  401. }
  402. }
  403. node.index = index;
  404. if (!action(node, parentNode)) {
  405. return;
  406. }
  407. if (node.children) {
  408. for (var i = 0; i < node.children.length; i++) {
  409. this._traverseNode(nodeNames, node.children[i], action, node);
  410. }
  411. }
  412. }
  413. private _loadAnimations(): void {
  414. var animations = this._gltf.animations;
  415. if (!animations || animations.length === 0) {
  416. return;
  417. }
  418. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  419. var animation = animations[animationIndex];
  420. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  421. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  422. }
  423. }
  424. }
  425. private _loadAnimationChannel(animation: IGLTFAnimation, animationIndex: number, channelIndex: number): void {
  426. var channel = animation.channels[channelIndex];
  427. var samplerIndex = channel.sampler;
  428. var sampler = animation.samplers[samplerIndex];
  429. var targetNode = this._gltf.nodes[channel.target.node].babylonNode;
  430. if (!targetNode) {
  431. Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  432. return;
  433. }
  434. var targetPath = {
  435. "translation": "position",
  436. "rotation": "rotationQuaternion",
  437. "scale": "scaling",
  438. "weights": "influence"
  439. }[channel.target.path];
  440. if (!targetPath) {
  441. Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  442. return;
  443. }
  444. var animationType = {
  445. "position": Animation.ANIMATIONTYPE_VECTOR3,
  446. "rotationQuaternion": Animation.ANIMATIONTYPE_QUATERNION,
  447. "scaling": Animation.ANIMATIONTYPE_VECTOR3,
  448. "influence": Animation.ANIMATIONTYPE_FLOAT,
  449. }[targetPath];
  450. var inputData: Float32Array;
  451. var outputData: Float32Array;
  452. var checkSuccess = () => {
  453. if (!inputData || !outputData) {
  454. return;
  455. }
  456. var outputBufferOffset = 0;
  457. var getNextOutputValue: () => any = {
  458. "position": () => {
  459. var value = Vector3.FromArray(outputData, outputBufferOffset);
  460. outputBufferOffset += 3;
  461. return value;
  462. },
  463. "rotationQuaternion": () => {
  464. var value = Quaternion.FromArray(outputData, outputBufferOffset);
  465. outputBufferOffset += 4;
  466. return value;
  467. },
  468. "scaling": () => {
  469. var value = Vector3.FromArray(outputData, outputBufferOffset);
  470. outputBufferOffset += 3;
  471. return value;
  472. },
  473. "influence": () => {
  474. var numTargets = (<Mesh>targetNode).morphTargetManager.numTargets;
  475. var value = new Array(numTargets);
  476. for (var i = 0; i < numTargets; i++) {
  477. value[i] = outputData[outputBufferOffset++];
  478. }
  479. return value;
  480. },
  481. }[targetPath];
  482. var getNextKey: (frameIndex) => any = {
  483. "LINEAR": frameIndex => ({
  484. frame: inputData[frameIndex],
  485. value: getNextOutputValue()
  486. }),
  487. "CUBICSPLINE": frameIndex => ({
  488. frame: inputData[frameIndex],
  489. inTangent: getNextOutputValue(),
  490. value: getNextOutputValue(),
  491. outTangent: getNextOutputValue()
  492. }),
  493. }[sampler.interpolation];
  494. var keys = new Array(inputData.length);
  495. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  496. keys[frameIndex] = getNextKey(frameIndex);
  497. }
  498. animation.targets = animation.targets || [];
  499. if (targetPath === "influence") {
  500. var targetMesh = <Mesh>targetNode;
  501. for (var targetIndex = 0; targetIndex < targetMesh.morphTargetManager.numTargets; targetIndex++) {
  502. var morphTarget = targetMesh.morphTargetManager.getTarget(targetIndex);
  503. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  504. var babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  505. babylonAnimation.setKeys(keys.map(key => ({
  506. frame: key.frame,
  507. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  508. value: key.value[targetIndex],
  509. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  510. })));
  511. morphTarget.animations.push(babylonAnimation);
  512. animation.targets.push(morphTarget);
  513. }
  514. }
  515. else {
  516. var animationName = animation.name || "anim" + animationIndex;
  517. var babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  518. babylonAnimation.setKeys(keys);
  519. targetNode.animations.push(babylonAnimation);
  520. animation.targets.push(targetNode);
  521. }
  522. };
  523. this._loadAccessorAsync(this._gltf.accessors[sampler.input], data =>
  524. {
  525. inputData = <Float32Array>data;
  526. checkSuccess();
  527. });
  528. this._loadAccessorAsync(this._gltf.accessors[sampler.output], data =>
  529. {
  530. outputData = <Float32Array>data;
  531. checkSuccess();
  532. });
  533. }
  534. private _loadBufferAsync(index: number, onSuccess: (data: ArrayBufferView) => void): void {
  535. var buffer = this._gltf.buffers[index];
  536. this._addPendingData(buffer);
  537. if (buffer.loadedData) {
  538. setTimeout(() => {
  539. onSuccess(buffer.loadedData);
  540. this._removePendingData(buffer);
  541. });
  542. }
  543. else if (GLTFUtils.IsBase64(buffer.uri)) {
  544. var data = GLTFUtils.DecodeBase64(buffer.uri);
  545. buffer.loadedData = new Uint8Array(data);
  546. setTimeout(() => {
  547. onSuccess(buffer.loadedData);
  548. this._removePendingData(buffer);
  549. });
  550. }
  551. else if (buffer.loadedObservable) {
  552. buffer.loadedObservable.add(buffer => {
  553. onSuccess(buffer.loadedData);
  554. this._removePendingData(buffer);
  555. });
  556. }
  557. else {
  558. buffer.loadedObservable = new Observable<IGLTFBuffer>();
  559. buffer.loadedObservable.add(buffer => {
  560. onSuccess(buffer.loadedData);
  561. this._removePendingData(buffer);
  562. });
  563. Tools.LoadFile(this._rootUrl + buffer.uri, data => {
  564. buffer.loadedData = new Uint8Array(data);
  565. buffer.loadedObservable.notifyObservers(buffer);
  566. buffer.loadedObservable = null;
  567. }, null, null, true, request => {
  568. this._errors.push("Failed to load file '" + buffer.uri + "': " + request.statusText + "(" + request.status + ")");
  569. this._removePendingData(buffer);
  570. });
  571. }
  572. }
  573. private _loadBufferViewAsync(bufferView: IGLTFBufferView, byteOffset: number, byteLength: number, componentType: EComponentType, onSuccess: (data: ArrayBufferView) => void): void {
  574. byteOffset += (bufferView.byteOffset || 0);
  575. this._loadBufferAsync(bufferView.buffer, bufferData => {
  576. if (byteOffset + byteLength > bufferData.byteLength) {
  577. this._errors.push("Buffer access is out of range");
  578. return;
  579. }
  580. var buffer = bufferData.buffer;
  581. byteOffset += bufferData.byteOffset;
  582. var bufferViewData;
  583. switch (componentType) {
  584. case EComponentType.BYTE:
  585. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  586. break;
  587. case EComponentType.UNSIGNED_BYTE:
  588. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  589. break;
  590. case EComponentType.SHORT:
  591. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  592. break;
  593. case EComponentType.UNSIGNED_SHORT:
  594. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  595. break;
  596. case EComponentType.UNSIGNED_INT:
  597. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  598. break;
  599. case EComponentType.FLOAT:
  600. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  601. break;
  602. default:
  603. this._errors.push("Invalid component type (" + componentType + ")");
  604. return;
  605. }
  606. onSuccess(bufferViewData);
  607. });
  608. }
  609. private _loadAccessorAsync(accessor: IGLTFAccessor, onSuccess: (data: ArrayBufferView) => void): void {
  610. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  611. var byteOffset = accessor.byteOffset || 0;
  612. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  613. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  614. }
  615. private _addPendingData(data: any) {
  616. this._pendingCount++;
  617. }
  618. private _removePendingData(data: any) {
  619. if (--this._pendingCount === 0) {
  620. this._onLoaded();
  621. }
  622. }
  623. private _getDefaultMaterial(): Material {
  624. if (!this._defaultMaterial) {
  625. var id = "__gltf_default";
  626. var material = <PBRMaterial>this._babylonScene.getMaterialByName(id);
  627. if (!material) {
  628. material = new PBRMaterial(id, this._babylonScene);
  629. material.sideOrientation = Material.CounterClockWiseSideOrientation;
  630. material.metallic = 1;
  631. material.roughness = 1;
  632. }
  633. this._defaultMaterial = material;
  634. }
  635. return this._defaultMaterial;
  636. }
  637. private _loadMaterial(index: number): IGLTFMaterial {
  638. var materials = this._gltf.materials;
  639. var material = materials ? materials[index] : null;
  640. if (!material) {
  641. Tools.Warn("Material index (" + index + ") does not exist");
  642. return null;
  643. }
  644. material.babylonMaterial = new PBRMaterial(material.name || "mat" + index, this._babylonScene);
  645. material.babylonMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  646. material.babylonMaterial.useScalarInLinearSpace = true;
  647. return material;
  648. }
  649. private _loadCoreMaterial(index: number): Material {
  650. var material = this._loadMaterial(index);
  651. if (!material) {
  652. return null;
  653. }
  654. this._loadCommonMaterialProperties(material);
  655. // Ensure metallic workflow
  656. material.babylonMaterial.metallic = 1;
  657. material.babylonMaterial.roughness = 1;
  658. var properties = material.pbrMetallicRoughness;
  659. if (!properties) {
  660. return;
  661. }
  662. material.babylonMaterial.albedoColor = properties.baseColorFactor ? Color3.FromArray(properties.baseColorFactor) : new Color3(1, 1, 1);
  663. material.babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  664. material.babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  665. if (properties.baseColorTexture) {
  666. material.babylonMaterial.albedoTexture = this._loadTexture(properties.baseColorTexture);
  667. this._loadAlphaProperties(material);
  668. }
  669. if (properties.metallicRoughnessTexture) {
  670. material.babylonMaterial.metallicTexture = this._loadTexture(properties.metallicRoughnessTexture);
  671. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  672. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  673. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  674. }
  675. return material.babylonMaterial;
  676. }
  677. private _loadCommonMaterialProperties(material: IGLTFMaterial): void {
  678. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  679. material.babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  680. if (material.doubleSided) {
  681. material.babylonMaterial.backFaceCulling = false;
  682. material.babylonMaterial.twoSidedLighting = true;
  683. }
  684. if (material.normalTexture) {
  685. material.babylonMaterial.bumpTexture = this._loadTexture(material.normalTexture);
  686. if (material.normalTexture.scale !== undefined) {
  687. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  688. }
  689. }
  690. if (material.occlusionTexture) {
  691. material.babylonMaterial.ambientTexture = this._loadTexture(material.occlusionTexture);
  692. material.babylonMaterial.useAmbientInGrayScale = true;
  693. if (material.occlusionTexture.strength !== undefined) {
  694. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  695. }
  696. }
  697. if (material.emissiveTexture) {
  698. material.babylonMaterial.emissiveTexture = this._loadTexture(material.emissiveTexture);
  699. }
  700. }
  701. private _loadAlphaProperties(material: IGLTFMaterial): void {
  702. var alphaMode = material.alphaMode || "OPAQUE";
  703. switch (alphaMode) {
  704. case "OPAQUE":
  705. // default is opaque
  706. break;
  707. case "MASK":
  708. material.babylonMaterial.albedoTexture.hasAlpha = true;
  709. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  710. material.babylonMaterial.alphaMode = Engine.ALPHA_DISABLE;
  711. break;
  712. case "BLEND":
  713. material.babylonMaterial.albedoTexture.hasAlpha = true;
  714. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  715. material.babylonMaterial.alphaMode = Engine.ALPHA_COMBINE;
  716. break;
  717. default:
  718. Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  719. }
  720. }
  721. private _loadTexture(textureInfo: IGLTFTextureInfo): Texture {
  722. var texture = this._gltf.textures[textureInfo.index];
  723. var texCoord = textureInfo.texCoord || 0;
  724. if (!texture || texture.source === undefined) {
  725. return null;
  726. }
  727. // check the cache first
  728. var babylonTexture: Texture;
  729. if (texture.babylonTextures) {
  730. babylonTexture = texture.babylonTextures[texCoord];
  731. if (!babylonTexture) {
  732. for (var i = 0; i < texture.babylonTextures.length; i++) {
  733. babylonTexture = texture.babylonTextures[i];
  734. if (babylonTexture) {
  735. babylonTexture = babylonTexture.clone();
  736. babylonTexture.coordinatesIndex = texCoord;
  737. break;
  738. }
  739. }
  740. }
  741. return babylonTexture;
  742. }
  743. var source = this._gltf.images[texture.source];
  744. var url: string;
  745. if (!source.uri) {
  746. var bufferView = this._gltf.bufferViews[source.bufferView];
  747. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE, data => {
  748. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  749. texture.babylonTextures[texCoord].updateURL(texture.blobURL);
  750. });
  751. }
  752. else if (GLTFUtils.IsBase64(source.uri)) {
  753. var data = new Uint8Array(GLTFUtils.DecodeBase64(source.uri));
  754. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  755. url = texture.blobURL;
  756. }
  757. else {
  758. url = this._rootUrl + source.uri;
  759. }
  760. var sampler = (texture.sampler === undefined ? <IGLTFSampler>{} : this._gltf.samplers[texture.sampler]);
  761. var noMipMaps = (sampler.minFilter === ETextureMinFilter.NEAREST || sampler.minFilter === ETextureMinFilter.LINEAR);
  762. var samplingMode = GLTFUtils.GetTextureFilterMode(sampler.minFilter);
  763. this._addPendingData(texture);
  764. var babylonTexture = new Texture(url, this._babylonScene, noMipMaps, false, samplingMode, () => {
  765. this._removePendingData(texture);
  766. }, () => {
  767. this._errors.push("Failed to load texture '" + source.uri + "'");
  768. this._removePendingData(texture);
  769. });
  770. babylonTexture.coordinatesIndex = texCoord;
  771. babylonTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
  772. babylonTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
  773. babylonTexture.name = texture.name;
  774. // Cache the texture
  775. texture.babylonTextures = texture.babylonTextures || [];
  776. texture.babylonTextures[texCoord] = babylonTexture;
  777. return babylonTexture;
  778. }
  779. }
  780. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  781. }