babylon.glTFFileLoader.ts 65 KB

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