glTFLoader.ts 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481
  1. import { IndicesArray, Nullable } from "babylonjs/types";
  2. import { Deferred } from "babylonjs/Misc/deferred";
  3. import { Quaternion, Vector3, Matrix } from "babylonjs/Maths/math.vector";
  4. import { Color3 } from 'babylonjs/Maths/math.color';
  5. import { Tools } from "babylonjs/Misc/tools";
  6. import { Camera } from "babylonjs/Cameras/camera";
  7. import { TargetCamera } from "babylonjs/Cameras/targetCamera";
  8. import { AnimationGroup } from "babylonjs/Animations/animationGroup";
  9. import { Animation } from "babylonjs/Animations/animation";
  10. import { Bone } from "babylonjs/Bones/bone";
  11. import { Skeleton } from "babylonjs/Bones/skeleton";
  12. import { Material } from "babylonjs/Materials/material";
  13. import { PBRMaterial } from "babylonjs/Materials/PBR/pbrMaterial";
  14. import { BaseTexture } from "babylonjs/Materials/Textures/baseTexture";
  15. import { Texture } from "babylonjs/Materials/Textures/texture";
  16. import { TransformNode } from "babylonjs/Meshes/transformNode";
  17. import { Buffer, VertexBuffer } from "babylonjs/Meshes/buffer";
  18. import { Geometry } from "babylonjs/Meshes/geometry";
  19. import { AbstractMesh } from "babylonjs/Meshes/abstractMesh";
  20. import { InstancedMesh } from "babylonjs/Meshes/instancedMesh";
  21. import { Mesh } from "babylonjs/Meshes/mesh";
  22. import { MorphTarget } from "babylonjs/Morph/morphTarget";
  23. import { MorphTargetManager } from "babylonjs/Morph/morphTargetManager";
  24. import { ISceneLoaderAsyncResult, ISceneLoaderProgressEvent } from "babylonjs/Loading/sceneLoader";
  25. import { Scene } from "babylonjs/scene";
  26. import { IProperty, AccessorType, CameraType, AnimationChannelTargetPath, AnimationSamplerInterpolation, AccessorComponentType, MaterialAlphaMode, TextureMinFilter, TextureWrapMode, TextureMagFilter, MeshPrimitiveMode } from "babylonjs-gltf2interface";
  27. import { _IAnimationSamplerData, IGLTF, ISampler, INode, IScene, IMesh, IAccessor, ISkin, ICamera, IAnimation, IAnimationChannel, IAnimationSampler, IBuffer, IBufferView, IMaterialPbrMetallicRoughness, IMaterial, ITextureInfo, ITexture, IImage, IMeshPrimitive, IArrayItem as IArrItem, _ISamplerData } from "./glTFLoaderInterfaces";
  28. import { IGLTFLoaderExtension } from "./glTFLoaderExtension";
  29. import { IGLTFLoader, GLTFFileLoader, GLTFLoaderState, IGLTFLoaderData, GLTFLoaderCoordinateSystemMode, GLTFLoaderAnimationStartMode } from "../glTFFileLoader";
  30. import { IAnimationKey, AnimationKeyInterpolation } from 'babylonjs/Animations/animationKey';
  31. import { IAnimatable } from 'babylonjs/Animations/animatable.interface';
  32. import { IDataBuffer } from 'babylonjs/Misc/dataReader';
  33. import { LoadFileError } from 'babylonjs/Misc/fileTools';
  34. import { Logger } from 'babylonjs/Misc/logger';
  35. import { Light } from 'babylonjs/Lights/light';
  36. import { TmpVectors } from 'babylonjs/Maths/math.vector';
  37. import { BoundingInfo } from 'babylonjs/Culling/boundingInfo';
  38. import { StringTools } from 'babylonjs/Misc/stringTools';
  39. interface TypedArrayLike extends ArrayBufferView {
  40. readonly length: number;
  41. [n: number]: number;
  42. }
  43. interface TypedArrayConstructor {
  44. new(length: number): TypedArrayLike;
  45. new(buffer: ArrayBufferLike, byteOffset: number, length?: number): TypedArrayLike;
  46. }
  47. interface ILoaderProperty extends IProperty {
  48. _activeLoaderExtensionFunctions: {
  49. [id: string]: boolean
  50. };
  51. }
  52. interface IRegisteredExtension {
  53. factory: (loader: GLTFLoader) => IGLTFLoaderExtension;
  54. }
  55. /**
  56. * Helper class for working with arrays when loading the glTF asset
  57. */
  58. export class ArrayItem {
  59. /**
  60. * Gets an item from the given array.
  61. * @param context The context when loading the asset
  62. * @param array The array to get the item from
  63. * @param index The index to the array
  64. * @returns The array item
  65. */
  66. public static Get<T>(context: string, array: ArrayLike<T> | undefined, index: number | undefined): T {
  67. if (!array || index == undefined || !array[index]) {
  68. throw new Error(`${context}: Failed to find index (${index})`);
  69. }
  70. return array[index];
  71. }
  72. /**
  73. * Assign an `index` field to each item of the given array.
  74. * @param array The array of items
  75. */
  76. public static Assign(array?: IArrItem[]): void {
  77. if (array) {
  78. for (let index = 0; index < array.length; index++) {
  79. array[index].index = index;
  80. }
  81. }
  82. }
  83. }
  84. /**
  85. * The glTF 2.0 loader
  86. */
  87. export class GLTFLoader implements IGLTFLoader {
  88. /** @hidden */
  89. public _completePromises = new Array<Promise<any>>();
  90. /** @hidden */
  91. public _forAssetContainer = false;
  92. /** Storage */
  93. public _babylonLights: Light[] = [];
  94. /** @hidden */
  95. public _disableInstancedMesh = 0;
  96. private _disposed = false;
  97. private _parent: GLTFFileLoader;
  98. private _state: Nullable<GLTFLoaderState> = null;
  99. private _extensions = new Array<IGLTFLoaderExtension>();
  100. private _rootUrl: string;
  101. private _fileName: string;
  102. private _uniqueRootUrl: string;
  103. private _gltf: IGLTF;
  104. private _bin: Nullable<IDataBuffer>;
  105. private _babylonScene: Scene;
  106. private _rootBabylonMesh: Mesh;
  107. private _defaultBabylonMaterialData: { [drawMode: number]: Material } = {};
  108. private static _RegisteredExtensions: { [name: string]: IRegisteredExtension } = {};
  109. /**
  110. * The default glTF sampler.
  111. */
  112. public static readonly DefaultSampler: ISampler = { index: -1 };
  113. /**
  114. * Registers a loader extension.
  115. * @param name The name of the loader extension.
  116. * @param factory The factory function that creates the loader extension.
  117. */
  118. public static RegisterExtension(name: string, factory: (loader: GLTFLoader) => IGLTFLoaderExtension): void {
  119. if (GLTFLoader.UnregisterExtension(name)) {
  120. Logger.Warn(`Extension with the name '${name}' already exists`);
  121. }
  122. GLTFLoader._RegisteredExtensions[name] = {
  123. factory: factory
  124. };
  125. }
  126. /**
  127. * Unregisters a loader extension.
  128. * @param name The name of the loader extension.
  129. * @returns A boolean indicating whether the extension has been unregistered
  130. */
  131. public static UnregisterExtension(name: string): boolean {
  132. if (!GLTFLoader._RegisteredExtensions[name]) {
  133. return false;
  134. }
  135. delete GLTFLoader._RegisteredExtensions[name];
  136. return true;
  137. }
  138. /**
  139. * The loader state.
  140. */
  141. public get state(): Nullable<GLTFLoaderState> {
  142. return this._state;
  143. }
  144. /**
  145. * The object that represents the glTF JSON.
  146. */
  147. public get gltf(): IGLTF {
  148. return this._gltf;
  149. }
  150. /**
  151. * The BIN chunk of a binary glTF.
  152. */
  153. public get bin(): Nullable<IDataBuffer> {
  154. return this._bin;
  155. }
  156. /**
  157. * The parent file loader.
  158. */
  159. public get parent(): GLTFFileLoader {
  160. return this._parent;
  161. }
  162. /**
  163. * The Babylon scene when loading the asset.
  164. */
  165. public get babylonScene(): Scene {
  166. return this._babylonScene;
  167. }
  168. /**
  169. * The root Babylon mesh when loading the asset.
  170. */
  171. public get rootBabylonMesh(): Mesh {
  172. return this._rootBabylonMesh;
  173. }
  174. /** @hidden */
  175. constructor(parent: GLTFFileLoader) {
  176. this._parent = parent;
  177. }
  178. /** @hidden */
  179. public dispose(): void {
  180. if (this._disposed) {
  181. return;
  182. }
  183. this._disposed = true;
  184. this._completePromises.length = 0;
  185. for (const name in this._extensions) {
  186. const extension = this._extensions[name];
  187. extension.dispose && extension.dispose();
  188. delete this._extensions[name];
  189. }
  190. (this._gltf as any) = null;
  191. (this._babylonScene as any) = null;
  192. (this._rootBabylonMesh as any) = null;
  193. this._parent.dispose();
  194. }
  195. /** @hidden */
  196. public importMeshAsync(meshesNames: any, scene: Scene, forAssetContainer: boolean, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: ISceneLoaderProgressEvent) => void, fileName = ""): Promise<ISceneLoaderAsyncResult> {
  197. return Promise.resolve().then(() => {
  198. this._babylonScene = scene;
  199. this._forAssetContainer = forAssetContainer;
  200. this._loadData(data);
  201. let nodes: Nullable<Array<number>> = null;
  202. if (meshesNames) {
  203. const nodeMap: { [name: string]: number } = {};
  204. if (this._gltf.nodes) {
  205. for (const node of this._gltf.nodes) {
  206. if (node.name) {
  207. nodeMap[node.name] = node.index;
  208. }
  209. }
  210. }
  211. const names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  212. nodes = names.map((name) => {
  213. const node = nodeMap[name];
  214. if (node === undefined) {
  215. throw new Error(`Failed to find node '${name}'`);
  216. }
  217. return node;
  218. });
  219. }
  220. return this._loadAsync(rootUrl, fileName, nodes, () => {
  221. return {
  222. meshes: this._getMeshes(),
  223. particleSystems: [],
  224. skeletons: this._getSkeletons(),
  225. animationGroups: this._getAnimationGroups(),
  226. lights: this._babylonLights,
  227. transformNodes: this._getTransformNodes(),
  228. geometries: this._getGeometries()
  229. };
  230. });
  231. });
  232. }
  233. /** @hidden */
  234. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: ISceneLoaderProgressEvent) => void, fileName = ""): Promise<void> {
  235. return Promise.resolve().then(() => {
  236. this._babylonScene = scene;
  237. this._loadData(data);
  238. return this._loadAsync(rootUrl, fileName, null, () => undefined);
  239. });
  240. }
  241. private _loadAsync<T>(rootUrl: string, fileName: string, nodes: Nullable<Array<number>>, resultFunc: () => T): Promise<T> {
  242. return Promise.resolve().then(() => {
  243. this._rootUrl = rootUrl;
  244. this._uniqueRootUrl = (!StringTools.StartsWith(rootUrl, "file:") && fileName) ? rootUrl : `${rootUrl}${Date.now()}/`;
  245. this._fileName = fileName;
  246. this._loadExtensions();
  247. this._checkExtensions();
  248. const loadingToReadyCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.READY]}`;
  249. const loadingToCompleteCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.COMPLETE]}`;
  250. this._parent._startPerformanceCounter(loadingToReadyCounterName);
  251. this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  252. this._setState(GLTFLoaderState.LOADING);
  253. this._extensionsOnLoading();
  254. const promises = new Array<Promise<any>>();
  255. // Block the marking of materials dirty until the scene is loaded.
  256. const oldBlockMaterialDirtyMechanism = this._babylonScene.blockMaterialDirtyMechanism;
  257. this._babylonScene.blockMaterialDirtyMechanism = true;
  258. if (nodes) {
  259. promises.push(this.loadSceneAsync("/nodes", { nodes: nodes, index: -1 }));
  260. }
  261. else if (this._gltf.scene != undefined || (this._gltf.scenes && this._gltf.scenes[0])) {
  262. const scene = ArrayItem.Get(`/scene`, this._gltf.scenes, this._gltf.scene || 0);
  263. promises.push(this.loadSceneAsync(`/scenes/${scene.index}`, scene));
  264. }
  265. if (this.parent.loadAllMaterials && this._gltf.materials) {
  266. for (let m = 0; m < this._gltf.materials.length; ++m) {
  267. const material = this._gltf.materials[m];
  268. const context = "/materials/" + m;
  269. const babylonDrawMode = Material.TriangleFillMode;
  270. promises.push(this._loadMaterialAsync(context, material, null, babylonDrawMode, (material) => { }));
  271. }
  272. }
  273. // Restore the blocking of material dirty.
  274. this._babylonScene.blockMaterialDirtyMechanism = oldBlockMaterialDirtyMechanism;
  275. if (this._parent.compileMaterials) {
  276. promises.push(this._compileMaterialsAsync());
  277. }
  278. if (this._parent.compileShadowGenerators) {
  279. promises.push(this._compileShadowGeneratorsAsync());
  280. }
  281. const resultPromise = Promise.all(promises).then(() => {
  282. if (this._rootBabylonMesh) {
  283. this._rootBabylonMesh.setEnabled(true);
  284. }
  285. this._extensionsOnReady();
  286. this._setState(GLTFLoaderState.READY);
  287. this._startAnimations();
  288. return resultFunc();
  289. });
  290. resultPromise.then(() => {
  291. this._parent._endPerformanceCounter(loadingToReadyCounterName);
  292. Tools.SetImmediate(() => {
  293. if (!this._disposed) {
  294. Promise.all(this._completePromises).then(() => {
  295. this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  296. this._setState(GLTFLoaderState.COMPLETE);
  297. this._parent.onCompleteObservable.notifyObservers(undefined);
  298. this._parent.onCompleteObservable.clear();
  299. this.dispose();
  300. }, (error) => {
  301. this._parent.onErrorObservable.notifyObservers(error);
  302. this._parent.onErrorObservable.clear();
  303. this.dispose();
  304. });
  305. }
  306. });
  307. });
  308. return resultPromise;
  309. }).catch((error) => {
  310. if (!this._disposed) {
  311. this._parent.onErrorObservable.notifyObservers(error);
  312. this._parent.onErrorObservable.clear();
  313. this.dispose();
  314. }
  315. throw error;
  316. });
  317. }
  318. private _loadData(data: IGLTFLoaderData): void {
  319. this._gltf = data.json as IGLTF;
  320. this._setupData();
  321. if (data.bin) {
  322. const buffers = this._gltf.buffers;
  323. if (buffers && buffers[0] && !buffers[0].uri) {
  324. const binaryBuffer = buffers[0];
  325. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  326. Logger.Warn(`Binary buffer length (${binaryBuffer.byteLength}) from JSON does not match chunk length (${data.bin.byteLength})`);
  327. }
  328. this._bin = data.bin;
  329. }
  330. else {
  331. Logger.Warn("Unexpected BIN chunk");
  332. }
  333. }
  334. }
  335. private _setupData(): void {
  336. ArrayItem.Assign(this._gltf.accessors);
  337. ArrayItem.Assign(this._gltf.animations);
  338. ArrayItem.Assign(this._gltf.buffers);
  339. ArrayItem.Assign(this._gltf.bufferViews);
  340. ArrayItem.Assign(this._gltf.cameras);
  341. ArrayItem.Assign(this._gltf.images);
  342. ArrayItem.Assign(this._gltf.materials);
  343. ArrayItem.Assign(this._gltf.meshes);
  344. ArrayItem.Assign(this._gltf.nodes);
  345. ArrayItem.Assign(this._gltf.samplers);
  346. ArrayItem.Assign(this._gltf.scenes);
  347. ArrayItem.Assign(this._gltf.skins);
  348. ArrayItem.Assign(this._gltf.textures);
  349. if (this._gltf.nodes) {
  350. const nodeParents: { [index: number]: number } = {};
  351. for (const node of this._gltf.nodes) {
  352. if (node.children) {
  353. for (const index of node.children) {
  354. nodeParents[index] = node.index;
  355. }
  356. }
  357. }
  358. const rootNode = this._createRootNode();
  359. for (const node of this._gltf.nodes) {
  360. const parentIndex = nodeParents[node.index];
  361. node.parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  362. }
  363. }
  364. }
  365. private _loadExtensions(): void {
  366. for (const name in GLTFLoader._RegisteredExtensions) {
  367. const extension = GLTFLoader._RegisteredExtensions[name].factory(this);
  368. if (extension.name !== name) {
  369. Logger.Warn(`The name of the glTF loader extension instance does not match the registered name: ${extension.name} !== ${name}`);
  370. }
  371. this._extensions.push(extension);
  372. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  373. }
  374. this._extensions.sort((a, b) => (a.order || Number.MAX_VALUE) - (b.order || Number.MAX_VALUE));
  375. this._parent.onExtensionLoadedObservable.clear();
  376. }
  377. private _checkExtensions(): void {
  378. if (this._gltf.extensionsRequired) {
  379. for (const name of this._gltf.extensionsRequired) {
  380. const available = this._extensions.some((extension) => extension.name === name && extension.enabled);
  381. if (!available) {
  382. throw new Error(`Require extension ${name} is not available`);
  383. }
  384. }
  385. }
  386. }
  387. private _setState(state: GLTFLoaderState): void {
  388. this._state = state;
  389. this.log(GLTFLoaderState[this._state]);
  390. }
  391. private _createRootNode(): INode {
  392. this._babylonScene._blockEntityCollection = this._forAssetContainer;
  393. this._rootBabylonMesh = new Mesh("__root__", this._babylonScene);
  394. this._babylonScene._blockEntityCollection = false;
  395. this._rootBabylonMesh.setEnabled(false);
  396. const rootNode: INode = {
  397. _babylonTransformNode: this._rootBabylonMesh,
  398. index: -1
  399. };
  400. switch (this._parent.coordinateSystemMode) {
  401. case GLTFLoaderCoordinateSystemMode.AUTO: {
  402. if (!this._babylonScene.useRightHandedSystem) {
  403. rootNode.rotation = [0, 1, 0, 0];
  404. rootNode.scale = [1, 1, -1];
  405. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  406. }
  407. break;
  408. }
  409. case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  410. this._babylonScene.useRightHandedSystem = true;
  411. break;
  412. }
  413. default: {
  414. throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`);
  415. }
  416. }
  417. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  418. return rootNode;
  419. }
  420. /**
  421. * Loads a glTF scene.
  422. * @param context The context when loading the asset
  423. * @param scene The glTF scene property
  424. * @returns A promise that resolves when the load is complete
  425. */
  426. public loadSceneAsync(context: string, scene: IScene): Promise<void> {
  427. const extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  428. if (extensionPromise) {
  429. return extensionPromise;
  430. }
  431. const promises = new Array<Promise<any>>();
  432. this.logOpen(`${context} ${scene.name || ""}`);
  433. if (scene.nodes) {
  434. for (let index of scene.nodes) {
  435. const node = ArrayItem.Get(`${context}/nodes/${index}`, this._gltf.nodes, index);
  436. promises.push(this.loadNodeAsync(`/nodes/${node.index}`, node, (babylonMesh) => {
  437. babylonMesh.parent = this._rootBabylonMesh;
  438. }));
  439. }
  440. }
  441. // Link all Babylon bones for each glTF node with the corresponding Babylon transform node.
  442. // A glTF joint is a pointer to a glTF node in the glTF node hierarchy similar to Unity3D.
  443. if (this._gltf.nodes) {
  444. for (const node of this._gltf.nodes) {
  445. if (node._babylonTransformNode && node._babylonBones) {
  446. for (const babylonBone of node._babylonBones) {
  447. babylonBone.linkTransformNode(node._babylonTransformNode);
  448. }
  449. }
  450. }
  451. }
  452. promises.push(this._loadAnimationsAsync());
  453. this.logClose();
  454. return Promise.all(promises).then(() => { });
  455. }
  456. private _forEachPrimitive(node: INode, callback: (babylonMesh: AbstractMesh) => void): void {
  457. if (node._primitiveBabylonMeshes) {
  458. for (const babylonMesh of node._primitiveBabylonMeshes) {
  459. callback(babylonMesh);
  460. }
  461. }
  462. }
  463. private _getGeometries(): Geometry[] {
  464. const geometries = new Array<Geometry>();
  465. const nodes = this._gltf.nodes;
  466. if (nodes) {
  467. for (const node of nodes) {
  468. this._forEachPrimitive(node, (babylonMesh) => {
  469. const geometry = (babylonMesh as Mesh).geometry;
  470. if (geometry && geometries.indexOf(geometry) === -1) {
  471. geometries.push(geometry);
  472. }
  473. });
  474. }
  475. }
  476. return geometries;
  477. }
  478. private _getMeshes(): AbstractMesh[] {
  479. const meshes = new Array<AbstractMesh>();
  480. // Root mesh is always first.
  481. meshes.push(this._rootBabylonMesh);
  482. const nodes = this._gltf.nodes;
  483. if (nodes) {
  484. for (const node of nodes) {
  485. this._forEachPrimitive(node, (babylonMesh) => {
  486. meshes.push(babylonMesh);
  487. });
  488. }
  489. }
  490. return meshes;
  491. }
  492. private _getTransformNodes(): TransformNode[] {
  493. const transformNodes = new Array<TransformNode>();
  494. const nodes = this._gltf.nodes;
  495. if (nodes) {
  496. for (const node of nodes) {
  497. if (node._babylonTransformNode && node._babylonTransformNode.getClassName() === "TransformNode") {
  498. transformNodes.push(node._babylonTransformNode);
  499. }
  500. }
  501. }
  502. return transformNodes;
  503. }
  504. private _getSkeletons(): Skeleton[] {
  505. const skeletons = new Array<Skeleton>();
  506. const skins = this._gltf.skins;
  507. if (skins) {
  508. for (const skin of skins) {
  509. if (skin._data) {
  510. skeletons.push(skin._data.babylonSkeleton);
  511. }
  512. }
  513. }
  514. return skeletons;
  515. }
  516. private _getAnimationGroups(): AnimationGroup[] {
  517. const animationGroups = new Array<AnimationGroup>();
  518. const animations = this._gltf.animations;
  519. if (animations) {
  520. for (const animation of animations) {
  521. if (animation._babylonAnimationGroup) {
  522. animationGroups.push(animation._babylonAnimationGroup);
  523. }
  524. }
  525. }
  526. return animationGroups;
  527. }
  528. private _startAnimations(): void {
  529. switch (this._parent.animationStartMode) {
  530. case GLTFLoaderAnimationStartMode.NONE: {
  531. // do nothing
  532. break;
  533. }
  534. case GLTFLoaderAnimationStartMode.FIRST: {
  535. const babylonAnimationGroups = this._getAnimationGroups();
  536. if (babylonAnimationGroups.length !== 0) {
  537. babylonAnimationGroups[0].start(true);
  538. }
  539. break;
  540. }
  541. case GLTFLoaderAnimationStartMode.ALL: {
  542. const babylonAnimationGroups = this._getAnimationGroups();
  543. for (const babylonAnimationGroup of babylonAnimationGroups) {
  544. babylonAnimationGroup.start(true);
  545. }
  546. break;
  547. }
  548. default: {
  549. Logger.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);
  550. return;
  551. }
  552. }
  553. }
  554. /**
  555. * Loads a glTF node.
  556. * @param context The context when loading the asset
  557. * @param node The glTF node property
  558. * @param assign A function called synchronously after parsing the glTF properties
  559. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  560. */
  561. public loadNodeAsync(context: string, node: INode, assign: (babylonTransformNode: TransformNode) => void = () => { }): Promise<TransformNode> {
  562. const extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  563. if (extensionPromise) {
  564. return extensionPromise;
  565. }
  566. if (node._babylonTransformNode) {
  567. throw new Error(`${context}: Invalid recursive node hierarchy`);
  568. }
  569. const promises = new Array<Promise<any>>();
  570. this.logOpen(`${context} ${node.name || ""}`);
  571. const loadNode = (babylonTransformNode: TransformNode) => {
  572. GLTFLoader.AddPointerMetadata(babylonTransformNode, context);
  573. GLTFLoader._LoadTransform(node, babylonTransformNode);
  574. if (node.camera != undefined) {
  575. const camera = ArrayItem.Get(`${context}/camera`, this._gltf.cameras, node.camera);
  576. promises.push(this.loadCameraAsync(`/cameras/${camera.index}`, camera, (babylonCamera) => {
  577. babylonCamera.parent = babylonTransformNode;
  578. }));
  579. }
  580. if (node.children) {
  581. for (const index of node.children) {
  582. const childNode = ArrayItem.Get(`${context}/children/${index}`, this._gltf.nodes, index);
  583. promises.push(this.loadNodeAsync(`/nodes/${childNode.index}`, childNode, (childBabylonMesh) => {
  584. childBabylonMesh.parent = babylonTransformNode;
  585. }));
  586. }
  587. }
  588. assign(babylonTransformNode);
  589. };
  590. if (node.mesh == undefined) {
  591. const nodeName = node.name || `node${node.index}`;
  592. this._babylonScene._blockEntityCollection = this._forAssetContainer;
  593. node._babylonTransformNode = new TransformNode(nodeName, this._babylonScene);
  594. this._babylonScene._blockEntityCollection = false;
  595. loadNode(node._babylonTransformNode);
  596. }
  597. else {
  598. const mesh = ArrayItem.Get(`${context}/mesh`, this._gltf.meshes, node.mesh);
  599. promises.push(this._loadMeshAsync(`/meshes/${mesh.index}`, node, mesh, loadNode));
  600. }
  601. this.logClose();
  602. return Promise.all(promises).then(() => {
  603. this._forEachPrimitive(node, (babylonMesh) => {
  604. if ((babylonMesh as Mesh).geometry && (babylonMesh as Mesh).geometry!.useBoundingInfoFromGeometry) {
  605. // simply apply the world matrices to the bounding info - the extends are already ok
  606. babylonMesh._updateBoundingInfo();
  607. } else {
  608. babylonMesh.refreshBoundingInfo(true);
  609. }
  610. });
  611. return node._babylonTransformNode!;
  612. });
  613. }
  614. private _loadMeshAsync(context: string, node: INode, mesh: IMesh, assign: (babylonTransformNode: TransformNode) => void): Promise<TransformNode> {
  615. const primitives = mesh.primitives;
  616. if (!primitives || !primitives.length) {
  617. throw new Error(`${context}: Primitives are missing`);
  618. }
  619. if (primitives[0].index == undefined) {
  620. ArrayItem.Assign(primitives);
  621. }
  622. const promises = new Array<Promise<any>>();
  623. this.logOpen(`${context} ${mesh.name || ""}`);
  624. const name = node.name || `node${node.index}`;
  625. if (primitives.length === 1) {
  626. const primitive = mesh.primitives[0];
  627. promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, name, node, mesh, primitive, (babylonMesh) => {
  628. node._babylonTransformNode = babylonMesh;
  629. node._primitiveBabylonMeshes = [babylonMesh];
  630. }));
  631. }
  632. else {
  633. this._babylonScene._blockEntityCollection = this._forAssetContainer;
  634. node._babylonTransformNode = new TransformNode(name, this._babylonScene);
  635. this._babylonScene._blockEntityCollection = false;
  636. node._primitiveBabylonMeshes = [];
  637. for (const primitive of primitives) {
  638. promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, `${name}_primitive${primitive.index}`, node, mesh, primitive, (babylonMesh) => {
  639. babylonMesh.parent = node._babylonTransformNode!;
  640. node._primitiveBabylonMeshes!.push(babylonMesh);
  641. }));
  642. }
  643. }
  644. if (node.skin != undefined) {
  645. const skin = ArrayItem.Get(`${context}/skin`, this._gltf.skins, node.skin);
  646. promises.push(this._loadSkinAsync(`/skins/${skin.index}`, node, skin));
  647. }
  648. assign(node._babylonTransformNode!);
  649. this.logClose();
  650. return Promise.all(promises).then(() => {
  651. return node._babylonTransformNode!;
  652. });
  653. }
  654. /**
  655. * @hidden Define this method to modify the default behavior when loading data for mesh primitives.
  656. * @param context The context when loading the asset
  657. * @param name The mesh name when loading the asset
  658. * @param node The glTF node when loading the asset
  659. * @param mesh The glTF mesh when loading the asset
  660. * @param primitive The glTF mesh primitive property
  661. * @param assign A function called synchronously after parsing the glTF properties
  662. * @returns A promise that resolves with the loaded mesh when the load is complete or null if not handled
  663. */
  664. public _loadMeshPrimitiveAsync(context: string, name: string, node: INode, mesh: IMesh, primitive: IMeshPrimitive, assign: (babylonMesh: AbstractMesh) => void): Promise<AbstractMesh> {
  665. const extensionPromise = this._extensionsLoadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign);
  666. if (extensionPromise) {
  667. return extensionPromise;
  668. }
  669. this.logOpen(`${context}`);
  670. const shouldInstance = (this._disableInstancedMesh === 0) && this._parent.createInstances && (node.skin == undefined && !mesh.primitives[0].targets);
  671. let babylonAbstractMesh: AbstractMesh;
  672. let promise: Promise<any>;
  673. if (shouldInstance && primitive._instanceData) {
  674. babylonAbstractMesh = primitive._instanceData.babylonSourceMesh.createInstance(name) as InstancedMesh;
  675. promise = primitive._instanceData.promise;
  676. }
  677. else {
  678. const promises = new Array<Promise<any>>();
  679. this._babylonScene._blockEntityCollection = this._forAssetContainer;
  680. const babylonMesh = new Mesh(name, this._babylonScene);
  681. this._babylonScene._blockEntityCollection = false;
  682. babylonMesh.overrideMaterialSideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
  683. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  684. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then((babylonGeometry) => {
  685. return this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(() => {
  686. this._babylonScene._blockEntityCollection = this._forAssetContainer;
  687. babylonGeometry.applyToMesh(babylonMesh);
  688. this._babylonScene._blockEntityCollection = false;
  689. });
  690. }));
  691. const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  692. if (primitive.material == undefined) {
  693. let babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  694. if (!babylonMaterial) {
  695. babylonMaterial = this._createDefaultMaterial("__GLTFLoader._default", babylonDrawMode);
  696. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  697. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  698. }
  699. babylonMesh.material = babylonMaterial;
  700. }
  701. else {
  702. const material = ArrayItem.Get(`${context}/material`, this._gltf.materials, primitive.material);
  703. promises.push(this._loadMaterialAsync(`/materials/${material.index}`, material, babylonMesh, babylonDrawMode, (babylonMaterial) => {
  704. babylonMesh.material = babylonMaterial;
  705. }));
  706. }
  707. promise = Promise.all(promises);
  708. if (shouldInstance) {
  709. primitive._instanceData = {
  710. babylonSourceMesh: babylonMesh,
  711. promise: promise
  712. };
  713. }
  714. babylonAbstractMesh = babylonMesh;
  715. }
  716. GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context);
  717. this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh);
  718. assign(babylonAbstractMesh);
  719. this.logClose();
  720. return promise.then(() => {
  721. return babylonAbstractMesh;
  722. });
  723. }
  724. private _loadVertexDataAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh): Promise<Geometry> {
  725. const extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  726. if (extensionPromise) {
  727. return extensionPromise;
  728. }
  729. const attributes = primitive.attributes;
  730. if (!attributes) {
  731. throw new Error(`${context}: Attributes are missing`);
  732. }
  733. const promises = new Array<Promise<any>>();
  734. const babylonGeometry = new Geometry(babylonMesh.name, this._babylonScene);
  735. if (primitive.indices == undefined) {
  736. babylonMesh.isUnIndexed = true;
  737. }
  738. else {
  739. const accessor = ArrayItem.Get(`${context}/indices`, this._gltf.accessors, primitive.indices);
  740. promises.push(this._loadIndicesAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  741. babylonGeometry.setIndices(data);
  742. }));
  743. }
  744. const loadAttribute = (attribute: string, kind: string, callback?: (accessor: IAccessor) => void) => {
  745. if (attributes[attribute] == undefined) {
  746. return;
  747. }
  748. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  749. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  750. babylonMesh._delayInfo.push(kind);
  751. }
  752. const accessor = ArrayItem.Get(`${context}/attributes/${attribute}`, this._gltf.accessors, attributes[attribute]);
  753. promises.push(this._loadVertexAccessorAsync(`/accessors/${accessor.index}`, accessor, kind).then((babylonVertexBuffer) => {
  754. if (babylonVertexBuffer.getKind() === VertexBuffer.PositionKind && !this.parent.alwaysComputeBoundingBox && !babylonMesh.skeleton) {
  755. const mmin = accessor.min as [number, number, number], mmax = accessor.max as [number, number, number];
  756. if (mmin !== undefined && mmax !== undefined) {
  757. const min = TmpVectors.Vector3[0], max = TmpVectors.Vector3[1];
  758. min.copyFromFloats(...mmin);
  759. max.copyFromFloats(...mmax);
  760. babylonGeometry._boundingInfo = new BoundingInfo(min, max);
  761. babylonGeometry.useBoundingInfoFromGeometry = true;
  762. }
  763. }
  764. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  765. }));
  766. if (kind == VertexBuffer.MatricesIndicesExtraKind) {
  767. babylonMesh.numBoneInfluencers = 8;
  768. }
  769. if (callback) {
  770. callback(accessor);
  771. }
  772. };
  773. loadAttribute("POSITION", VertexBuffer.PositionKind);
  774. loadAttribute("NORMAL", VertexBuffer.NormalKind);
  775. loadAttribute("TANGENT", VertexBuffer.TangentKind);
  776. loadAttribute("TEXCOORD_0", VertexBuffer.UVKind);
  777. loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind);
  778. loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind);
  779. loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind);
  780. loadAttribute("JOINTS_1", VertexBuffer.MatricesIndicesExtraKind);
  781. loadAttribute("WEIGHTS_1", VertexBuffer.MatricesWeightsExtraKind);
  782. loadAttribute("COLOR_0", VertexBuffer.ColorKind, (accessor) => {
  783. if (accessor.type === AccessorType.VEC4) {
  784. babylonMesh.hasVertexAlpha = true;
  785. }
  786. });
  787. return Promise.all(promises).then(() => {
  788. return babylonGeometry;
  789. });
  790. }
  791. private _createMorphTargets(context: string, node: INode, mesh: IMesh, primitive: IMeshPrimitive, babylonMesh: Mesh): void {
  792. if (!primitive.targets) {
  793. return;
  794. }
  795. if (node._numMorphTargets == undefined) {
  796. node._numMorphTargets = primitive.targets.length;
  797. }
  798. else if (primitive.targets.length !== node._numMorphTargets) {
  799. throw new Error(`${context}: Primitives do not have the same number of targets`);
  800. }
  801. const targetNames = mesh.extras ? mesh.extras.targetNames : null;
  802. babylonMesh.morphTargetManager = new MorphTargetManager(babylonMesh.getScene());
  803. for (let index = 0; index < primitive.targets.length; index++) {
  804. const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  805. const name = targetNames ? targetNames[index] : `morphTarget${index}`;
  806. babylonMesh.morphTargetManager.addTarget(new MorphTarget(name, weight, babylonMesh.getScene()));
  807. // TODO: tell the target whether it has positions, normals, tangents
  808. }
  809. }
  810. private _loadMorphTargetsAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh, babylonGeometry: Geometry): Promise<void> {
  811. if (!primitive.targets) {
  812. return Promise.resolve();
  813. }
  814. const promises = new Array<Promise<any>>();
  815. const morphTargetManager = babylonMesh.morphTargetManager!;
  816. for (let index = 0; index < morphTargetManager.numTargets; index++) {
  817. const babylonMorphTarget = morphTargetManager.getTarget(index);
  818. promises.push(this._loadMorphTargetVertexDataAsync(`${context}/targets/${index}`, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  819. }
  820. return Promise.all(promises).then(() => { });
  821. }
  822. private _loadMorphTargetVertexDataAsync(context: string, babylonGeometry: Geometry, attributes: { [name: string]: number }, babylonMorphTarget: MorphTarget): Promise<void> {
  823. const promises = new Array<Promise<any>>();
  824. const loadAttribute = (attribute: string, kind: string, setData: (babylonVertexBuffer: VertexBuffer, data: Float32Array) => void) => {
  825. if (attributes[attribute] == undefined) {
  826. return;
  827. }
  828. const babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  829. if (!babylonVertexBuffer) {
  830. return;
  831. }
  832. const accessor = ArrayItem.Get(`${context}/${attribute}`, this._gltf.accessors, attributes[attribute]);
  833. promises.push(this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  834. setData(babylonVertexBuffer, data);
  835. }));
  836. };
  837. loadAttribute("POSITION", VertexBuffer.PositionKind, (babylonVertexBuffer, data) => {
  838. const positions = new Float32Array(data.length);
  839. babylonVertexBuffer.forEach(data.length, (value, index) => {
  840. positions[index] = data[index] + value;
  841. });
  842. babylonMorphTarget.setPositions(positions);
  843. });
  844. loadAttribute("NORMAL", VertexBuffer.NormalKind, (babylonVertexBuffer, data) => {
  845. const normals = new Float32Array(data.length);
  846. babylonVertexBuffer.forEach(normals.length, (value, index) => {
  847. normals[index] = data[index] + value;
  848. });
  849. babylonMorphTarget.setNormals(normals);
  850. });
  851. loadAttribute("TANGENT", VertexBuffer.TangentKind, (babylonVertexBuffer, data) => {
  852. const tangents = new Float32Array(data.length / 3 * 4);
  853. let dataIndex = 0;
  854. babylonVertexBuffer.forEach(data.length / 3 * 4, (value, index) => {
  855. // Tangent data for morph targets is stored as xyz delta.
  856. // The vertexData.tangent is stored as xyzw.
  857. // So we need to skip every fourth vertexData.tangent.
  858. if (((index + 1) % 4) !== 0) {
  859. tangents[dataIndex] = data[dataIndex] + value;
  860. dataIndex++;
  861. }
  862. });
  863. babylonMorphTarget.setTangents(tangents);
  864. });
  865. return Promise.all(promises).then(() => { });
  866. }
  867. private static _LoadTransform(node: INode, babylonNode: TransformNode): void {
  868. // Ignore the TRS of skinned nodes.
  869. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  870. if (node.skin != undefined) {
  871. return;
  872. }
  873. let position = Vector3.Zero();
  874. let rotation = Quaternion.Identity();
  875. let scaling = Vector3.One();
  876. if (node.matrix) {
  877. const matrix = Matrix.FromArray(node.matrix);
  878. matrix.decompose(scaling, rotation, position);
  879. }
  880. else {
  881. if (node.translation) { position = Vector3.FromArray(node.translation); }
  882. if (node.rotation) { rotation = Quaternion.FromArray(node.rotation); }
  883. if (node.scale) { scaling = Vector3.FromArray(node.scale); }
  884. }
  885. babylonNode.position = position;
  886. babylonNode.rotationQuaternion = rotation;
  887. babylonNode.scaling = scaling;
  888. }
  889. private _loadSkinAsync(context: string, node: INode, skin: ISkin): Promise<void> {
  890. const extensionPromise = this._extensionsLoadSkinAsync(context, node, skin);
  891. if (extensionPromise) {
  892. return extensionPromise;
  893. }
  894. const assignSkeleton = (skeleton: Skeleton) => {
  895. this._forEachPrimitive(node, (babylonMesh) => {
  896. babylonMesh.skeleton = skeleton;
  897. });
  898. };
  899. if (skin._data) {
  900. assignSkeleton(skin._data.babylonSkeleton);
  901. return skin._data.promise;
  902. }
  903. const skeletonId = `skeleton${skin.index}`;
  904. this._babylonScene._blockEntityCollection = this._forAssetContainer;
  905. const babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  906. this._babylonScene._blockEntityCollection = false;
  907. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  908. babylonSkeleton.overrideMesh = this._rootBabylonMesh;
  909. this._loadBones(context, skin, babylonSkeleton);
  910. assignSkeleton(babylonSkeleton);
  911. const promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then((inverseBindMatricesData) => {
  912. this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  913. });
  914. skin._data = {
  915. babylonSkeleton: babylonSkeleton,
  916. promise: promise
  917. };
  918. return promise;
  919. }
  920. private _loadBones(context: string, skin: ISkin, babylonSkeleton: Skeleton): void {
  921. const babylonBones: { [index: number]: Bone } = {};
  922. for (const index of skin.joints) {
  923. const node = ArrayItem.Get(`${context}/joints/${index}`, this._gltf.nodes, index);
  924. this._loadBone(node, skin, babylonSkeleton, babylonBones);
  925. }
  926. }
  927. private _loadBone(node: INode, skin: ISkin, babylonSkeleton: Skeleton, babylonBones: { [index: number]: Bone }): Bone {
  928. let babylonBone = babylonBones[node.index];
  929. if (babylonBone) {
  930. return babylonBone;
  931. }
  932. let babylonParentBone: Nullable<Bone> = null;
  933. if (node.parent && node.parent._babylonTransformNode !== this._rootBabylonMesh) {
  934. babylonParentBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones);
  935. }
  936. const boneIndex = skin.joints.indexOf(node.index);
  937. babylonBone = new Bone(node.name || `joint${node.index}`, babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  938. babylonBones[node.index] = babylonBone;
  939. node._babylonBones = node._babylonBones || [];
  940. node._babylonBones.push(babylonBone);
  941. return babylonBone;
  942. }
  943. private _loadSkinInverseBindMatricesDataAsync(context: string, skin: ISkin): Promise<Nullable<Float32Array>> {
  944. if (skin.inverseBindMatrices == undefined) {
  945. return Promise.resolve(null);
  946. }
  947. const accessor = ArrayItem.Get(`${context}/inverseBindMatrices`, this._gltf.accessors, skin.inverseBindMatrices);
  948. return this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor);
  949. }
  950. private _updateBoneMatrices(babylonSkeleton: Skeleton, inverseBindMatricesData: Nullable<Float32Array>): void {
  951. for (const babylonBone of babylonSkeleton.bones) {
  952. let baseMatrix = Matrix.Identity();
  953. const boneIndex = babylonBone._index!;
  954. if (inverseBindMatricesData && boneIndex !== -1) {
  955. Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  956. baseMatrix.invertToRef(baseMatrix);
  957. }
  958. const babylonParentBone = babylonBone.getParent();
  959. if (babylonParentBone) {
  960. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  961. }
  962. babylonBone.setBindPose(baseMatrix);
  963. babylonBone.updateMatrix(baseMatrix, false, false);
  964. babylonBone._updateDifferenceMatrix(undefined, false);
  965. }
  966. }
  967. private _getNodeMatrix(node: INode): Matrix {
  968. return node.matrix ?
  969. Matrix.FromArray(node.matrix) :
  970. Matrix.Compose(
  971. node.scale ? Vector3.FromArray(node.scale) : Vector3.One(),
  972. node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(),
  973. node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());
  974. }
  975. /**
  976. * Loads a glTF camera.
  977. * @param context The context when loading the asset
  978. * @param camera The glTF camera property
  979. * @param assign A function called synchronously after parsing the glTF properties
  980. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  981. */
  982. public loadCameraAsync(context: string, camera: ICamera, assign: (babylonCamera: Camera) => void = () => { }): Promise<Camera> {
  983. const extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  984. if (extensionPromise) {
  985. return extensionPromise;
  986. }
  987. const promises = new Array<Promise<any>>();
  988. this.logOpen(`${context} ${camera.name || ""}`);
  989. this._babylonScene._blockEntityCollection = this._forAssetContainer;
  990. const babylonCamera = new TargetCamera(camera.name || `camera${camera.index}`, Vector3.Zero(), this._babylonScene, false);
  991. this._babylonScene._blockEntityCollection = false;
  992. babylonCamera.ignoreParentScaling = true;
  993. babylonCamera.rotation = new Vector3(0, Math.PI, 0);
  994. switch (camera.type) {
  995. case CameraType.PERSPECTIVE: {
  996. const perspective = camera.perspective;
  997. if (!perspective) {
  998. throw new Error(`${context}: Camera perspective properties are missing`);
  999. }
  1000. babylonCamera.fov = perspective.yfov;
  1001. babylonCamera.minZ = perspective.znear;
  1002. babylonCamera.maxZ = perspective.zfar || 0;
  1003. break;
  1004. }
  1005. case CameraType.ORTHOGRAPHIC: {
  1006. if (!camera.orthographic) {
  1007. throw new Error(`${context}: Camera orthographic properties are missing`);
  1008. }
  1009. babylonCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  1010. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  1011. babylonCamera.orthoRight = camera.orthographic.xmag;
  1012. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  1013. babylonCamera.orthoTop = camera.orthographic.ymag;
  1014. babylonCamera.minZ = camera.orthographic.znear;
  1015. babylonCamera.maxZ = camera.orthographic.zfar;
  1016. break;
  1017. }
  1018. default: {
  1019. throw new Error(`${context}: Invalid camera type (${camera.type})`);
  1020. }
  1021. }
  1022. GLTFLoader.AddPointerMetadata(babylonCamera, context);
  1023. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  1024. assign(babylonCamera);
  1025. this.logClose();
  1026. return Promise.all(promises).then(() => {
  1027. return babylonCamera;
  1028. });
  1029. }
  1030. private _loadAnimationsAsync(): Promise<void> {
  1031. const animations = this._gltf.animations;
  1032. if (!animations) {
  1033. return Promise.resolve();
  1034. }
  1035. const promises = new Array<Promise<void>>();
  1036. for (let index = 0; index < animations.length; index++) {
  1037. const animation = animations[index];
  1038. promises.push(this.loadAnimationAsync(`/animations/${animation.index}`, animation).then((animationGroup) => {
  1039. // Delete the animation group if it ended up not having any animations in it.
  1040. if (animationGroup.targetedAnimations.length === 0) {
  1041. animationGroup.dispose();
  1042. }
  1043. }));
  1044. }
  1045. return Promise.all(promises).then(() => { });
  1046. }
  1047. /**
  1048. * Loads a glTF animation.
  1049. * @param context The context when loading the asset
  1050. * @param animation The glTF animation property
  1051. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  1052. */
  1053. public loadAnimationAsync(context: string, animation: IAnimation): Promise<AnimationGroup> {
  1054. const promise = this._extensionsLoadAnimationAsync(context, animation);
  1055. if (promise) {
  1056. return promise;
  1057. }
  1058. this._babylonScene._blockEntityCollection = this._forAssetContainer;
  1059. const babylonAnimationGroup = new AnimationGroup(animation.name || `animation${animation.index}`, this._babylonScene);
  1060. this._babylonScene._blockEntityCollection = false;
  1061. animation._babylonAnimationGroup = babylonAnimationGroup;
  1062. const promises = new Array<Promise<any>>();
  1063. ArrayItem.Assign(animation.channels);
  1064. ArrayItem.Assign(animation.samplers);
  1065. for (const channel of animation.channels) {
  1066. promises.push(this._loadAnimationChannelAsync(`${context}/channels/${channel.index}`, context, animation, channel, babylonAnimationGroup));
  1067. }
  1068. return Promise.all(promises).then(() => {
  1069. babylonAnimationGroup.normalize(0);
  1070. return babylonAnimationGroup;
  1071. });
  1072. }
  1073. /**
  1074. * @hidden Loads a glTF animation channel.
  1075. * @param context The context when loading the asset
  1076. * @param animationContext The context of the animation when loading the asset
  1077. * @param animation The glTF animation property
  1078. * @param channel The glTF animation channel property
  1079. * @param babylonAnimationGroup The babylon animation group property
  1080. * @param animationTargetOverride The babylon animation channel target override property. My be null.
  1081. * @returns A void promise when the channel load is complete
  1082. */
  1083. public _loadAnimationChannelAsync(context: string, animationContext: string, animation: IAnimation, channel: IAnimationChannel, babylonAnimationGroup: AnimationGroup, animationTargetOverride: Nullable<IAnimatable> = null): Promise<void> {
  1084. if (channel.target.node == undefined) {
  1085. return Promise.resolve();
  1086. }
  1087. const targetNode = ArrayItem.Get(`${context}/target/node`, this._gltf.nodes, channel.target.node);
  1088. // Ignore animations that have no animation targets.
  1089. if ((channel.target.path === AnimationChannelTargetPath.WEIGHTS && !targetNode._numMorphTargets) ||
  1090. (channel.target.path !== AnimationChannelTargetPath.WEIGHTS && !targetNode._babylonTransformNode)) {
  1091. return Promise.resolve();
  1092. }
  1093. const sampler = ArrayItem.Get(`${context}/sampler`, animation.samplers, channel.sampler);
  1094. return this._loadAnimationSamplerAsync(`${animationContext}/samplers/${channel.sampler}`, sampler).then((data) => {
  1095. let targetPath: string;
  1096. let animationType: number;
  1097. switch (channel.target.path) {
  1098. case AnimationChannelTargetPath.TRANSLATION: {
  1099. targetPath = "position";
  1100. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  1101. break;
  1102. }
  1103. case AnimationChannelTargetPath.ROTATION: {
  1104. targetPath = "rotationQuaternion";
  1105. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  1106. break;
  1107. }
  1108. case AnimationChannelTargetPath.SCALE: {
  1109. targetPath = "scaling";
  1110. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  1111. break;
  1112. }
  1113. case AnimationChannelTargetPath.WEIGHTS: {
  1114. targetPath = "influence";
  1115. animationType = Animation.ANIMATIONTYPE_FLOAT;
  1116. break;
  1117. }
  1118. default: {
  1119. throw new Error(`${context}/target/path: Invalid value (${channel.target.path})`);
  1120. }
  1121. }
  1122. let outputBufferOffset = 0;
  1123. let getNextOutputValue: () => Vector3 | Quaternion | Array<number>;
  1124. switch (targetPath) {
  1125. case "position": {
  1126. getNextOutputValue = () => {
  1127. const value = Vector3.FromArray(data.output, outputBufferOffset);
  1128. outputBufferOffset += 3;
  1129. return value;
  1130. };
  1131. break;
  1132. }
  1133. case "rotationQuaternion": {
  1134. getNextOutputValue = () => {
  1135. const value = Quaternion.FromArray(data.output, outputBufferOffset);
  1136. outputBufferOffset += 4;
  1137. return value;
  1138. };
  1139. break;
  1140. }
  1141. case "scaling": {
  1142. getNextOutputValue = () => {
  1143. const value = Vector3.FromArray(data.output, outputBufferOffset);
  1144. outputBufferOffset += 3;
  1145. return value;
  1146. };
  1147. break;
  1148. }
  1149. case "influence": {
  1150. getNextOutputValue = () => {
  1151. const value = new Array<number>(targetNode._numMorphTargets!);
  1152. for (let i = 0; i < targetNode._numMorphTargets!; i++) {
  1153. value[i] = data.output[outputBufferOffset++];
  1154. }
  1155. return value;
  1156. };
  1157. break;
  1158. }
  1159. }
  1160. let getNextKey: (frameIndex: number) => IAnimationKey;
  1161. switch (data.interpolation) {
  1162. case AnimationSamplerInterpolation.STEP: {
  1163. getNextKey = (frameIndex) => ({
  1164. frame: data.input[frameIndex],
  1165. value: getNextOutputValue(),
  1166. interpolation: AnimationKeyInterpolation.STEP
  1167. });
  1168. break;
  1169. }
  1170. case AnimationSamplerInterpolation.LINEAR: {
  1171. getNextKey = (frameIndex) => ({
  1172. frame: data.input[frameIndex],
  1173. value: getNextOutputValue()
  1174. });
  1175. break;
  1176. }
  1177. case AnimationSamplerInterpolation.CUBICSPLINE: {
  1178. getNextKey = (frameIndex) => ({
  1179. frame: data.input[frameIndex],
  1180. inTangent: getNextOutputValue(),
  1181. value: getNextOutputValue(),
  1182. outTangent: getNextOutputValue()
  1183. });
  1184. break;
  1185. }
  1186. }
  1187. const keys = new Array(data.input.length);
  1188. for (let frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  1189. keys[frameIndex] = getNextKey!(frameIndex);
  1190. }
  1191. if (targetPath === "influence") {
  1192. for (let targetIndex = 0; targetIndex < targetNode._numMorphTargets!; targetIndex++) {
  1193. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  1194. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  1195. babylonAnimation.setKeys(keys.map((key) => ({
  1196. frame: key.frame,
  1197. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1198. value: key.value[targetIndex],
  1199. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1200. })));
  1201. this._forEachPrimitive(targetNode, (babylonAbstractMesh: AbstractMesh) => {
  1202. const babylonMesh = babylonAbstractMesh as Mesh;
  1203. const morphTarget = babylonMesh.morphTargetManager!.getTarget(targetIndex);
  1204. const babylonAnimationClone = babylonAnimation.clone();
  1205. morphTarget.animations.push(babylonAnimationClone);
  1206. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  1207. });
  1208. }
  1209. }
  1210. else {
  1211. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  1212. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  1213. babylonAnimation.setKeys(keys);
  1214. if (animationTargetOverride != null && animationTargetOverride.animations != null) {
  1215. animationTargetOverride.animations.push(babylonAnimation);
  1216. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, animationTargetOverride);
  1217. } else {
  1218. targetNode._babylonTransformNode!.animations.push(babylonAnimation);
  1219. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonTransformNode!);
  1220. }
  1221. }
  1222. });
  1223. }
  1224. private _loadAnimationSamplerAsync(context: string, sampler: IAnimationSampler): Promise<_IAnimationSamplerData> {
  1225. if (sampler._data) {
  1226. return sampler._data;
  1227. }
  1228. const interpolation = sampler.interpolation || AnimationSamplerInterpolation.LINEAR;
  1229. switch (interpolation) {
  1230. case AnimationSamplerInterpolation.STEP:
  1231. case AnimationSamplerInterpolation.LINEAR:
  1232. case AnimationSamplerInterpolation.CUBICSPLINE: {
  1233. break;
  1234. }
  1235. default: {
  1236. throw new Error(`${context}/interpolation: Invalid value (${sampler.interpolation})`);
  1237. }
  1238. }
  1239. const inputAccessor = ArrayItem.Get(`${context}/input`, this._gltf.accessors, sampler.input);
  1240. const outputAccessor = ArrayItem.Get(`${context}/output`, this._gltf.accessors, sampler.output);
  1241. sampler._data = Promise.all([
  1242. this._loadFloatAccessorAsync(`/accessors/${inputAccessor.index}`, inputAccessor),
  1243. this._loadFloatAccessorAsync(`/accessors/${outputAccessor.index}`, outputAccessor)
  1244. ]).then(([inputData, outputData]) => {
  1245. return {
  1246. input: inputData,
  1247. interpolation: interpolation,
  1248. output: outputData,
  1249. };
  1250. });
  1251. return sampler._data;
  1252. }
  1253. /**
  1254. * Loads a glTF buffer.
  1255. * @param context The context when loading the asset
  1256. * @param buffer The glTF buffer property
  1257. * @param byteOffset The byte offset to use
  1258. * @param byteLength The byte length to use
  1259. * @returns A promise that resolves with the loaded data when the load is complete
  1260. */
  1261. public loadBufferAsync(context: string, buffer: IBuffer, byteOffset: number, byteLength: number): Promise<ArrayBufferView> {
  1262. const extensionPromise = this._extensionsLoadBufferAsync(context, buffer, byteOffset, byteLength);
  1263. if (extensionPromise) {
  1264. return extensionPromise;
  1265. }
  1266. if (!buffer._data) {
  1267. if (buffer.uri) {
  1268. buffer._data = this.loadUriAsync(`${context}/uri`, buffer, buffer.uri);
  1269. }
  1270. else {
  1271. if (!this._bin) {
  1272. throw new Error(`${context}: Uri is missing or the binary glTF is missing its binary chunk`);
  1273. }
  1274. buffer._data = this._bin.readAsync(0, buffer.byteLength);
  1275. }
  1276. }
  1277. return buffer._data.then((data) => {
  1278. try {
  1279. return new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  1280. }
  1281. catch (e) {
  1282. throw new Error(`${context}: ${e.message}`);
  1283. }
  1284. });
  1285. }
  1286. /**
  1287. * Loads a glTF buffer view.
  1288. * @param context The context when loading the asset
  1289. * @param bufferView The glTF buffer view property
  1290. * @returns A promise that resolves with the loaded data when the load is complete
  1291. */
  1292. public loadBufferViewAsync(context: string, bufferView: IBufferView): Promise<ArrayBufferView> {
  1293. const extensionPromise = this._extensionsLoadBufferViewAsync(context, bufferView);
  1294. if (extensionPromise) {
  1295. return extensionPromise;
  1296. }
  1297. if (bufferView._data) {
  1298. return bufferView._data;
  1299. }
  1300. const buffer = ArrayItem.Get(`${context}/buffer`, this._gltf.buffers, bufferView.buffer);
  1301. bufferView._data = this.loadBufferAsync(`/buffers/${buffer.index}`, buffer, (bufferView.byteOffset || 0), bufferView.byteLength);
  1302. return bufferView._data;
  1303. }
  1304. private _loadAccessorAsync(context: string, accessor: IAccessor, constructor: TypedArrayConstructor): Promise<ArrayBufferView> {
  1305. if (accessor._data) {
  1306. return accessor._data;
  1307. }
  1308. const numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1309. const byteStride = numComponents * VertexBuffer.GetTypeByteLength(accessor.componentType);
  1310. const length = numComponents * accessor.count;
  1311. if (accessor.bufferView == undefined) {
  1312. accessor._data = Promise.resolve(new constructor(length));
  1313. }
  1314. else {
  1315. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  1316. accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
  1317. if (accessor.componentType === AccessorComponentType.FLOAT && !accessor.normalized && (!bufferView.byteStride || bufferView.byteStride === byteStride)) {
  1318. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  1319. }
  1320. else {
  1321. const typedArray = new constructor(length);
  1322. VertexBuffer.ForEach(data, accessor.byteOffset || 0, bufferView.byteStride || byteStride, numComponents, accessor.componentType, typedArray.length, accessor.normalized || false, (value, index) => {
  1323. typedArray[index] = value;
  1324. });
  1325. return typedArray;
  1326. }
  1327. });
  1328. }
  1329. if (accessor.sparse) {
  1330. const sparse = accessor.sparse;
  1331. accessor._data = accessor._data.then((data) => {
  1332. const typedArray = data as TypedArrayLike;
  1333. const indicesBufferView = ArrayItem.Get(`${context}/sparse/indices/bufferView`, this._gltf.bufferViews, sparse.indices.bufferView);
  1334. const valuesBufferView = ArrayItem.Get(`${context}/sparse/values/bufferView`, this._gltf.bufferViews, sparse.values.bufferView);
  1335. return Promise.all([
  1336. this.loadBufferViewAsync(`/bufferViews/${indicesBufferView.index}`, indicesBufferView),
  1337. this.loadBufferViewAsync(`/bufferViews/${valuesBufferView.index}`, valuesBufferView)
  1338. ]).then(([indicesData, valuesData]) => {
  1339. const indices = GLTFLoader._GetTypedArray(`${context}/sparse/indices`, sparse.indices.componentType, indicesData, sparse.indices.byteOffset, sparse.count) as IndicesArray;
  1340. const sparseLength = numComponents * sparse.count;
  1341. let values: TypedArrayLike;
  1342. if (accessor.componentType === AccessorComponentType.FLOAT && !accessor.normalized) {
  1343. values = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, sparseLength);
  1344. }
  1345. else {
  1346. const sparseData = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, sparseLength);
  1347. values = new constructor(sparseLength);
  1348. VertexBuffer.ForEach(sparseData, 0, byteStride, numComponents, accessor.componentType, values.length, accessor.normalized || false, (value, index) => {
  1349. values[index] = value;
  1350. });
  1351. }
  1352. let valuesIndex = 0;
  1353. for (let indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  1354. let dataIndex = indices[indicesIndex] * numComponents;
  1355. for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1356. typedArray[dataIndex++] = values[valuesIndex++];
  1357. }
  1358. }
  1359. return typedArray;
  1360. });
  1361. });
  1362. }
  1363. return accessor._data;
  1364. }
  1365. /** @hidden */
  1366. public _loadFloatAccessorAsync(context: string, accessor: IAccessor): Promise<Float32Array> {
  1367. return this._loadAccessorAsync(context, accessor, Float32Array) as Promise<Float32Array>;
  1368. }
  1369. private _loadIndicesAccessorAsync(context: string, accessor: IAccessor): Promise<IndicesArray> {
  1370. if (accessor.type !== AccessorType.SCALAR) {
  1371. throw new Error(`${context}/type: Invalid value ${accessor.type}`);
  1372. }
  1373. if (accessor.componentType !== AccessorComponentType.UNSIGNED_BYTE &&
  1374. accessor.componentType !== AccessorComponentType.UNSIGNED_SHORT &&
  1375. accessor.componentType !== AccessorComponentType.UNSIGNED_INT) {
  1376. throw new Error(`${context}/componentType: Invalid value ${accessor.componentType}`);
  1377. }
  1378. if (accessor._data) {
  1379. return accessor._data as Promise<IndicesArray>;
  1380. }
  1381. if (accessor.sparse) {
  1382. const constructor = GLTFLoader._GetTypedArrayConstructor(`${context}/componentType`, accessor.componentType);
  1383. accessor._data = this._loadAccessorAsync(context, accessor, constructor);
  1384. }
  1385. else {
  1386. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  1387. accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
  1388. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  1389. });
  1390. }
  1391. return accessor._data as Promise<IndicesArray>;
  1392. }
  1393. private _loadVertexBufferViewAsync(bufferView: IBufferView, kind: string): Promise<Buffer> {
  1394. if (bufferView._babylonBuffer) {
  1395. return bufferView._babylonBuffer;
  1396. }
  1397. bufferView._babylonBuffer = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {
  1398. return new Buffer(this._babylonScene.getEngine(), data, false);
  1399. });
  1400. return bufferView._babylonBuffer;
  1401. }
  1402. private _loadVertexAccessorAsync(context: string, accessor: IAccessor, kind: string): Promise<VertexBuffer> {
  1403. if (accessor._babylonVertexBuffer) {
  1404. return accessor._babylonVertexBuffer;
  1405. }
  1406. if (accessor.sparse) {
  1407. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  1408. return new VertexBuffer(this._babylonScene.getEngine(), data, kind, false);
  1409. });
  1410. }
  1411. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  1412. else if (accessor.byteOffset && accessor.byteOffset % VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  1413. Logger.Warn("Accessor byte offset is not a multiple of component type byte length");
  1414. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  1415. return new VertexBuffer(this._babylonScene.getEngine(), data, kind, false);
  1416. });
  1417. }
  1418. // Load joint indices as a float array since the shaders expect float data but glTF uses unsigned byte/short.
  1419. // This prevents certain platforms (e.g. D3D) from having to convert the data to float on the fly.
  1420. else if (kind === VertexBuffer.MatricesIndicesKind || kind === VertexBuffer.MatricesIndicesExtraKind) {
  1421. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {
  1422. return new VertexBuffer(this._babylonScene.getEngine(), data, kind, false);
  1423. });
  1424. }
  1425. else {
  1426. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);
  1427. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView, kind).then((babylonBuffer) => {
  1428. const size = GLTFLoader._GetNumComponents(context, accessor.type);
  1429. return new VertexBuffer(this._babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView.byteStride,
  1430. false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true, 1, true);
  1431. });
  1432. }
  1433. return accessor._babylonVertexBuffer;
  1434. }
  1435. private _loadMaterialMetallicRoughnessPropertiesAsync(context: string, properties: IMaterialPbrMetallicRoughness, babylonMaterial: Material): Promise<void> {
  1436. if (!(babylonMaterial instanceof PBRMaterial)) {
  1437. throw new Error(`${context}: Material type not supported`);
  1438. }
  1439. const promises = new Array<Promise<any>>();
  1440. if (properties) {
  1441. if (properties.baseColorFactor) {
  1442. babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);
  1443. babylonMaterial.alpha = properties.baseColorFactor[3];
  1444. }
  1445. else {
  1446. babylonMaterial.albedoColor = Color3.White();
  1447. }
  1448. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1449. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1450. if (properties.baseColorTexture) {
  1451. promises.push(this.loadTextureInfoAsync(`${context}/baseColorTexture`, properties.baseColorTexture, (texture) => {
  1452. texture.name = `${babylonMaterial.name} (Base Color)`;
  1453. babylonMaterial.albedoTexture = texture;
  1454. }));
  1455. }
  1456. if (properties.metallicRoughnessTexture) {
  1457. properties.metallicRoughnessTexture.nonColorData = true;
  1458. promises.push(this.loadTextureInfoAsync(`${context}/metallicRoughnessTexture`, properties.metallicRoughnessTexture, (texture) => {
  1459. texture.name = `${babylonMaterial.name} (Metallic Roughness)`;
  1460. babylonMaterial.metallicTexture = texture;
  1461. }));
  1462. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1463. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1464. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1465. }
  1466. }
  1467. return Promise.all(promises).then(() => { });
  1468. }
  1469. /** @hidden */
  1470. public _loadMaterialAsync(context: string, material: IMaterial, babylonMesh: Nullable<Mesh>, babylonDrawMode: number, assign: (babylonMaterial: Material) => void = () => { }): Promise<Material> {
  1471. const extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  1472. if (extensionPromise) {
  1473. return extensionPromise;
  1474. }
  1475. material._data = material._data || {};
  1476. let babylonData = material._data[babylonDrawMode];
  1477. if (!babylonData) {
  1478. this.logOpen(`${context} ${material.name || ""}`);
  1479. const babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  1480. babylonData = {
  1481. babylonMaterial: babylonMaterial,
  1482. babylonMeshes: [],
  1483. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  1484. };
  1485. material._data[babylonDrawMode] = babylonData;
  1486. GLTFLoader.AddPointerMetadata(babylonMaterial, context);
  1487. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1488. this.logClose();
  1489. }
  1490. if (babylonMesh) {
  1491. babylonData.babylonMeshes.push(babylonMesh);
  1492. babylonMesh.onDisposeObservable.addOnce(() => {
  1493. const index = babylonData.babylonMeshes.indexOf(babylonMesh);
  1494. if (index !== -1) {
  1495. babylonData.babylonMeshes.splice(index, 1);
  1496. }
  1497. });
  1498. }
  1499. assign(babylonData.babylonMaterial);
  1500. return babylonData.promise.then(() => {
  1501. return babylonData.babylonMaterial;
  1502. });
  1503. }
  1504. private _createDefaultMaterial(name: string, babylonDrawMode: number): Material {
  1505. this._babylonScene._blockEntityCollection = this._forAssetContainer;
  1506. const babylonMaterial = new PBRMaterial(name, this._babylonScene);
  1507. this._babylonScene._blockEntityCollection = false;
  1508. // Moved to mesh so user can change materials on gltf meshes: babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
  1509. babylonMaterial.fillMode = babylonDrawMode;
  1510. babylonMaterial.enableSpecularAntiAliasing = true;
  1511. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  1512. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  1513. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1514. babylonMaterial.metallic = 1;
  1515. babylonMaterial.roughness = 1;
  1516. return babylonMaterial;
  1517. }
  1518. /**
  1519. * Creates a Babylon material from a glTF material.
  1520. * @param context The context when loading the asset
  1521. * @param material The glTF material property
  1522. * @param babylonDrawMode The draw mode for the Babylon material
  1523. * @returns The Babylon material
  1524. */
  1525. public createMaterial(context: string, material: IMaterial, babylonDrawMode: number): Material {
  1526. const extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  1527. if (extensionPromise) {
  1528. return extensionPromise;
  1529. }
  1530. const name = material.name || `material${material.index}`;
  1531. const babylonMaterial = this._createDefaultMaterial(name, babylonDrawMode);
  1532. return babylonMaterial;
  1533. }
  1534. /**
  1535. * Loads properties from a glTF material into a Babylon material.
  1536. * @param context The context when loading the asset
  1537. * @param material The glTF material property
  1538. * @param babylonMaterial The Babylon material
  1539. * @returns A promise that resolves when the load is complete
  1540. */
  1541. public loadMaterialPropertiesAsync(context: string, material: IMaterial, babylonMaterial: Material): Promise<void> {
  1542. const extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  1543. if (extensionPromise) {
  1544. return extensionPromise;
  1545. }
  1546. const promises = new Array<Promise<any>>();
  1547. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  1548. if (material.pbrMetallicRoughness) {
  1549. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${context}/pbrMetallicRoughness`, material.pbrMetallicRoughness, babylonMaterial));
  1550. }
  1551. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  1552. return Promise.all(promises).then(() => { });
  1553. }
  1554. /**
  1555. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  1556. * @param context The context when loading the asset
  1557. * @param material The glTF material property
  1558. * @param babylonMaterial The Babylon material
  1559. * @returns A promise that resolves when the load is complete
  1560. */
  1561. public loadMaterialBasePropertiesAsync(context: string, material: IMaterial, babylonMaterial: Material): Promise<void> {
  1562. if (!(babylonMaterial instanceof PBRMaterial)) {
  1563. throw new Error(`${context}: Material type not supported`);
  1564. }
  1565. const promises = new Array<Promise<any>>();
  1566. babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  1567. if (material.doubleSided) {
  1568. babylonMaterial.backFaceCulling = false;
  1569. babylonMaterial.twoSidedLighting = true;
  1570. }
  1571. if (material.normalTexture) {
  1572. material.normalTexture.nonColorData = true;
  1573. promises.push(this.loadTextureInfoAsync(`${context}/normalTexture`, material.normalTexture, (texture) => {
  1574. texture.name = `${babylonMaterial.name} (Normal)`;
  1575. babylonMaterial.bumpTexture = texture;
  1576. }));
  1577. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1578. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1579. if (material.normalTexture.scale != undefined) {
  1580. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1581. }
  1582. babylonMaterial.forceIrradianceInFragment = true;
  1583. }
  1584. if (material.occlusionTexture) {
  1585. material.occlusionTexture.nonColorData = true;
  1586. promises.push(this.loadTextureInfoAsync(`${context}/occlusionTexture`, material.occlusionTexture, (texture) => {
  1587. texture.name = `${babylonMaterial.name} (Occlusion)`;
  1588. babylonMaterial.ambientTexture = texture;
  1589. }));
  1590. babylonMaterial.useAmbientInGrayScale = true;
  1591. if (material.occlusionTexture.strength != undefined) {
  1592. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1593. }
  1594. }
  1595. if (material.emissiveTexture) {
  1596. promises.push(this.loadTextureInfoAsync(`${context}/emissiveTexture`, material.emissiveTexture, (texture) => {
  1597. texture.name = `${babylonMaterial.name} (Emissive)`;
  1598. babylonMaterial.emissiveTexture = texture;
  1599. }));
  1600. }
  1601. return Promise.all(promises).then(() => { });
  1602. }
  1603. /**
  1604. * Loads the alpha properties from a glTF material into a Babylon material.
  1605. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  1606. * @param context The context when loading the asset
  1607. * @param material The glTF material property
  1608. * @param babylonMaterial The Babylon material
  1609. */
  1610. public loadMaterialAlphaProperties(context: string, material: IMaterial, babylonMaterial: Material): void {
  1611. if (!(babylonMaterial instanceof PBRMaterial)) {
  1612. throw new Error(`${context}: Material type not supported`);
  1613. }
  1614. const alphaMode = material.alphaMode || MaterialAlphaMode.OPAQUE;
  1615. switch (alphaMode) {
  1616. case MaterialAlphaMode.OPAQUE: {
  1617. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1618. break;
  1619. }
  1620. case MaterialAlphaMode.MASK: {
  1621. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;
  1622. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  1623. if (babylonMaterial.albedoTexture) {
  1624. babylonMaterial.albedoTexture.hasAlpha = true;
  1625. }
  1626. break;
  1627. }
  1628. case MaterialAlphaMode.BLEND: {
  1629. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1630. if (babylonMaterial.albedoTexture) {
  1631. babylonMaterial.albedoTexture.hasAlpha = true;
  1632. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1633. }
  1634. break;
  1635. }
  1636. default: {
  1637. throw new Error(`${context}/alphaMode: Invalid value (${material.alphaMode})`);
  1638. }
  1639. }
  1640. }
  1641. /**
  1642. * Loads a glTF texture info.
  1643. * @param context The context when loading the asset
  1644. * @param textureInfo The glTF texture info property
  1645. * @param assign A function called synchronously after parsing the glTF properties
  1646. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  1647. */
  1648. public loadTextureInfoAsync(context: string, textureInfo: ITextureInfo, assign: (babylonTexture: BaseTexture) => void = () => { }): Promise<BaseTexture> {
  1649. const extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  1650. if (extensionPromise) {
  1651. return extensionPromise;
  1652. }
  1653. this.logOpen(`${context}`);
  1654. if (textureInfo.texCoord! >= 2) {
  1655. throw new Error(`${context}/texCoord: Invalid value (${textureInfo.texCoord})`);
  1656. }
  1657. const texture = ArrayItem.Get(`${context}/index`, this._gltf.textures, textureInfo.index);
  1658. texture._textureInfo = textureInfo;
  1659. const promise = this._loadTextureAsync(`/textures/${textureInfo.index}`, texture, (babylonTexture) => {
  1660. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  1661. GLTFLoader.AddPointerMetadata(babylonTexture, context);
  1662. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1663. assign(babylonTexture);
  1664. });
  1665. this.logClose();
  1666. return promise;
  1667. }
  1668. /** @hidden */
  1669. public _loadTextureAsync(context: string, texture: ITexture, assign: (babylonTexture: BaseTexture) => void = () => { }): Promise<BaseTexture> {
  1670. const extensionPromise = this._extensionsLoadTextureAsync(context, texture, assign);
  1671. if (extensionPromise) {
  1672. return extensionPromise;
  1673. }
  1674. this.logOpen(`${context} ${texture.name || ""}`);
  1675. const sampler = (texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._gltf.samplers, texture.sampler));
  1676. const image = ArrayItem.Get(`${context}/source`, this._gltf.images, texture.source);
  1677. const promise = this._createTextureAsync(context, sampler, image, assign);
  1678. this.logClose();
  1679. return promise;
  1680. }
  1681. /** @hidden */
  1682. public _createTextureAsync(context: string, sampler: ISampler, image: IImage, assign: (babylonTexture: BaseTexture) => void = () => { }, textureLoaderOptions?: any): Promise<BaseTexture> {
  1683. const samplerData = this._loadSampler(`/samplers/${sampler.index}`, sampler);
  1684. const promises = new Array<Promise<any>>();
  1685. const deferred = new Deferred<void>();
  1686. this._babylonScene._blockEntityCollection = this._forAssetContainer;
  1687. const babylonTexture = new Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, () => {
  1688. if (!this._disposed) {
  1689. deferred.resolve();
  1690. }
  1691. }, (message, exception) => {
  1692. if (!this._disposed) {
  1693. deferred.reject(new Error(`${context}: ${(exception && exception.message) ? exception.message : message || "Failed to load texture"}`));
  1694. }
  1695. }, undefined, undefined, undefined, image.mimeType, textureLoaderOptions);
  1696. this._babylonScene._blockEntityCollection = false;
  1697. promises.push(deferred.promise);
  1698. promises.push(this.loadImageAsync(`/images/${image.index}`, image).then((data) => {
  1699. const name = image.uri || `${this._fileName}#image${image.index}`;
  1700. const dataUrl = `data:${this._uniqueRootUrl}${name}`;
  1701. babylonTexture.updateURL(dataUrl, data);
  1702. }));
  1703. babylonTexture.wrapU = samplerData.wrapU;
  1704. babylonTexture.wrapV = samplerData.wrapV;
  1705. assign(babylonTexture);
  1706. return Promise.all(promises).then(() => {
  1707. return babylonTexture;
  1708. });
  1709. }
  1710. private _loadSampler(context: string, sampler: ISampler): _ISamplerData {
  1711. if (!sampler._data) {
  1712. sampler._data = {
  1713. noMipMaps: (sampler.minFilter === TextureMinFilter.NEAREST || sampler.minFilter === TextureMinFilter.LINEAR),
  1714. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  1715. wrapU: GLTFLoader._GetTextureWrapMode(`${context}/wrapS`, sampler.wrapS),
  1716. wrapV: GLTFLoader._GetTextureWrapMode(`${context}/wrapT`, sampler.wrapT)
  1717. };
  1718. }
  1719. return sampler._data;
  1720. }
  1721. /**
  1722. * Loads a glTF image.
  1723. * @param context The context when loading the asset
  1724. * @param image The glTF image property
  1725. * @returns A promise that resolves with the loaded data when the load is complete
  1726. */
  1727. public loadImageAsync(context: string, image: IImage): Promise<ArrayBufferView> {
  1728. if (!image._data) {
  1729. this.logOpen(`${context} ${image.name || ""}`);
  1730. if (image.uri) {
  1731. image._data = this.loadUriAsync(`${context}/uri`, image, image.uri);
  1732. }
  1733. else {
  1734. const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, image.bufferView);
  1735. image._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView);
  1736. }
  1737. this.logClose();
  1738. }
  1739. return image._data;
  1740. }
  1741. /**
  1742. * Loads a glTF uri.
  1743. * @param context The context when loading the asset
  1744. * @param property The glTF property associated with the uri
  1745. * @param uri The base64 or relative uri
  1746. * @returns A promise that resolves with the loaded data when the load is complete
  1747. */
  1748. public loadUriAsync(context: string, property: IProperty, uri: string): Promise<ArrayBufferView> {
  1749. const extensionPromise = this._extensionsLoadUriAsync(context, property, uri);
  1750. if (extensionPromise) {
  1751. return extensionPromise;
  1752. }
  1753. if (!GLTFLoader._ValidateUri(uri)) {
  1754. throw new Error(`${context}: '${uri}' is invalid`);
  1755. }
  1756. if (Tools.IsBase64(uri)) {
  1757. const data = new Uint8Array(Tools.DecodeBase64(uri));
  1758. this.log(`${context}: Decoded ${uri.substr(0, 64)}... (${data.length} bytes)`);
  1759. return Promise.resolve(data);
  1760. }
  1761. this.log(`${context}: Loading ${uri}`);
  1762. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then((url) => {
  1763. return new Promise((resolve, reject) => {
  1764. this._parent._loadFile(url, this._babylonScene, (data) => {
  1765. if (!this._disposed) {
  1766. this.log(`${context}: Loaded ${uri} (${(data as ArrayBuffer).byteLength} bytes)`);
  1767. resolve(new Uint8Array(data as ArrayBuffer));
  1768. }
  1769. }, true, (request) => {
  1770. reject(new LoadFileError(`${context}: Failed to load '${uri}'${request ? ": " + request.status + " " + request.statusText : ""}`, request));
  1771. });
  1772. });
  1773. });
  1774. }
  1775. /**
  1776. * Adds a JSON pointer to the metadata of the Babylon object at `<object>.metadata.gltf.pointers`.
  1777. * @param babylonObject the Babylon object with metadata
  1778. * @param pointer the JSON pointer
  1779. */
  1780. public static AddPointerMetadata(babylonObject: { metadata: any }, pointer: string): void {
  1781. const metadata = (babylonObject.metadata = babylonObject.metadata || {});
  1782. const gltf = (metadata.gltf = metadata.gltf || {});
  1783. const pointers = (gltf.pointers = gltf.pointers || []);
  1784. pointers.push(pointer);
  1785. }
  1786. private static _GetTextureWrapMode(context: string, mode: TextureWrapMode | undefined): number {
  1787. // Set defaults if undefined
  1788. mode = mode == undefined ? TextureWrapMode.REPEAT : mode;
  1789. switch (mode) {
  1790. case TextureWrapMode.CLAMP_TO_EDGE: return Texture.CLAMP_ADDRESSMODE;
  1791. case TextureWrapMode.MIRRORED_REPEAT: return Texture.MIRROR_ADDRESSMODE;
  1792. case TextureWrapMode.REPEAT: return Texture.WRAP_ADDRESSMODE;
  1793. default:
  1794. Logger.Warn(`${context}: Invalid value (${mode})`);
  1795. return Texture.WRAP_ADDRESSMODE;
  1796. }
  1797. }
  1798. private static _GetTextureSamplingMode(context: string, sampler: ISampler): number {
  1799. // Set defaults if undefined
  1800. const magFilter = sampler.magFilter == undefined ? TextureMagFilter.LINEAR : sampler.magFilter;
  1801. const minFilter = sampler.minFilter == undefined ? TextureMinFilter.LINEAR_MIPMAP_LINEAR : sampler.minFilter;
  1802. if (magFilter === TextureMagFilter.LINEAR) {
  1803. switch (minFilter) {
  1804. case TextureMinFilter.NEAREST: return Texture.LINEAR_NEAREST;
  1805. case TextureMinFilter.LINEAR: return Texture.LINEAR_LINEAR;
  1806. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.LINEAR_NEAREST_MIPNEAREST;
  1807. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.LINEAR_LINEAR_MIPNEAREST;
  1808. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.LINEAR_NEAREST_MIPLINEAR;
  1809. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.LINEAR_LINEAR_MIPLINEAR;
  1810. default:
  1811. Logger.Warn(`${context}/minFilter: Invalid value (${minFilter})`);
  1812. return Texture.LINEAR_LINEAR_MIPLINEAR;
  1813. }
  1814. }
  1815. else {
  1816. if (magFilter !== TextureMagFilter.NEAREST) {
  1817. Logger.Warn(`${context}/magFilter: Invalid value (${magFilter})`);
  1818. }
  1819. switch (minFilter) {
  1820. case TextureMinFilter.NEAREST: return Texture.NEAREST_NEAREST;
  1821. case TextureMinFilter.LINEAR: return Texture.NEAREST_LINEAR;
  1822. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.NEAREST_NEAREST_MIPNEAREST;
  1823. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.NEAREST_LINEAR_MIPNEAREST;
  1824. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.NEAREST_NEAREST_MIPLINEAR;
  1825. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.NEAREST_LINEAR_MIPLINEAR;
  1826. default:
  1827. Logger.Warn(`${context}/minFilter: Invalid value (${minFilter})`);
  1828. return Texture.NEAREST_NEAREST_MIPNEAREST;
  1829. }
  1830. }
  1831. }
  1832. private static _GetTypedArrayConstructor(context: string, componentType: AccessorComponentType): TypedArrayConstructor {
  1833. switch (componentType) {
  1834. case AccessorComponentType.BYTE: return Int8Array;
  1835. case AccessorComponentType.UNSIGNED_BYTE: return Uint8Array;
  1836. case AccessorComponentType.SHORT: return Int16Array;
  1837. case AccessorComponentType.UNSIGNED_SHORT: return Uint16Array;
  1838. case AccessorComponentType.UNSIGNED_INT: return Uint32Array;
  1839. case AccessorComponentType.FLOAT: return Float32Array;
  1840. default: throw new Error(`${context}: Invalid component type ${componentType}`);
  1841. }
  1842. }
  1843. private static _GetTypedArray(context: string, componentType: AccessorComponentType, bufferView: ArrayBufferView, byteOffset: number | undefined, length: number): TypedArrayLike {
  1844. const buffer = bufferView.buffer;
  1845. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  1846. const constructor = GLTFLoader._GetTypedArrayConstructor(`${context}/componentType`, componentType);
  1847. try {
  1848. return new constructor(buffer, byteOffset, length);
  1849. }
  1850. catch (e) {
  1851. throw new Error(`${context}: ${e}`);
  1852. }
  1853. }
  1854. private static _GetNumComponents(context: string, type: string): number {
  1855. switch (type) {
  1856. case "SCALAR": return 1;
  1857. case "VEC2": return 2;
  1858. case "VEC3": return 3;
  1859. case "VEC4": return 4;
  1860. case "MAT2": return 4;
  1861. case "MAT3": return 9;
  1862. case "MAT4": return 16;
  1863. }
  1864. throw new Error(`${context}: Invalid type (${type})`);
  1865. }
  1866. private static _ValidateUri(uri: string): boolean {
  1867. return (Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  1868. }
  1869. /** @hidden */
  1870. public static _GetDrawMode(context: string, mode: number | undefined): number {
  1871. if (mode == undefined) {
  1872. mode = MeshPrimitiveMode.TRIANGLES;
  1873. }
  1874. switch (mode) {
  1875. case MeshPrimitiveMode.POINTS: return Material.PointListDrawMode;
  1876. case MeshPrimitiveMode.LINES: return Material.LineListDrawMode;
  1877. case MeshPrimitiveMode.LINE_LOOP: return Material.LineLoopDrawMode;
  1878. case MeshPrimitiveMode.LINE_STRIP: return Material.LineStripDrawMode;
  1879. case MeshPrimitiveMode.TRIANGLES: return Material.TriangleFillMode;
  1880. case MeshPrimitiveMode.TRIANGLE_STRIP: return Material.TriangleStripDrawMode;
  1881. case MeshPrimitiveMode.TRIANGLE_FAN: return Material.TriangleFanDrawMode;
  1882. }
  1883. throw new Error(`${context}: Invalid mesh primitive mode (${mode})`);
  1884. }
  1885. private _compileMaterialsAsync(): Promise<void> {
  1886. this._parent._startPerformanceCounter("Compile materials");
  1887. const promises = new Array<Promise<any>>();
  1888. if (this._gltf.materials) {
  1889. for (const material of this._gltf.materials) {
  1890. if (material._data) {
  1891. for (const babylonDrawMode in material._data) {
  1892. const babylonData = material._data[babylonDrawMode];
  1893. for (const babylonMesh of babylonData.babylonMeshes) {
  1894. // Ensure nonUniformScaling is set if necessary.
  1895. babylonMesh.computeWorldMatrix(true);
  1896. const babylonMaterial = babylonData.babylonMaterial;
  1897. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  1898. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { useInstances: true }));
  1899. if (this._parent.useClipPlane) {
  1900. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  1901. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true, useInstances: true }));
  1902. }
  1903. }
  1904. }
  1905. }
  1906. }
  1907. }
  1908. return Promise.all(promises).then(() => {
  1909. this._parent._endPerformanceCounter("Compile materials");
  1910. });
  1911. }
  1912. private _compileShadowGeneratorsAsync(): Promise<void> {
  1913. this._parent._startPerformanceCounter("Compile shadow generators");
  1914. const promises = new Array<Promise<any>>();
  1915. const lights = this._babylonScene.lights;
  1916. for (let light of lights) {
  1917. let generator = light.getShadowGenerator();
  1918. if (generator) {
  1919. promises.push(generator.forceCompilationAsync());
  1920. }
  1921. }
  1922. return Promise.all(promises).then(() => {
  1923. this._parent._endPerformanceCounter("Compile shadow generators");
  1924. });
  1925. }
  1926. private _forEachExtensions(action: (extension: IGLTFLoaderExtension) => void): void {
  1927. for (const extension of this._extensions) {
  1928. if (extension.enabled) {
  1929. action(extension);
  1930. }
  1931. }
  1932. }
  1933. private _applyExtensions<T>(property: IProperty, functionName: string, actionAsync: (extension: IGLTFLoaderExtension) => Nullable<T> | undefined): Nullable<T> {
  1934. for (const extension of this._extensions) {
  1935. if (extension.enabled) {
  1936. const id = `${extension.name}.${functionName}`;
  1937. const loaderProperty = property as ILoaderProperty;
  1938. loaderProperty._activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions || {};
  1939. const activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions;
  1940. if (!activeLoaderExtensionFunctions[id]) {
  1941. activeLoaderExtensionFunctions[id] = true;
  1942. try {
  1943. const result = actionAsync(extension);
  1944. if (result) {
  1945. return result;
  1946. }
  1947. }
  1948. finally {
  1949. delete activeLoaderExtensionFunctions[id];
  1950. }
  1951. }
  1952. }
  1953. }
  1954. return null;
  1955. }
  1956. private _extensionsOnLoading(): void {
  1957. this._forEachExtensions((extension) => extension.onLoading && extension.onLoading());
  1958. }
  1959. private _extensionsOnReady(): void {
  1960. this._forEachExtensions((extension) => extension.onReady && extension.onReady());
  1961. }
  1962. private _extensionsLoadSceneAsync(context: string, scene: IScene): Nullable<Promise<void>> {
  1963. return this._applyExtensions(scene, "loadScene", (extension) => extension.loadSceneAsync && extension.loadSceneAsync(context, scene));
  1964. }
  1965. private _extensionsLoadNodeAsync(context: string, node: INode, assign: (babylonTransformNode: TransformNode) => void): Nullable<Promise<TransformNode>> {
  1966. return this._applyExtensions(node, "loadNode", (extension) => extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign));
  1967. }
  1968. private _extensionsLoadCameraAsync(context: string, camera: ICamera, assign: (babylonCamera: Camera) => void): Nullable<Promise<Camera>> {
  1969. return this._applyExtensions(camera, "loadCamera", (extension) => extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign));
  1970. }
  1971. private _extensionsLoadVertexDataAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh): Nullable<Promise<Geometry>> {
  1972. return this._applyExtensions(primitive, "loadVertexData", (extension) => extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh));
  1973. }
  1974. private _extensionsLoadMeshPrimitiveAsync(context: string, name: string, node: INode, mesh: IMesh, primitive: IMeshPrimitive, assign: (babylonMesh: AbstractMesh) => void): Nullable<Promise<AbstractMesh>> {
  1975. return this._applyExtensions(primitive, "loadMeshPrimitive", (extension) => extension._loadMeshPrimitiveAsync && extension._loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign));
  1976. }
  1977. private _extensionsLoadMaterialAsync(context: string, material: IMaterial, babylonMesh: Nullable<Mesh>, babylonDrawMode: number, assign: (babylonMaterial: Material) => void): Nullable<Promise<Material>> {
  1978. return this._applyExtensions(material, "loadMaterial", (extension) => extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign));
  1979. }
  1980. private _extensionsCreateMaterial(context: string, material: IMaterial, babylonDrawMode: number): Nullable<Material> {
  1981. return this._applyExtensions(material, "createMaterial", (extension) => extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode));
  1982. }
  1983. private _extensionsLoadMaterialPropertiesAsync(context: string, material: IMaterial, babylonMaterial: Material): Nullable<Promise<void>> {
  1984. return this._applyExtensions(material, "loadMaterialProperties", (extension) => extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial));
  1985. }
  1986. private _extensionsLoadTextureInfoAsync(context: string, textureInfo: ITextureInfo, assign: (babylonTexture: BaseTexture) => void): Nullable<Promise<BaseTexture>> {
  1987. return this._applyExtensions(textureInfo, "loadTextureInfo", (extension) => extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign));
  1988. }
  1989. private _extensionsLoadTextureAsync(context: string, texture: ITexture, assign: (babylonTexture: BaseTexture) => void): Nullable<Promise<BaseTexture>> {
  1990. return this._applyExtensions(texture, "loadTexture", (extension) => extension._loadTextureAsync && extension._loadTextureAsync(context, texture, assign));
  1991. }
  1992. private _extensionsLoadAnimationAsync(context: string, animation: IAnimation): Nullable<Promise<AnimationGroup>> {
  1993. return this._applyExtensions(animation, "loadAnimation", (extension) => extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation));
  1994. }
  1995. private _extensionsLoadSkinAsync(context: string, node: INode, skin: ISkin): Nullable<Promise<void>> {
  1996. return this._applyExtensions(skin, "loadSkin", (extension) => extension._loadSkinAsync && extension._loadSkinAsync(context, node, skin));
  1997. }
  1998. private _extensionsLoadUriAsync(context: string, property: IProperty, uri: string): Nullable<Promise<ArrayBufferView>> {
  1999. return this._applyExtensions(property, "loadUri", (extension) => extension._loadUriAsync && extension._loadUriAsync(context, property, uri));
  2000. }
  2001. private _extensionsLoadBufferViewAsync(context: string, bufferView: IBufferView): Nullable<Promise<ArrayBufferView>> {
  2002. return this._applyExtensions(bufferView, "loadBufferView", (extension) => extension.loadBufferViewAsync && extension.loadBufferViewAsync(context, bufferView));
  2003. }
  2004. private _extensionsLoadBufferAsync(context: string, buffer: IBuffer, byteOffset: number, byteLength: number): Nullable<Promise<ArrayBufferView>> {
  2005. return this._applyExtensions(buffer, "loadBuffer", (extension) => extension.loadBufferAsync && extension.loadBufferAsync(context, buffer, byteOffset, byteLength));
  2006. }
  2007. /**
  2008. * Helper method called by a loader extension to load an glTF extension.
  2009. * @param context The context when loading the asset
  2010. * @param property The glTF property to load the extension from
  2011. * @param extensionName The name of the extension to load
  2012. * @param actionAsync The action to run
  2013. * @returns The promise returned by actionAsync or null if the extension does not exist
  2014. */
  2015. public static LoadExtensionAsync<TExtension = any, TResult = void>(context: string, property: IProperty, extensionName: string, actionAsync: (extensionContext: string, extension: TExtension) => Nullable<Promise<TResult>>): Nullable<Promise<TResult>> {
  2016. if (!property.extensions) {
  2017. return null;
  2018. }
  2019. const extensions = property.extensions;
  2020. const extension = extensions[extensionName] as TExtension;
  2021. if (!extension) {
  2022. return null;
  2023. }
  2024. return actionAsync(`${context}/extensions/${extensionName}`, extension);
  2025. }
  2026. /**
  2027. * Helper method called by a loader extension to load a glTF extra.
  2028. * @param context The context when loading the asset
  2029. * @param property The glTF property to load the extra from
  2030. * @param extensionName The name of the extension to load
  2031. * @param actionAsync The action to run
  2032. * @returns The promise returned by actionAsync or null if the extra does not exist
  2033. */
  2034. public static LoadExtraAsync<TExtra = any, TResult = void>(context: string, property: IProperty, extensionName: string, actionAsync: (extraContext: string, extra: TExtra) => Nullable<Promise<TResult>>): Nullable<Promise<TResult>> {
  2035. if (!property.extras) {
  2036. return null;
  2037. }
  2038. const extras = property.extras;
  2039. const extra = extras[extensionName] as TExtra;
  2040. if (!extra) {
  2041. return null;
  2042. }
  2043. return actionAsync(`${context}/extras/${extensionName}`, extra);
  2044. }
  2045. /**
  2046. * Checks for presence of an extension.
  2047. * @param name The name of the extension to check
  2048. * @returns A boolean indicating the presence of the given extension name in `extensionsUsed`
  2049. */
  2050. public isExtensionUsed(name: string): boolean {
  2051. return !!this._gltf.extensionsUsed && this._gltf.extensionsUsed.indexOf(name) !== -1;
  2052. }
  2053. /**
  2054. * Increments the indentation level and logs a message.
  2055. * @param message The message to log
  2056. */
  2057. public logOpen(message: string): void {
  2058. this._parent._logOpen(message);
  2059. }
  2060. /**
  2061. * Decrements the indentation level.
  2062. */
  2063. public logClose(): void {
  2064. this._parent._logClose();
  2065. }
  2066. /**
  2067. * Logs a message
  2068. * @param message The message to log
  2069. */
  2070. public log(message: string): void {
  2071. this._parent._log(message);
  2072. }
  2073. /**
  2074. * Starts a performance counter.
  2075. * @param counterName The name of the performance counter
  2076. */
  2077. public startPerformanceCounter(counterName: string): void {
  2078. this._parent._startPerformanceCounter(counterName);
  2079. }
  2080. /**
  2081. * Ends a performance counter.
  2082. * @param counterName The name of the performance counter
  2083. */
  2084. public endPerformanceCounter(counterName: string): void {
  2085. this._parent._endPerformanceCounter(counterName);
  2086. }
  2087. }
  2088. GLTFFileLoader._CreateGLTF2Loader = (parent) => new GLTFLoader(parent);