babylon.glTFLoader.ts 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF2 {
  3. /**
  4. * Values
  5. */
  6. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  7. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  8. /**
  9. * Utils
  10. */
  11. var normalizeUVs = (buffer: any): void => {
  12. if (!buffer) {
  13. return;
  14. }
  15. for (var i = 0; i < buffer.length / 2; i++) {
  16. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  17. }
  18. };
  19. var createStringId = (index: number): string => {
  20. return "node" + index;
  21. };
  22. /**
  23. * Returns the animation path (glTF -> Babylon)
  24. */
  25. var getAnimationPath = (path: string): string => {
  26. var index = glTFAnimationPaths.indexOf(path);
  27. if (index !== -1) {
  28. return babylonAnimationPaths[index];
  29. }
  30. return path;
  31. };
  32. /**
  33. * Loads and creates animations
  34. */
  35. var loadAnimations = (runtime: IGLTFRuntime): void => {
  36. var animations = runtime.gltf.animations;
  37. if (!animations) {
  38. return;
  39. }
  40. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  41. var animation = animations[animationIndex];
  42. if (!animation || !animation.channels || !animation.samplers) {
  43. continue;
  44. }
  45. var lastAnimation: Animation = null;
  46. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  47. var channel = animation.channels[channelIndex];
  48. if (!channel) {
  49. continue;
  50. }
  51. var sampler = animation.samplers[channel.sampler];
  52. if (!sampler) {
  53. continue;
  54. }
  55. var inputData = sampler.input;
  56. var outputData = sampler.output;
  57. var bufferInput = GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[inputData]);
  58. var bufferOutput = GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[outputData]);
  59. var targetID = channel.target.node;
  60. var targetNode: any = runtime.babylonScene.getNodeByID(createStringId(targetID));
  61. if (targetNode === null) {
  62. Tools.Warn("Creating animation index " + animationIndex + " but cannot find node index " + targetID + " to attach to");
  63. continue;
  64. }
  65. var isBone = targetNode instanceof Bone;
  66. // Get target path (position, rotation or scaling)
  67. var targetPath = channel.target.path;
  68. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  69. if (targetPathIndex !== -1) {
  70. targetPath = babylonAnimationPaths[targetPathIndex];
  71. }
  72. // Determine animation type
  73. var animationType = Animation.ANIMATIONTYPE_MATRIX;
  74. if (!isBone) {
  75. if (targetPath === "rotationQuaternion") {
  76. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  77. targetNode.rotationQuaternion = new Quaternion();
  78. }
  79. else {
  80. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  81. }
  82. }
  83. // Create animation and key frames
  84. var babylonAnimation: Animation = null;
  85. var keys = [];
  86. var arrayOffset = 0;
  87. var modifyKey = false;
  88. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  89. babylonAnimation = lastAnimation;
  90. modifyKey = true;
  91. }
  92. if (!modifyKey) {
  93. var animationName = animation.name || "anim" + animationIndex;
  94. babylonAnimation = new Animation(animationName, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
  95. }
  96. // For each frame
  97. for (var j = 0; j < bufferInput.length; j++) {
  98. var value: any = null;
  99. if (targetPath === "rotationQuaternion") { // VEC4
  100. value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  101. arrayOffset += 4;
  102. }
  103. else { // Position and scaling are VEC3
  104. value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  105. arrayOffset += 3;
  106. }
  107. if (isBone) {
  108. var bone = <Bone>targetNode;
  109. var translation = Vector3.Zero();
  110. var rotationQuaternion = new Quaternion();
  111. var scaling = Vector3.Zero();
  112. // Warning on decompose
  113. var mat = bone.getBaseMatrix();
  114. if (modifyKey) {
  115. mat = lastAnimation.getKeys()[j].value;
  116. }
  117. mat.decompose(scaling, rotationQuaternion, translation);
  118. if (targetPath === "position") {
  119. translation = value;
  120. }
  121. else if (targetPath === "rotationQuaternion") {
  122. rotationQuaternion = value;
  123. }
  124. else {
  125. scaling = value;
  126. }
  127. value = Matrix.Compose(scaling, rotationQuaternion, translation);
  128. }
  129. if (!modifyKey) {
  130. keys.push({
  131. frame: bufferInput[j],
  132. value: value
  133. });
  134. }
  135. else {
  136. lastAnimation.getKeys()[j].value = value;
  137. }
  138. }
  139. // Finish
  140. if (!modifyKey) {
  141. babylonAnimation.setKeys(keys);
  142. targetNode.animations.push(babylonAnimation);
  143. }
  144. lastAnimation = babylonAnimation;
  145. runtime.babylonScene.stopAnimation(targetNode);
  146. runtime.babylonScene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  147. }
  148. }
  149. };
  150. /**
  151. * Returns the bones transformation matrix
  152. */
  153. var configureBoneTransformation = (node: IGLTFNode): Matrix => {
  154. var mat: Matrix = null;
  155. if (node.translation || node.rotation || node.scale) {
  156. var scale = Vector3.FromArray(node.scale || [1, 1, 1]);
  157. var rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  158. var position = Vector3.FromArray(node.translation || [0, 0, 0]);
  159. mat = Matrix.Compose(scale, rotation, position);
  160. }
  161. else {
  162. mat = node.matrix ? Matrix.FromArray(node.matrix) : Matrix.Identity();
  163. }
  164. return mat;
  165. };
  166. /**
  167. * Returns the parent bone
  168. */
  169. var getParentBone = (runtime: IGLTFRuntime, skin: IGLTFSkin, index: number, newSkeleton: Skeleton): Bone => {
  170. // Try to find
  171. var nodeStringID = createStringId(index);
  172. for (var i = 0; i < newSkeleton.bones.length; i++) {
  173. if (newSkeleton.bones[i].id === nodeStringID) {
  174. return newSkeleton.bones[i].getParent();
  175. }
  176. }
  177. // Not found, search in gltf nodes
  178. var joints = skin.joints;
  179. for (var j = 0; j < joints.length; j++) {
  180. var parentID = joints[j];
  181. var parent = runtime.gltf.nodes[parentID];
  182. var children = parent.children;
  183. for (var i = 0; i < children.length; i++) {
  184. var childID = children[i];
  185. var child = runtime.gltf.nodes[childID];
  186. if (!nodeIsInJoints(skin, childID)) {
  187. continue;
  188. }
  189. if (childID === index)
  190. {
  191. var mat = configureBoneTransformation(parent);
  192. var bone = new Bone(parent.name || createStringId(parentID), newSkeleton, getParentBone(runtime, skin, parentID, newSkeleton), mat);
  193. bone.id = createStringId(parentID);
  194. return bone;
  195. }
  196. }
  197. }
  198. return null;
  199. }
  200. /**
  201. * Returns the appropriate root node
  202. */
  203. var getNodeToRoot = (nodesToRoot: INodeToRoot[], index: number): Bone => {
  204. for (var i = 0; i < nodesToRoot.length; i++) {
  205. var nodeToRoot = nodesToRoot[i];
  206. if (nodeToRoot.node.children) {
  207. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  208. var child = nodeToRoot.node.children[j];
  209. if (child === index) {
  210. return nodeToRoot.bone;
  211. }
  212. }
  213. }
  214. }
  215. return null;
  216. };
  217. /**
  218. * Returns the node with the node index
  219. */
  220. var getJointNode = (runtime: IGLTFRuntime, index: number): IJointNode => {
  221. var node = runtime.gltf.nodes[index];
  222. if (node) {
  223. return {
  224. node: node,
  225. index: index
  226. };
  227. }
  228. return null;
  229. }
  230. /**
  231. * Checks if a nodes is in joints
  232. */
  233. var nodeIsInJoints = (skin: IGLTFSkin, index: number): boolean => {
  234. for (var i = 0; i < skin.joints.length; i++) {
  235. if (skin.joints[i] === index) {
  236. return true;
  237. }
  238. }
  239. return false;
  240. }
  241. /**
  242. * Fills the nodes to root for bones and builds hierarchy
  243. */
  244. var getNodesToRoot = (runtime: IGLTFRuntime, newSkeleton: Skeleton, skin: IGLTFSkin, nodesToRoot: INodeToRoot[]): void => {
  245. // Creates nodes for root
  246. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  247. var node = runtime.gltf.nodes[i];
  248. if (nodeIsInJoints(skin, i)) {
  249. continue;
  250. }
  251. // Create node to root bone
  252. var mat = configureBoneTransformation(node);
  253. var bone = new Bone(node.name || createStringId(i), newSkeleton, null, mat);
  254. bone.id = createStringId(i);
  255. nodesToRoot.push({ bone: bone, node: node, index: i });
  256. }
  257. // Parenting
  258. for (var i = 0; i < nodesToRoot.length; i++) {
  259. var nodeToRoot = nodesToRoot[i];
  260. var children = nodeToRoot.node.children;
  261. if (children) {
  262. for (var j = 0; j < children.length; j++) {
  263. var child: INodeToRoot = null;
  264. for (var k = 0; k < nodesToRoot.length; k++) {
  265. if (nodesToRoot[k].index === children[j]) {
  266. child = nodesToRoot[k];
  267. break;
  268. }
  269. }
  270. if (child) {
  271. (<any>child.bone)._parent = nodeToRoot.bone;
  272. nodeToRoot.bone.children.push(child.bone);
  273. }
  274. }
  275. }
  276. }
  277. };
  278. /**
  279. * Imports a skeleton
  280. */
  281. var importSkeleton = (runtime: IGLTFRuntime, skinNode: IGLTFNode, skin: IGLTFSkin): Skeleton => {
  282. var name = skin.name || "skin" + skinNode.skin;
  283. var babylonSkeleton = <Skeleton>skin.babylonSkeleton;
  284. if (!babylonSkeleton) {
  285. babylonSkeleton = new Skeleton(name, "skin" + skinNode.skin, runtime.babylonScene);
  286. }
  287. if (!skin.babylonSkeleton) {
  288. return babylonSkeleton;
  289. }
  290. // Matrices
  291. var accessor = runtime.gltf.accessors[skin.inverseBindMatrices];
  292. var buffer = GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  293. // Find the root bones
  294. var nodesToRoot: INodeToRoot[] = [];
  295. var nodesToRootToAdd: Bone[] = [];
  296. getNodesToRoot(runtime, babylonSkeleton, skin, nodesToRoot);
  297. babylonSkeleton.bones = [];
  298. // Joints
  299. for (var i = 0; i < skin.joints.length; i++) {
  300. var jointNode = getJointNode(runtime, skin.joints[i]);
  301. var node = jointNode.node;
  302. if (!node) {
  303. Tools.Warn("Joint index " + skin.joints[i] + " does not exist");
  304. continue;
  305. }
  306. var index = jointNode.index;
  307. var stringID = createStringId(index);
  308. // Optimize, if the bone already exists...
  309. var existingBone = runtime.babylonScene.getBoneByID(stringID);
  310. if (existingBone) {
  311. babylonSkeleton.bones.push(existingBone);
  312. continue;
  313. }
  314. // Search for parent bone
  315. var foundBone = false;
  316. var parentBone: Bone = null;
  317. for (var j = 0; j < i; j++) {
  318. var joint: IGLTFNode = getJointNode(runtime, skin.joints[j]).node;
  319. if (!joint) {
  320. Tools.Warn("Joint index " + skin.joints[j] + " does not exist when looking for parent");
  321. continue;
  322. }
  323. var children = joint.children;
  324. foundBone = false;
  325. for (var k = 0; k < children.length; k++) {
  326. if (children[k] === index) {
  327. parentBone = getParentBone(runtime, skin, skin.joints[j], babylonSkeleton);
  328. foundBone = true;
  329. break;
  330. }
  331. }
  332. if (foundBone) {
  333. break;
  334. }
  335. }
  336. // Create bone
  337. var mat = configureBoneTransformation(node);
  338. if (!parentBone && nodesToRoot.length > 0) {
  339. parentBone = getNodeToRoot(nodesToRoot, index);
  340. if (parentBone) {
  341. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  342. nodesToRootToAdd.push(parentBone);
  343. }
  344. }
  345. }
  346. var bone = new Bone(node.name || stringID, babylonSkeleton, parentBone, mat);
  347. bone.id = stringID;
  348. }
  349. // Polish
  350. var bones = babylonSkeleton.bones;
  351. babylonSkeleton.bones = [];
  352. for (var i = 0; i < skin.joints.length; i++) {
  353. var jointNode = getJointNode(runtime, skin.joints[i]);
  354. if (!jointNode) {
  355. continue;
  356. }
  357. var jointNodeStringId = createStringId(jointNode.index);
  358. for (var j = 0; j < bones.length; j++) {
  359. if (bones[j].id === jointNodeStringId) {
  360. babylonSkeleton.bones.push(bones[j]);
  361. break;
  362. }
  363. }
  364. }
  365. babylonSkeleton.prepare();
  366. // Finish
  367. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  368. babylonSkeleton.bones.push(nodesToRootToAdd[i]);
  369. }
  370. return babylonSkeleton;
  371. };
  372. /**
  373. * Gets a material
  374. */
  375. var getMaterial = (runtime: IGLTFRuntime, index?: number): PBRMaterial => {
  376. if (index === undefined) {
  377. return GLTFUtils.GetDefaultMaterial(runtime);
  378. }
  379. var materials = runtime.gltf.materials;
  380. if (!materials || index < 0 || index >= materials.length) {
  381. Tools.Error("Invalid material index");
  382. return GLTFUtils.GetDefaultMaterial(runtime);
  383. }
  384. var material = runtime.gltf.materials[index].babylonMaterial;
  385. if (!material)
  386. {
  387. return GLTFUtils.GetDefaultMaterial(runtime);
  388. }
  389. return material;
  390. };
  391. /**
  392. * Imports a mesh and its geometries
  393. */
  394. var importMesh = (runtime: IGLTFRuntime, node: IGLTFNode, mesh: IGLTFMesh): Mesh => {
  395. var name = mesh.name || node.name || "mesh" + node.mesh;
  396. var babylonMesh = <Mesh>node.babylonNode;
  397. if (!babylonMesh) {
  398. babylonMesh = new Mesh(name, runtime.babylonScene);
  399. }
  400. if (!node.babylonNode) {
  401. return babylonMesh;
  402. }
  403. var multiMat = new MultiMaterial(name, runtime.babylonScene);
  404. if (!babylonMesh.material) {
  405. babylonMesh.material = multiMat;
  406. }
  407. var vertexData = new VertexData();
  408. var geometry = new Geometry(name, runtime.babylonScene, vertexData, false, babylonMesh);
  409. var verticesStarts = [];
  410. var verticesCounts = [];
  411. var indexStarts = [];
  412. var indexCounts = [];
  413. // Positions, normals and UVs
  414. for (var index = 0; index < mesh.primitives.length; index++) {
  415. // Temporary vertex data
  416. var tempVertexData = new VertexData();
  417. var primitive = mesh.primitives[index];
  418. if (primitive.mode !== EMeshPrimitiveMode.TRIANGLES) {
  419. // continue;
  420. }
  421. var attributes = primitive.attributes;
  422. var accessor: IGLTFAccessor = null;
  423. var buffer: any = null;
  424. // Set positions, normal and uvs
  425. for (var semantic in attributes) {
  426. // Link accessor and buffer view
  427. accessor = runtime.gltf.accessors[attributes[semantic]];
  428. buffer = GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  429. if (semantic === "NORMAL") {
  430. tempVertexData.normals = new Float32Array(buffer.length);
  431. (<Float32Array>tempVertexData.normals).set(buffer);
  432. }
  433. else if (semantic === "POSITION") {
  434. tempVertexData.positions = new Float32Array(buffer.length);
  435. (<Float32Array>tempVertexData.positions).set(buffer);
  436. verticesCounts.push(tempVertexData.positions.length);
  437. }
  438. else if (semantic === "TANGENT") {
  439. tempVertexData.tangents = new Float32Array(buffer.length);
  440. (<Float32Array>tempVertexData.tangents).set(buffer);
  441. }
  442. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  443. var channel = Number(semantic.split("_")[1]);
  444. var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  445. var uvs = new Float32Array(buffer.length);
  446. (<Float32Array>uvs).set(buffer);
  447. normalizeUVs(uvs);
  448. tempVertexData.set(uvs, uvKind);
  449. }
  450. else if (semantic === "JOINT") {
  451. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  452. (<Float32Array>tempVertexData.matricesIndices).set(buffer);
  453. }
  454. else if (semantic === "WEIGHT") {
  455. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  456. (<Float32Array>tempVertexData.matricesWeights).set(buffer);
  457. }
  458. else if (semantic === "COLOR_0") {
  459. tempVertexData.colors = new Float32Array(buffer.length);
  460. (<Float32Array>tempVertexData.colors).set(buffer);
  461. }
  462. else {
  463. Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  464. }
  465. }
  466. // Indices
  467. accessor = runtime.gltf.accessors[primitive.indices];
  468. if (accessor) {
  469. buffer = GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  470. tempVertexData.indices = new Int32Array(buffer.length);
  471. (<Float32Array>tempVertexData.indices).set(buffer);
  472. indexCounts.push(tempVertexData.indices.length);
  473. }
  474. else {
  475. // Set indices on the fly
  476. var indices: number[] = [];
  477. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  478. indices.push(j);
  479. }
  480. tempVertexData.indices = new Int32Array(indices);
  481. indexCounts.push(tempVertexData.indices.length);
  482. }
  483. vertexData.merge(tempVertexData);
  484. tempVertexData = undefined;
  485. // Sub material
  486. var material = getMaterial(runtime, primitive.material);
  487. multiMat.subMaterials.push(material);
  488. // Update vertices start and index start
  489. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  490. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  491. }
  492. // Apply geometry
  493. geometry.setAllVerticesData(vertexData, false);
  494. babylonMesh.computeWorldMatrix(true);
  495. // Apply submeshes
  496. babylonMesh.subMeshes = [];
  497. for (var index = 0; index < mesh.primitives.length; index++) {
  498. if (mesh.primitives[index].mode !== EMeshPrimitiveMode.TRIANGLES) {
  499. //continue;
  500. }
  501. var subMesh = new SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], babylonMesh, babylonMesh, true);
  502. }
  503. // Finish
  504. return babylonMesh;
  505. };
  506. /**
  507. * Configures node transformation
  508. */
  509. var configureNode = (babylonNode: Mesh | TargetCamera, node: IGLTFNode): void => {
  510. var position = Vector3.Zero();
  511. var rotation = Quaternion.Identity();
  512. var scaling = new Vector3(1, 1, 1);
  513. if (node.matrix) {
  514. var mat = Matrix.FromArray(node.matrix);
  515. mat.decompose(scaling, rotation, position);
  516. }
  517. else {
  518. if (node.translation) {
  519. position = Vector3.FromArray(node.translation);
  520. }
  521. if (node.rotation) {
  522. rotation = Quaternion.FromArray(node.rotation);
  523. }
  524. if (node.scale) {
  525. scaling = Vector3.FromArray(node.scale);
  526. }
  527. }
  528. babylonNode.position = position;
  529. babylonNode.rotationQuaternion = rotation;
  530. if (babylonNode instanceof Mesh) {
  531. var mesh = <Mesh>babylonNode;
  532. mesh.scaling = scaling;
  533. }
  534. };
  535. /**
  536. * Imports a node
  537. */
  538. var importNode = (runtime: IGLTFRuntime, node: IGLTFNode): Node => {
  539. var babylonNode: Mesh | TargetCamera = null;
  540. if (runtime.importOnlyMeshes && (node.skin !== undefined || node.mesh !== undefined)) {
  541. if (runtime.importMeshesNames.length > 0 && runtime.importMeshesNames.indexOf(node.name) === -1) {
  542. return null;
  543. }
  544. }
  545. // Meshes
  546. if (node.skin !== undefined) {
  547. if (node.mesh !== undefined) {
  548. var skin = runtime.gltf.skins[node.skin];
  549. var newMesh = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  550. var newSkeleton = importSkeleton(runtime, node, skin);
  551. if (newSkeleton)
  552. {
  553. newMesh.skeleton = newSkeleton;
  554. skin.babylonSkeleton = newSkeleton;
  555. }
  556. babylonNode = newMesh;
  557. }
  558. }
  559. else if (node.mesh !== undefined) {
  560. babylonNode = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  561. }
  562. // Cameras
  563. else if (node.camera !== undefined && !node.babylonNode && !runtime.importOnlyMeshes) {
  564. var camera = runtime.gltf.cameras[node.camera];
  565. if (camera !== undefined) {
  566. if (camera.type === "orthographic") {
  567. var orthographicCamera = camera.orthographic;
  568. var orthoCamera = new FreeCamera(node.name || "camera" + node.camera, Vector3.Zero(), runtime.babylonScene);
  569. orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  570. orthoCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  571. babylonNode = orthoCamera;
  572. }
  573. else if (camera.type === "perspective") {
  574. var perspectiveCamera = camera.perspective;
  575. var persCamera = new FreeCamera(node.name || "camera" + node.camera, Vector3.Zero(), runtime.babylonScene);
  576. persCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  577. if (!perspectiveCamera.aspectRatio) {
  578. perspectiveCamera.aspectRatio = runtime.babylonScene.getEngine().getRenderWidth() / runtime.babylonScene.getEngine().getRenderHeight();
  579. }
  580. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  581. persCamera.maxZ = perspectiveCamera.zfar;
  582. persCamera.minZ = perspectiveCamera.znear;
  583. }
  584. babylonNode = persCamera;
  585. }
  586. }
  587. }
  588. // Empty node
  589. if (node.babylonNode) {
  590. return node.babylonNode;
  591. }
  592. else if (babylonNode === null) {
  593. var dummy = new Mesh(node.name || "mesh" + node.mesh, runtime.babylonScene);
  594. node.babylonNode = dummy;
  595. babylonNode = dummy;
  596. }
  597. if (babylonNode !== null) {
  598. configureNode(babylonNode, node);
  599. babylonNode.updateCache(true);
  600. node.babylonNode = babylonNode;
  601. }
  602. return babylonNode;
  603. };
  604. /**
  605. * Traverses nodes and creates them
  606. */
  607. var traverseNodes = (runtime: IGLTFRuntime, index: number, parent: Node, meshIncluded?: boolean): void => {
  608. var node = runtime.gltf.nodes[index];
  609. var newNode: Node = null;
  610. if (runtime.importOnlyMeshes && !meshIncluded) {
  611. if (runtime.importMeshesNames.indexOf(node.name) !== -1 || runtime.importMeshesNames.length === 0) {
  612. meshIncluded = true;
  613. }
  614. else {
  615. meshIncluded = false;
  616. }
  617. }
  618. else {
  619. meshIncluded = true;
  620. }
  621. if (meshIncluded) {
  622. newNode = importNode(runtime, node);
  623. if (newNode !== null) {
  624. newNode.id = createStringId(index);
  625. newNode.parent = parent;
  626. }
  627. }
  628. if (node.children) {
  629. for (var i = 0; i < node.children.length; i++) {
  630. traverseNodes(runtime, node.children[i], newNode, meshIncluded);
  631. }
  632. }
  633. };
  634. var importScene = (runtime: IGLTFRuntime): void => {
  635. var scene = runtime.gltf.scene || 0;
  636. var scenes = runtime.gltf.scenes;
  637. if (scenes) {
  638. var nodes = scenes[scene].nodes;
  639. for (var i = 0; i < nodes.length; i++) {
  640. traverseNodes(runtime, nodes[i], null);
  641. }
  642. }
  643. else {
  644. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  645. traverseNodes(runtime, i, null);
  646. }
  647. }
  648. };
  649. /**
  650. * do stuff after buffers are loaded (e.g. hook up materials, load animations, etc.)
  651. */
  652. var postLoad = (runtime: IGLTFRuntime): void => {
  653. importScene(runtime);
  654. // Set animations
  655. loadAnimations(runtime);
  656. for (var i = 0; i < runtime.babylonScene.skeletons.length; i++) {
  657. var skeleton = runtime.babylonScene.skeletons[i];
  658. runtime.babylonScene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  659. }
  660. // Revoke object urls created during load
  661. for (var i = 0; i < runtime.gltf.textures.length; i++) {
  662. var texture = runtime.gltf.textures[i];
  663. if (texture.blobURL) {
  664. URL.revokeObjectURL(texture.blobURL);
  665. }
  666. }
  667. };
  668. class BinaryReader {
  669. private _arrayBuffer: ArrayBuffer;
  670. private _dataView: DataView;
  671. private _byteOffset: number;
  672. constructor(arrayBuffer: ArrayBuffer) {
  673. this._arrayBuffer = arrayBuffer;
  674. this._dataView = new DataView(arrayBuffer);
  675. this._byteOffset = 0;
  676. }
  677. public getPosition(): number {
  678. return this._byteOffset;
  679. }
  680. public getLength(): number {
  681. return this._arrayBuffer.byteLength;
  682. }
  683. public readUint32(): number {
  684. var value = this._dataView.getUint32(this._byteOffset, true);
  685. this._byteOffset += 4;
  686. return value;
  687. }
  688. public readUint8Array(length: number): Uint8Array {
  689. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  690. this._byteOffset += length;
  691. return value;
  692. }
  693. public skipBytes(length: number): void {
  694. this._byteOffset += length;
  695. }
  696. }
  697. /**
  698. * glTF File Loader Plugin
  699. */
  700. export class GLTFLoader implements IGLTFLoader {
  701. public static Extensions: { [name: string]: GLTFLoaderExtension } = {};
  702. public static RegisterExtension(extension: GLTFLoaderExtension): void {
  703. if (GLTFLoader.Extensions[extension.name]) {
  704. Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  705. return;
  706. }
  707. GLTFLoader.Extensions[extension.name] = extension;
  708. }
  709. public static LoadMaterial(runtime: IGLTFRuntime, index: number): IGLTFMaterial {
  710. var material = runtime.gltf.materials[index];
  711. if (!material) return null;
  712. material.babylonMaterial = new PBRMaterial(material.name || "mat" + index, runtime.babylonScene);
  713. material.babylonMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  714. material.babylonMaterial.useScalarInLinearSpace = true;
  715. return material;
  716. }
  717. public static LoadMetallicRoughnessMaterialPropertiesAsync(runtime: IGLTFRuntime, material: IGLTFMaterial, onSuccess: () => void, onError: () => void): void {
  718. // Ensure metallic workflow
  719. material.babylonMaterial.metallic = 1;
  720. material.babylonMaterial.roughness = 1;
  721. var properties = material.pbrMetallicRoughness;
  722. if (!properties) {
  723. onSuccess();
  724. return;
  725. }
  726. //
  727. // Load Factors
  728. //
  729. material.babylonMaterial.albedoColor = properties.baseColorFactor ? Color3.FromArray(properties.baseColorFactor) : new Color3(1, 1, 1);
  730. material.babylonMaterial.metallic = properties.metallicFactor || 1;
  731. material.babylonMaterial.roughness = properties.roughnessFactor || 1;
  732. //
  733. // Load Textures
  734. //
  735. if (!properties.baseColorTexture && !properties.metallicRoughnessTexture) {
  736. onSuccess();
  737. return;
  738. }
  739. var checkSuccess = () => {
  740. if ((!properties.baseColorTexture || material.babylonMaterial.albedoTexture) &&
  741. (!properties.metallicRoughnessTexture || material.babylonMaterial.metallicTexture))
  742. {
  743. onSuccess();
  744. }
  745. };
  746. if (properties.baseColorTexture) {
  747. GLTFLoader.LoadTextureAsync(runtime, properties.baseColorTexture,
  748. texture => {
  749. material.babylonMaterial.albedoTexture = texture;
  750. GLTFLoader.LoadAlphaProperties(runtime, material);
  751. checkSuccess();
  752. },
  753. () => {
  754. Tools.Error("Failed to load base color texture");
  755. onError();
  756. });
  757. }
  758. if (properties.metallicRoughnessTexture) {
  759. GLTFLoader.LoadTextureAsync(runtime, properties.metallicRoughnessTexture,
  760. texture => {
  761. material.babylonMaterial.metallicTexture = texture;
  762. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  763. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  764. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  765. checkSuccess();
  766. },
  767. () => {
  768. Tools.Error("Failed to load metallic roughness texture");
  769. onError();
  770. });
  771. }
  772. }
  773. public static LoadCommonMaterialPropertiesAsync(runtime: IGLTFRuntime, material: IGLTFMaterial, onSuccess: () => void, onError: () => void): void {
  774. //
  775. // Load Factors
  776. //
  777. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  778. material.babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  779. if (material.doubleSided) {
  780. material.babylonMaterial.backFaceCulling = false;
  781. material.babylonMaterial.twoSidedLighting = true;
  782. }
  783. //
  784. // Load Textures
  785. //
  786. if (!material.normalTexture && !material.occlusionTexture && !material.emissiveTexture) {
  787. onSuccess();
  788. return;
  789. }
  790. var checkSuccess = () => {
  791. if ((!material.normalTexture || material.babylonMaterial.bumpTexture) &&
  792. (!material.occlusionTexture || material.babylonMaterial.ambientTexture) &&
  793. (!material.emissiveTexture || material.babylonMaterial.emissiveTexture)) {
  794. onSuccess();
  795. }
  796. }
  797. if (material.normalTexture) {
  798. GLTFLoader.LoadTextureAsync(runtime, material.normalTexture, babylonTexture => {
  799. material.babylonMaterial.bumpTexture = babylonTexture;
  800. if (material.normalTexture.scale !== undefined) {
  801. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  802. }
  803. checkSuccess();
  804. },
  805. () => {
  806. Tools.Error("Failed to load normal texture");
  807. onError();
  808. });
  809. }
  810. if (material.occlusionTexture) {
  811. GLTFLoader.LoadTextureAsync(runtime, material.occlusionTexture, babylonTexture => {
  812. material.babylonMaterial.ambientTexture = babylonTexture;
  813. material.babylonMaterial.useAmbientInGrayScale = true;
  814. if (material.occlusionTexture.strength !== undefined) {
  815. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  816. }
  817. checkSuccess();
  818. },
  819. () => {
  820. Tools.Error("Failed to load occlusion texture");
  821. onError();
  822. });
  823. }
  824. if (material.emissiveTexture) {
  825. GLTFLoader.LoadTextureAsync(runtime, material.emissiveTexture, babylonTexture => {
  826. material.babylonMaterial.emissiveTexture = babylonTexture;
  827. checkSuccess();
  828. },
  829. () => {
  830. Tools.Error("Failed to load emissive texture");
  831. onError();
  832. });
  833. }
  834. }
  835. public static LoadAlphaProperties(runtime: IGLTFRuntime, material: IGLTFMaterial): void {
  836. var alphaMode = material.alphaMode || "OPAQUE";
  837. switch (alphaMode) {
  838. case "OPAQUE":
  839. // default is opaque
  840. break;
  841. case "MASK":
  842. material.babylonMaterial.albedoTexture.hasAlpha = true;
  843. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  844. material.babylonMaterial.alphaMode = Engine.ALPHA_DISABLE;
  845. break;
  846. case "BLEND":
  847. material.babylonMaterial.albedoTexture.hasAlpha = true;
  848. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  849. material.babylonMaterial.alphaMode = Engine.ALPHA_COMBINE;
  850. break;
  851. default:
  852. Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  853. }
  854. }
  855. public static LoadTextureAsync(runtime: IGLTFRuntime, textureInfo: IGLTFTextureInfo, onSuccess: (babylonTexture: Texture) => void, onError: () => void): void {
  856. var texture = runtime.gltf.textures[textureInfo.index];
  857. var texCoord = textureInfo.texCoord || 0;
  858. if (!texture || texture.source === undefined) {
  859. onError();
  860. return;
  861. }
  862. if (texture.babylonTextures) {
  863. var babylonTexture = texture.babylonTextures[texCoord];
  864. if (!babylonTexture) {
  865. for (var i = 0; i < texture.babylonTextures.length; i++) {
  866. babylonTexture = texture.babylonTextures[i];
  867. if (babylonTexture) {
  868. babylonTexture = babylonTexture.clone();
  869. babylonTexture.coordinatesIndex = texCoord;
  870. break;
  871. }
  872. }
  873. }
  874. onSuccess(babylonTexture);
  875. return;
  876. }
  877. var source = runtime.gltf.images[texture.source];
  878. var sourceURL = runtime.rootUrl + source.uri;
  879. if (texture.blobURL) {
  880. sourceURL = texture.blobURL;
  881. }
  882. else {
  883. if (source.uri === undefined) {
  884. var bufferView = runtime.gltf.bufferViews[source.bufferView];
  885. var buffer = GLTFUtils.GetBufferFromBufferView(runtime, bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE);
  886. texture.blobURL = URL.createObjectURL(new Blob([buffer], { type: source.mimeType }));
  887. sourceURL = texture.blobURL;
  888. }
  889. else if (GLTFUtils.IsBase64(source.uri)) {
  890. var decodedBuffer = new Uint8Array(GLTFUtils.DecodeBase64(source.uri));
  891. texture.blobURL = URL.createObjectURL(new Blob([decodedBuffer], { type: source.mimeType }));
  892. sourceURL = texture.blobURL;
  893. }
  894. }
  895. GLTFLoader._createTextureAsync(runtime, texture, texCoord, sourceURL, onSuccess, onError);
  896. }
  897. private static _createTextureAsync(runtime: IGLTFRuntime, texture: IGLTFTexture, texCoord: number, url: string, onSuccess: (babylonTexture: Texture) => void, onError: () => void): void {
  898. var sampler: IGLTFSampler = texture.sampler ? runtime.gltf.samplers[texture.sampler] : {};
  899. var noMipMaps = (sampler.minFilter === ETextureMinFilter.NEAREST || sampler.minFilter === ETextureMinFilter.LINEAR);
  900. var samplingMode = Texture.BILINEAR_SAMPLINGMODE;
  901. var babylonTexture = new Texture(url, runtime.babylonScene, noMipMaps, true, samplingMode, () => {
  902. onSuccess(babylonTexture);
  903. }, onError);
  904. babylonTexture.coordinatesIndex = texCoord;
  905. babylonTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
  906. babylonTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
  907. babylonTexture.name = texture.name;
  908. // Cache the texture
  909. texture.babylonTextures = texture.babylonTextures || [];
  910. texture.babylonTextures[texCoord] = babylonTexture;
  911. }
  912. /**
  913. * Import meshes
  914. */
  915. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onError?: () => void): void {
  916. scene.useRightHandedSystem = true;
  917. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, true);
  918. if (!runtime) {
  919. onError();
  920. return;
  921. }
  922. if (meshesNames === "") {
  923. runtime.importMeshesNames = [];
  924. }
  925. else if (typeof meshesNames === "string") {
  926. runtime.importMeshesNames = [meshesNames];
  927. }
  928. else if (meshesNames && !(meshesNames instanceof Array)) {
  929. runtime.importMeshesNames = [meshesNames];
  930. }
  931. else {
  932. runtime.importMeshesNames = [];
  933. Tools.Warn("Argument meshesNames must be of type string or string[]");
  934. }
  935. // Load scene
  936. importScene(runtime);
  937. var meshes = [];
  938. var skeletons = [];
  939. // Fill arrays of meshes and skeletons
  940. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  941. var node = runtime.gltf.nodes[i];
  942. if (node.babylonNode instanceof AbstractMesh) {
  943. meshes.push(<AbstractMesh>node.babylonNode);
  944. }
  945. }
  946. for (var i = 0; i < runtime.gltf.skins.length; i++) {
  947. var skin = runtime.gltf.skins[i];
  948. if (skin.babylonSkeleton instanceof Skeleton) {
  949. skeletons.push(skin.babylonSkeleton);
  950. }
  951. }
  952. // Load buffers, materials, etc.
  953. GLTFLoader._loadBuffersAsync(runtime, () => {
  954. GLTFLoader._loadMaterialsAsync(runtime, () => {
  955. postLoad(runtime);
  956. onSuccess(meshes, null, skeletons);
  957. }, onError);
  958. }, onError);
  959. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  960. onSuccess(meshes, null, skeletons);
  961. }
  962. }
  963. /**
  964. * Load scene
  965. */
  966. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onError: () => void): void {
  967. scene.useRightHandedSystem = true;
  968. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, false);
  969. if (!runtime) {
  970. onError();
  971. return;
  972. }
  973. importScene(runtime);
  974. GLTFLoader._loadBuffersAsync(runtime, () => {
  975. GLTFLoader._loadMaterialsAsync(runtime, () => {
  976. postLoad(runtime);
  977. onSuccess();
  978. }, onError);
  979. }, onError);
  980. }
  981. private static _loadBuffersAsync(runtime: IGLTFRuntime, onSuccess: () => void, onError: () => void): void {
  982. if (runtime.gltf.buffers.length == 0) {
  983. onSuccess();
  984. return;
  985. }
  986. var successCount = 0;
  987. runtime.gltf.buffers.forEach((buffer, index) => {
  988. this._loadBufferAsync(runtime, index, () => {
  989. if (++successCount === runtime.gltf.buffers.length) {
  990. onSuccess();
  991. }
  992. }, onError);
  993. });
  994. }
  995. private static _loadBufferAsync(runtime: IGLTFRuntime, index: number, onSuccess: () => void, onError: () => void): void {
  996. var buffer = runtime.gltf.buffers[index];
  997. if (buffer.uri === undefined) {
  998. // buffer.loadedBufferView should already be set
  999. onSuccess();
  1000. }
  1001. else if (GLTFUtils.IsBase64(buffer.uri)) {
  1002. var data = GLTFUtils.DecodeBase64(buffer.uri);
  1003. setTimeout(() => {
  1004. buffer.loadedBufferView = new Uint8Array(data);
  1005. onSuccess();
  1006. });
  1007. }
  1008. else {
  1009. Tools.LoadFile(runtime.rootUrl + buffer.uri, data => {
  1010. buffer.loadedBufferView = new Uint8Array(data);
  1011. onSuccess();
  1012. }, null, null, true, onError);
  1013. }
  1014. }
  1015. private static _loadMaterialsAsync(runtime: IGLTFRuntime, onSuccess: () => void, onError: () => void): void {
  1016. var materials = runtime.gltf.materials;
  1017. if (!materials) {
  1018. onSuccess();
  1019. return;
  1020. }
  1021. var successCount = 0;
  1022. for (var i = 0; i < materials.length; i++) {
  1023. GLTFLoaderExtension.LoadMaterialAsync(runtime, i, () => {
  1024. if (++successCount === materials.length) {
  1025. onSuccess();
  1026. }
  1027. }, onError);
  1028. }
  1029. }
  1030. private static _createRuntime(scene: Scene, data: IGLTFLoaderData, rootUrl: string, importOnlyMeshes: boolean): IGLTFRuntime {
  1031. var runtime: IGLTFRuntime = {
  1032. gltf: <IGLTF>data.json,
  1033. babylonScene: scene,
  1034. rootUrl: rootUrl,
  1035. importOnlyMeshes: importOnlyMeshes,
  1036. }
  1037. var binaryBuffer: IGLTFBuffer;
  1038. var buffers = runtime.gltf.buffers;
  1039. if (buffers.length > 0 && buffers[0].uri === undefined) {
  1040. binaryBuffer = buffers[0];
  1041. }
  1042. if (data.bin) {
  1043. if (!binaryBuffer) {
  1044. Tools.Error("Unexpected BIN chunk");
  1045. return null;
  1046. }
  1047. if (binaryBuffer.byteLength != data.bin.byteLength) {
  1048. Tools.Error("Binary buffer length from JSON does not match chunk length");
  1049. return null;
  1050. }
  1051. binaryBuffer.loadedBufferView = data.bin;
  1052. }
  1053. GLTFLoaderExtension.PostCreateRuntime(runtime);
  1054. return runtime;
  1055. }
  1056. }
  1057. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  1058. }