glTFLoader.ts 73 KB

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