babylon.glTFFileLoader.ts 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854
  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. var lastAnimation: Animation = null;
  313. for (var i = 0; i < animation.channels.length; i++) {
  314. // Get parameters and load buffers
  315. var channel = animation.channels[i];
  316. var sampler: IGLTFAnimationSampler = animation.samplers[channel.sampler];
  317. if (!sampler) {
  318. continue;
  319. }
  320. var inputData = animation.parameters[sampler.input];
  321. var outputData = animation.parameters[sampler.output];
  322. var bufferInput = getBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  323. var bufferOutput = getBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  324. var targetID = channel.target.id;
  325. var targetNode: any = gltfRuntime.scene.getNodeByID(targetID);
  326. if (targetNode === null) {
  327. Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  328. continue;
  329. }
  330. var isBone = targetNode instanceof Bone;
  331. // Get target path (position, rotation or scaling)
  332. var targetPath = channel.target.path;
  333. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  334. if (targetPathIndex !== -1) {
  335. targetPath = babylonAnimationPaths[targetPathIndex];
  336. }
  337. // Determine animation type
  338. var animationType = Animation.ANIMATIONTYPE_MATRIX;
  339. if (!isBone) {
  340. if (targetPath === "rotationQuaternion") {
  341. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  342. targetNode.rotationQuaternion = new Quaternion();
  343. }
  344. else {
  345. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  346. }
  347. }
  348. // Create animation and key frames
  349. var babylonAnimation: Animation = null;
  350. var keys = [];
  351. var arrayOffset = 0;
  352. var modifyKey = false;
  353. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  354. babylonAnimation = lastAnimation;
  355. modifyKey = true;
  356. }
  357. if (!modifyKey) {
  358. babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
  359. }
  360. // For each frame
  361. for (var j = 0; j < bufferInput.length; j++) {
  362. var value: any = null;
  363. if (targetPath === "rotationQuaternion") { // VEC4
  364. value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  365. arrayOffset += 4;
  366. }
  367. else { // Position and scaling are VEC3
  368. value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  369. arrayOffset += 3;
  370. }
  371. if (isBone) {
  372. var bone = <Bone>targetNode;
  373. var translation = Vector3.Zero();
  374. var rotationQuaternion = new Quaternion();
  375. var scaling = Vector3.Zero();
  376. // Warning on decompose
  377. var mat = bone.getBaseMatrix();
  378. if (modifyKey) {
  379. mat = lastAnimation.getKeys()[j].value;
  380. }
  381. mat.decompose(scaling, rotationQuaternion, translation);
  382. if (targetPath === "position") {
  383. translation = value;
  384. }
  385. else if (targetPath === "rotationQuaternion") {
  386. rotationQuaternion = value;
  387. // Y is Up
  388. if (GLTFFileLoader.MakeYUP) {
  389. rotationQuaternion = rotationQuaternion.multiply(new Quaternion(-0.707107, 0, 0, 0.707107));
  390. }
  391. }
  392. else {
  393. scaling = value;
  394. }
  395. value = Matrix.Compose(scaling, rotationQuaternion, translation);
  396. }
  397. if (!modifyKey) {
  398. keys.push({
  399. frame: bufferInput[j],
  400. value: value
  401. });
  402. }
  403. else {
  404. lastAnimation.getKeys()[j].value = value;
  405. }
  406. }
  407. // Finish
  408. if (!modifyKey) {
  409. babylonAnimation.setKeys(keys);
  410. targetNode.animations.push(babylonAnimation);
  411. }
  412. lastAnimation = babylonAnimation;
  413. gltfRuntime.scene.stopAnimation(targetNode);
  414. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  415. }
  416. }
  417. };
  418. /**
  419. * Returns the bones transformation matrix
  420. */
  421. var configureBoneTransformation = (node: IGLTFNode): Matrix => {
  422. var mat: Matrix = null;
  423. if (node.translation && node.rotation && node.scale) {
  424. var scale = Vector3.FromArray(node.scale);
  425. var rotation = Quaternion.FromArray(node.rotation);
  426. var position = Vector3.FromArray(node.translation);
  427. // Y is Up
  428. if (GLTFFileLoader.MakeYUP) {
  429. rotation = rotation.multiply(new Quaternion(-0.707107, 0, 0, 0.707107));
  430. }
  431. mat = Matrix.Compose(scale, rotation, position);
  432. }
  433. else {
  434. mat = Matrix.FromArray(node.matrix);
  435. }
  436. return mat;
  437. };
  438. /**
  439. * Returns the parent bone
  440. */
  441. var getParentBone = (gltfRuntime: IGLTFRuntime, skins: IGLTFSkins, jointName: string, newSkeleton: Skeleton): Bone => {
  442. // Try to find
  443. for (var i = 0; i < newSkeleton.bones.length; i++) {
  444. if (newSkeleton.bones[i].id === jointName) {
  445. return newSkeleton.bones[i];
  446. }
  447. }
  448. // Not found, search in gltf nodes
  449. var nodes = gltfRuntime.nodes;
  450. for (var nde in nodes) {
  451. var node: IGLTFNode = nodes[nde];
  452. if (!node.jointName) {
  453. continue;
  454. }
  455. var children = node.children;
  456. for (var i = 0; i < children.length; i++) {
  457. var child: IGLTFNode = gltfRuntime.nodes[children[i]];
  458. if (!child.jointName) {
  459. continue;
  460. }
  461. if (child.jointName === jointName) {
  462. var mat = configureBoneTransformation(node);
  463. var bone = new Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  464. bone.id = nde;
  465. return bone;
  466. }
  467. }
  468. }
  469. return null;
  470. }
  471. /**
  472. * Returns the appropriate root node
  473. */
  474. var getNodeToRoot = (nodesToRoot: INodeToRoot[], id: string): Bone => {
  475. for (var i = 0; i < nodesToRoot.length; i++) {
  476. var nodeToRoot = nodesToRoot[i];
  477. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  478. var child = nodeToRoot.node.children[j];
  479. if (child === id) {
  480. return nodeToRoot.bone;
  481. }
  482. }
  483. }
  484. return null;
  485. };
  486. /**
  487. * Returns the node with the joint name
  488. */
  489. var getJointNode = (gltfRuntime: IGLTFRuntime, jointName: string): IJointNode => {
  490. var nodes = gltfRuntime.nodes;
  491. var node: IGLTFNode = nodes[jointName];
  492. if (node) {
  493. return {
  494. node: node,
  495. id: jointName
  496. };
  497. }
  498. for (var nde in nodes) {
  499. node = nodes[nde];
  500. if (node.jointName === jointName) {
  501. return {
  502. node: node,
  503. id: nde
  504. };
  505. }
  506. }
  507. return null;
  508. }
  509. /**
  510. * Checks if a nodes is in joints
  511. */
  512. var nodeIsInJoints = (skins: IGLTFSkins, id: string): boolean => {
  513. for (var i = 0; i < skins.jointNames.length; i++) {
  514. if (skins.jointNames[i] === id) {
  515. return true;
  516. }
  517. }
  518. return false;
  519. }
  520. /**
  521. * Fills the nodes to root for bones and builds hierarchy
  522. */
  523. var getNodesToRoot = (gltfRuntime: IGLTFRuntime, newSkeleton: Skeleton, skins: IGLTFSkins, nodesToRoot: INodeToRoot[]) => {
  524. // Creates nodes for root
  525. for (var nde in gltfRuntime.nodes) {
  526. var node: IGLTFNode = gltfRuntime.nodes[nde];
  527. var id = nde;
  528. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  529. continue;
  530. }
  531. // Create node to root bone
  532. var mat = configureBoneTransformation(node);
  533. var bone = new Bone(node.name, newSkeleton, null, mat);
  534. bone.id = id;
  535. nodesToRoot.push({ bone: bone, node: node, id: id });
  536. }
  537. // Parenting
  538. for (var i = 0; i < nodesToRoot.length; i++) {
  539. var nodeToRoot = nodesToRoot[i];
  540. var children = nodeToRoot.node.children;
  541. for (var j = 0; j < children.length; j++) {
  542. var child: INodeToRoot = null;
  543. for (var k = 0; k < nodesToRoot.length; k++) {
  544. if (nodesToRoot[k].id === children[j]) {
  545. child = nodesToRoot[k];
  546. break;
  547. }
  548. }
  549. if (child) {
  550. (<any>child.bone)._parent = nodeToRoot.bone;
  551. nodeToRoot.bone.children.push(child.bone);
  552. }
  553. }
  554. }
  555. };
  556. var printMat = (m: Float32Array) => {
  557. console.log(
  558. m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  559. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  560. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  561. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n"
  562. );
  563. }
  564. /**
  565. * Imports a skeleton
  566. */
  567. var importSkeleton = (gltfRuntime: IGLTFRuntime, skins: IGLTFSkins, mesh: Mesh, newSkeleton: Skeleton): Skeleton => {
  568. if (!newSkeleton) {
  569. newSkeleton = new Skeleton(skins.name, "", gltfRuntime.scene);
  570. }
  571. if (!skins.babylonSkeleton) {
  572. return newSkeleton;
  573. }
  574. // Matrices
  575. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  576. var buffer = getBufferFromAccessor(gltfRuntime, accessor);
  577. var bindShapeMatrix = Matrix.FromArray(skins.bindShapeMatrix);
  578. // Find the root bones
  579. var nodesToRoot: INodeToRoot[] = [];
  580. var nodesToRootToAdd: Bone[] = [];
  581. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  582. newSkeleton.bones = [];
  583. if (nodesToRoot.length === 0) {
  584. newSkeleton.needInitialSkinMatrix = true;
  585. }
  586. // Joints
  587. for (var i = 0; i < skins.jointNames.length; i++) {
  588. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  589. var node = jointNode.node;
  590. if (!node) {
  591. Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  592. continue;
  593. }
  594. var id = jointNode.id;
  595. // Optimize, if the bone already exists...
  596. var existingBone = gltfRuntime.scene.getBoneByID(id);
  597. if (existingBone) {
  598. newSkeleton.bones.push(existingBone);
  599. continue;
  600. }
  601. // Check if node already exists
  602. var foundBone = false;
  603. for (var j = 0; j < newSkeleton.bones.length; j++) {
  604. if (newSkeleton.bones[j].id === id) {
  605. foundBone = true;
  606. break;
  607. }
  608. }
  609. if (foundBone) {
  610. continue;
  611. }
  612. // Search for parent bone
  613. var parentBone: Bone = null;
  614. for (var j = 0; j < i; j++) {
  615. var joint: IGLTFNode = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  616. if (!joint) {
  617. Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  618. continue;
  619. }
  620. var children = joint.children;
  621. foundBone = false;
  622. for (var k = 0; k < children.length; k++) {
  623. if (children[k] === id) {
  624. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  625. foundBone = true;
  626. break;
  627. }
  628. }
  629. if (foundBone) {
  630. break;
  631. }
  632. }
  633. // Create bone
  634. var mat = configureBoneTransformation(node);
  635. if (!parentBone && nodesToRoot.length > 0) {
  636. parentBone = getNodeToRoot(nodesToRoot, id);
  637. if (parentBone) {
  638. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  639. nodesToRootToAdd.push(parentBone);
  640. }
  641. }
  642. }
  643. if (!parentBone && nodesToRoot.length === 0) {
  644. var inverseBindMatrix = Matrix.FromArray(buffer, i * 16);
  645. var invertMesh = Matrix.Invert(mesh.getWorldMatrix());
  646. mat = mat.multiply(mesh.getWorldMatrix());
  647. }
  648. var bone = new Bone(node.name, newSkeleton, parentBone, mat);
  649. bone.id = id;
  650. }
  651. // Polish
  652. var bones = newSkeleton.bones;
  653. newSkeleton.bones = [];
  654. for (var i = 0; i < skins.jointNames.length; i++) {
  655. var jointNode: IJointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  656. if (!jointNode) {
  657. continue;
  658. }
  659. for (var j = 0; j < bones.length; j++) {
  660. if (bones[j].id === jointNode.id) {
  661. newSkeleton.bones.push(bones[j]);
  662. break;
  663. }
  664. }
  665. }
  666. // Finish
  667. newSkeleton.prepare();
  668. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  669. newSkeleton.bones.push(nodesToRootToAdd[i]);
  670. }
  671. return newSkeleton;
  672. };
  673. /**
  674. * Imports a mesh and its geometries
  675. */
  676. var importMesh = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, meshes: string[], id: string, newMesh: Mesh): Mesh => {
  677. if (!newMesh) {
  678. newMesh = new Mesh(node.name, gltfRuntime.scene);
  679. newMesh.id = id;
  680. }
  681. if (!node.babylonNode) {
  682. return newMesh;
  683. }
  684. var multiMat = new MultiMaterial("multimat" + id, gltfRuntime.scene);
  685. newMesh.material = multiMat;
  686. var vertexData = new VertexData();
  687. var geometry = new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  688. var verticesStarts = [];
  689. var verticesCounts = [];
  690. var indexStarts = [];
  691. var indexCounts = [];
  692. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  693. var meshID = meshes[meshIndex];
  694. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  695. if (!mesh) {
  696. continue;
  697. }
  698. // Positions, normals and UVs
  699. for (var i = 0; i < mesh.primitives.length; i++) {
  700. // Temporary vertex data
  701. var tempVertexData = new VertexData();
  702. var primitive = mesh.primitives[i];
  703. if (primitive.mode !== 4) {
  704. //continue;
  705. }
  706. var attributes = primitive.attributes;
  707. var accessor: IGLTFAccessor = null;
  708. var buffer: any = null;
  709. // Set positions, normal and uvs
  710. for (var semantic in attributes) {
  711. // Link accessor and buffer view
  712. accessor = gltfRuntime.accessors[attributes[semantic]];
  713. buffer = getBufferFromAccessor(gltfRuntime, accessor);
  714. if (semantic === "NORMAL") {
  715. tempVertexData.normals = [];
  716. for (var j = 0; j < buffer.length; j++) {
  717. (<number[]>tempVertexData.normals).push(buffer[j]);
  718. }
  719. }
  720. else if (semantic === "POSITION") {
  721. tempVertexData.positions = [];
  722. var count = 3;
  723. if (GLTFFileLoader.HomogeneousCoordinates) {
  724. count = 4;
  725. }
  726. for (var j = 0; j < buffer.length; j += count) {
  727. (<number[]>tempVertexData.positions).push(buffer[j]);
  728. (<number[]>tempVertexData.positions).push(buffer[j+1]);
  729. (<number[]>tempVertexData.positions).push(buffer[j+2]);
  730. }
  731. verticesCounts.push(tempVertexData.positions.length);
  732. }
  733. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  734. var channel = Number(semantic.split("_")[1]);
  735. var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  736. var uvs = [];
  737. for (var j = 0; j < buffer.length; j++) {
  738. uvs.push(buffer[j]);
  739. }
  740. normalizeUVs(uvs);
  741. tempVertexData.set(uvs, uvKind);
  742. }
  743. else if (semantic === "JOINT") {
  744. tempVertexData.matricesIndices = [];
  745. for (var j = 0; j < buffer.length; j++) {
  746. (<number[]>tempVertexData.matricesIndices).push(buffer[j]);
  747. }
  748. }
  749. else if (semantic === "WEIGHT") {
  750. tempVertexData.matricesWeights = [];
  751. for (var j = 0; j < buffer.length; j++) {
  752. (<number[]>tempVertexData.matricesWeights).push(buffer[j]);
  753. }
  754. }
  755. else if (semantic === "COLOR") {
  756. tempVertexData.colors = [];
  757. for (var j = 0; j < buffer.length; j++) {
  758. (<number[]>tempVertexData.colors).push(buffer[j]);
  759. }
  760. }
  761. }
  762. // Indices
  763. accessor = gltfRuntime.accessors[primitive.indices];
  764. buffer = getBufferFromAccessor(gltfRuntime, accessor);
  765. tempVertexData.indices = [];
  766. for (var j = 0; j < buffer.length; j++) {
  767. (<number[]>tempVertexData.indices).push(buffer[j]);
  768. }
  769. indexCounts.push(buffer.length);
  770. vertexData.merge(tempVertexData);
  771. tempVertexData = undefined;
  772. // Sub material
  773. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  774. multiMat.subMaterials.push(material === null ? gltfRuntime.scene.defaultMaterial : material);
  775. // Update vertices start and index start
  776. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  777. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  778. }
  779. }
  780. // Apply geometry
  781. geometry.setAllVerticesData(vertexData, false);
  782. newMesh.flipFaces(true);
  783. newMesh.computeWorldMatrix(true);
  784. // Apply submeshes
  785. newMesh.subMeshes = [];
  786. var index = 0;
  787. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  788. var meshID = meshes[meshIndex];
  789. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  790. if (!mesh) {
  791. continue;
  792. }
  793. for (var i = 0; i < mesh.primitives.length; i++) {
  794. if (mesh.primitives[i].mode !== 4) {
  795. //continue;
  796. }
  797. var subMesh = new SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  798. index++;
  799. }
  800. }
  801. // Finish
  802. return newMesh;
  803. };
  804. /**
  805. * Configure node transformation from position, rotation and scaling
  806. */
  807. var configureNode = (newNode: any, position: Vector3, rotation: Quaternion, scaling: Vector3) => {
  808. if (newNode.position) {
  809. newNode.position = position;
  810. }
  811. if (newNode.rotationQuaternion || newNode.rotation) {
  812. newNode.rotationQuaternion = rotation;
  813. }
  814. if (newNode.scaling) {
  815. newNode.scaling = scaling;
  816. }
  817. };
  818. /**
  819. * Configures node from transformation matrix
  820. */
  821. var configureNodeFromMatrix = (newNode: any, node: IGLTFNode) => {
  822. if (node.matrix) {
  823. var position = new Vector3(0, 0, 0);
  824. var rotation = new Quaternion();
  825. var scaling = new Vector3(0, 0, 0);
  826. var mat = Matrix.FromArray(node.matrix);
  827. mat.decompose(scaling, rotation, position);
  828. // Y is Up
  829. if (GLTFFileLoader.MakeYUP) {
  830. rotation = rotation.multiply(new Quaternion(-0.707107, 0, 0, 0.707107));
  831. }
  832. configureNode(newNode, position, rotation, scaling);
  833. if (newNode instanceof TargetCamera) {
  834. (<TargetCamera>newNode).setTarget(Vector3.Zero());
  835. }
  836. }
  837. else {
  838. configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
  839. }
  840. };
  841. /**
  842. * Imports a node
  843. */
  844. var importNode = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, id: string): Node => {
  845. var lastNode: Node = null;
  846. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  847. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  848. return null;
  849. }
  850. }
  851. // Meshes
  852. if (node.skin) {
  853. if (node.meshes) {
  854. var skin: IGLTFSkins = gltfRuntime.skins[node.skin];
  855. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, <Mesh>node.babylonNode);
  856. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  857. if (newMesh.skeleton === null) {
  858. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton);
  859. if (!skin.babylonSkeleton) {
  860. skin.babylonSkeleton = newMesh.skeleton;
  861. }
  862. }
  863. if (newMesh.skeleton !== null) {
  864. newMesh.useBones = true;
  865. }
  866. lastNode = newMesh;
  867. }
  868. }
  869. else if (node.meshes) {
  870. /**
  871. * Improve meshes property
  872. */
  873. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, <Mesh>node.babylonNode);
  874. lastNode = newMesh;
  875. }
  876. // Lights
  877. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  878. var light = gltfRuntime.lights[node.light];
  879. if (light) {
  880. if (light.type === "ambient") {
  881. var ambienLight: IGLTFAmbienLight = light[light.type];
  882. var hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  883. hemiLight.name = node.name;
  884. if (ambienLight.color) {
  885. hemiLight.diffuse = Color3.FromArray(ambienLight.color);
  886. }
  887. lastNode = hemiLight;
  888. }
  889. else if (light.type === "directional") {
  890. var directionalLight: IGLTFDirectionalLight = light[light.type];
  891. var dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  892. dirLight.name = node.name;
  893. if (directionalLight.color) {
  894. dirLight.diffuse = Color3.FromArray(directionalLight.color);
  895. }
  896. lastNode = dirLight;
  897. }
  898. else if (light.type === "point") {
  899. var pointLight: IGLTFPointLight = light[light.type];
  900. var ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  901. ptLight.name = node.name;
  902. if (pointLight.color) {
  903. ptLight.diffuse = Color3.FromArray(pointLight.color);
  904. }
  905. lastNode = ptLight;
  906. }
  907. else if (light.type === "spot") {
  908. var spotLight: IGLTFSpotLight = light[light.type];
  909. var spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
  910. spLight.name = node.name;
  911. if (spotLight.color) {
  912. spLight.diffuse = Color3.FromArray(spotLight.color);
  913. }
  914. if (spotLight.fallOfAngle) {
  915. spLight.angle = spotLight.fallOfAngle;
  916. }
  917. if (spotLight.fallOffExponent) {
  918. spLight.exponent = spotLight.fallOffExponent;
  919. }
  920. lastNode = spLight;
  921. }
  922. }
  923. }
  924. // Cameras
  925. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  926. var camera: IGLTFCamera = gltfRuntime.cameras[node.camera];
  927. if (camera) {
  928. if (camera.type === "orthographic") {
  929. var orthographicCamera: IGLTFCameraOrthographic = camera[camera.type];
  930. var orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  931. orthoCamera.name = node.name;
  932. orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  933. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  934. lastNode = orthoCamera;
  935. }
  936. else if (camera.type === "perspective") {
  937. var perspectiveCamera: IGLTFCameraPerspective = camera[camera.type];
  938. var persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  939. persCamera.name = node.name;
  940. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  941. if (!perspectiveCamera.aspectRatio) {
  942. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  943. }
  944. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  945. persCamera.maxZ = perspectiveCamera.zfar;
  946. persCamera.minZ = perspectiveCamera.znear;
  947. }
  948. lastNode = persCamera;
  949. }
  950. }
  951. }
  952. // Empty node
  953. if (!node.jointName) {
  954. if (node.babylonNode) {
  955. return node.babylonNode;
  956. }
  957. else if (lastNode === null) {
  958. var dummy = new Mesh(node.name, gltfRuntime.scene);
  959. node.babylonNode = dummy;
  960. lastNode = dummy;
  961. }
  962. }
  963. if (lastNode !== null) {
  964. if (node.matrix) {
  965. configureNodeFromMatrix(lastNode, node);
  966. }
  967. else {
  968. configureNode(lastNode, Vector3.FromArray(node.translation), Quaternion.RotationAxis(Vector3.FromArray(node.rotation).normalize(), node.rotation[3]), Vector3.FromArray(node.scale));
  969. }
  970. lastNode.updateCache(true);
  971. node.babylonNode = lastNode;
  972. }
  973. return lastNode;
  974. };
  975. /**
  976. * Traverses nodes and creates them
  977. */
  978. var traverseNodes = (gltfRuntime: IGLTFRuntime, id: string, parent: Node, meshIncluded?: boolean) => {
  979. var node: IGLTFNode = gltfRuntime.nodes[id];
  980. var newNode: Node = null;
  981. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  982. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  983. meshIncluded = true;
  984. }
  985. else {
  986. meshIncluded = false;
  987. }
  988. }
  989. else {
  990. meshIncluded = true;
  991. }
  992. if (!node.jointName && meshIncluded) {
  993. newNode = importNode(gltfRuntime, node, id);
  994. if (newNode !== null) {
  995. newNode.id = id;
  996. newNode.parent = parent;
  997. }
  998. }
  999. for (var i = 0; i < node.children.length; i++) {
  1000. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1001. }
  1002. };
  1003. /**
  1004. * Buffers loaded, create nodes
  1005. */
  1006. var onBuffersLoaded = (gltfRuntime: IGLTFRuntime) => {
  1007. // Nodes
  1008. var currentScene: IGLTFScene = <IGLTFScene>gltfRuntime.currentScene;
  1009. for (var i = 0; i < currentScene.nodes.length; i++) {
  1010. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1011. }
  1012. // Set animations
  1013. loadAnimations(gltfRuntime);
  1014. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1015. var skeleton = gltfRuntime.scene.skeletons[i];
  1016. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1017. }
  1018. };
  1019. /**
  1020. * On a buffer is loaded
  1021. */
  1022. var onLoadBuffer = (gltfRuntime: IGLTFRuntime, buf: string) => {
  1023. return (data: any) => {
  1024. gltfRuntime.loadedBuffers++;
  1025. if (!(data instanceof ArrayBuffer)) {
  1026. Tools.Error("Buffer named " + buf + " is not an array buffer");
  1027. }
  1028. else if ((<ArrayBuffer>data).byteLength != gltfRuntime.buffers[buf].byteLength) {
  1029. Tools.Error("Buffer named " + buf + " is length " + data.byteLength + ". Expected: " + gltfRuntime.buffers[buf].byteLength); // Improve error message
  1030. }
  1031. gltfRuntime.arrayBuffers[buf] = data;
  1032. if (gltfRuntime.loadedBuffers === gltfRuntime.buffersCount) {
  1033. onBuffersLoaded(gltfRuntime);
  1034. }
  1035. };
  1036. };
  1037. /**
  1038. * Error when loaded buffer
  1039. */
  1040. var onLoadBufferError = (gltfRuntime: IGLTFRuntime, buf: string) => {
  1041. return () => {
  1042. Tools.Error("Error when loading buffer named " + buf + " located at " + gltfRuntime.buffers[buf].uri);
  1043. };
  1044. };
  1045. /**
  1046. * Decode array buffer from base64
  1047. */
  1048. var decodeArrayBuffer = (base64: string): ArrayBuffer => {
  1049. var decodedString = atob(base64);
  1050. var bufferLength = decodedString.length;
  1051. var arraybuffer = new Uint8Array(new ArrayBuffer(bufferLength));
  1052. for (var i = 0; i < bufferLength; i++) {
  1053. arraybuffer[i] = decodedString.charCodeAt(i);
  1054. }
  1055. return arraybuffer.buffer;
  1056. };
  1057. /**
  1058. * Loads buffers (geometries)
  1059. */
  1060. var loadBuffers = (gltfRuntime: IGLTFRuntime) => {
  1061. for (var buf in gltfRuntime.buffers) {
  1062. var buffer: IGLTFBuffer = gltfRuntime.buffers[buf];
  1063. if (buffer) {
  1064. if (isBase64(buffer.uri)) {
  1065. var arrayBuffer = decodeArrayBuffer(buffer.uri.split(",")[1]);
  1066. onLoadBuffer(gltfRuntime, buf)(arrayBuffer);
  1067. }
  1068. else {
  1069. Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, onLoadBuffer(gltfRuntime, buf), null, null, true, onLoadBufferError(gltfRuntime, buf));
  1070. }
  1071. }
  1072. else {
  1073. Tools.Error("No buffer named : " + buf);
  1074. }
  1075. }
  1076. };
  1077. /**
  1078. * onBind shaderrs callback to set uniforms and matrices
  1079. */
  1080. var onBindShaderMaterial = (mesh: Mesh, gltfRuntime: IGLTFRuntime, unTreatedUniforms: Object, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial) => {
  1081. for (var unif in unTreatedUniforms) {
  1082. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  1083. var type = uniform.type;
  1084. if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
  1085. if (uniform.semantic && !uniform.source && !uniform.node) {
  1086. setMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1087. }
  1088. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1089. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  1090. if (source === null) {
  1091. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  1092. }
  1093. if (source === null) {
  1094. continue;
  1095. }
  1096. setMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1097. }
  1098. }
  1099. else {
  1100. var value = material.values[technique.uniforms[unif]];
  1101. if (!value) {
  1102. continue;
  1103. }
  1104. if (type === EParameterType.SAMPLER_2D) {
  1105. var texture: Texture = gltfRuntime.textures[value].babylonTexture;
  1106. if (texture === null) {
  1107. continue;
  1108. }
  1109. shaderMaterial.getEffect().setTexture(unif, texture);
  1110. }
  1111. else {
  1112. setUniform(shaderMaterial.getEffect(), unif, value, type);
  1113. }
  1114. }
  1115. }
  1116. };
  1117. /**
  1118. * Prepare uniforms to send the only one time
  1119. * Loads the appropriate textures
  1120. */
  1121. var prepareShaderMaterialUniforms = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, unTreatedUniforms: Object) => {
  1122. var materialValues = material.values;
  1123. var techniqueUniforms = technique.uniforms;
  1124. /**
  1125. * Prepare values here (not matrices)
  1126. */
  1127. for (var unif in unTreatedUniforms) {
  1128. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  1129. var type = uniform.type;
  1130. var value = materialValues[techniqueUniforms[unif]] || uniform.value;
  1131. if (!value) {
  1132. continue;
  1133. }
  1134. // Texture (sampler2D)
  1135. if (type === EParameterType.SAMPLER_2D) {
  1136. var texture: IGLTFTexture = gltfRuntime.textures[<string>value];
  1137. var sampler: IGLTFSampler = gltfRuntime.samplers[texture.sampler];
  1138. if (!texture || !texture.source) {
  1139. continue;
  1140. }
  1141. var source: IGLTFImage = gltfRuntime.images[texture.source];
  1142. var newTexture: Texture = null;
  1143. var createMipMaps = (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1144. (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1145. (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1146. (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1147. var samplingMode = Texture.BILINEAR_SAMPLINGMODE;
  1148. if (isBase64(source.uri)) {
  1149. newTexture = new Texture(source.uri, gltfRuntime.scene, !createMipMaps, true, samplingMode, null, null, source.uri, true);
  1150. }
  1151. else {
  1152. newTexture = new Texture(gltfRuntime.rootUrl + source.uri, gltfRuntime.scene, !createMipMaps, true, samplingMode);
  1153. }
  1154. newTexture.wrapU = getWrapMode(sampler.wrapS);
  1155. newTexture.wrapV = getWrapMode(sampler.wrapT);
  1156. newTexture.name = <string>value;
  1157. texture.babylonTexture = newTexture;
  1158. if (uniform.value) {
  1159. // Static uniform
  1160. shaderMaterial.setTexture(unif, newTexture);
  1161. delete unTreatedUniforms[unif];
  1162. }
  1163. }
  1164. // Others
  1165. else {
  1166. if (uniform.value && setUniform(shaderMaterial, unif, value, type)) {
  1167. // Static uniform
  1168. delete unTreatedUniforms[unif];
  1169. }
  1170. }
  1171. }
  1172. };
  1173. /**
  1174. * Shader compilation failed
  1175. */
  1176. var onShaderCompileError = (program: IGLTFProgram, shaderMaterial: ShaderMaterial) => {
  1177. return (effect: Effect, error: string) => {
  1178. Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1179. shaderMaterial.dispose(true);
  1180. };
  1181. };
  1182. /**
  1183. * Shader compilation success
  1184. */
  1185. var onShaderCompileSuccess = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, unTreatedUniforms: Object) => {
  1186. return (_: Effect) => {
  1187. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1188. shaderMaterial.onBind = (mat: Material, mesh: Mesh) => {
  1189. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material);
  1190. };
  1191. };
  1192. };
  1193. /**
  1194. * Returns the appropriate uniform if already handled by babylon
  1195. */
  1196. var parseShaderUniforms = (tokenizer: Tokenizer, technique: IGLTFTechnique, unTreatedUniforms: Object): string => {
  1197. for (var unif in technique.uniforms) {
  1198. var uniform = technique.uniforms[unif];
  1199. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  1200. if (tokenizer.currentIdentifier === unif) {
  1201. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1202. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1203. if (transformIndex !== -1) {
  1204. delete unTreatedUniforms[unif];
  1205. return babylonTransforms[transformIndex];
  1206. }
  1207. }
  1208. }
  1209. }
  1210. return tokenizer.currentIdentifier;
  1211. };
  1212. /**
  1213. * All shaders loaded. Create materials one by one
  1214. */
  1215. var onShadersLoaded = (gltfRuntime: IGLTFRuntime) => {
  1216. // Create materials
  1217. for (var mat in gltfRuntime.materials) {
  1218. var material: IGLTFMaterial = gltfRuntime.materials[mat];
  1219. var technique: IGLTFTechnique = gltfRuntime.techniques[material.technique];
  1220. var program: IGLTFProgram = gltfRuntime.programs[technique.program];
  1221. var states: IGLTFTechniqueStates = technique.states;
  1222. var vertexShader: string = Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1223. var pixelShader: string = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1224. var newVertexShader = "";
  1225. var newPixelShader = "";
  1226. var vertexTokenizer = new Tokenizer(vertexShader);
  1227. var pixelTokenizer = new Tokenizer(pixelShader);
  1228. var unTreatedUniforms: Object = {};
  1229. var uniforms = [];
  1230. var attributes = [];
  1231. var samplers = [];
  1232. // Fill uniform, sampler2D and attributes
  1233. for (var unif in technique.uniforms) {
  1234. var uniform = technique.uniforms[unif];
  1235. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  1236. unTreatedUniforms[unif] = uniformParameter;
  1237. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1238. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1239. if (transformIndex !== -1) {
  1240. uniforms.push(babylonTransforms[transformIndex]);
  1241. delete unTreatedUniforms[unif];
  1242. }
  1243. else {
  1244. uniforms.push(unif);
  1245. }
  1246. }
  1247. else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
  1248. samplers.push(unif);
  1249. }
  1250. else {
  1251. uniforms.push(unif);
  1252. }
  1253. }
  1254. for (var attr in technique.attributes) {
  1255. var attribute = technique.attributes[attr];
  1256. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  1257. if (attributeParameter.semantic) {
  1258. attributes.push(getAttribute(attributeParameter));
  1259. }
  1260. }
  1261. // Configure vertex shader
  1262. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1263. var tokenType = vertexTokenizer.currentToken;
  1264. if (tokenType !== ETokenType.IDENTIFIER) {
  1265. newVertexShader += vertexTokenizer.currentString;
  1266. continue;
  1267. }
  1268. var foundAttribute = false;
  1269. for (var attr in technique.attributes) {
  1270. var attribute = technique.attributes[attr];
  1271. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  1272. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1273. newVertexShader += getAttribute(attributeParameter);
  1274. foundAttribute = true;
  1275. break;
  1276. }
  1277. }
  1278. if (foundAttribute) {
  1279. continue;
  1280. }
  1281. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1282. }
  1283. // Configure pixel shader
  1284. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1285. var tokenType = pixelTokenizer.currentToken;
  1286. if (tokenType !== ETokenType.IDENTIFIER) {
  1287. newPixelShader += pixelTokenizer.currentString;
  1288. continue;
  1289. }
  1290. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1291. }
  1292. // Create shader material
  1293. var shaderPath = {
  1294. vertex: program.vertexShader + mat,
  1295. fragment: program.fragmentShader + mat
  1296. };
  1297. var options = {
  1298. attributes: attributes,
  1299. uniforms: uniforms,
  1300. samplers: samplers,
  1301. needAlphaBlending: states.functions && states.functions.blendEquationSeparate
  1302. };
  1303. Effect.ShadersStore[program.vertexShader + mat + "VertexShader"] = newVertexShader;
  1304. Effect.ShadersStore[program.fragmentShader + mat + "PixelShader"] = newPixelShader;
  1305. var shaderMaterial = new ShaderMaterial(material.name, gltfRuntime.scene, shaderPath, options);
  1306. shaderMaterial.id = mat;
  1307. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial);
  1308. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1309. if (states.functions) {
  1310. var functions = states.functions;
  1311. if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {
  1312. shaderMaterial.backFaceCulling = false;
  1313. }
  1314. var blendFunc = functions.blendFuncSeparate;
  1315. if (blendFunc) {
  1316. if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1317. shaderMaterial.alphaMode = Engine.ALPHA_COMBINE;
  1318. }
  1319. else if (blendFunc[0] === EBlendingFunction.ONE && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
  1320. shaderMaterial.alphaMode = Engine.ALPHA_ONEONE;
  1321. }
  1322. else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
  1323. shaderMaterial.alphaMode = Engine.ALPHA_ADD;
  1324. }
  1325. else if (blendFunc[0] === EBlendingFunction.ZERO && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1326. shaderMaterial.alphaMode = Engine.ALPHA_SUBTRACT;
  1327. }
  1328. else if (blendFunc[0] === EBlendingFunction.DST_COLOR && blendFunc[1] === EBlendingFunction.ZERO && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1329. shaderMaterial.alphaMode = Engine.ALPHA_MULTIPLY;
  1330. }
  1331. else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1332. shaderMaterial.alphaMode = Engine.ALPHA_MAXIMIZED;
  1333. }
  1334. }
  1335. }
  1336. }
  1337. // Finish
  1338. loadBuffers(gltfRuntime);
  1339. };
  1340. /**
  1341. * Shader loaded
  1342. */
  1343. var onLoadShader = (gltfRuntime: IGLTFRuntime, sha: string) => {
  1344. return (data: any) => {
  1345. gltfRuntime.loadedShaders++;
  1346. Effect.ShadersStore[sha + (gltfRuntime.shaders[sha].type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = data;
  1347. if (gltfRuntime.loadedShaders === gltfRuntime.shaderscount) {
  1348. onShadersLoaded(gltfRuntime);
  1349. }
  1350. };
  1351. };
  1352. /**
  1353. * Error callback when loading a shader
  1354. */
  1355. var onLoadShaderError = (gltfRuntime: IGLTFRuntime, sha: string) => {
  1356. return () => {
  1357. Tools.Error("Error when loading shader program named " + sha + " located at " + gltfRuntime.shaders[sha].uri);
  1358. };
  1359. };
  1360. /**
  1361. * Load shaders
  1362. */
  1363. var load = (gltfRuntime: IGLTFRuntime) => {
  1364. // Begin with shaders
  1365. for (var sha in gltfRuntime.shaders) {
  1366. var shader: IGLTFShader = gltfRuntime.shaders[sha];
  1367. if (shader) {
  1368. if (isBase64(shader.uri)) {
  1369. var shaderString = atob(shader.uri.split(",")[1]);
  1370. onLoadShader(gltfRuntime, sha)(shaderString);
  1371. }
  1372. else {
  1373. Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onLoadShader(gltfRuntime, sha), null, null, false, onLoadShaderError(gltfRuntime, sha));
  1374. }
  1375. }
  1376. else {
  1377. Tools.Error("No shader file named " + shader.uri);
  1378. }
  1379. }
  1380. };
  1381. /**
  1382. * glTF File Loader Plugin
  1383. */
  1384. export class GLTFFileLoader implements ISceneLoaderPlugin {
  1385. /**
  1386. * Public members
  1387. */
  1388. public extensions = ".gltf";
  1389. /**
  1390. * Private members
  1391. */
  1392. // None
  1393. /**
  1394. * Static members
  1395. */
  1396. public static MakeYUP: boolean = false;
  1397. public static HomogeneousCoordinates: boolean = false;
  1398. /**
  1399. * Import meshes
  1400. */
  1401. public importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]): boolean {
  1402. var parsedData = JSON.parse(data);
  1403. var gltfRuntime = this._createGlTFRuntime(parsedData, scene, rootUrl);
  1404. gltfRuntime.importOnlyMeshes = true;
  1405. if (meshesNames === "") {
  1406. gltfRuntime.importMeshesNames = [];
  1407. }
  1408. else if (typeof meshesNames === "string") {
  1409. gltfRuntime.importMeshesNames = [meshesNames];
  1410. }
  1411. else if (meshesNames && !(meshesNames instanceof Array)) {
  1412. gltfRuntime.importMeshesNames = [meshesNames];
  1413. }
  1414. else {
  1415. gltfRuntime.importMeshesNames = [];
  1416. Tools.Warn("Argument meshesNames must be of type string or string[]");
  1417. }
  1418. // Create nodes
  1419. this._createNodes(gltfRuntime);
  1420. // Fill arrays of meshes and skeletons
  1421. for (var nde in gltfRuntime.nodes) {
  1422. var node: IGLTFNode = gltfRuntime.nodes[nde];
  1423. if (node.babylonNode instanceof AbstractMesh) {
  1424. meshes.push(<AbstractMesh>node.babylonNode);
  1425. }
  1426. }
  1427. for (var skl in gltfRuntime.skins) {
  1428. var skin: IGLTFSkins = gltfRuntime.skins[skl];
  1429. if (skin.babylonSkeleton instanceof Skeleton) {
  1430. skeletons.push(skin.babylonSkeleton);
  1431. }
  1432. }
  1433. // Load shaders and buffers to apply
  1434. load(gltfRuntime);
  1435. return true;
  1436. }
  1437. /**
  1438. * Load scene
  1439. */
  1440. public load(scene: Scene, data: string, rootUrl: string): boolean {
  1441. var parsedData = JSON.parse(data);
  1442. var gltfRuntime = this._createGlTFRuntime(parsedData, scene, rootUrl);
  1443. // Create nodes
  1444. this._createNodes(gltfRuntime);
  1445. // Load shaders and buffers to apply
  1446. load(gltfRuntime);
  1447. // Finish
  1448. return true;
  1449. }
  1450. // Creates nodes before loading buffers and shaders
  1451. private _createNodes(gltfRuntime: IGLTFRuntime): void {
  1452. var currentScene: IGLTFScene = <IGLTFScene>gltfRuntime.currentScene;
  1453. for (var i = 0; i < currentScene.nodes.length; i++) {
  1454. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1455. }
  1456. }
  1457. // Creates the gltfRuntime
  1458. private _createGlTFRuntime(parsedData: any, scene: Scene, rootUrl: string): IGLTFRuntime {
  1459. var gltfRuntime: IGLTFRuntime = {
  1460. accessors: {},
  1461. buffers: {},
  1462. bufferViews: {},
  1463. meshes: {},
  1464. lights: {},
  1465. cameras: {},
  1466. nodes: {},
  1467. images: {},
  1468. textures: {},
  1469. shaders: {},
  1470. programs: {},
  1471. samplers: {},
  1472. techniques: {},
  1473. materials: {},
  1474. animations: {},
  1475. skins: {},
  1476. currentScene: {},
  1477. buffersCount: 0,
  1478. shaderscount: 0,
  1479. scene: scene,
  1480. dummyNodes: [],
  1481. loadedBuffers: 0,
  1482. loadedShaders: 0,
  1483. rootUrl: rootUrl,
  1484. importOnlyMeshes: false,
  1485. arrayBuffers: []
  1486. }
  1487. // Parse
  1488. if (parsedData.buffers) {
  1489. parseBuffers(parsedData.buffers, gltfRuntime);
  1490. }
  1491. if (parsedData.bufferViews) {
  1492. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1493. }
  1494. if (parsedData.accessors) {
  1495. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1496. }
  1497. if (parsedData.meshes) {
  1498. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1499. }
  1500. if (parsedData.lights) {
  1501. parseObject(parsedData.lights, "lights", gltfRuntime);
  1502. }
  1503. if (parsedData.cameras) {
  1504. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1505. }
  1506. if (parsedData.nodes) {
  1507. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1508. }
  1509. if (parsedData.images) {
  1510. parseObject(parsedData.images, "images", gltfRuntime);
  1511. }
  1512. if (parsedData.textures) {
  1513. parseObject(parsedData.textures, "textures", gltfRuntime);
  1514. }
  1515. if (parsedData.shaders) {
  1516. parseShaders(parsedData.shaders, gltfRuntime);
  1517. }
  1518. if (parsedData.programs) {
  1519. parseObject(parsedData.programs, "programs", gltfRuntime);
  1520. }
  1521. if (parsedData.samplers) {
  1522. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1523. }
  1524. if (parsedData.techniques) {
  1525. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1526. }
  1527. if (parsedData.materials) {
  1528. parseObject(parsedData.materials, "materials", gltfRuntime);
  1529. }
  1530. if (parsedData.animations) {
  1531. parseObject(parsedData.animations, "animations", gltfRuntime);
  1532. }
  1533. if (parsedData.skins) {
  1534. parseObject(parsedData.skins, "skins", gltfRuntime);
  1535. }
  1536. if (parsedData.scene && parsedData.scenes) {
  1537. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1538. }
  1539. return gltfRuntime;
  1540. }
  1541. };
  1542. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1543. }