babylon.glTFFileLoader.ts 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  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. /**
  60. * Tokenizer. Used for shaders compatibility
  61. * Automatically map world, view, projection, worldViewProjection and attributes
  62. */
  63. enum ETokenType {
  64. IDENTIFIER = 1,
  65. UNKNOWN = 2,
  66. END_OF_INPUT = 3
  67. }
  68. class Tokenizer {
  69. private _toParse: string;
  70. private _pos: number = 0;
  71. private _maxPos: number;
  72. public currentToken: ETokenType;
  73. public currentIdentifier: string;
  74. public currentString: string;
  75. public isLetterOrDigitPattern: RegExp = /^[a-zA-Z0-9]+$/;
  76. constructor(toParse: string) {
  77. this._toParse = toParse;
  78. this._maxPos = toParse.length;
  79. }
  80. public getNextToken(): ETokenType {
  81. if (this.isEnd()) return ETokenType.END_OF_INPUT;
  82. this.currentString = this.read();
  83. this.currentToken = ETokenType.UNKNOWN;
  84. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  85. this.currentToken = ETokenType.IDENTIFIER;
  86. this.currentIdentifier = this.currentString;
  87. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  88. this.currentIdentifier += this.currentString;
  89. this.forward();
  90. }
  91. }
  92. return this.currentToken;
  93. }
  94. public peek(): string {
  95. return this._toParse[this._pos];
  96. }
  97. public read(): string {
  98. return this._toParse[this._pos++];
  99. }
  100. public forward(): void {
  101. this._pos++;
  102. }
  103. public isEnd(): boolean {
  104. return this._pos >= this._maxPos;
  105. }
  106. }
  107. /**
  108. * Values
  109. */
  110. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  111. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  112. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  113. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  114. /**
  115. * Parse
  116. */
  117. var parseBuffers = (parsedBuffers: any, gltfRuntime: IGLTFRuntime) => {
  118. for (var buf in parsedBuffers) {
  119. var parsedBuffer = parsedBuffers[buf];
  120. gltfRuntime.buffers[buf] = parsedBuffer;
  121. gltfRuntime.buffersCount++;
  122. }
  123. };
  124. var parseShaders = (parsedShaders: any, gltfRuntime: IGLTFRuntime) => {
  125. for (var sha in parsedShaders) {
  126. var parsedShader = parsedShaders[sha];
  127. gltfRuntime.shaders[sha] = parsedShader;
  128. gltfRuntime.shaderscount++;
  129. }
  130. };
  131. var parseObject = (parsedObjects: any, runtimeProperty: string, gltfRuntime: IGLTFRuntime) => {
  132. for (var object in parsedObjects) {
  133. var parsedObject = parsedObjects[object];
  134. gltfRuntime[runtimeProperty][object] = parsedObject;
  135. }
  136. };
  137. /**
  138. * Utils
  139. */
  140. var getByteStrideFromType = (accessor: IGLTFAccessor): number => {
  141. // Needs this function since "byteStride" isn't requiered in glTF format
  142. var type = accessor.type;
  143. switch (type) {
  144. case "VEC2": return 2;
  145. case "VEC3": return 3;
  146. case "VEC4": return 4;
  147. case "MAT2": return 4;
  148. case "MAT3": return 9;
  149. case "MAT4": return 16;
  150. default: return 1;
  151. }
  152. };
  153. var setMatrix = (scene: Scene, source: Node, parameter: IGLTFTechniqueParameter, uniformName: string, shaderMaterial: any) => {
  154. var mat: Matrix = null;
  155. if (parameter.semantic === "MODEL") {
  156. mat = source.getWorldMatrix();
  157. }
  158. else if (parameter.semantic === "PROJECTION") {
  159. mat = scene.getProjectionMatrix();
  160. }
  161. else if (parameter.semantic === "VIEW") {
  162. mat = scene.getViewMatrix();
  163. }
  164. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  165. mat = Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  166. }
  167. else if (parameter.semantic === "MODELVIEW") {
  168. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  169. }
  170. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  171. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  172. }
  173. else if (parameter.semantic === "MODELINVERSE") {
  174. mat = source.getWorldMatrix().invert();
  175. }
  176. else if (parameter.semantic === "VIEWINVERSE") {
  177. mat = scene.getViewMatrix().invert();
  178. }
  179. else if (parameter.semantic === "PROJECTIONINVERSE") {
  180. mat = scene.getProjectionMatrix().invert();
  181. }
  182. else if (parameter.semantic === "MODELVIEWINVERSE") {
  183. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  184. }
  185. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  186. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  187. }
  188. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  189. mat = Matrix.Transpose(source.getWorldMatrix().invert());
  190. }
  191. switch (parameter.type) {
  192. case EParameterType.FLOAT_MAT2: shaderMaterial.setMatrix2x2(uniformName, Matrix.GetAsMatrix2x2(mat)); break;
  193. case EParameterType.FLOAT_MAT3: shaderMaterial.setMatrix3x3(uniformName, Matrix.GetAsMatrix3x3(mat)); break;
  194. case EParameterType.FLOAT_MAT4: shaderMaterial.setMatrix(uniformName, mat); break;
  195. default: break;
  196. }
  197. };
  198. var setUniform = (shaderMaterial: any, uniform: string, value: any, type: number): boolean => {
  199. switch (type) {
  200. case EParameterType.FLOAT: shaderMaterial.setFloat(uniform, value); return true;
  201. case EParameterType.FLOAT_VEC2: shaderMaterial.setVector2(uniform, Vector2.FromArray(value)); return true;
  202. case EParameterType.FLOAT_VEC3: shaderMaterial.setVector3(uniform, Vector3.FromArray(value)); return true;
  203. case EParameterType.FLOAT_VEC4: shaderMaterial.setVector4(uniform, Vector4.FromArray(value)); return true;
  204. default: return false;
  205. }
  206. };
  207. var getWrapMode = (mode: number): ETextureWrapMode => {
  208. switch (mode) {
  209. case ETextureWrapMode.CLAMP_TO_EDGE: return Texture.CLAMP_ADDRESSMODE;
  210. case ETextureWrapMode.MIRRORED_REPEAT: return Texture.MIRROR_ADDRESSMODE;
  211. case ETextureWrapMode.REPEAT: return Texture.WRAP_ADDRESSMODE;
  212. default: return Texture.WRAP_ADDRESSMODE;
  213. }
  214. };
  215. var getTextureFilterMode = (mode: number): ETextureFilterType => {
  216. switch (mode) {
  217. case ETextureFilterType.LINEAR:
  218. case ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  219. case ETextureFilterType.LINEAR_MIPMAP_LINEAR: return Texture.TRILINEAR_SAMPLINGMODE;
  220. case ETextureFilterType.NEAREST:
  221. case ETextureFilterType.NEAREST_MIPMAP_NEAREST: return Texture.NEAREST_SAMPLINGMODE;
  222. default: return Texture.BILINEAR_SAMPLINGMODE;
  223. }
  224. };
  225. var getBufferFromAccessor = (gltfRuntime: IGLTFRuntime, accessor: IGLTFAccessor): any => {
  226. var bufferView: IGLTFBufferView = gltfRuntime.bufferViews[accessor.bufferView];
  227. var arrayBuffer: ArrayBuffer = gltfRuntime.arrayBuffers[bufferView.buffer];
  228. var byteOffset = accessor.byteOffset + bufferView.byteOffset;
  229. var count = accessor.count * getByteStrideFromType(accessor);
  230. switch (accessor.componentType) {
  231. case EComponentType.BYTE: return new Int8Array(arrayBuffer, byteOffset, count);
  232. case EComponentType.UNSIGNED_BYTE: return new Uint8Array(arrayBuffer, byteOffset, count);
  233. case EComponentType.SHORT: return new Int16Array(arrayBuffer, byteOffset, count);
  234. case EComponentType.UNSIGNED_SHORT: return new Uint16Array(arrayBuffer, byteOffset, count);
  235. default: return new Float32Array(arrayBuffer, byteOffset, count);
  236. }
  237. };
  238. var normalizeUVs = (buffer: any) => {
  239. if (!buffer) {
  240. return;
  241. }
  242. for (var i = 0; i < buffer.length / 2; i++) {
  243. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  244. }
  245. };
  246. var replaceInString = (str: string, searchValue: string, replaceValue: string) => {
  247. while (str.indexOf(searchValue) !== -1) {
  248. str = str.replace(searchValue, replaceValue);
  249. }
  250. return str;
  251. };
  252. var getAttribute = (attributeParameter: IGLTFTechniqueParameter) => {
  253. if (attributeParameter.semantic === "NORMAL") {
  254. return "normal";
  255. }
  256. else if (attributeParameter.semantic === "POSITION") {
  257. return "position";
  258. }
  259. else if (attributeParameter.semantic === "JOINT") {
  260. return "matricesIndices";
  261. }
  262. else if (attributeParameter.semantic === "WEIGHT") {
  263. return "matricesWeights";
  264. }
  265. else if (attributeParameter.semantic === "COLOR") {
  266. return "color";
  267. }
  268. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  269. var channel = Number(attributeParameter.semantic.split("_")[1]);
  270. return "uv" + (channel === 0 ? "" : channel + 1);
  271. }
  272. };
  273. var isBase64 = (uri: string): boolean => {
  274. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  275. };
  276. /**
  277. * Load animations
  278. */
  279. var getAnimationPath = (path: string): string => {
  280. var index = glTFAnimationPaths.indexOf(path);
  281. if (index !== -1) {
  282. return babylonAnimationPaths[index];
  283. }
  284. return path;
  285. };
  286. var loadAnimations = (gltfRuntime: IGLTFRuntime) => {
  287. for (var anim in gltfRuntime.animations) {
  288. var animation: IGLTFAnimation = gltfRuntime.animations[anim];
  289. for (var i = 0; i < animation.channels.length; i++) {
  290. // Get parameters and load buffers
  291. var channel = animation.channels[i];
  292. var sampler: IGLTFAnimationSampler = animation.samplers[channel.sampler];
  293. if (!sampler) {
  294. continue;
  295. }
  296. var inputData = animation.parameters[sampler.input];
  297. var outputData = animation.parameters[sampler.output];
  298. var bufferInput = getBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  299. var bufferOutput = getBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  300. var targetID = channel.target.id;
  301. var targetNode: any = gltfRuntime.scene.getNodeByID(targetID);
  302. if (targetNode === null) {
  303. Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  304. continue;
  305. }
  306. var isBone = targetNode instanceof Bone;
  307. // Get target path (position, rotation or scaling)
  308. var targetPath = channel.target.path;
  309. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  310. if (targetPathIndex !== -1) {
  311. targetPath = babylonAnimationPaths[targetPathIndex];
  312. }
  313. // Determine animation type
  314. var animationType = Animation.ANIMATIONTYPE_MATRIX;
  315. if (!isBone) {
  316. if (targetPath === "rotationQuaternion") {
  317. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  318. targetNode.rotationQuaternion = new Quaternion();
  319. }
  320. else {
  321. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  322. }
  323. }
  324. // Create animation and key frames
  325. var babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
  326. var keys = [];
  327. var arrayOffset = 0;
  328. for (var i = 0; i < bufferInput.length; i++) {
  329. var value: any = null;
  330. if (targetPath === "rotationQuaternion") { // VEC4
  331. value = Quaternion.RotationAxis(Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]).normalize(), bufferOutput[arrayOffset + 3]);
  332. arrayOffset += 4;
  333. }
  334. else { // Position and scaling are VEC3
  335. value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  336. arrayOffset += 3;
  337. }
  338. if (isBone) {
  339. var translation = Vector3.Zero();
  340. var rotationQuaternion = new Quaternion();
  341. var scaling = Vector3.Zero();
  342. var bone = <Bone>targetNode;
  343. var mat = bone.getBaseMatrix();
  344. mat.decompose(scaling, rotationQuaternion, translation);
  345. if (targetPath === "position") {
  346. translation = value;
  347. }
  348. else if (targetPath === "rotationQuaternion") {
  349. rotationQuaternion = value;
  350. }
  351. else {
  352. scaling = value;
  353. }
  354. value = Matrix.Compose(scaling, rotationQuaternion, translation);
  355. }
  356. keys.push({
  357. frame: bufferInput[i],
  358. value: value
  359. });
  360. }
  361. // Finish
  362. babylonAnimation.setKeys(keys);
  363. targetNode.animations.push(babylonAnimation);
  364. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true);
  365. }
  366. }
  367. };
  368. /**
  369. * Import skeletons and bones
  370. */
  371. var configureBoneTransformation = (node: IGLTFNode): Matrix => {
  372. var mat: Matrix = null;
  373. if (node.translation && node.rotation && node.scale) {
  374. mat = Matrix.Compose(Vector3.FromArray(node.scale),
  375. Quaternion.RotationAxis(Vector3.FromArray([node.rotation[0], node.rotation[1], node.rotation[2]]).normalize(), node.rotation[3]),
  376. Vector3.FromArray(node.translation));
  377. }
  378. else {
  379. mat = Matrix.FromArray(node.matrix);
  380. }
  381. return mat;
  382. };
  383. var getParentBone = (gltfRuntime: IGLTFRuntime, jointName: string, newSkeleton: Skeleton): Bone => {
  384. // Try to find
  385. for (var i = 0; i < newSkeleton.bones.length; i++) {
  386. if (newSkeleton.bones[i].id === jointName) {
  387. return newSkeleton.bones[i];
  388. }
  389. }
  390. // Not found
  391. for (var nde in gltfRuntime.nodes) {
  392. var node: IGLTFNode = gltfRuntime.nodes[nde];
  393. if (!node || !node.jointName) {
  394. continue;
  395. }
  396. for (var i = 0; i < node.children.length; i++) {
  397. var childID = node.children[i];
  398. var childNode: IGLTFNode = gltfRuntime.nodes[childID];
  399. if (!childNode || !childNode.jointName) {
  400. continue;
  401. }
  402. if (childID === jointName) {
  403. var mat = configureBoneTransformation(node);
  404. var parentBone = getParentBone(gltfRuntime, node.jointName, newSkeleton);
  405. var bone = new Bone(node.name, newSkeleton, parentBone, mat);
  406. bone.id = node.jointName;
  407. return bone;
  408. }
  409. }
  410. }
  411. // Does not exists
  412. return null;
  413. };
  414. var importSkeleton = (gltfRuntime: IGLTFRuntime, skins: IGLTFSkins): Skeleton => {
  415. var newSkeleton = new Skeleton(skins.name, "", gltfRuntime.scene);
  416. // Matrices
  417. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  418. var buffer = getBufferFromAccessor(gltfRuntime, accessor);
  419. // Joints
  420. for (var i = 0; i < skins.jointNames.length; i++) {
  421. var node: IGLTFNode = gltfRuntime.nodes[skins.jointNames[i]];
  422. if (!node) {
  423. Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  424. continue;
  425. }
  426. var mat = configureBoneTransformation(node);
  427. var parentBone = getParentBone(gltfRuntime, skins.jointNames[i], newSkeleton);
  428. var bone = new Bone(node.name, newSkeleton, parentBone, mat);
  429. bone.id = skins.jointNames[i];
  430. }
  431. newSkeleton.prepare();
  432. return newSkeleton;
  433. };
  434. /**
  435. * Load geometries and nodes
  436. */
  437. var importMesh = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, meshes: string[], id: string, skin?: IGLTFSkins): Mesh => {
  438. var newMesh = new Mesh(node.name, gltfRuntime.scene);
  439. newMesh.id = id;
  440. newMesh.layerMask = 0x0FFFFFFF;
  441. newMesh.subMeshes = [];
  442. var multiMat = new MultiMaterial("multimat" + id, gltfRuntime.scene);
  443. newMesh.material = multiMat;
  444. var vertexData = new VertexData();
  445. var geometry = new Geometry(id, gltfRuntime.scene, vertexData, true);
  446. var verticesStarts = [];
  447. var verticesCounts = [];
  448. var indexStarts = [];
  449. var indexCounts = [];
  450. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  451. var meshID = meshes[meshIndex];
  452. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  453. if (!mesh) {
  454. continue;
  455. }
  456. // Positions, normals and UVs
  457. for (var i = 0; i < mesh.primitives.length; i++) {
  458. // Temporary vertex data
  459. var tempVertexData = new VertexData();
  460. var primitive = mesh.primitives[i];
  461. if (primitive.primitive !== 4) {
  462. continue;
  463. }
  464. var attributes = primitive.attributes;
  465. var accessor: IGLTFAccessor = null;
  466. var buffer: any = null;
  467. // Set positions, normal and uvs
  468. for (var semantic in attributes) {
  469. // Link accessor and buffer view
  470. accessor = gltfRuntime.accessors[attributes[semantic]];
  471. buffer = getBufferFromAccessor(gltfRuntime, accessor);
  472. if (semantic === "NORMAL") {
  473. tempVertexData.set(buffer, VertexBuffer.NormalKind);
  474. }
  475. else if (semantic === "POSITION") {
  476. verticesCounts.push(buffer.length);
  477. tempVertexData.set(buffer, VertexBuffer.PositionKind);
  478. }
  479. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  480. var channel = Number(semantic.split("_")[1]);
  481. var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  482. tempVertexData.uvs = [];
  483. for (var j = 0; j < buffer.length; j++) {
  484. tempVertexData.uvs.push(buffer[j]);
  485. }
  486. normalizeUVs(tempVertexData.uvs);
  487. }
  488. else if (semantic === "JOINT") {
  489. tempVertexData.set(buffer, VertexBuffer.MatricesIndicesKind);
  490. }
  491. else if (semantic === "WEIGHT") {
  492. tempVertexData.set(buffer, VertexBuffer.MatricesWeightsKind);
  493. }
  494. else if (semantic === "COLOR") {
  495. tempVertexData.set(buffer, VertexBuffer.ColorKind);
  496. }
  497. }
  498. // Indices
  499. accessor = gltfRuntime.accessors[primitive.indices];
  500. buffer = getBufferFromAccessor(gltfRuntime, accessor);
  501. tempVertexData.indices = [];
  502. for (var j = 0; j < buffer.length; j++) {
  503. tempVertexData.indices.push(buffer[j]);
  504. }
  505. indexCounts.push(buffer.length);
  506. vertexData.merge(tempVertexData);
  507. tempVertexData = undefined;
  508. // Sub material
  509. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  510. multiMat.subMaterials.push(material === null ? gltfRuntime.scene.defaultMaterial : material);
  511. // Update vertices start and index start
  512. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  513. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  514. }
  515. }
  516. // Apply skin
  517. if (skin) {
  518. var vector = Vector3.Zero();
  519. var mat = Matrix.FromArray(skin.bindShapeMatrix);
  520. var positions = vertexData.positions;
  521. for (var i = 0; i < positions.length / 3; i++) {
  522. vector.copyFromFloats(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  523. var result = Vector3.TransformCoordinates(vector, mat);
  524. positions[i * 3] = result.x;
  525. positions[i * 3 + 1] = result.y;
  526. positions[i * 3 + 2] = result.z;
  527. }
  528. }
  529. // Apply geometry
  530. geometry.setAllVerticesData(vertexData);
  531. geometry.applyToMesh(newMesh);
  532. newMesh.flipFaces(true);
  533. // Apply submeshes
  534. newMesh.subMeshes = [];
  535. var index = 0;
  536. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  537. var meshID = meshes[meshIndex];
  538. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  539. if (!mesh) {
  540. continue;
  541. }
  542. for (var i = 0; i < mesh.primitives.length; i++) {
  543. if (mesh.primitives[i].primitive !== 4) {
  544. continue;
  545. }
  546. var subMesh = SubMesh.CreateFromIndices(index, indexStarts[index], indexCounts[index], newMesh, newMesh);
  547. index++;
  548. }
  549. }
  550. // Finish
  551. return newMesh;
  552. };
  553. var configureNode = (newNode: any, position: Vector3, rotation: Quaternion, scaling: Vector3) => {
  554. if (newNode.position) {
  555. newNode.position = position;
  556. }
  557. if (newNode.rotationQuaternion || newNode.rotation) {
  558. newNode.rotationQuaternion = rotation;
  559. }
  560. if (newNode.scaling) {
  561. newNode.scaling = scaling;
  562. }
  563. };
  564. var configureNodeFromMatrix = (newNode: any, node: IGLTFNode) => {
  565. if (node.matrix) {
  566. var position = new Vector3(0, 0, 0);
  567. var rotation = new Quaternion();
  568. var scaling = new Vector3(0, 0, 0);
  569. var mat = Matrix.FromArray(node.matrix);
  570. mat.decompose(scaling, rotation, position);
  571. configureNode(newNode, position, rotation, scaling);
  572. if (newNode instanceof TargetCamera) {
  573. (<TargetCamera>newNode).setTarget(Vector3.Zero());
  574. }
  575. }
  576. else {
  577. configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.RotationAxis(Vector3.FromArray(node.rotation).normalize(), node.rotation[3]), Vector3.FromArray(node.scale));
  578. }
  579. };
  580. var importNode = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, id: string): Node => {
  581. var lastNode: Node = null;
  582. // Meshes
  583. if (node.instanceSkin) {
  584. var instanceSkin = node.instanceSkin;
  585. if (instanceSkin.meshes) {
  586. var skin: IGLTFSkins = gltfRuntime.skins[instanceSkin.skin];
  587. var newMesh = importMesh(gltfRuntime, node, instanceSkin.meshes, id, skin);
  588. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(instanceSkin.skin);
  589. if (newMesh.skeleton === null) {
  590. newMesh.skeleton = importSkeleton(gltfRuntime, gltfRuntime.skins[instanceSkin.skin]);
  591. }
  592. if (newMesh.skeleton !== null) {
  593. newMesh.useBones = true;
  594. newMesh.computeBonesUsingShaders = true;
  595. newMesh.applySkeleton(newMesh.skeleton);
  596. }
  597. lastNode = newMesh;
  598. }
  599. }
  600. else if (node.meshes) {
  601. /**
  602. * Improve meshes property
  603. */
  604. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id);
  605. lastNode = newMesh;
  606. }
  607. // Lights
  608. else if (node.light) {
  609. var light = gltfRuntime.lights[node.light];
  610. if (light) {
  611. if (light.type === "ambient") {
  612. var ambienLight: IGLTFAmbienLight = light[light.type];
  613. var hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  614. hemiLight.name = node.name;
  615. if (ambienLight.color) {
  616. hemiLight.diffuse = Color3.FromArray(ambienLight.color);
  617. }
  618. lastNode = hemiLight;
  619. }
  620. else if (light.type === "directional") {
  621. var directionalLight: IGLTFDirectionalLight = light[light.type];
  622. var dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  623. dirLight.name = node.name;
  624. if (directionalLight.color) {
  625. dirLight.diffuse = Color3.FromArray(directionalLight.color);
  626. }
  627. lastNode = dirLight;
  628. }
  629. else if (light.type === "point") {
  630. var pointLight: IGLTFPointLight = light[light.type];
  631. var ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  632. ptLight.name = node.name;
  633. if (pointLight.color) {
  634. ptLight.diffuse = Color3.FromArray(pointLight.color);
  635. }
  636. lastNode = ptLight;
  637. }
  638. else if (light.type === "spot") {
  639. var spotLight: IGLTFSpotLight = light[light.type];
  640. var spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
  641. spLight.name = node.name;
  642. if (spotLight.color) {
  643. spLight.diffuse = Color3.FromArray(spotLight.color);
  644. }
  645. if (spotLight.fallOfAngle) {
  646. spLight.angle = spotLight.fallOfAngle;
  647. }
  648. if (spotLight.fallOffExponent) {
  649. spLight.exponent = spotLight.fallOffExponent;
  650. }
  651. lastNode = spLight;
  652. }
  653. }
  654. }
  655. // Cameras
  656. else if (node.camera) {
  657. var camera: IGLTFCamera = gltfRuntime.cameras[node.camera];
  658. if (camera) {
  659. if (camera.type === "orthographic") {
  660. var orthographicCamera: IGLTFCameraOrthographic = camera[camera.type];
  661. var orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  662. orthoCamera.name = node.name;
  663. orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  664. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  665. lastNode = orthoCamera;
  666. }
  667. else if (camera.type === "perspective") {
  668. var perspectiveCamera: IGLTFCameraPerspective = camera[camera.type];
  669. var persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  670. persCamera.name = node.name;
  671. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  672. if (!perspectiveCamera.aspectRatio) {
  673. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  674. }
  675. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  676. persCamera.maxZ = perspectiveCamera.zfar;
  677. persCamera.minZ = perspectiveCamera.znear;
  678. }
  679. lastNode = persCamera;
  680. }
  681. }
  682. }
  683. // Empty node
  684. if (lastNode === null && !node.jointName) {
  685. var dummy = new Mesh(node.name, gltfRuntime.scene);
  686. lastNode = dummy;
  687. }
  688. if (lastNode !== null) {
  689. if (node.matrix) {
  690. configureNodeFromMatrix(lastNode, node);
  691. }
  692. else {
  693. configureNode(lastNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
  694. }
  695. lastNode.updateCache(true);
  696. }
  697. return lastNode;
  698. };
  699. /**
  700. * Load buffers
  701. */
  702. var onBuffersLoaded = (gltfRuntime: IGLTFRuntime) => {
  703. // Nodes
  704. var parsedNodes = gltfRuntime.nodes;
  705. var currentScene: IGLTFScene = <IGLTFScene>gltfRuntime.currentScene;
  706. for (var nde in parsedNodes) {
  707. var node: IGLTFNode = parsedNodes[nde];
  708. var newNode = importNode(gltfRuntime, node, nde);
  709. if (newNode !== null) {
  710. newNode.id = nde;
  711. }
  712. }
  713. // Resolve parenting once all nodes were created
  714. for (var nde in parsedNodes) {
  715. var node: IGLTFNode = parsedNodes[nde];
  716. var parent = gltfRuntime.scene.getNodeByID(nde);
  717. if (node.children && parent !== null) {
  718. for (var i = 0; i < node.children.length; i++) {
  719. var child: IGLTFNode = gltfRuntime.nodes[node.children[i]];
  720. var childNode = gltfRuntime.scene.getNodeByID(node.children[i]);
  721. if (childNode !== null) {
  722. childNode.parent = parent;
  723. }
  724. else {
  725. Tools.Warn("Node named " + node.name + " as a children named " + node.children[i] + " but does not exists");
  726. }
  727. }
  728. }
  729. }
  730. // Set animations
  731. loadAnimations(gltfRuntime);
  732. };
  733. var onLoadBuffer = (gltfRuntime: IGLTFRuntime, buf: string) => {
  734. return (data: any) => {
  735. gltfRuntime.loadedBuffers++;
  736. if (!(data instanceof ArrayBuffer)) {
  737. Tools.Error("Buffer named " + buf + " is not an array buffer");
  738. }
  739. else if ((<ArrayBuffer>data).byteLength != gltfRuntime.buffers[buf].byteLength) {
  740. Tools.Error("Buffer named " + buf + " is length " + data.byteLength + ". Expected: " + gltfRuntime.buffers[buf].byteLength); // Improve error message
  741. }
  742. gltfRuntime.arrayBuffers[buf] = data;
  743. if (gltfRuntime.loadedBuffers === gltfRuntime.buffersCount) {
  744. onBuffersLoaded(gltfRuntime);
  745. }
  746. };
  747. };
  748. var onLoadBufferError = (gltfRuntime: IGLTFRuntime, buf: string) => {
  749. return () => {
  750. Tools.Error("Error when loading buffer named " + buf + " located at " + gltfRuntime.buffers[buf].uri);
  751. };
  752. };
  753. var decodeArrayBuffer = (base64: string): ArrayBuffer => {
  754. var decodedString = atob(base64);
  755. var bufferLength = decodedString.length;
  756. var arraybuffer = new Uint8Array(new ArrayBuffer(bufferLength));
  757. for (var i = 0; i < bufferLength; i++) {
  758. arraybuffer[i] = decodedString.charCodeAt(i);
  759. }
  760. return arraybuffer.buffer;
  761. };
  762. var loadBuffers = (gltfRuntime: IGLTFRuntime) => {
  763. for (var buf in gltfRuntime.buffers) {
  764. var buffer: IGLTFBuffer = gltfRuntime.buffers[buf];
  765. if (buffer) {
  766. if (isBase64(buffer.uri)) {
  767. var arrayBuffer = decodeArrayBuffer(buffer.uri.split(",")[1]);
  768. onLoadBuffer(gltfRuntime, buf)(arrayBuffer);
  769. }
  770. else {
  771. Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, onLoadBuffer(gltfRuntime, buf), null, null, true, onLoadBufferError(gltfRuntime, buf));
  772. }
  773. }
  774. else {
  775. Tools.Error("No buffer named : " + buf);
  776. }
  777. }
  778. };
  779. /**
  780. * Load shaders
  781. */
  782. var onBindShaderMaterial = (mesh: Mesh, gltfRuntime: IGLTFRuntime, unTreatedUniforms: Object, shaderMaterial: ShaderMaterial, pass: IGLTFTechniquePass, material: IGLTFMaterial) => {
  783. for (var unif in unTreatedUniforms) {
  784. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  785. var type = uniform.type;
  786. if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
  787. if (uniform.semantic && !uniform.source && !uniform.node) {
  788. setMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  789. }
  790. else if (uniform.semantic && (uniform.source || uniform.node)) {
  791. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  792. if (source === null) {
  793. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  794. }
  795. if (source === null) {
  796. continue;
  797. }
  798. setMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  799. }
  800. }
  801. else {
  802. var value = material.instanceTechnique.values[pass.instanceProgram.uniforms[unif]];
  803. if (!value) {
  804. continue;
  805. }
  806. if (type === EParameterType.SAMPLER_2D) {
  807. var texture: Texture = gltfRuntime.textures[value].babylonTexture;
  808. if (texture === null) {
  809. continue;
  810. }
  811. shaderMaterial.getEffect().setTexture(unif, texture);
  812. }
  813. else {
  814. setUniform(shaderMaterial.getEffect(), unif, value, type);
  815. }
  816. }
  817. }
  818. };
  819. var prepareShaderMaterialUniforms = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, pass: IGLTFTechniquePass, material: IGLTFMaterial, unTreatedUniforms: Object) => {
  820. var materialValues = material.instanceTechnique.values;
  821. var instanceProgramUniforms = pass.instanceProgram.uniforms;
  822. /**
  823. * Prepare values here (not matrices)
  824. */
  825. for (var unif in unTreatedUniforms) {
  826. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  827. var type = uniform.type;
  828. var value = materialValues[instanceProgramUniforms[unif]] || uniform.value;
  829. if (!value) {
  830. continue;
  831. }
  832. // Texture (sampler2D)
  833. if (type === EParameterType.SAMPLER_2D) {
  834. var texture: IGLTFTexture = gltfRuntime.textures[value];
  835. var sampler: IGLTFSampler = gltfRuntime.samplers[texture.sampler];
  836. if (!texture || !texture.source) {
  837. continue;
  838. }
  839. var source: IGLTFImage = gltfRuntime.images[texture.source];
  840. var newTexture: Texture = null;
  841. if (isBase64(source.uri)) {
  842. newTexture = new Texture(source.uri, gltfRuntime.scene, true, undefined, undefined, undefined, undefined, source.uri, true);
  843. }
  844. else {
  845. newTexture = new Texture(gltfRuntime.rootUrl + source.uri, gltfRuntime.scene, true);
  846. }
  847. newTexture.name = value;
  848. texture.babylonTexture = newTexture;
  849. if (uniform.value) {
  850. // Static uniform
  851. shaderMaterial.setTexture(unif, newTexture);
  852. delete unTreatedUniforms[unif];
  853. }
  854. }
  855. // Others
  856. else {
  857. if (uniform.value && setUniform(shaderMaterial, unif, value, type)) {
  858. // Static uniform
  859. delete unTreatedUniforms[unif];
  860. }
  861. }
  862. }
  863. };
  864. var onShaderCompileError = (program: IGLTFProgram, shaderMaterial: ShaderMaterial) => {
  865. return (effect: Effect, error: string) => {
  866. Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  867. shaderMaterial.dispose(true);
  868. };
  869. };
  870. var onShaderCompileSuccess = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, pass: IGLTFTechniquePass, material: IGLTFMaterial, unTreatedUniforms: Object) => {
  871. return (_: Effect) => {
  872. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, pass, material, unTreatedUniforms);
  873. shaderMaterial.onBind = (mat: Material, mesh: Mesh) => {
  874. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, pass, material);
  875. };
  876. };
  877. };
  878. var parseShaderUniforms = (tokenizer: Tokenizer, instanceProgram: IGLTFTechniquePassInstanceProgram, technique: IGLTFTechnique, unTreatedUniforms: Object): string => {
  879. for (var unif in instanceProgram.uniforms) {
  880. var uniform = instanceProgram.uniforms[unif];
  881. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  882. if (tokenizer.currentIdentifier === unif) {
  883. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  884. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  885. if (transformIndex !== -1) {
  886. delete unTreatedUniforms[unif];
  887. return babylonTransforms[transformIndex];
  888. }
  889. }
  890. }
  891. }
  892. return tokenizer.currentIdentifier;
  893. };
  894. var onShadersLoaded = (gltfRuntime: IGLTFRuntime) => {
  895. // Create materials
  896. for (var mat in gltfRuntime.materials) {
  897. var material: IGLTFMaterial = gltfRuntime.materials[mat];
  898. var instanceTechnique: IGLTFMaterialInstanceTechnique = material.instanceTechnique;
  899. var technique: IGLTFTechnique = gltfRuntime.techniques[instanceTechnique.technique];
  900. var pass: IGLTFTechniquePass = technique.passes[technique.pass];
  901. var instanceProgram: IGLTFTechniquePassInstanceProgram = pass.instanceProgram;
  902. var program: IGLTFProgram = gltfRuntime.programs[instanceProgram.program];
  903. var states: IGLTFTechniquePassStates = pass.states;
  904. var vertexShader: string = Effect.ShadersStore[program.vertexShader + "VertexShader"];
  905. var pixelShader: string = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  906. var newVertexShader = "";
  907. var newPixelShader = "";
  908. var vertexTokenizer = new Tokenizer(vertexShader);
  909. var pixelTokenizer = new Tokenizer(pixelShader);
  910. var unTreatedUniforms: Object = {};
  911. var uniforms = [];
  912. var attributes = [];
  913. var samplers = [];
  914. // Fill uniform, sampler2D and attributes
  915. for (var unif in instanceProgram.uniforms) {
  916. var uniform = instanceProgram.uniforms[unif];
  917. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  918. unTreatedUniforms[unif] = uniformParameter;
  919. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  920. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  921. if (transformIndex !== -1) {
  922. uniforms.push(babylonTransforms[transformIndex]);
  923. }
  924. else {
  925. uniforms.push(unif);
  926. }
  927. }
  928. else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
  929. samplers.push(unif);
  930. }
  931. else {
  932. uniforms.push(unif);
  933. }
  934. }
  935. for (var attr in instanceProgram.attributes) {
  936. var attribute = instanceProgram.attributes[attr];
  937. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  938. if (attributeParameter.semantic) {
  939. attributes.push(getAttribute(attributeParameter));
  940. }
  941. }
  942. // Configure vertex shader
  943. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  944. var tokenType = vertexTokenizer.currentToken;
  945. if (tokenType !== ETokenType.IDENTIFIER) {
  946. newVertexShader += vertexTokenizer.currentString;
  947. continue;
  948. }
  949. var foundAttribute = false;
  950. for (var attr in instanceProgram.attributes) {
  951. var attribute = instanceProgram.attributes[attr];
  952. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  953. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  954. newVertexShader += getAttribute(attributeParameter);
  955. foundAttribute = true;
  956. break;
  957. }
  958. }
  959. if (foundAttribute) {
  960. continue;
  961. }
  962. newVertexShader += parseShaderUniforms(vertexTokenizer, instanceProgram, technique, unTreatedUniforms);
  963. }
  964. // Configure pixel shader
  965. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  966. var tokenType = pixelTokenizer.currentToken;
  967. if (tokenType !== ETokenType.IDENTIFIER) {
  968. newPixelShader += pixelTokenizer.currentString;
  969. continue;
  970. }
  971. newPixelShader += parseShaderUniforms(pixelTokenizer, instanceProgram, technique, unTreatedUniforms);
  972. }
  973. // Create shader material
  974. var shaderPath = {
  975. vertex: program.vertexShader,
  976. fragment: program.fragmentShader
  977. };
  978. var options = {
  979. attributes: attributes,
  980. uniforms: uniforms,
  981. samplers: samplers,
  982. needAlphaBlending: states.functions && states.functions.blendEquationSeparate
  983. };
  984. Effect.ShadersStore[program.vertexShader + "VertexShader"] = newVertexShader;
  985. Effect.ShadersStore[program.fragmentShader + "PixelShader"] = newPixelShader;
  986. var shaderMaterial = new ShaderMaterial(material.name, gltfRuntime.scene, shaderPath, options);
  987. shaderMaterial.id = mat;
  988. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial);
  989. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, pass, material, unTreatedUniforms);
  990. }
  991. // Finish
  992. loadBuffers(gltfRuntime);
  993. };
  994. var onLoadShader = (gltfRuntime: IGLTFRuntime, sha: string) => {
  995. return (data: any) => {
  996. gltfRuntime.loadedShaders++;
  997. Effect.ShadersStore[sha + (gltfRuntime.shaders[sha].type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = data;
  998. if (gltfRuntime.loadedShaders === gltfRuntime.shaderscount) {
  999. onShadersLoaded(gltfRuntime);
  1000. }
  1001. };
  1002. };
  1003. var onLoadShaderError = (gltfRuntime: IGLTFRuntime, sha: string) => {
  1004. return () => {
  1005. Tools.Error("Error when loading shader program named " + sha + " located at " + gltfRuntime.shaders[sha].uri);
  1006. };
  1007. };
  1008. var load = (gltfRuntime: IGLTFRuntime) => {
  1009. // Begin with shaders
  1010. for (var sha in gltfRuntime.shaders) {
  1011. var shader: IGLTFShader = gltfRuntime.shaders[sha];
  1012. if (shader) {
  1013. if (isBase64(shader.uri)) {
  1014. var shaderString = atob(shader.uri.split(",")[1]);
  1015. onLoadShader(gltfRuntime, sha)(shaderString);
  1016. }
  1017. else {
  1018. Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onLoadShader(gltfRuntime, sha), null, null, false, onLoadShaderError(gltfRuntime, sha));
  1019. }
  1020. }
  1021. else {
  1022. Tools.Error("No shader file named " + shader.uri);
  1023. }
  1024. }
  1025. };
  1026. /**
  1027. * glTF File Loader Plugin
  1028. */
  1029. export class GLTFFileLoader implements ISceneLoaderPlugin {
  1030. /**
  1031. * Public members
  1032. */
  1033. public extensions = ".gltf";
  1034. /**
  1035. * Private members
  1036. */
  1037. // None
  1038. /**
  1039. * Import meshes
  1040. */
  1041. public importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]): boolean {
  1042. return true;
  1043. }
  1044. /**
  1045. * Load scene
  1046. */
  1047. public load(scene: Scene, data: string, rootUrl: string): boolean {
  1048. var parsedData = JSON.parse(data);
  1049. var gltfRuntime: IGLTFRuntime = {
  1050. accessors: {},
  1051. buffers: {},
  1052. bufferViews: {},
  1053. meshes: {},
  1054. lights: {},
  1055. cameras: {},
  1056. nodes: {},
  1057. images: {},
  1058. textures: {},
  1059. shaders: {},
  1060. programs: {},
  1061. samplers: {},
  1062. techniques: {},
  1063. materials: {},
  1064. animations: {},
  1065. skins: {},
  1066. currentScene: {},
  1067. buffersCount: 0,
  1068. shaderscount: 0,
  1069. scene: scene,
  1070. dummyNodes: [],
  1071. loadedBuffers: 0,
  1072. loadedShaders: 0,
  1073. rootUrl: rootUrl,
  1074. arrayBuffers: []
  1075. }
  1076. // Parse
  1077. if (parsedData.buffers) {
  1078. parseBuffers(parsedData.buffers, gltfRuntime);
  1079. }
  1080. if (parsedData.bufferViews) {
  1081. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1082. }
  1083. if (parsedData.accessors) {
  1084. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1085. }
  1086. if (parsedData.meshes) {
  1087. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1088. }
  1089. if (parsedData.lights) {
  1090. parseObject(parsedData.lights, "lights", gltfRuntime);
  1091. }
  1092. if (parsedData.cameras) {
  1093. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1094. }
  1095. if (parsedData.nodes) {
  1096. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1097. }
  1098. if (parsedData.images) {
  1099. parseObject(parsedData.images, "images", gltfRuntime);
  1100. }
  1101. if (parsedData.textures) {
  1102. parseObject(parsedData.textures, "textures", gltfRuntime);
  1103. }
  1104. if (parsedData.shaders) {
  1105. parseShaders(parsedData.shaders, gltfRuntime);
  1106. }
  1107. if (parsedData.programs) {
  1108. parseObject(parsedData.programs, "programs", gltfRuntime);
  1109. }
  1110. if (parsedData.samplers) {
  1111. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1112. }
  1113. if (parsedData.techniques) {
  1114. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1115. }
  1116. if (parsedData.materials) {
  1117. parseObject(parsedData.materials, "materials", gltfRuntime);
  1118. }
  1119. if (parsedData.animations) {
  1120. parseObject(parsedData.animations, "animations", gltfRuntime);
  1121. }
  1122. if (parsedData.skins) {
  1123. parseObject(parsedData.skins, "skins", gltfRuntime);
  1124. }
  1125. if (parsedData.scene && parsedData.scenes) {
  1126. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1127. }
  1128. // Load shaders and buffers
  1129. load(gltfRuntime);
  1130. // Test on bones
  1131. /*
  1132. for (var i = 0; i < scene.meshes.length; i++) {
  1133. var mesh = scene.meshes[i];
  1134. if (mesh.skeleton) {
  1135. scene.beginAnimation(mesh.skeleton, 0, 1000, true, 1, () => {
  1136. console.log("finished");
  1137. });
  1138. }
  1139. }
  1140. */
  1141. // Finish
  1142. return true;
  1143. }
  1144. };
  1145. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1146. }