babylon.glTFLoader.ts 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF1 {
  3. /**
  4. * Tokenizer. Used for shaders compatibility
  5. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  6. */
  7. enum ETokenType {
  8. IDENTIFIER = 1,
  9. UNKNOWN = 2,
  10. END_OF_INPUT = 3
  11. }
  12. class Tokenizer {
  13. private _toParse: string;
  14. private _pos: number = 0;
  15. private _maxPos: number;
  16. public currentToken: ETokenType;
  17. public currentIdentifier: string;
  18. public currentString: string;
  19. public isLetterOrDigitPattern: RegExp = /^[a-zA-Z0-9]+$/;
  20. constructor(toParse: string) {
  21. this._toParse = toParse;
  22. this._maxPos = toParse.length;
  23. }
  24. public getNextToken(): ETokenType {
  25. if (this.isEnd()) return ETokenType.END_OF_INPUT;
  26. this.currentString = this.read();
  27. this.currentToken = ETokenType.UNKNOWN;
  28. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  29. this.currentToken = ETokenType.IDENTIFIER;
  30. this.currentIdentifier = this.currentString;
  31. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  32. this.currentIdentifier += this.currentString;
  33. this.forward();
  34. }
  35. }
  36. return this.currentToken;
  37. }
  38. public peek(): string {
  39. return this._toParse[this._pos];
  40. }
  41. public read(): string {
  42. return this._toParse[this._pos++];
  43. }
  44. public forward(): void {
  45. this._pos++;
  46. }
  47. public isEnd(): boolean {
  48. return this._pos >= this._maxPos;
  49. }
  50. }
  51. /**
  52. * Values
  53. */
  54. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  55. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  56. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  57. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  58. /**
  59. * Parse
  60. */
  61. var parseBuffers = (parsedBuffers: any, gltfRuntime: IGLTFRuntime) => {
  62. for (var buf in parsedBuffers) {
  63. var parsedBuffer = parsedBuffers[buf];
  64. gltfRuntime.buffers[buf] = parsedBuffer;
  65. gltfRuntime.buffersCount++;
  66. }
  67. };
  68. var parseShaders = (parsedShaders: any, gltfRuntime: IGLTFRuntime) => {
  69. for (var sha in parsedShaders) {
  70. var parsedShader = parsedShaders[sha];
  71. gltfRuntime.shaders[sha] = parsedShader;
  72. gltfRuntime.shaderscount++;
  73. }
  74. };
  75. var parseObject = (parsedObjects: any, runtimeProperty: string, gltfRuntime: IGLTFRuntime) => {
  76. for (var object in parsedObjects) {
  77. var parsedObject = parsedObjects[object];
  78. (<any>gltfRuntime)[runtimeProperty][object] = parsedObject;
  79. }
  80. };
  81. /**
  82. * Utils
  83. */
  84. var normalizeUVs = (buffer: any) => {
  85. if (!buffer) {
  86. return;
  87. }
  88. for (var i = 0; i < buffer.length / 2; i++) {
  89. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90. }
  91. };
  92. var getAttribute = (attributeParameter: IGLTFTechniqueParameter): Nullable<string> => {
  93. if (attributeParameter.semantic === "NORMAL") {
  94. return "normal";
  95. } else if (attributeParameter.semantic === "POSITION") {
  96. return "position";
  97. } else if (attributeParameter.semantic === "JOINT") {
  98. return "matricesIndices";
  99. } else if (attributeParameter.semantic === "WEIGHT") {
  100. return "matricesWeights";
  101. } else if (attributeParameter.semantic === "COLOR") {
  102. return "color";
  103. } else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  104. var channel = Number(attributeParameter.semantic.split("_")[1]);
  105. return "uv" + (channel === 0 ? "" : channel + 1);
  106. }
  107. return null;
  108. };
  109. /**
  110. * Loads and creates animations
  111. */
  112. var loadAnimations = (gltfRuntime: IGLTFRuntime) => {
  113. for (var anim in gltfRuntime.animations) {
  114. var animation: IGLTFAnimation = gltfRuntime.animations[anim];
  115. if (!animation.channels || !animation.samplers) {
  116. continue;
  117. }
  118. var lastAnimation: Nullable<Animation> = null;
  119. for (var i = 0; i < animation.channels.length; i++) {
  120. // Get parameters and load buffers
  121. var channel = animation.channels[i];
  122. var sampler: IGLTFAnimationSampler = animation.samplers[channel.sampler];
  123. if (!sampler) {
  124. continue;
  125. }
  126. var inputData: Nullable<string> = null;
  127. var outputData: Nullable<string> = null;
  128. if (animation.parameters) {
  129. inputData = animation.parameters[sampler.input];
  130. outputData = animation.parameters[sampler.output];
  131. }
  132. else {
  133. inputData = sampler.input;
  134. outputData = sampler.output;
  135. }
  136. var bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  137. var bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  138. var targetID = channel.target.id;
  139. var targetNode: any = gltfRuntime.scene.getNodeByID(targetID);
  140. if (targetNode === null) {
  141. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  142. }
  143. if (targetNode === null) {
  144. Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  145. continue;
  146. }
  147. var isBone = targetNode instanceof Bone;
  148. // Get target path (position, rotation or scaling)
  149. var targetPath = channel.target.path;
  150. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  151. if (targetPathIndex !== -1) {
  152. targetPath = babylonAnimationPaths[targetPathIndex];
  153. }
  154. // Determine animation type
  155. var animationType = Animation.ANIMATIONTYPE_MATRIX;
  156. if (!isBone) {
  157. if (targetPath === "rotationQuaternion") {
  158. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  159. targetNode.rotationQuaternion = new Quaternion();
  160. }
  161. else {
  162. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  163. }
  164. }
  165. // Create animation and key frames
  166. var babylonAnimation: Nullable<Animation> = null;
  167. var keys = [];
  168. var arrayOffset = 0;
  169. var modifyKey = false;
  170. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  171. babylonAnimation = lastAnimation;
  172. modifyKey = true;
  173. }
  174. if (!modifyKey) {
  175. babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
  176. }
  177. // For each frame
  178. for (var j = 0; j < bufferInput.length; j++) {
  179. var value: any = null;
  180. if (targetPath === "rotationQuaternion") { // VEC4
  181. value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  182. arrayOffset += 4;
  183. }
  184. else { // Position and scaling are VEC3
  185. value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  186. arrayOffset += 3;
  187. }
  188. if (isBone) {
  189. var bone = <Bone>targetNode;
  190. var translation = Vector3.Zero();
  191. var rotationQuaternion = new Quaternion();
  192. var scaling = Vector3.Zero();
  193. // Warning on decompose
  194. var mat = bone.getBaseMatrix();
  195. if (modifyKey && lastAnimation) {
  196. mat = lastAnimation.getKeys()[j].value;
  197. }
  198. mat.decompose(scaling, rotationQuaternion, translation);
  199. if (targetPath === "position") {
  200. translation = value;
  201. }
  202. else if (targetPath === "rotationQuaternion") {
  203. rotationQuaternion = value;
  204. }
  205. else {
  206. scaling = value;
  207. }
  208. value = Matrix.Compose(scaling, rotationQuaternion, translation);
  209. }
  210. if (!modifyKey) {
  211. keys.push({
  212. frame: bufferInput[j],
  213. value: value
  214. });
  215. }
  216. else if (lastAnimation) {
  217. lastAnimation.getKeys()[j].value = value;
  218. }
  219. }
  220. // Finish
  221. if (!modifyKey && babylonAnimation) {
  222. babylonAnimation.setKeys(keys);
  223. targetNode.animations.push(babylonAnimation);
  224. }
  225. lastAnimation = babylonAnimation;
  226. gltfRuntime.scene.stopAnimation(targetNode);
  227. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  228. }
  229. }
  230. };
  231. /**
  232. * Returns the bones transformation matrix
  233. */
  234. var configureBoneTransformation = (node: IGLTFNode): Matrix => {
  235. var mat: Nullable<Matrix> = null;
  236. if (node.translation || node.rotation || node.scale) {
  237. var scale = Vector3.FromArray(node.scale || [1, 1, 1]);
  238. var rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  239. var position = Vector3.FromArray(node.translation || [0, 0, 0]);
  240. mat = Matrix.Compose(scale, rotation, position);
  241. }
  242. else {
  243. mat = Matrix.FromArray(node.matrix);
  244. }
  245. return mat;
  246. };
  247. /**
  248. * Returns the parent bone
  249. */
  250. var getParentBone = (gltfRuntime: IGLTFRuntime, skins: IGLTFSkins, jointName: string, newSkeleton: Skeleton): Nullable<Bone> => {
  251. // Try to find
  252. for (var i = 0; i < newSkeleton.bones.length; i++) {
  253. if (newSkeleton.bones[i].name === jointName) {
  254. return newSkeleton.bones[i];
  255. }
  256. }
  257. // Not found, search in gltf nodes
  258. var nodes = gltfRuntime.nodes;
  259. for (var nde in nodes) {
  260. var node: IGLTFNode = nodes[nde];
  261. if (!node.jointName) {
  262. continue;
  263. }
  264. var children = node.children;
  265. for (var i = 0; i < children.length; i++) {
  266. var child: IGLTFNode = gltfRuntime.nodes[children[i]];
  267. if (!child.jointName) {
  268. continue;
  269. }
  270. if (child.jointName === jointName) {
  271. var mat = configureBoneTransformation(node);
  272. var bone = new Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  273. bone.id = nde;
  274. return bone;
  275. }
  276. }
  277. }
  278. return null;
  279. }
  280. /**
  281. * Returns the appropriate root node
  282. */
  283. var getNodeToRoot = (nodesToRoot: INodeToRoot[], id: string): Nullable<Bone> => {
  284. for (var i = 0; i < nodesToRoot.length; i++) {
  285. var nodeToRoot = nodesToRoot[i];
  286. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  287. var child = nodeToRoot.node.children[j];
  288. if (child === id) {
  289. return nodeToRoot.bone;
  290. }
  291. }
  292. }
  293. return null;
  294. };
  295. /**
  296. * Returns the node with the joint name
  297. */
  298. var getJointNode = (gltfRuntime: IGLTFRuntime, jointName: string): Nullable<IJointNode> => {
  299. var nodes = gltfRuntime.nodes;
  300. var node: IGLTFNode = nodes[jointName];
  301. if (node) {
  302. return {
  303. node: node,
  304. id: jointName
  305. };
  306. }
  307. for (var nde in nodes) {
  308. node = nodes[nde];
  309. if (node.jointName === jointName) {
  310. return {
  311. node: node,
  312. id: nde
  313. };
  314. }
  315. }
  316. return null;
  317. }
  318. /**
  319. * Checks if a nodes is in joints
  320. */
  321. var nodeIsInJoints = (skins: IGLTFSkins, id: string): boolean => {
  322. for (var i = 0; i < skins.jointNames.length; i++) {
  323. if (skins.jointNames[i] === id) {
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. /**
  330. * Fills the nodes to root for bones and builds hierarchy
  331. */
  332. var getNodesToRoot = (gltfRuntime: IGLTFRuntime, newSkeleton: Skeleton, skins: IGLTFSkins, nodesToRoot: INodeToRoot[]) => {
  333. // Creates nodes for root
  334. for (var nde in gltfRuntime.nodes) {
  335. var node: IGLTFNode = gltfRuntime.nodes[nde];
  336. var id = nde;
  337. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  338. continue;
  339. }
  340. // Create node to root bone
  341. var mat = configureBoneTransformation(node);
  342. var bone = new Bone(node.name || "", newSkeleton, null, mat);
  343. bone.id = id;
  344. nodesToRoot.push({ bone: bone, node: node, id: id });
  345. }
  346. // Parenting
  347. for (var i = 0; i < nodesToRoot.length; i++) {
  348. var nodeToRoot = nodesToRoot[i];
  349. var children = nodeToRoot.node.children;
  350. for (var j = 0; j < children.length; j++) {
  351. var child: Nullable<INodeToRoot> = null;
  352. for (var k = 0; k < nodesToRoot.length; k++) {
  353. if (nodesToRoot[k].id === children[j]) {
  354. child = nodesToRoot[k];
  355. break;
  356. }
  357. }
  358. if (child) {
  359. (<any>child.bone)._parent = nodeToRoot.bone;
  360. nodeToRoot.bone.children.push(child.bone);
  361. }
  362. }
  363. }
  364. };
  365. /**
  366. * Imports a skeleton
  367. */
  368. var importSkeleton = (gltfRuntime: IGLTFRuntime, skins: IGLTFSkins, mesh: Mesh, newSkeleton: Skeleton, id: string): Skeleton => {
  369. if (!newSkeleton) {
  370. newSkeleton = new Skeleton(skins.name || "", "", gltfRuntime.scene);
  371. }
  372. if (!skins.babylonSkeleton) {
  373. return newSkeleton;
  374. }
  375. // Find the root bones
  376. var nodesToRoot: INodeToRoot[] = [];
  377. var nodesToRootToAdd: Bone[] = [];
  378. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  379. newSkeleton.bones = [];
  380. // Joints
  381. for (var i = 0; i < skins.jointNames.length; i++) {
  382. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  383. if (!jointNode) {
  384. continue;
  385. }
  386. var node = jointNode.node;
  387. if (!node) {
  388. Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  389. continue;
  390. }
  391. var id = jointNode.id;
  392. // Optimize, if the bone already exists...
  393. var existingBone = gltfRuntime.scene.getBoneByID(id);
  394. if (existingBone) {
  395. newSkeleton.bones.push(existingBone);
  396. continue;
  397. }
  398. // Search for parent bone
  399. var foundBone = false;
  400. var parentBone: Nullable<Bone> = null;
  401. for (var j = 0; j < i; j++) {
  402. let jointNode = getJointNode(gltfRuntime, skins.jointNames[j]);
  403. if (!jointNode) {
  404. continue;
  405. }
  406. var joint: IGLTFNode = jointNode.node;
  407. if (!joint) {
  408. Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  409. continue;
  410. }
  411. var children = joint.children;
  412. if (!children) {
  413. continue;
  414. }
  415. foundBone = false;
  416. for (var k = 0; k < children.length; k++) {
  417. if (children[k] === id) {
  418. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  419. foundBone = true;
  420. break;
  421. }
  422. }
  423. if (foundBone) {
  424. break;
  425. }
  426. }
  427. // Create bone
  428. var mat = configureBoneTransformation(node);
  429. if (!parentBone && nodesToRoot.length > 0) {
  430. parentBone = getNodeToRoot(nodesToRoot, id);
  431. if (parentBone) {
  432. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  433. nodesToRootToAdd.push(parentBone);
  434. }
  435. }
  436. }
  437. var bone = new Bone(node.jointName || "", newSkeleton, parentBone, mat);
  438. bone.id = id;
  439. }
  440. // Polish
  441. var bones = newSkeleton.bones;
  442. newSkeleton.bones = [];
  443. for (var i = 0; i < skins.jointNames.length; i++) {
  444. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  445. if (!jointNode) {
  446. continue;
  447. }
  448. for (var j = 0; j < bones.length; j++) {
  449. if (bones[j].id === jointNode.id) {
  450. newSkeleton.bones.push(bones[j]);
  451. break;
  452. }
  453. }
  454. }
  455. newSkeleton.prepare();
  456. // Finish
  457. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  458. newSkeleton.bones.push(nodesToRootToAdd[i]);
  459. }
  460. return newSkeleton;
  461. };
  462. /**
  463. * Imports a mesh and its geometries
  464. */
  465. var importMesh = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, meshes: string[], id: string, newMesh: Mesh): Mesh => {
  466. if (!newMesh) {
  467. newMesh = new Mesh(node.name || "", gltfRuntime.scene);
  468. newMesh.id = id;
  469. }
  470. if (!node.babylonNode) {
  471. return newMesh;
  472. }
  473. var multiMat = new MultiMaterial("multimat" + id, gltfRuntime.scene);
  474. if (!newMesh.material) {
  475. newMesh.material = multiMat;
  476. }
  477. var vertexData = new VertexData();
  478. var geometry = new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  479. var verticesStarts = new Array<number>();
  480. var verticesCounts = new Array<number>();
  481. var indexStarts = new Array<number>();
  482. var indexCounts = new Array<number>();
  483. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  484. var meshID = meshes[meshIndex];
  485. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  486. if (!mesh) {
  487. continue;
  488. }
  489. // Positions, normals and UVs
  490. for (var i = 0; i < mesh.primitives.length; i++) {
  491. // Temporary vertex data
  492. var tempVertexData = new VertexData();
  493. var primitive = mesh.primitives[i];
  494. if (primitive.mode !== 4) {
  495. // continue;
  496. }
  497. var attributes = primitive.attributes;
  498. var accessor: Nullable<IGLTFAccessor> = null;
  499. var buffer: any = null;
  500. // Set positions, normal and uvs
  501. for (var semantic in attributes) {
  502. // Link accessor and buffer view
  503. accessor = gltfRuntime.accessors[attributes[semantic]];
  504. buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  505. if (semantic === "NORMAL") {
  506. tempVertexData.normals = new Float32Array(buffer.length);
  507. (<Float32Array>tempVertexData.normals).set(buffer);
  508. }
  509. else if (semantic === "POSITION") {
  510. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  511. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  512. for (var j = 0; j < buffer.length; j += 4) {
  513. tempVertexData.positions[j] = buffer[j];
  514. tempVertexData.positions[j + 1] = buffer[j + 1];
  515. tempVertexData.positions[j + 2] = buffer[j + 2];
  516. }
  517. }
  518. else {
  519. tempVertexData.positions = new Float32Array(buffer.length);
  520. (<Float32Array>tempVertexData.positions).set(buffer);
  521. }
  522. verticesCounts.push(tempVertexData.positions.length);
  523. }
  524. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  525. var channel = Number(semantic.split("_")[1]);
  526. var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  527. var uvs = new Float32Array(buffer.length);
  528. (<Float32Array>uvs).set(buffer);
  529. normalizeUVs(uvs);
  530. tempVertexData.set(uvs, uvKind);
  531. }
  532. else if (semantic === "JOINT") {
  533. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  534. (<Float32Array>tempVertexData.matricesIndices).set(buffer);
  535. }
  536. else if (semantic === "WEIGHT") {
  537. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  538. (<Float32Array>tempVertexData.matricesWeights).set(buffer);
  539. }
  540. else if (semantic === "COLOR") {
  541. tempVertexData.colors = new Float32Array(buffer.length);
  542. (<Float32Array>tempVertexData.colors).set(buffer);
  543. }
  544. }
  545. // Indices
  546. accessor = gltfRuntime.accessors[primitive.indices];
  547. if (accessor) {
  548. buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  549. tempVertexData.indices = new Int32Array(buffer.length);
  550. (<Float32Array>tempVertexData.indices).set(buffer);
  551. indexCounts.push(tempVertexData.indices.length);
  552. }
  553. else {
  554. // Set indices on the fly
  555. var indices: number[] = [];
  556. for (var j = 0; j < (<FloatArray>tempVertexData.positions).length / 3; j++) {
  557. indices.push(j);
  558. }
  559. tempVertexData.indices = new Int32Array(indices);
  560. indexCounts.push(tempVertexData.indices.length);
  561. }
  562. vertexData.merge(tempVertexData);
  563. // Sub material
  564. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  565. multiMat.subMaterials.push(material === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  566. // Update vertices start and index start
  567. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  568. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  569. }
  570. }
  571. // Apply geometry
  572. geometry.setAllVerticesData(vertexData, false);
  573. newMesh.computeWorldMatrix(true);
  574. // Apply submeshes
  575. newMesh.subMeshes = [];
  576. var index = 0;
  577. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  578. var meshID = meshes[meshIndex];
  579. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  580. if (!mesh) {
  581. continue;
  582. }
  583. for (var i = 0; i < mesh.primitives.length; i++) {
  584. if (mesh.primitives[i].mode !== 4) {
  585. //continue;
  586. }
  587. SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  588. index++;
  589. }
  590. }
  591. // Finish
  592. return newMesh;
  593. };
  594. /**
  595. * Configure node transformation from position, rotation and scaling
  596. */
  597. var configureNode = (newNode: any, position: Vector3, rotation: Quaternion, scaling: Vector3) => {
  598. if (newNode.position) {
  599. newNode.position = position;
  600. }
  601. if (newNode.rotationQuaternion || newNode.rotation) {
  602. newNode.rotationQuaternion = rotation;
  603. }
  604. if (newNode.scaling) {
  605. newNode.scaling = scaling;
  606. }
  607. };
  608. /**
  609. * Configures node from transformation matrix
  610. */
  611. var configureNodeFromMatrix = (newNode: Mesh, node: IGLTFNode, parent: Nullable<Node>) => {
  612. if (node.matrix) {
  613. var position = new Vector3(0, 0, 0);
  614. var rotation = new Quaternion();
  615. var scaling = new Vector3(0, 0, 0);
  616. var mat = Matrix.FromArray(node.matrix);
  617. mat.decompose(scaling, rotation, position);
  618. configureNode(newNode, position, rotation, scaling);
  619. }
  620. else if (node.translation && node.rotation && node.scale) {
  621. configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
  622. }
  623. newNode.computeWorldMatrix(true);
  624. };
  625. /**
  626. * Imports a node
  627. */
  628. var importNode = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, id: string, parent: Nullable<Node>): Nullable<Node> => {
  629. var lastNode: Nullable<Node> = null;
  630. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  631. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  632. return null;
  633. }
  634. }
  635. // Meshes
  636. if (node.skin) {
  637. if (node.meshes) {
  638. var skin: IGLTFSkins = gltfRuntime.skins[node.skin];
  639. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, <Mesh>node.babylonNode);
  640. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  641. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  642. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  643. if (!skin.babylonSkeleton) {
  644. skin.babylonSkeleton = newMesh.skeleton;
  645. }
  646. }
  647. lastNode = newMesh;
  648. }
  649. }
  650. else if (node.meshes) {
  651. /**
  652. * Improve meshes property
  653. */
  654. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, <Mesh>node.babylonNode);
  655. lastNode = newMesh;
  656. }
  657. // Lights
  658. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  659. var light: IGLTFLight = gltfRuntime.lights[node.light];
  660. if (light) {
  661. if (light.type === "ambient") {
  662. var ambienLight: IGLTFAmbienLight = (<any>light)[light.type];
  663. var hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  664. hemiLight.name = node.name || "";
  665. if (ambienLight.color) {
  666. hemiLight.diffuse = Color3.FromArray(ambienLight.color);
  667. }
  668. lastNode = hemiLight;
  669. }
  670. else if (light.type === "directional") {
  671. var directionalLight: IGLTFDirectionalLight = (<any>light)[light.type];
  672. var dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  673. dirLight.name = node.name || "";
  674. if (directionalLight.color) {
  675. dirLight.diffuse = Color3.FromArray(directionalLight.color);
  676. }
  677. lastNode = dirLight;
  678. }
  679. else if (light.type === "point") {
  680. var pointLight: IGLTFPointLight = (<any>light)[light.type];
  681. var ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  682. ptLight.name = node.name || "";
  683. if (pointLight.color) {
  684. ptLight.diffuse = Color3.FromArray(pointLight.color);
  685. }
  686. lastNode = ptLight;
  687. }
  688. else if (light.type === "spot") {
  689. var spotLight: IGLTFSpotLight = (<any>light)[light.type];
  690. var spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
  691. spLight.name = node.name || "";
  692. if (spotLight.color) {
  693. spLight.diffuse = Color3.FromArray(spotLight.color);
  694. }
  695. if (spotLight.fallOfAngle) {
  696. spLight.angle = spotLight.fallOfAngle;
  697. }
  698. if (spotLight.fallOffExponent) {
  699. spLight.exponent = spotLight.fallOffExponent;
  700. }
  701. lastNode = spLight;
  702. }
  703. }
  704. }
  705. // Cameras
  706. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  707. var camera: IGLTFCamera = gltfRuntime.cameras[node.camera];
  708. if (camera) {
  709. if (camera.type === "orthographic") {
  710. var orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  711. orthoCamera.name = node.name || "";
  712. orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  713. orthoCamera.attachControl(<HTMLElement>gltfRuntime.scene.getEngine().getRenderingCanvas());
  714. lastNode = orthoCamera;
  715. }
  716. else if (camera.type === "perspective") {
  717. var perspectiveCamera: IGLTFCameraPerspective = (<any>camera)[camera.type];
  718. var persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  719. persCamera.name = node.name || "";
  720. persCamera.attachControl(<HTMLElement>gltfRuntime.scene.getEngine().getRenderingCanvas());
  721. if (!perspectiveCamera.aspectRatio) {
  722. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  723. }
  724. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  725. persCamera.maxZ = perspectiveCamera.zfar;
  726. persCamera.minZ = perspectiveCamera.znear;
  727. }
  728. lastNode = persCamera;
  729. }
  730. }
  731. }
  732. // Empty node
  733. if (!node.jointName) {
  734. if (node.babylonNode) {
  735. return node.babylonNode;
  736. }
  737. else if (lastNode === null) {
  738. var dummy = new Mesh(node.name || "", gltfRuntime.scene);
  739. node.babylonNode = dummy;
  740. lastNode = dummy;
  741. }
  742. }
  743. if (lastNode !== null) {
  744. if (node.matrix && lastNode instanceof Mesh) {
  745. configureNodeFromMatrix(lastNode, node, parent);
  746. }
  747. else {
  748. var translation = node.translation || [0, 0, 0];
  749. var rotation = node.rotation || [0, 0, 0, 1];
  750. var scale = node.scale || [1, 1, 1];
  751. configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale));
  752. }
  753. lastNode.updateCache(true);
  754. node.babylonNode = lastNode;
  755. }
  756. return lastNode;
  757. };
  758. /**
  759. * Traverses nodes and creates them
  760. */
  761. var traverseNodes = (gltfRuntime: IGLTFRuntime, id: string, parent: Nullable<Node>, meshIncluded: boolean = false) => {
  762. var node: IGLTFNode = gltfRuntime.nodes[id];
  763. var newNode: Nullable<Node> = null;
  764. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  765. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  766. meshIncluded = true;
  767. }
  768. else {
  769. meshIncluded = false;
  770. }
  771. }
  772. else {
  773. meshIncluded = true;
  774. }
  775. if (!node.jointName && meshIncluded) {
  776. newNode = importNode(gltfRuntime, node, id, parent);
  777. if (newNode !== null) {
  778. newNode.id = id;
  779. newNode.parent = parent;
  780. }
  781. }
  782. if (node.children) {
  783. for (var i = 0; i < node.children.length; i++) {
  784. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  785. }
  786. }
  787. };
  788. /**
  789. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  790. */
  791. var postLoad = (gltfRuntime: IGLTFRuntime) => {
  792. // Nodes
  793. var currentScene: IGLTFScene = <IGLTFScene>gltfRuntime.currentScene;
  794. if (currentScene) {
  795. for (var i = 0; i < currentScene.nodes.length; i++) {
  796. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  797. }
  798. }
  799. else {
  800. for (var thing in gltfRuntime.scenes) {
  801. currentScene = <IGLTFScene>gltfRuntime.scenes[thing];
  802. for (var i = 0; i < currentScene.nodes.length; i++) {
  803. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  804. }
  805. }
  806. }
  807. // Set animations
  808. loadAnimations(gltfRuntime);
  809. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  810. var skeleton = gltfRuntime.scene.skeletons[i];
  811. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  812. }
  813. };
  814. /**
  815. * onBind shaderrs callback to set uniforms and matrices
  816. */
  817. var onBindShaderMaterial = (mesh: Mesh, gltfRuntime: IGLTFRuntime, unTreatedUniforms: {[key: string]: IGLTFTechniqueParameter}, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, onSuccess: (shaderMaterial: ShaderMaterial) => void) => {
  818. var materialValues = material.values || technique.parameters;
  819. for (var unif in unTreatedUniforms) {
  820. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  821. var type = uniform.type;
  822. if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
  823. if (uniform.semantic && !uniform.source && !uniform.node) {
  824. GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, <Effect>shaderMaterial.getEffect());
  825. }
  826. else if (uniform.semantic && (uniform.source || uniform.node)) {
  827. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  828. if (source === null) {
  829. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  830. }
  831. if (source === null) {
  832. continue;
  833. }
  834. GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, <Effect>shaderMaterial.getEffect());
  835. }
  836. }
  837. else {
  838. var value = (<any>materialValues)[technique.uniforms[unif]];
  839. if (!value) {
  840. continue;
  841. }
  842. if (type === EParameterType.SAMPLER_2D) {
  843. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  844. if (texture === null || texture === undefined) {
  845. continue;
  846. }
  847. (<Effect>shaderMaterial.getEffect()).setTexture(unif, texture);
  848. }
  849. else {
  850. GLTFUtils.SetUniform(<Effect>(shaderMaterial.getEffect()), unif, value, type);
  851. }
  852. }
  853. }
  854. onSuccess(shaderMaterial);
  855. };
  856. /**
  857. * Prepare uniforms to send the only one time
  858. * Loads the appropriate textures
  859. */
  860. var prepareShaderMaterialUniforms = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, unTreatedUniforms: {[key: string]: IGLTFTechniqueParameter}) => {
  861. var materialValues = material.values || technique.parameters;
  862. var techniqueUniforms = technique.uniforms;
  863. /**
  864. * Prepare values here (not matrices)
  865. */
  866. for (var unif in unTreatedUniforms) {
  867. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  868. var type = uniform.type;
  869. var value = (<any>materialValues)[techniqueUniforms[unif]];
  870. if (value === undefined) {
  871. // In case the value is the same for all materials
  872. value = <any>uniform.value;
  873. }
  874. if (!value) {
  875. continue;
  876. }
  877. var onLoadTexture = (uniformName: Nullable<string>) => {
  878. return (texture: Texture) => {
  879. if (uniform.value && uniformName) {
  880. // Static uniform
  881. shaderMaterial.setTexture(uniformName, texture);
  882. delete unTreatedUniforms[uniformName];
  883. }
  884. }
  885. };
  886. // Texture (sampler2D)
  887. if (type === EParameterType.SAMPLER_2D) {
  888. GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), () => onLoadTexture(null));
  889. }
  890. // Others
  891. else {
  892. if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  893. // Static uniform
  894. delete unTreatedUniforms[unif];
  895. }
  896. }
  897. }
  898. };
  899. /**
  900. * Shader compilation failed
  901. */
  902. var onShaderCompileError = (program: IGLTFProgram, shaderMaterial: ShaderMaterial, onError: (message: string) => void) => {
  903. return (effect: Effect, error: string) => {
  904. shaderMaterial.dispose(true);
  905. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  906. };
  907. };
  908. /**
  909. * Shader compilation success
  910. */
  911. var onShaderCompileSuccess = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, unTreatedUniforms: {[key: string]: IGLTFTechniqueParameter}, onSuccess: (shaderMaterial: ShaderMaterial) => void) => {
  912. return (_: Effect) => {
  913. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  914. shaderMaterial.onBind = (mesh: Mesh) => {
  915. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  916. };
  917. };
  918. };
  919. /**
  920. * Returns the appropriate uniform if already handled by babylon
  921. */
  922. var parseShaderUniforms = (tokenizer: Tokenizer, technique: IGLTFTechnique, unTreatedUniforms: {[key: string]: IGLTFTechniqueParameter}): string => {
  923. for (var unif in technique.uniforms) {
  924. var uniform = technique.uniforms[unif];
  925. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  926. if (tokenizer.currentIdentifier === unif) {
  927. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  928. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  929. if (transformIndex !== -1) {
  930. delete unTreatedUniforms[unif];
  931. return babylonTransforms[transformIndex];
  932. }
  933. }
  934. }
  935. }
  936. return tokenizer.currentIdentifier;
  937. };
  938. /**
  939. * All shaders loaded. Create materials one by one
  940. */
  941. var importMaterials = (gltfRuntime: IGLTFRuntime) => {
  942. // Create materials
  943. for (var mat in gltfRuntime.materials) {
  944. GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, (material: Material) => { }, () => { });
  945. }
  946. };
  947. /**
  948. * Implementation of the base glTF spec
  949. */
  950. export class GLTFLoaderBase {
  951. public static CreateRuntime(parsedData: any, scene: Scene, rootUrl: string): IGLTFRuntime {
  952. var gltfRuntime: IGLTFRuntime = {
  953. extensions: {},
  954. accessors: {},
  955. buffers: {},
  956. bufferViews: {},
  957. meshes: {},
  958. lights: {},
  959. cameras: {},
  960. nodes: {},
  961. images: {},
  962. textures: {},
  963. shaders: {},
  964. programs: {},
  965. samplers: {},
  966. techniques: {},
  967. materials: {},
  968. animations: {},
  969. skins: {},
  970. extensionsUsed: [],
  971. scenes: {},
  972. buffersCount: 0,
  973. shaderscount: 0,
  974. scene: scene,
  975. rootUrl: rootUrl,
  976. loadedBufferCount: 0,
  977. loadedBufferViews: {},
  978. loadedShaderCount: 0,
  979. importOnlyMeshes: false,
  980. dummyNodes: []
  981. }
  982. // Parse
  983. if (parsedData.extensions) {
  984. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  985. }
  986. if (parsedData.extensionsUsed) {
  987. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  988. }
  989. if (parsedData.buffers) {
  990. parseBuffers(parsedData.buffers, gltfRuntime);
  991. }
  992. if (parsedData.bufferViews) {
  993. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  994. }
  995. if (parsedData.accessors) {
  996. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  997. }
  998. if (parsedData.meshes) {
  999. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1000. }
  1001. if (parsedData.lights) {
  1002. parseObject(parsedData.lights, "lights", gltfRuntime);
  1003. }
  1004. if (parsedData.cameras) {
  1005. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1006. }
  1007. if (parsedData.nodes) {
  1008. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1009. }
  1010. if (parsedData.images) {
  1011. parseObject(parsedData.images, "images", gltfRuntime);
  1012. }
  1013. if (parsedData.textures) {
  1014. parseObject(parsedData.textures, "textures", gltfRuntime);
  1015. }
  1016. if (parsedData.shaders) {
  1017. parseShaders(parsedData.shaders, gltfRuntime);
  1018. }
  1019. if (parsedData.programs) {
  1020. parseObject(parsedData.programs, "programs", gltfRuntime);
  1021. }
  1022. if (parsedData.samplers) {
  1023. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1024. }
  1025. if (parsedData.techniques) {
  1026. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1027. }
  1028. if (parsedData.materials) {
  1029. parseObject(parsedData.materials, "materials", gltfRuntime);
  1030. }
  1031. if (parsedData.animations) {
  1032. parseObject(parsedData.animations, "animations", gltfRuntime);
  1033. }
  1034. if (parsedData.skins) {
  1035. parseObject(parsedData.skins, "skins", gltfRuntime);
  1036. }
  1037. if (parsedData.scenes) {
  1038. gltfRuntime.scenes = parsedData.scenes;
  1039. }
  1040. if (parsedData.scene && parsedData.scenes) {
  1041. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1042. }
  1043. return gltfRuntime;
  1044. }
  1045. public static LoadBufferAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (buffer: ArrayBufferView) => void, onError: (message: string) => void, onProgress?: () => void): void {
  1046. var buffer: IGLTFBuffer = gltfRuntime.buffers[id];
  1047. if (GLTFUtils.IsBase64(buffer.uri)) {
  1048. setTimeout(() => onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(buffer.uri))));
  1049. }
  1050. else {
  1051. Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, data => onSuccess(new Uint8Array(data)), onProgress, undefined, true, request => {
  1052. if (request) {
  1053. onError(request.status + " " + request.statusText);
  1054. }
  1055. });
  1056. }
  1057. }
  1058. public static LoadTextureBufferAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (buffer: Nullable<ArrayBufferView>) => void, onError: (message: string) => void): void {
  1059. var texture: IGLTFTexture = gltfRuntime.textures[id];
  1060. if (!texture || !texture.source) {
  1061. onError("");
  1062. return;
  1063. }
  1064. if (texture.babylonTexture) {
  1065. onSuccess(null);
  1066. return;
  1067. }
  1068. var source: IGLTFImage = gltfRuntime.images[texture.source];
  1069. if (GLTFUtils.IsBase64(source.uri)) {
  1070. setTimeout(() => onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(source.uri))));
  1071. }
  1072. else {
  1073. Tools.LoadFile(gltfRuntime.rootUrl + source.uri, data => onSuccess(new Uint8Array(data)), undefined, undefined, true, request => {
  1074. if (request) {
  1075. onError(request.status + " " + request.statusText);
  1076. }
  1077. });
  1078. }
  1079. }
  1080. public static CreateTextureAsync(gltfRuntime: IGLTFRuntime, id: string, buffer: Nullable<ArrayBufferView>, onSuccess: (texture: Texture) => void, onError: (message: string) => void): void {
  1081. var texture: IGLTFTexture = gltfRuntime.textures[id];
  1082. if (texture.babylonTexture) {
  1083. onSuccess(texture.babylonTexture);
  1084. return;
  1085. }
  1086. var sampler: IGLTFSampler = gltfRuntime.samplers[texture.sampler];
  1087. var createMipMaps =
  1088. (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1089. (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1090. (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1091. (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1092. var samplingMode = Texture.BILINEAR_SAMPLINGMODE;
  1093. var blob = new Blob([buffer]);
  1094. var blobURL = URL.createObjectURL(blob);
  1095. var revokeBlobURL = () => URL.revokeObjectURL(blobURL);
  1096. var newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1097. if (sampler.wrapS !== undefined) {
  1098. newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
  1099. }
  1100. if (sampler.wrapT !== undefined) {
  1101. newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
  1102. }
  1103. newTexture.name = id;
  1104. texture.babylonTexture = newTexture;
  1105. onSuccess(newTexture);
  1106. }
  1107. public static LoadShaderStringAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (shaderString: string) => void, onError: (message: string) => void): void {
  1108. var shader: IGLTFShader = gltfRuntime.shaders[id];
  1109. if (GLTFUtils.IsBase64(shader.uri)) {
  1110. var shaderString = atob(shader.uri.split(",")[1]);
  1111. onSuccess(shaderString);
  1112. }
  1113. else {
  1114. Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, request => {
  1115. if (request) {
  1116. onError(request.status + " " + request.statusText);
  1117. }
  1118. });
  1119. }
  1120. }
  1121. public static LoadMaterialAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (material: Material) => void, onError: (message: string) => void): void {
  1122. var material: IGLTFMaterial = gltfRuntime.materials[id];
  1123. if (!material.technique) {
  1124. if (onError) {
  1125. onError("No technique found.");
  1126. }
  1127. return;
  1128. }
  1129. var technique: IGLTFTechnique = gltfRuntime.techniques[material.technique];
  1130. if (!technique) {
  1131. var defaultMaterial = new StandardMaterial(id, gltfRuntime.scene);
  1132. defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5);
  1133. defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  1134. onSuccess(defaultMaterial);
  1135. return;
  1136. }
  1137. var program: IGLTFProgram = gltfRuntime.programs[technique.program];
  1138. var states: IGLTFTechniqueStates = technique.states;
  1139. var vertexShader: string = Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1140. var pixelShader: string = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1141. var newVertexShader = "";
  1142. var newPixelShader = "";
  1143. var vertexTokenizer = new Tokenizer(vertexShader);
  1144. var pixelTokenizer = new Tokenizer(pixelShader);
  1145. var unTreatedUniforms: {[key: string]: IGLTFTechniqueParameter} = {};
  1146. var uniforms = [];
  1147. var attributes = [];
  1148. var samplers = [];
  1149. // Fill uniform, sampler2D and attributes
  1150. for (var unif in technique.uniforms) {
  1151. var uniform = technique.uniforms[unif];
  1152. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  1153. unTreatedUniforms[unif] = uniformParameter;
  1154. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1155. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1156. if (transformIndex !== -1) {
  1157. uniforms.push(babylonTransforms[transformIndex]);
  1158. delete unTreatedUniforms[unif];
  1159. }
  1160. else {
  1161. uniforms.push(unif);
  1162. }
  1163. }
  1164. else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
  1165. samplers.push(unif);
  1166. }
  1167. else {
  1168. uniforms.push(unif);
  1169. }
  1170. }
  1171. for (var attr in technique.attributes) {
  1172. var attribute = technique.attributes[attr];
  1173. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  1174. if (attributeParameter.semantic) {
  1175. attributes.push(getAttribute(attributeParameter));
  1176. }
  1177. }
  1178. // Configure vertex shader
  1179. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1180. var tokenType = vertexTokenizer.currentToken;
  1181. if (tokenType !== ETokenType.IDENTIFIER) {
  1182. newVertexShader += vertexTokenizer.currentString;
  1183. continue;
  1184. }
  1185. var foundAttribute = false;
  1186. for (var attr in technique.attributes) {
  1187. var attribute = technique.attributes[attr];
  1188. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  1189. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1190. newVertexShader += getAttribute(attributeParameter);
  1191. foundAttribute = true;
  1192. break;
  1193. }
  1194. }
  1195. if (foundAttribute) {
  1196. continue;
  1197. }
  1198. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1199. }
  1200. // Configure pixel shader
  1201. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1202. var tokenType = pixelTokenizer.currentToken;
  1203. if (tokenType !== ETokenType.IDENTIFIER) {
  1204. newPixelShader += pixelTokenizer.currentString;
  1205. continue;
  1206. }
  1207. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1208. }
  1209. // Create shader material
  1210. var shaderPath = {
  1211. vertex: program.vertexShader + id,
  1212. fragment: program.fragmentShader + id
  1213. };
  1214. var options = {
  1215. attributes: attributes,
  1216. uniforms: uniforms,
  1217. samplers: samplers,
  1218. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1219. };
  1220. Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1221. Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1222. var shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1223. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1224. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1225. shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  1226. if (states && states.functions) {
  1227. var functions = states.functions;
  1228. if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {
  1229. shaderMaterial.backFaceCulling = false;
  1230. }
  1231. var blendFunc = functions.blendFuncSeparate;
  1232. if (blendFunc) {
  1233. if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1234. shaderMaterial.alphaMode = Engine.ALPHA_COMBINE;
  1235. }
  1236. else if (blendFunc[0] === EBlendingFunction.ONE && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
  1237. shaderMaterial.alphaMode = Engine.ALPHA_ONEONE;
  1238. }
  1239. else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
  1240. shaderMaterial.alphaMode = Engine.ALPHA_ADD;
  1241. }
  1242. else if (blendFunc[0] === EBlendingFunction.ZERO && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1243. shaderMaterial.alphaMode = Engine.ALPHA_SUBTRACT;
  1244. }
  1245. else if (blendFunc[0] === EBlendingFunction.DST_COLOR && blendFunc[1] === EBlendingFunction.ZERO && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1246. shaderMaterial.alphaMode = Engine.ALPHA_MULTIPLY;
  1247. }
  1248. else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1249. shaderMaterial.alphaMode = Engine.ALPHA_MAXIMIZED;
  1250. }
  1251. }
  1252. }
  1253. }
  1254. }
  1255. /**
  1256. * glTF V1 Loader
  1257. */
  1258. export class GLTFLoader implements IGLTFLoader {
  1259. public static Extensions: { [name: string]: GLTFLoaderExtension } = {};
  1260. public static RegisterExtension(extension: GLTFLoaderExtension): void {
  1261. if (GLTFLoader.Extensions[extension.name]) {
  1262. Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1263. return;
  1264. }
  1265. GLTFLoader.Extensions[extension.name] = extension;
  1266. }
  1267. public dispose(): void {
  1268. // do nothing
  1269. }
  1270. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: (meshes: Nullable<AbstractMesh[]>, particleSystems: Nullable<ParticleSystem[]>, skeletons: Nullable<Skeleton[]>) => void, onProgress: (event: ProgressEvent) => void, onError: (message: string) => void): boolean {
  1271. scene.useRightHandedSystem = true;
  1272. GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, gltfRuntime => {
  1273. gltfRuntime.importOnlyMeshes = true;
  1274. if (meshesNames === "") {
  1275. gltfRuntime.importMeshesNames = [];
  1276. }
  1277. else if (typeof meshesNames === "string") {
  1278. gltfRuntime.importMeshesNames = [meshesNames];
  1279. }
  1280. else if (meshesNames && !(meshesNames instanceof Array)) {
  1281. gltfRuntime.importMeshesNames = [meshesNames];
  1282. }
  1283. else {
  1284. gltfRuntime.importMeshesNames = [];
  1285. Tools.Warn("Argument meshesNames must be of type string or string[]");
  1286. }
  1287. // Create nodes
  1288. this._createNodes(gltfRuntime);
  1289. var meshes = new Array<AbstractMesh>();
  1290. var skeletons = new Array<Skeleton>();
  1291. // Fill arrays of meshes and skeletons
  1292. for (var nde in gltfRuntime.nodes) {
  1293. var node: IGLTFNode = gltfRuntime.nodes[nde];
  1294. if (node.babylonNode instanceof AbstractMesh) {
  1295. meshes.push(<AbstractMesh>node.babylonNode);
  1296. }
  1297. }
  1298. for (var skl in gltfRuntime.skins) {
  1299. var skin: IGLTFSkins = gltfRuntime.skins[skl];
  1300. if (skin.babylonSkeleton instanceof Skeleton) {
  1301. skeletons.push(skin.babylonSkeleton);
  1302. }
  1303. }
  1304. // Load buffers, shaders, materials, etc.
  1305. this._loadBuffersAsync(gltfRuntime, () => {
  1306. this._loadShadersAsync(gltfRuntime, () => {
  1307. importMaterials(gltfRuntime);
  1308. postLoad(gltfRuntime);
  1309. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1310. onSuccess(meshes, null, skeletons);
  1311. }
  1312. });
  1313. }, onProgress);
  1314. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1315. onSuccess(meshes, null, skeletons);
  1316. }
  1317. }, onError);
  1318. return true;
  1319. }
  1320. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: ProgressEvent) => void, onError: (message: string) => void): void {
  1321. scene.useRightHandedSystem = true;
  1322. GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, gltfRuntime => {
  1323. // Load runtime extensios
  1324. GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, () => {
  1325. // Create nodes
  1326. this._createNodes(gltfRuntime);
  1327. // Load buffers, shaders, materials, etc.
  1328. this._loadBuffersAsync(gltfRuntime, () => {
  1329. this._loadShadersAsync(gltfRuntime, () => {
  1330. importMaterials(gltfRuntime);
  1331. postLoad(gltfRuntime);
  1332. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1333. onSuccess();
  1334. }
  1335. });
  1336. });
  1337. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1338. onSuccess();
  1339. }
  1340. }, onError);
  1341. }, onError);
  1342. }
  1343. private _loadShadersAsync(gltfRuntime: IGLTFRuntime, onload: () => void): void {
  1344. var hasShaders = false;
  1345. var processShader = (sha: string, shader: IGLTFShader) => {
  1346. GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, shaderString => {
  1347. gltfRuntime.loadedShaderCount++;
  1348. if (shaderString) {
  1349. Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1350. }
  1351. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1352. onload();
  1353. }
  1354. }, () => {
  1355. Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1356. });
  1357. };
  1358. for (var sha in gltfRuntime.shaders) {
  1359. hasShaders = true;
  1360. var shader: IGLTFShader = gltfRuntime.shaders[sha];
  1361. if (shader) {
  1362. processShader.bind(this, sha, shader)();
  1363. }
  1364. else {
  1365. Tools.Error("No shader named: " + sha);
  1366. }
  1367. }
  1368. if (!hasShaders) {
  1369. onload();
  1370. }
  1371. };
  1372. private _loadBuffersAsync(gltfRuntime: IGLTFRuntime, onLoad: () => void, onProgress?: (event: ProgressEvent) => void): void {
  1373. var hasBuffers = false;
  1374. var processBuffer = (buf: string, buffer: IGLTFBuffer) => {
  1375. GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, bufferView => {
  1376. gltfRuntime.loadedBufferCount++;
  1377. if (bufferView) {
  1378. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1379. Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1380. }
  1381. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1382. }
  1383. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1384. onLoad();
  1385. }
  1386. }, () => {
  1387. Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1388. });
  1389. };
  1390. for (var buf in gltfRuntime.buffers) {
  1391. hasBuffers = true;
  1392. var buffer: IGLTFBuffer = gltfRuntime.buffers[buf];
  1393. if (buffer) {
  1394. processBuffer.bind(this, buf, buffer)();
  1395. }
  1396. else {
  1397. Tools.Error("No buffer named: " + buf);
  1398. }
  1399. }
  1400. if (!hasBuffers) {
  1401. onLoad();
  1402. }
  1403. }
  1404. private _createNodes(gltfRuntime: IGLTFRuntime): void {
  1405. var currentScene = <IGLTFScene>gltfRuntime.currentScene;
  1406. if (currentScene) {
  1407. // Only one scene even if multiple scenes are defined
  1408. for (var i = 0; i < currentScene.nodes.length; i++) {
  1409. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1410. }
  1411. }
  1412. else {
  1413. // Load all scenes
  1414. for (var thing in gltfRuntime.scenes) {
  1415. currentScene = <IGLTFScene>gltfRuntime.scenes[thing];
  1416. for (var i = 0; i < currentScene.nodes.length; i++) {
  1417. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1418. }
  1419. }
  1420. }
  1421. }
  1422. };
  1423. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = () => new GLTFLoader();
  1424. }