glTFLoader.ts 102 KB

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