babylon.glTFLoader.ts 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF2 {
  3. class GLTFLoaderTracker {
  4. private _pendingCount = 0;
  5. private _callback: () => void;
  6. constructor(onComplete: () => void) {
  7. this._callback = onComplete;
  8. }
  9. public _addPendingData(data: any): void {
  10. this._pendingCount++;
  11. }
  12. public _removePendingData(data: any): void {
  13. if (--this._pendingCount === 0) {
  14. this._callback();
  15. }
  16. }
  17. }
  18. interface TypedArray extends ArrayBufferView {
  19. [index: number]: number;
  20. }
  21. interface TypedArrayConstructor<T extends TypedArray> {
  22. readonly prototype: T;
  23. new(length: number): T;
  24. new(array: ArrayLike<number>): T;
  25. new(buffer: ArrayBuffer, byteOffset?: number, length?: number): T;
  26. readonly BYTES_PER_ELEMENT: number;
  27. }
  28. interface IGLTFLoaderFileRequest extends IFileRequest {
  29. _lengthComputable?: boolean;
  30. _loaded?: number;
  31. _total?: number;
  32. }
  33. export class GLTFLoader implements IGLTFLoader {
  34. public _gltf: _IGLTF;
  35. public _babylonScene: Scene;
  36. private _disposed = false;
  37. private _rootUrl: string;
  38. private _defaultMaterial: PBRMaterial;
  39. private _defaultSampler = {} as IGLTFSampler;
  40. private _rootNode: IGLTFNode;
  41. private _successCallback?: () => void;
  42. private _progressCallback?: (event: SceneLoaderProgressEvent) => void;
  43. private _errorCallback?: (message: string, exception?: any) => void;
  44. private _renderReady = false;
  45. private _requests = new Array<IGLTFLoaderFileRequest>();
  46. private _renderReadyObservable = new Observable<GLTFLoader>();
  47. // Count of pending work that needs to complete before the asset is rendered.
  48. private _renderPendingCount = 0;
  49. // Count of pending work that needs to complete before the loader is disposed.
  50. private _loaderPendingCount = 0;
  51. private _loaderTrackers = new Array<GLTFLoaderTracker>();
  52. public static Extensions: { [name: string]: GLTFLoaderExtension } = {};
  53. public static RegisterExtension(extension: GLTFLoaderExtension): void {
  54. if (GLTFLoader.Extensions[extension.name]) {
  55. Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  56. return;
  57. }
  58. GLTFLoader.Extensions[extension.name] = extension;
  59. // Keep the order of registration so that extensions registered first are called first.
  60. GLTFLoaderExtension._Extensions.push(extension);
  61. }
  62. public coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  63. public animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  64. public compileMaterials = false;
  65. public useClipPlane = false;
  66. public compileShadowGenerators = false;
  67. public onDisposeObservable = new Observable<IGLTFLoader>();
  68. public onMeshLoadedObservable = new Observable<AbstractMesh>();
  69. public onTextureLoadedObservable = new Observable<BaseTexture>();
  70. public onMaterialLoadedObservable = new Observable<Material>();
  71. public onCompleteObservable = new Observable<IGLTFLoader>();
  72. public dispose(): void {
  73. if (this._disposed) {
  74. return;
  75. }
  76. this._disposed = true;
  77. this._abortRequests();
  78. this._releaseResources();
  79. this.onDisposeObservable.notifyObservers(this);
  80. }
  81. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void {
  82. this._loadAsync(meshesNames, scene, data, rootUrl, () => {
  83. if (onSuccess) {
  84. onSuccess(this._getMeshes(), [], this._getSkeletons());
  85. }
  86. }, onProgress, onError);
  87. }
  88. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void {
  89. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  90. }
  91. private _loadAsync(nodeNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: () => void, onProgress?: (event: SceneLoaderProgressEvent) => void, onError?: (message: string, exception?: any) => void): void {
  92. this._babylonScene = scene;
  93. this._rootUrl = rootUrl;
  94. this._successCallback = onSuccess;
  95. this._progressCallback = onProgress;
  96. this._errorCallback = onError;
  97. this._tryCatchOnError(() => {
  98. this._loadData(data);
  99. this._addPendingData(this);
  100. this._loadDefaultScene(nodeNames);
  101. this._loadAnimations();
  102. this._removePendingData(this);
  103. });
  104. }
  105. private _onProgress(): void {
  106. if (!this._progressCallback) {
  107. return;
  108. }
  109. let lengthComputable = true;
  110. let loaded = 0;
  111. let total = 0;
  112. for (let request of this._requests) {
  113. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  114. return;
  115. }
  116. lengthComputable = lengthComputable && request._lengthComputable;
  117. loaded += request._loaded;
  118. total += request._total;
  119. }
  120. this._progressCallback(new SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  121. }
  122. public _executeWhenRenderReady(func: () => void): void {
  123. if (this._renderReady) {
  124. func();
  125. }
  126. else {
  127. this._renderReadyObservable.add(func);
  128. }
  129. }
  130. private _onRenderReady(): void {
  131. this._rootNode.babylonMesh.setEnabled(true);
  132. this._startAnimations();
  133. if (this._successCallback) {
  134. this._successCallback();
  135. }
  136. this._renderReadyObservable.notifyObservers(this);
  137. }
  138. private _onComplete(): void {
  139. this._abortRequests();
  140. this._releaseResources();
  141. this.onCompleteObservable.notifyObservers(this);
  142. }
  143. private _loadData(data: IGLTFLoaderData): void {
  144. this._gltf = <_IGLTF>data.json;
  145. // Assign the index of each object for convinience.
  146. GLTFLoader._AssignIndices(this._gltf.accessors);
  147. GLTFLoader._AssignIndices(this._gltf.animations);
  148. GLTFLoader._AssignIndices(this._gltf.buffers);
  149. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  150. GLTFLoader._AssignIndices(this._gltf.images);
  151. GLTFLoader._AssignIndices(this._gltf.materials);
  152. GLTFLoader._AssignIndices(this._gltf.meshes);
  153. GLTFLoader._AssignIndices(this._gltf.nodes);
  154. GLTFLoader._AssignIndices(this._gltf.samplers);
  155. GLTFLoader._AssignIndices(this._gltf.scenes);
  156. GLTFLoader._AssignIndices(this._gltf.skins);
  157. GLTFLoader._AssignIndices(this._gltf.textures);
  158. // Handle global extensions as they may add their own data types.
  159. GLTFLoaderExtension.LoadRoot(this, "#/", this._gltf);
  160. if (data.bin) {
  161. const buffers = this._gltf.buffers;
  162. if (buffers && buffers[0] && !buffers[0].uri) {
  163. const binaryBuffer = buffers[0];
  164. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  165. Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  166. }
  167. binaryBuffer.loadedData = data.bin;
  168. }
  169. else {
  170. Tools.Warn("Unexpected BIN chunk");
  171. }
  172. }
  173. }
  174. private _getMeshes(): AbstractMesh[] {
  175. const meshes = new Array<AbstractMesh>();
  176. // Root mesh is always first.
  177. meshes.push(this._rootNode.babylonMesh);
  178. const nodes = this._gltf.nodes;
  179. if (nodes) {
  180. for (const node of nodes) {
  181. if (node.babylonMesh) {
  182. meshes.push(node.babylonMesh);
  183. }
  184. }
  185. }
  186. return meshes;
  187. }
  188. private _getSkeletons(): Skeleton[] {
  189. const skeletons = new Array<Skeleton>();
  190. const skins = this._gltf.skins;
  191. if (skins) {
  192. for (const skin of skins) {
  193. if (skin.babylonSkeleton) {
  194. skeletons.push(skin.babylonSkeleton);
  195. }
  196. }
  197. }
  198. return skeletons;
  199. }
  200. private _startAnimations(): void {
  201. const animations = this._gltf.animations;
  202. if (!animations) {
  203. return;
  204. }
  205. for (const animation of animations) {
  206. animation.babylonAnimationGroup.normalize();
  207. }
  208. switch (this.animationStartMode) {
  209. case GLTFLoaderAnimationStartMode.NONE: {
  210. // do nothing
  211. break;
  212. }
  213. case GLTFLoaderAnimationStartMode.FIRST: {
  214. const animation = animations[0];
  215. animation.babylonAnimationGroup.start(true);
  216. break;
  217. }
  218. case GLTFLoaderAnimationStartMode.ALL: {
  219. for (const animation of animations) {
  220. animation.babylonAnimationGroup.start(true);
  221. }
  222. break;
  223. }
  224. default: {
  225. Tools.Error("Invalid animation start mode " + this.animationStartMode);
  226. return;
  227. }
  228. }
  229. }
  230. private _loadDefaultScene(nodeNames: any): void {
  231. const scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  232. if (!scene) {
  233. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  234. }
  235. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  236. }
  237. private _loadScene(context: string, scene: IGLTFScene, nodeNames: any): void {
  238. GLTFLoaderExtension.LoadScene(this, context, scene);
  239. this._rootNode = { babylonMesh: new Mesh("__root__", this._babylonScene) } as IGLTFNode;
  240. switch (this.coordinateSystemMode) {
  241. case GLTFLoaderCoordinateSystemMode.AUTO: {
  242. if (!this._babylonScene.useRightHandedSystem) {
  243. this._rootNode.rotation = [0, 1, 0, 0];
  244. this._rootNode.scale = [1, 1, -1];
  245. this._loadTransform(this._rootNode);
  246. }
  247. break;
  248. }
  249. case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  250. this._babylonScene.useRightHandedSystem = true;
  251. break;
  252. }
  253. default: {
  254. Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  255. return;
  256. }
  257. }
  258. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  259. let nodeIndices = scene.nodes;
  260. this._traverseNodes(context, nodeIndices, (node, parentNode) => {
  261. node.parent = parentNode;
  262. return true;
  263. }, this._rootNode);
  264. if (nodeNames) {
  265. if (!(nodeNames instanceof Array)) {
  266. nodeNames = [nodeNames];
  267. }
  268. const filteredNodeIndices = new Array<number>();
  269. this._traverseNodes(context, nodeIndices, node => {
  270. if (nodeNames.indexOf(node.name) !== -1) {
  271. filteredNodeIndices.push(node.index);
  272. node.parent = this._rootNode;
  273. return false;
  274. }
  275. return true;
  276. }, this._rootNode);
  277. nodeIndices = filteredNodeIndices;
  278. }
  279. for (const index of nodeIndices) {
  280. const node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  281. if (!node) {
  282. throw new Error(context + ": Failed to find node " + index);
  283. }
  284. this._loadNode("#/nodes/" + index, node);
  285. }
  286. // Disable the root mesh until the asset is ready to render.
  287. this._rootNode.babylonMesh.setEnabled(false);
  288. }
  289. public _loadNode(context: string, node: IGLTFNode): void {
  290. if (GLTFLoaderExtension.LoadNode(this, context, node)) {
  291. return;
  292. }
  293. node.babylonMesh = new Mesh(node.name || "mesh" + node.index, this._babylonScene);
  294. this._loadTransform(node);
  295. if (node.mesh != null) {
  296. const mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  297. if (!mesh) {
  298. throw new Error(context + ": Failed to find mesh " + node.mesh);
  299. }
  300. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  301. }
  302. node.babylonMesh.parent = node.parent.babylonMesh;
  303. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  304. node.babylonAnimationTargets.push(node.babylonMesh);
  305. if (node.skin != null) {
  306. const skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  307. if (!skin) {
  308. throw new Error(context + ": Failed to find skin " + node.skin);
  309. }
  310. this._loadSkinAsync("#/skins/" + node.skin, skin, () => {
  311. node.babylonMesh.skeleton = skin.babylonSkeleton;
  312. node.babylonMesh._refreshBoundingInfo(true);
  313. });
  314. node.babylonMesh.parent = this._rootNode.babylonMesh;
  315. node.babylonMesh.position = Vector3.Zero();
  316. node.babylonMesh.rotationQuaternion = Quaternion.Identity();
  317. node.babylonMesh.scaling = Vector3.One();
  318. }
  319. if (node.camera != null) {
  320. // TODO: handle cameras
  321. }
  322. if (node.children) {
  323. for (const index of node.children) {
  324. const childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  325. if (!childNode) {
  326. throw new Error(context + ": Failed to find child node " + index);
  327. }
  328. this._loadNode("#/nodes/" + index, childNode);
  329. }
  330. }
  331. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  332. }
  333. private _loadMesh(context: string, node: IGLTFNode, mesh: IGLTFMesh): void {
  334. const primitives = mesh.primitives;
  335. if (!primitives || primitives.length === 0) {
  336. throw new Error(context + ": Primitives are missing");
  337. }
  338. this._createMorphTargets(context, node, mesh);
  339. this._loadAllVertexDataAsync(context, mesh, () => {
  340. this._loadMorphTargets(context, node, mesh);
  341. const vertexData = new VertexData();
  342. for (const primitive of primitives) {
  343. vertexData.merge(primitive.vertexData);
  344. }
  345. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  346. new Geometry(node.babylonMesh.name, this._babylonScene, vertexData, false, node.babylonMesh);
  347. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  348. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  349. node.babylonMesh.subMeshes = [];
  350. let verticesStart = 0;
  351. let indicesStart = 0;
  352. for (let index = 0; index < primitives.length; index++) {
  353. const vertexData = primitives[index].vertexData;
  354. const verticesCount = vertexData.positions!.length;
  355. const indicesCount = vertexData.indices!.length;
  356. SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  357. verticesStart += verticesCount;
  358. indicesStart += indicesCount;
  359. };
  360. });
  361. if (primitives.length === 1) {
  362. const primitive = primitives[0];
  363. if (primitive.material == null) {
  364. node.babylonMesh.material = this._getDefaultMaterial();
  365. }
  366. else {
  367. const material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  368. if (!material) {
  369. throw new Error(context + ": Failed to find material " + primitive.material);
  370. }
  371. this._loadMaterial("#/materials/" + material.index, material, (babylonMaterial, isNew) => {
  372. if (isNew) {
  373. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  374. }
  375. node.babylonMesh.material = babylonMaterial;
  376. });
  377. }
  378. }
  379. else {
  380. const multiMaterial = new MultiMaterial(node.babylonMesh.name, this._babylonScene);
  381. node.babylonMesh.material = multiMaterial;
  382. const subMaterials = multiMaterial.subMaterials;
  383. for (let index = 0; index < primitives.length; index++) {
  384. const primitive = primitives[index];
  385. if (primitive.material == null) {
  386. subMaterials[index] = this._getDefaultMaterial();
  387. }
  388. else {
  389. const material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  390. if (!material) {
  391. throw new Error(context + ": Failed to find material " + primitive.material);
  392. }
  393. this._loadMaterial("#/materials/" + material.index, material, (babylonMaterial, isNew) => {
  394. if (isNew) {
  395. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  396. }
  397. subMaterials[index] = babylonMaterial;
  398. });
  399. }
  400. };
  401. }
  402. }
  403. private _loadAllVertexDataAsync(context: string, mesh: IGLTFMesh, onSuccess: () => void): void {
  404. const primitives = mesh.primitives;
  405. let numRemainingPrimitives = primitives.length;
  406. for (let index = 0; index < primitives.length; index++) {
  407. let primitive = primitives[index];
  408. this._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, vertexData => {
  409. primitive.vertexData = vertexData;
  410. if (--numRemainingPrimitives === 0) {
  411. onSuccess();
  412. }
  413. });
  414. }
  415. }
  416. /**
  417. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  418. * @param {ArrayBufferView} data
  419. * @param {IGLTFAccessor} accessor
  420. */
  421. private _convertToFloat4TextureCoordArray(context: string, data: ArrayBufferView, accessor: IGLTFAccessor): Float32Array {
  422. if (accessor.componentType == EComponentType.FLOAT) {
  423. return data as Float32Array;
  424. }
  425. const buffer = data as TypedArray;
  426. let factor = 1;
  427. switch (accessor.componentType) {
  428. case EComponentType.UNSIGNED_BYTE: {
  429. factor = 1 / 255;
  430. break;
  431. }
  432. case EComponentType.UNSIGNED_SHORT: {
  433. factor = 1 / 65535;
  434. break;
  435. }
  436. default: {
  437. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  438. }
  439. }
  440. const result = new Float32Array(accessor.count * 2);
  441. for (let i = 0; i < result.length; ++i) {
  442. result[i] = buffer[i] * factor;
  443. }
  444. return result;
  445. }
  446. /**
  447. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  448. * @param {ArrayBufferView} data
  449. * @param {IGLTFAccessor} accessor
  450. */
  451. private _convertToFloat4ColorArray(context: string, data: ArrayBufferView, accessor: IGLTFAccessor): Float32Array {
  452. const colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  453. if (colorComponentCount === 4 && accessor.componentType === EComponentType.FLOAT) {
  454. return data as Float32Array;
  455. }
  456. const buffer = data as TypedArray;
  457. let factor = 1;
  458. switch (accessor.componentType) {
  459. case EComponentType.FLOAT: {
  460. factor = 1;
  461. break;
  462. }
  463. case EComponentType.UNSIGNED_BYTE: {
  464. factor = 1 / 255;
  465. break;
  466. }
  467. case EComponentType.UNSIGNED_SHORT: {
  468. factor = 1 / 65535;
  469. break;
  470. }
  471. default: {
  472. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  473. }
  474. }
  475. const result = new Float32Array(accessor.count * 4);
  476. if (colorComponentCount === 4) {
  477. for (let i = 0; i < result.length; ++i) {
  478. result[i] = buffer[i] * factor;
  479. }
  480. }
  481. else {
  482. let offset = 0;
  483. for (let i = 0; i < result.length; ++i) {
  484. if ((i + 1) % 4 === 0) {
  485. result[i] = 1;
  486. }
  487. else {
  488. result[i] = buffer[offset++] * factor;
  489. }
  490. }
  491. }
  492. return result;
  493. }
  494. private _loadVertexDataAsync(context: string, mesh: IGLTFMesh, primitive: IGLTFMeshPrimitive, onSuccess: (vertexData: VertexData) => void): void {
  495. const attributes = primitive.attributes;
  496. if (!attributes) {
  497. throw new Error(context + ": Attributes are missing");
  498. }
  499. if (primitive.mode && primitive.mode !== EMeshPrimitiveMode.TRIANGLES) {
  500. // TODO: handle other primitive modes
  501. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  502. }
  503. const vertexData = new VertexData();
  504. let numRemainingAttributes = Object.keys(attributes).length;
  505. for (const attribute in attributes) {
  506. const accessor = GLTFLoader._GetProperty(this._gltf.accessors, attributes[attribute]);
  507. if (!accessor) {
  508. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  509. }
  510. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, data => {
  511. switch (attribute) {
  512. case "POSITION": {
  513. vertexData.positions = <Float32Array>data;
  514. break;
  515. }
  516. case "NORMAL": {
  517. vertexData.normals = <Float32Array>data;
  518. break;
  519. }
  520. case "TANGENT": {
  521. vertexData.tangents = <Float32Array>data;
  522. break;
  523. }
  524. case "TEXCOORD_0": {
  525. vertexData.uvs = this._convertToFloat4TextureCoordArray(context, data, accessor);
  526. break;
  527. }
  528. case "TEXCOORD_1": {
  529. vertexData.uvs2 = this._convertToFloat4TextureCoordArray(context, data, accessor);
  530. break;
  531. }
  532. case "JOINTS_0": {
  533. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  534. break;
  535. }
  536. case "WEIGHTS_0": {
  537. //TODO: need to add support for normalized weights.
  538. vertexData.matricesWeights = <Float32Array>data;
  539. break;
  540. }
  541. case "COLOR_0": {
  542. vertexData.colors = this._convertToFloat4ColorArray(context, data, accessor);
  543. const hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  544. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  545. mesh.hasVertexAlpha = hasVertexAlpha;
  546. }
  547. break;
  548. }
  549. default: {
  550. Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  551. break;
  552. }
  553. }
  554. if (--numRemainingAttributes === 0) {
  555. if (primitive.indices == null) {
  556. vertexData.indices = new Uint32Array(vertexData.positions!.length / 3);
  557. for (let i = 0; i < vertexData.indices.length; i++) {
  558. vertexData.indices[i] = i;
  559. }
  560. onSuccess(vertexData);
  561. }
  562. else {
  563. const indicesAccessor = GLTFLoader._GetProperty(this._gltf.accessors, primitive.indices);
  564. if (!indicesAccessor) {
  565. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  566. }
  567. this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, data => {
  568. vertexData.indices = <IndicesArray>data;
  569. onSuccess(vertexData);
  570. });
  571. }
  572. }
  573. });
  574. }
  575. }
  576. private _createMorphTargets(context: string, node: IGLTFNode, mesh: IGLTFMesh): void {
  577. const primitives = mesh.primitives;
  578. const targets = primitives[0].targets;
  579. if (!targets) {
  580. return;
  581. }
  582. for (const primitive of primitives) {
  583. if (!primitive.targets || primitive.targets.length != targets.length) {
  584. throw new Error(context + ": All primitives are required to list the same number of targets");
  585. }
  586. }
  587. const morphTargetManager = new MorphTargetManager();
  588. node.babylonMesh.morphTargetManager = morphTargetManager;
  589. for (let index = 0; index < targets.length; index++) {
  590. const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  591. morphTargetManager.addTarget(new MorphTarget("morphTarget" + index, weight));
  592. }
  593. }
  594. private _loadMorphTargets(context: string, node: IGLTFNode, mesh: IGLTFMesh): void {
  595. const morphTargetManager = node.babylonMesh.morphTargetManager;
  596. if (!morphTargetManager) {
  597. return;
  598. }
  599. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, () => {
  600. const numTargets = morphTargetManager.numTargets;
  601. for (let index = 0; index < numTargets; index++) {
  602. const vertexData = new VertexData();
  603. for (const primitive of mesh.primitives) {
  604. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  605. }
  606. if (!vertexData.positions) {
  607. throw new Error(context + ": Positions are missing");
  608. }
  609. const target = morphTargetManager.getTarget(index);
  610. target.setPositions(vertexData.positions);
  611. target.setNormals(vertexData.normals);
  612. target.setTangents(vertexData.tangents);
  613. }
  614. });
  615. }
  616. private _loadAllMorphTargetVertexDataAsync(context: string, node: IGLTFNode, mesh: IGLTFMesh, onSuccess: () => void): void {
  617. let numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager!.numTargets;
  618. for (const primitive of mesh.primitives) {
  619. const targets = primitive.targets!;
  620. primitive.targetsVertexData = new Array<VertexData>(targets.length);
  621. for (let index = 0; index < targets.length; index++) {
  622. this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], vertexData => {
  623. primitive.targetsVertexData[index] = vertexData;
  624. if (--numRemainingTargets === 0) {
  625. onSuccess();
  626. }
  627. });
  628. }
  629. }
  630. }
  631. private _loadMorphTargetVertexDataAsync(context: string, vertexData: VertexData, attributes: { [name: string]: number }, onSuccess: (vertexData: VertexData) => void): void {
  632. const targetVertexData = new VertexData();
  633. let numRemainingAttributes = Object.keys(attributes).length;
  634. for (let attribute in attributes) {
  635. const accessor = GLTFLoader._GetProperty(this._gltf.accessors, attributes[attribute]);
  636. if (!accessor) {
  637. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  638. }
  639. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, data => {
  640. // glTF stores morph target information as deltas while babylon.js expects the final data.
  641. // As a result we have to add the original data to the delta to calculate the final data.
  642. const values = <Float32Array>data;
  643. switch (attribute) {
  644. case "POSITION": {
  645. for (let i = 0; i < values.length; i++) {
  646. values[i] += vertexData.positions![i];
  647. }
  648. targetVertexData.positions = values;
  649. break;
  650. }
  651. case "NORMAL": {
  652. for (let i = 0; i < values.length; i++) {
  653. values[i] += vertexData.normals![i];
  654. }
  655. targetVertexData.normals = values;
  656. break;
  657. }
  658. case "TANGENT": {
  659. // Tangent data for morph targets is stored as xyz delta.
  660. // The vertexData.tangent is stored as xyzw.
  661. // So we need to skip every fourth vertexData.tangent.
  662. for (let i = 0, j = 0; i < values.length; i++ , j++) {
  663. values[i] += vertexData.tangents![j];
  664. if ((i + 1) % 3 == 0) {
  665. j++;
  666. }
  667. }
  668. targetVertexData.tangents = values;
  669. break;
  670. }
  671. default: {
  672. Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  673. break;
  674. }
  675. }
  676. if (--numRemainingAttributes === 0) {
  677. onSuccess(targetVertexData);
  678. }
  679. });
  680. }
  681. }
  682. private _loadTransform(node: IGLTFNode): void {
  683. let position: Vector3 = Vector3.Zero();
  684. let rotation: Quaternion = Quaternion.Identity();
  685. let scaling: Vector3 = Vector3.One();
  686. if (node.matrix) {
  687. const matrix = Matrix.FromArray(node.matrix);
  688. matrix.decompose(scaling, rotation, position);
  689. }
  690. else {
  691. if (node.translation) position = Vector3.FromArray(node.translation);
  692. if (node.rotation) rotation = Quaternion.FromArray(node.rotation);
  693. if (node.scale) scaling = Vector3.FromArray(node.scale);
  694. }
  695. node.babylonMesh.position = position;
  696. node.babylonMesh.rotationQuaternion = rotation;
  697. node.babylonMesh.scaling = scaling;
  698. }
  699. private _loadSkinAsync(context: string, skin: IGLTFSkin, onSuccess: () => void): void {
  700. if (skin.babylonSkeleton) {
  701. onSuccess();
  702. return;
  703. }
  704. const skeletonId = "skeleton" + skin.index;
  705. skin.babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  706. if (skin.inverseBindMatrices == null) {
  707. this._loadBones(context, skin, null);
  708. onSuccess();
  709. }
  710. else {
  711. const accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  712. if (!accessor) {
  713. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  714. }
  715. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, data => {
  716. this._loadBones(context, skin, <Float32Array>data);
  717. onSuccess();
  718. });
  719. }
  720. }
  721. private _createBone(node: IGLTFNode, skin: IGLTFSkin, parent: Nullable<Bone>, localMatrix: Matrix, baseMatrix: Matrix, index: number): Bone {
  722. const babylonBone = new Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  723. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  724. node.babylonAnimationTargets.push(babylonBone);
  725. return babylonBone;
  726. }
  727. private _loadBones(context: string, skin: IGLTFSkin, inverseBindMatrixData: Nullable<Float32Array>): void {
  728. const babylonBones: { [index: number]: Bone } = {};
  729. for (const index of skin.joints) {
  730. const node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  731. if (!node) {
  732. throw new Error(context + ": Failed to find joint " + index);
  733. }
  734. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  735. }
  736. }
  737. private _loadBone(node: IGLTFNode, skin: IGLTFSkin, inverseBindMatrixData: Nullable<Float32Array>, babylonBones: { [index: number]: Bone }): Bone {
  738. let babylonBone = babylonBones[node.index];
  739. if (babylonBone) {
  740. return babylonBone;
  741. }
  742. const boneIndex = skin.joints.indexOf(node.index);
  743. let baseMatrix = Matrix.Identity();
  744. if (inverseBindMatrixData && boneIndex !== -1) {
  745. baseMatrix = Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  746. baseMatrix.invertToRef(baseMatrix);
  747. }
  748. let babylonParentBone: Nullable<Bone> = null;
  749. if (node.parent !== this._rootNode) {
  750. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  751. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  752. }
  753. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  754. babylonBones[node.index] = babylonBone;
  755. return babylonBone;
  756. }
  757. private _getNodeMatrix(node: IGLTFNode): Matrix {
  758. return node.matrix ?
  759. Matrix.FromArray(node.matrix) :
  760. Matrix.Compose(
  761. node.scale ? Vector3.FromArray(node.scale) : Vector3.One(),
  762. node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(),
  763. node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());
  764. }
  765. private _traverseNodes(context: string, indices: number[], action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): void {
  766. for (const index of indices) {
  767. const node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  768. if (!node) {
  769. throw new Error(context + ": Failed to find node " + index);
  770. }
  771. this._traverseNode(context, node, action, parentNode);
  772. }
  773. }
  774. public _traverseNode(context: string, node: IGLTFNode, action: (node: IGLTFNode, parentNode: IGLTFNode) => boolean, parentNode: IGLTFNode): void {
  775. if (GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  776. return;
  777. }
  778. if (!action(node, parentNode)) {
  779. return;
  780. }
  781. if (node.children) {
  782. this._traverseNodes(context, node.children, action, node);
  783. }
  784. }
  785. private _loadAnimations(): void {
  786. const animations = this._gltf.animations;
  787. if (!animations) {
  788. return;
  789. }
  790. for (let index = 0; index < animations.length; index++) {
  791. const animation = animations[index];
  792. this._loadAnimation("#/animations/" + index, animation);
  793. }
  794. }
  795. private _loadAnimation(context: string, animation: IGLTFAnimation): void {
  796. animation.babylonAnimationGroup = new AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  797. for (let index = 0; index < animation.channels.length; index++) {
  798. const channel = GLTFLoader._GetProperty(animation.channels, index);
  799. if (!channel) {
  800. throw new Error(context + ": Failed to find channel " + index);
  801. }
  802. const sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  803. if (!sampler) {
  804. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  805. }
  806. this._loadAnimationChannel(animation,
  807. context + "/channels/" + index, channel,
  808. context + "/samplers/" + channel.sampler, sampler);
  809. }
  810. }
  811. private _loadAnimationChannel(animation: IGLTFAnimation, channelContext: string, channel: IGLTFAnimationChannel, samplerContext: string, sampler: IGLTFAnimationSampler): void {
  812. const targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  813. if (!targetNode) {
  814. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  815. }
  816. let targetPath: string;
  817. let animationType: number;
  818. switch (channel.target.path) {
  819. case "translation": {
  820. targetPath = "position";
  821. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  822. break;
  823. }
  824. case "rotation": {
  825. targetPath = "rotationQuaternion";
  826. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  827. break;
  828. }
  829. case "scale": {
  830. targetPath = "scaling";
  831. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  832. break;
  833. }
  834. case "weights": {
  835. targetPath = "influence";
  836. animationType = Animation.ANIMATIONTYPE_FLOAT;
  837. break;
  838. }
  839. default: {
  840. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  841. }
  842. }
  843. let inputData: Float32Array;
  844. let outputData: Float32Array;
  845. const checkSuccess = () => {
  846. if (!inputData || !outputData) {
  847. return;
  848. }
  849. let outputBufferOffset = 0;
  850. let getNextOutputValue: () => any;
  851. switch (targetPath) {
  852. case "position": {
  853. getNextOutputValue = () => {
  854. const value = Vector3.FromArray(outputData, outputBufferOffset);
  855. outputBufferOffset += 3;
  856. return value;
  857. };
  858. break;
  859. }
  860. case "rotationQuaternion": {
  861. getNextOutputValue = () => {
  862. const value = Quaternion.FromArray(outputData, outputBufferOffset);
  863. outputBufferOffset += 4;
  864. return value;
  865. };
  866. break;
  867. }
  868. case "scaling": {
  869. getNextOutputValue = () => {
  870. const value = Vector3.FromArray(outputData, outputBufferOffset);
  871. outputBufferOffset += 3;
  872. return value;
  873. };
  874. break;
  875. }
  876. case "influence": {
  877. getNextOutputValue = () => {
  878. const numTargets = targetNode.babylonMesh.morphTargetManager!.numTargets;
  879. const value = new Array<number>(numTargets);
  880. for (let i = 0; i < numTargets; i++) {
  881. value[i] = outputData[outputBufferOffset++];
  882. }
  883. return value;
  884. };
  885. break;
  886. }
  887. }
  888. sampler.interpolation = sampler.interpolation || "LINEAR";
  889. let getNextKey: (frameIndex: number) => IAnimationKey;
  890. switch (sampler.interpolation) {
  891. case "STEP": {
  892. getNextKey = frameIndex => ({
  893. frame: inputData[frameIndex],
  894. value: getNextOutputValue(),
  895. interpolation: AnimationKeyInterpolation.STEP
  896. });
  897. break;
  898. }
  899. case "LINEAR": {
  900. getNextKey = frameIndex => ({
  901. frame: inputData[frameIndex],
  902. value: getNextOutputValue()
  903. });
  904. break;
  905. }
  906. case "CUBICSPLINE": {
  907. getNextKey = frameIndex => ({
  908. frame: inputData[frameIndex],
  909. inTangent: getNextOutputValue(),
  910. value: getNextOutputValue(),
  911. outTangent: getNextOutputValue()
  912. });
  913. break;
  914. }
  915. default: {
  916. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  917. }
  918. };
  919. let keys: Array<IAnimationKey>;
  920. if (inputData.length === 1) {
  921. let key = getNextKey(0);
  922. keys = [
  923. { frame: key.frame, value: key.value },
  924. { frame: key.frame + 1, value: key.value }
  925. ];
  926. }
  927. else {
  928. keys = new Array(inputData.length);
  929. for (let frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  930. keys[frameIndex] = getNextKey(frameIndex);
  931. }
  932. }
  933. if (targetPath === "influence") {
  934. const morphTargetManager = targetNode.babylonMesh.morphTargetManager!;
  935. for (let targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  936. const morphTarget = morphTargetManager.getTarget(targetIndex);
  937. const animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  938. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  939. babylonAnimation.setKeys(keys.map(key => ({
  940. frame: key.frame,
  941. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  942. value: key.value[targetIndex],
  943. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  944. })));
  945. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  946. }
  947. }
  948. else {
  949. const animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  950. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  951. babylonAnimation.setKeys(keys);
  952. if (targetNode.babylonAnimationTargets) {
  953. for (const target of targetNode.babylonAnimationTargets) {
  954. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  955. }
  956. }
  957. }
  958. };
  959. const inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  960. if (!inputAccessor) {
  961. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  962. }
  963. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, data => {
  964. inputData = <Float32Array>data;
  965. checkSuccess();
  966. });
  967. const outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  968. if (!outputAccessor) {
  969. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  970. }
  971. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, data => {
  972. outputData = <Float32Array>data;
  973. checkSuccess();
  974. });
  975. }
  976. private _loadBufferAsync(context: string, buffer: IGLTFBuffer, onSuccess: (data: ArrayBufferView) => void): void {
  977. this._addPendingData(buffer);
  978. if (buffer.loadedData) {
  979. onSuccess(buffer.loadedData);
  980. this._removePendingData(buffer);
  981. }
  982. else if (buffer.loadedObservable) {
  983. buffer.loadedObservable.add(buffer => {
  984. onSuccess(buffer.loadedData!);
  985. this._removePendingData(buffer);
  986. });
  987. }
  988. else {
  989. if (!buffer.uri) {
  990. throw new Error(context + ": Uri is missing");
  991. }
  992. buffer.loadedObservable = new Observable<IGLTFBuffer>();
  993. buffer.loadedObservable.add(buffer => {
  994. onSuccess(buffer.loadedData!);
  995. this._removePendingData(buffer);
  996. });
  997. this._loadUriAsync(context, buffer.uri, data => {
  998. buffer.loadedData = data;
  999. buffer.loadedObservable!.notifyObservers(buffer);
  1000. buffer.loadedObservable = undefined;
  1001. });
  1002. }
  1003. }
  1004. private _loadBufferViewAsync(context: string, bufferView: IGLTFBufferView, onSuccess: (data: ArrayBufferView) => void): void {
  1005. const buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  1006. if (!buffer) {
  1007. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  1008. }
  1009. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, bufferData => {
  1010. let data: ArrayBufferView;
  1011. try {
  1012. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1013. }
  1014. catch (e) {
  1015. throw new Error(context + ": " + e.message);
  1016. }
  1017. onSuccess(data);
  1018. });
  1019. }
  1020. private _loadAccessorAsync(context: string, accessor: IGLTFAccessor, onSuccess: (data: ArrayBufferView) => void): void {
  1021. if (accessor.sparse) {
  1022. throw new Error(context + ": Sparse accessors are not currently supported");
  1023. }
  1024. const bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  1025. if (!bufferView) {
  1026. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  1027. }
  1028. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, bufferViewData => {
  1029. const numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1030. let data: ArrayBufferView;
  1031. const byteOffset = accessor.byteOffset || 0;
  1032. const byteStride = bufferView.byteStride;
  1033. if (byteStride === 0) {
  1034. Tools.Warn(context + ": Byte stride of 0 is not valid");
  1035. }
  1036. try {
  1037. switch (accessor.componentType) {
  1038. case EComponentType.BYTE: {
  1039. data = this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1040. break;
  1041. }
  1042. case EComponentType.UNSIGNED_BYTE: {
  1043. data = this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1044. break;
  1045. }
  1046. case EComponentType.SHORT: {
  1047. data = this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1048. break;
  1049. }
  1050. case EComponentType.UNSIGNED_SHORT: {
  1051. data = this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1052. break;
  1053. }
  1054. case EComponentType.UNSIGNED_INT: {
  1055. data = this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1056. break;
  1057. }
  1058. case EComponentType.FLOAT: {
  1059. data = this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1060. break;
  1061. }
  1062. default: {
  1063. throw new Error(context + ": Invalid component type " + accessor.componentType);
  1064. }
  1065. }
  1066. }
  1067. catch (e) {
  1068. throw new Error(context + ": " + e);
  1069. }
  1070. onSuccess(data);
  1071. });
  1072. }
  1073. private _buildArrayBuffer<T extends TypedArray>(typedArray: TypedArrayConstructor<T>, data: ArrayBufferView, byteOffset: number, count: number, numComponents: number, byteStride?: number): T {
  1074. byteOffset += data.byteOffset;
  1075. const targetLength = count * numComponents;
  1076. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  1077. return new typedArray(data.buffer, byteOffset, targetLength);
  1078. }
  1079. const elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  1080. const sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  1081. const targetBuffer = new typedArray(targetLength);
  1082. let sourceIndex = 0;
  1083. let targetIndex = 0;
  1084. while (targetIndex < targetLength) {
  1085. for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1086. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  1087. targetIndex++;
  1088. }
  1089. sourceIndex += elementStride;
  1090. }
  1091. return targetBuffer;
  1092. }
  1093. public _addPendingData(data: any): void {
  1094. if (!this._renderReady) {
  1095. this._renderPendingCount++;
  1096. }
  1097. this._addLoaderPendingData(data);
  1098. }
  1099. public _removePendingData(data: any): void {
  1100. if (!this._renderReady) {
  1101. if (--this._renderPendingCount === 0) {
  1102. this._addLoaderPendingData(this);
  1103. this._compileMaterialsAsync(() => {
  1104. this._compileShadowGeneratorsAsync(() => {
  1105. this._removeLoaderPendingData(this);
  1106. this._renderReady = true;
  1107. this._onRenderReady();
  1108. });
  1109. });
  1110. }
  1111. }
  1112. this._removeLoaderPendingData(data);
  1113. }
  1114. public _addLoaderPendingData(data: any): void {
  1115. this._loaderPendingCount++;
  1116. for (const tracker of this._loaderTrackers) {
  1117. tracker._addPendingData(data);
  1118. }
  1119. }
  1120. public _removeLoaderPendingData(data: any): void {
  1121. for (const tracker of this._loaderTrackers) {
  1122. tracker._removePendingData(data);
  1123. }
  1124. if (--this._loaderPendingCount === 0) {
  1125. this._onComplete();
  1126. }
  1127. }
  1128. public _whenAction(action: () => void, onComplete: () => void): void {
  1129. const tracker = new GLTFLoaderTracker(() => {
  1130. this._loaderTrackers.splice(this._loaderTrackers.indexOf(tracker), 1);
  1131. onComplete();
  1132. });
  1133. this._loaderTrackers.push(tracker);
  1134. this._addLoaderPendingData(tracker);
  1135. action();
  1136. this._removeLoaderPendingData(tracker);
  1137. }
  1138. private _getDefaultMaterial(): Material {
  1139. if (!this._defaultMaterial) {
  1140. const id = "__gltf_default";
  1141. let material = <PBRMaterial>this._babylonScene.getMaterialByName(id);
  1142. if (!material) {
  1143. material = new PBRMaterial(id, this._babylonScene);
  1144. material.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1145. material.sideOrientation = Material.ClockWiseSideOrientation;
  1146. material.metallic = 1;
  1147. material.roughness = 1;
  1148. }
  1149. this._defaultMaterial = material;
  1150. }
  1151. return this._defaultMaterial;
  1152. }
  1153. private _loadMaterialMetallicRoughnessProperties(context: string, material: IGLTFMaterial): void {
  1154. const babylonMaterial = material.babylonMaterial as PBRMaterial;
  1155. // Ensure metallic workflow
  1156. babylonMaterial.metallic = 1;
  1157. babylonMaterial.roughness = 1;
  1158. const properties = material.pbrMetallicRoughness;
  1159. if (!properties) {
  1160. return;
  1161. }
  1162. babylonMaterial.albedoColor = properties.baseColorFactor ? Color3.FromArray(properties.baseColorFactor) : new Color3(1, 1, 1);
  1163. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  1164. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  1165. if (properties.baseColorTexture) {
  1166. const texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  1167. if (!texture) {
  1168. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  1169. }
  1170. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  1171. }
  1172. if (properties.metallicRoughnessTexture) {
  1173. const texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  1174. if (!texture) {
  1175. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  1176. }
  1177. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  1178. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1179. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1180. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1181. }
  1182. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  1183. }
  1184. public _loadMaterial(context: string, material: IGLTFMaterial, assign: (babylonMaterial: Material, isNew: boolean) => void): void {
  1185. if (material.babylonMaterial) {
  1186. assign(material.babylonMaterial, false);
  1187. return;
  1188. }
  1189. if (GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  1190. return;
  1191. }
  1192. this._createPbrMaterial(material);
  1193. this._loadMaterialBaseProperties(context, material);
  1194. this._loadMaterialMetallicRoughnessProperties(context, material);
  1195. assign(material.babylonMaterial, true);
  1196. }
  1197. public _createPbrMaterial(material: IGLTFMaterial): void {
  1198. const babylonMaterial = new PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1199. babylonMaterial.sideOrientation = Material.ClockWiseSideOrientation;
  1200. material.babylonMaterial = babylonMaterial;
  1201. }
  1202. public _loadMaterialBaseProperties(context: string, material: IGLTFMaterial): void {
  1203. const babylonMaterial = material.babylonMaterial as PBRMaterial;
  1204. babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  1205. if (material.doubleSided) {
  1206. babylonMaterial.backFaceCulling = false;
  1207. babylonMaterial.twoSidedLighting = true;
  1208. }
  1209. if (material.normalTexture) {
  1210. const texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  1211. if (!texture) {
  1212. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  1213. }
  1214. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  1215. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1216. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1217. if (material.normalTexture.scale != null) {
  1218. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1219. }
  1220. }
  1221. if (material.occlusionTexture) {
  1222. const texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  1223. if (!texture) {
  1224. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  1225. }
  1226. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  1227. babylonMaterial.useAmbientInGrayScale = true;
  1228. if (material.occlusionTexture.strength != null) {
  1229. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1230. }
  1231. }
  1232. if (material.emissiveTexture) {
  1233. const texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  1234. if (!texture) {
  1235. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  1236. }
  1237. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  1238. }
  1239. }
  1240. public _loadMaterialAlphaProperties(context: string, material: IGLTFMaterial, colorFactor: number[]): void {
  1241. const babylonMaterial = material.babylonMaterial as PBRMaterial;
  1242. const alphaMode = material.alphaMode || "OPAQUE";
  1243. switch (alphaMode) {
  1244. case "OPAQUE": {
  1245. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1246. break;
  1247. }
  1248. case "MASK": {
  1249. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;
  1250. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  1251. if (colorFactor) {
  1252. if (colorFactor[3] == 0) {
  1253. babylonMaterial.alphaCutOff = 1;
  1254. }
  1255. else {
  1256. babylonMaterial.alphaCutOff /= colorFactor[3];
  1257. }
  1258. }
  1259. if (babylonMaterial.albedoTexture) {
  1260. babylonMaterial.albedoTexture.hasAlpha = true;
  1261. }
  1262. break;
  1263. }
  1264. case "BLEND": {
  1265. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1266. if (colorFactor) {
  1267. babylonMaterial.alpha = colorFactor[3];
  1268. }
  1269. if (babylonMaterial.albedoTexture) {
  1270. babylonMaterial.albedoTexture.hasAlpha = true;
  1271. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1272. }
  1273. break;
  1274. }
  1275. default: {
  1276. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  1277. }
  1278. }
  1279. }
  1280. public _loadTexture(context: string, texture: IGLTFTexture, coordinatesIndex?: number): Texture {
  1281. const sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  1282. if (!sampler) {
  1283. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  1284. }
  1285. this._loadSampler("#/samplers/" + sampler.index, sampler);
  1286. this._addPendingData(texture);
  1287. const babylonTexture = new Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, () => {
  1288. this._tryCatchOnError(() => {
  1289. this._removePendingData(texture);
  1290. });
  1291. }, message => {
  1292. this._tryCatchOnError(() => {
  1293. throw new Error(context + ": " + message);
  1294. });
  1295. });
  1296. if (texture.url) {
  1297. babylonTexture.updateURL(texture.url);
  1298. }
  1299. else if (texture.dataReadyObservable) {
  1300. texture.dataReadyObservable.add(texture => {
  1301. babylonTexture.updateURL(texture.url!);
  1302. });
  1303. }
  1304. else {
  1305. texture.dataReadyObservable = new Observable<IGLTFTexture>();
  1306. texture.dataReadyObservable.add(texture => {
  1307. babylonTexture.updateURL(texture.url!);
  1308. });
  1309. const image = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  1310. if (!image) {
  1311. throw new Error(context + ": Failed to find source " + texture.source);
  1312. }
  1313. this._loadImageAsync("#/images/" + image.index, image, data => {
  1314. texture.url = URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  1315. texture.dataReadyObservable!.notifyObservers(texture);
  1316. texture.dataReadyObservable = undefined;
  1317. });
  1318. }
  1319. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  1320. babylonTexture.wrapU = sampler.wrapU;
  1321. babylonTexture.wrapV = sampler.wrapV;
  1322. babylonTexture.name = texture.name || "texture" + texture.index;
  1323. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1324. return babylonTexture;
  1325. }
  1326. private _loadSampler(context: string, sampler: IGLTFSampler): void {
  1327. if (sampler.noMipMaps != undefined) {
  1328. return;
  1329. }
  1330. sampler.noMipMaps = (sampler.minFilter === ETextureMinFilter.NEAREST || sampler.minFilter === ETextureMinFilter.LINEAR);
  1331. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  1332. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  1333. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  1334. }
  1335. private _loadImageAsync(context: string, image: IGLTFImage, onSuccess: (data: ArrayBufferView) => void): void {
  1336. if (image.uri) {
  1337. this._loadUriAsync(context, image.uri, onSuccess);
  1338. }
  1339. else {
  1340. const bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  1341. if (!bufferView) {
  1342. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  1343. }
  1344. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  1345. }
  1346. }
  1347. public _loadUriAsync(context: string, uri: string, onSuccess: (data: ArrayBufferView) => void): void {
  1348. if (GLTFUtils.IsBase64(uri)) {
  1349. onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(uri)));
  1350. return;
  1351. }
  1352. if (!GLTFUtils.ValidateUri(uri)) {
  1353. throw new Error(context + ": Uri '" + uri + "' is invalid");
  1354. }
  1355. let request = Tools.LoadFile(this._rootUrl + uri, data => {
  1356. this._tryCatchOnError(() => {
  1357. onSuccess(new Uint8Array(data as ArrayBuffer));
  1358. });
  1359. }, event => {
  1360. this._tryCatchOnError(() => {
  1361. if (request && !this._renderReady) {
  1362. request._lengthComputable = event.lengthComputable;
  1363. request._loaded = event.loaded;
  1364. request._total = event.total;
  1365. this._onProgress();
  1366. }
  1367. });
  1368. }, this._babylonScene.database, true, (request, exception) => {
  1369. this._tryCatchOnError(() => {
  1370. throw new LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  1371. });
  1372. }) as IGLTFLoaderFileRequest;
  1373. this._requests.push(request);
  1374. }
  1375. public _tryCatchOnError(handler: () => void): void {
  1376. if (this._disposed) {
  1377. return;
  1378. }
  1379. try {
  1380. handler();
  1381. }
  1382. catch (e) {
  1383. Tools.Error("glTF Loader: " + e.message);
  1384. if (this._errorCallback) {
  1385. this._errorCallback(e.message, e);
  1386. }
  1387. this.dispose();
  1388. }
  1389. }
  1390. private static _AssignIndices(array?: Array<{ index: number }>): void {
  1391. if (array) {
  1392. for (let index = 0; index < array.length; index++) {
  1393. array[index].index = index;
  1394. }
  1395. }
  1396. }
  1397. public static _GetProperty<T extends IGLTFProperty>(array?: ArrayLike<T>, index?: number): Nullable<T> {
  1398. if (!array || index == undefined || !array[index]) {
  1399. return null;
  1400. }
  1401. return array[index];
  1402. }
  1403. private static _GetTextureWrapMode(context: string, mode?: ETextureWrapMode): number {
  1404. // Set defaults if undefined
  1405. mode = mode == undefined ? ETextureWrapMode.REPEAT : mode;
  1406. switch (mode) {
  1407. case ETextureWrapMode.CLAMP_TO_EDGE: return Texture.CLAMP_ADDRESSMODE;
  1408. case ETextureWrapMode.MIRRORED_REPEAT: return Texture.MIRROR_ADDRESSMODE;
  1409. case ETextureWrapMode.REPEAT: return Texture.WRAP_ADDRESSMODE;
  1410. default:
  1411. Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  1412. return Texture.WRAP_ADDRESSMODE;
  1413. }
  1414. }
  1415. private static _GetTextureSamplingMode(context: string, magFilter?: ETextureMagFilter, minFilter?: ETextureMinFilter): number {
  1416. // Set defaults if undefined
  1417. magFilter = magFilter == undefined ? ETextureMagFilter.LINEAR : magFilter;
  1418. minFilter = minFilter == undefined ? ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  1419. if (magFilter === ETextureMagFilter.LINEAR) {
  1420. switch (minFilter) {
  1421. case ETextureMinFilter.NEAREST: return Texture.LINEAR_NEAREST;
  1422. case ETextureMinFilter.LINEAR: return Texture.LINEAR_LINEAR;
  1423. case ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.LINEAR_NEAREST_MIPNEAREST;
  1424. case ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.LINEAR_LINEAR_MIPNEAREST;
  1425. case ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.LINEAR_NEAREST_MIPLINEAR;
  1426. case ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.LINEAR_LINEAR_MIPLINEAR;
  1427. default:
  1428. Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  1429. return Texture.LINEAR_LINEAR_MIPLINEAR;
  1430. }
  1431. }
  1432. else {
  1433. if (magFilter !== ETextureMagFilter.NEAREST) {
  1434. Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  1435. }
  1436. switch (minFilter) {
  1437. case ETextureMinFilter.NEAREST: return Texture.NEAREST_NEAREST;
  1438. case ETextureMinFilter.LINEAR: return Texture.NEAREST_LINEAR;
  1439. case ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.NEAREST_NEAREST_MIPNEAREST;
  1440. case ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.NEAREST_LINEAR_MIPNEAREST;
  1441. case ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.NEAREST_NEAREST_MIPLINEAR;
  1442. case ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.NEAREST_LINEAR_MIPLINEAR;
  1443. default:
  1444. Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  1445. return Texture.NEAREST_NEAREST_MIPNEAREST;
  1446. }
  1447. }
  1448. }
  1449. private static _GetNumComponents(context: string, type: string): number {
  1450. switch (type) {
  1451. case "SCALAR": return 1;
  1452. case "VEC2": return 2;
  1453. case "VEC3": return 3;
  1454. case "VEC4": return 4;
  1455. case "MAT2": return 4;
  1456. case "MAT3": return 9;
  1457. case "MAT4": return 16;
  1458. }
  1459. throw new Error(context + ": Invalid type " + type);
  1460. }
  1461. private _compileMaterialAsync(babylonMaterial: Material, babylonMesh: AbstractMesh, onSuccess: () => void): void {
  1462. if (this.useClipPlane) {
  1463. babylonMaterial.forceCompilation(babylonMesh, () => {
  1464. babylonMaterial.forceCompilation(babylonMesh, () => {
  1465. this._tryCatchOnError(onSuccess);
  1466. }, { clipPlane: true });
  1467. });
  1468. }
  1469. else {
  1470. babylonMaterial.forceCompilation(babylonMesh, () => {
  1471. this._tryCatchOnError(onSuccess);
  1472. });
  1473. }
  1474. }
  1475. private _compileMaterialsAsync(onSuccess: () => void): void {
  1476. if (!this.compileMaterials || !this._gltf.materials) {
  1477. onSuccess();
  1478. return;
  1479. }
  1480. let meshes = this._getMeshes();
  1481. let remaining = 0;
  1482. for (let mesh of meshes) {
  1483. if (mesh.material instanceof MultiMaterial) {
  1484. for (let subMaterial of mesh.material.subMaterials) {
  1485. if (subMaterial) {
  1486. remaining++;
  1487. }
  1488. }
  1489. }
  1490. else if (mesh.material) {
  1491. remaining++;
  1492. }
  1493. }
  1494. if (remaining === 0) {
  1495. onSuccess();
  1496. return;
  1497. }
  1498. for (let mesh of meshes) {
  1499. if (mesh.material instanceof MultiMaterial) {
  1500. for (let subMaterial of mesh.material.subMaterials) {
  1501. if (subMaterial) {
  1502. this._compileMaterialAsync(subMaterial, mesh, () => {
  1503. if (--remaining === 0) {
  1504. onSuccess();
  1505. }
  1506. });
  1507. }
  1508. }
  1509. }
  1510. else if (mesh.material) {
  1511. this._compileMaterialAsync(mesh.material, mesh, () => {
  1512. if (--remaining === 0) {
  1513. onSuccess();
  1514. }
  1515. })
  1516. }
  1517. }
  1518. }
  1519. private _compileShadowGeneratorsAsync(onSuccess: () => void): void {
  1520. if (!this.compileShadowGenerators) {
  1521. onSuccess();
  1522. return;
  1523. }
  1524. let lights = this._babylonScene.lights;
  1525. let remaining = 0;
  1526. for (let light of lights) {
  1527. let generator = light.getShadowGenerator();
  1528. if (generator) {
  1529. remaining++;
  1530. }
  1531. }
  1532. if (remaining === 0) {
  1533. onSuccess();
  1534. return;
  1535. }
  1536. for (let light of lights) {
  1537. let generator = light.getShadowGenerator();
  1538. if (generator) {
  1539. generator.forceCompilation(() => {
  1540. if (--remaining === 0) {
  1541. this._tryCatchOnError(onSuccess);
  1542. }
  1543. });
  1544. }
  1545. }
  1546. }
  1547. private _abortRequests(): void {
  1548. for (const request of this._requests) {
  1549. request.abort();
  1550. }
  1551. this._requests.length = 0;
  1552. }
  1553. private _releaseResources(): void {
  1554. if (this._gltf.textures) {
  1555. for (const texture of this._gltf.textures) {
  1556. if (texture.url) {
  1557. URL.revokeObjectURL(texture.url);
  1558. texture.url = undefined;
  1559. }
  1560. }
  1561. }
  1562. }
  1563. }
  1564. GLTFFileLoader.CreateGLTFLoaderV2 = () => new GLTFLoader();
  1565. }