babylon.glTFFileLoader.ts 66 KB

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