babylon.glTFLoader.ts 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF2 {
  3. interface IFileRequestInfo extends IFileRequest {
  4. _lengthComputable?: boolean;
  5. _loaded?: number;
  6. _total?: number;
  7. }
  8. export interface MaterialConstructor<T extends Material> {
  9. readonly prototype: T;
  10. new(name: string, scene: Scene): T;
  11. }
  12. export class GLTFLoader implements IGLTFLoader {
  13. public _gltf: ILoaderGLTF;
  14. public _babylonScene: Scene;
  15. public _completePromises = new Array<Promise<void>>();
  16. private _disposed = false;
  17. private _state: Nullable<GLTFLoaderState> = null;
  18. private _extensions: { [name: string]: GLTFLoaderExtension } = {};
  19. private _rootUrl: string;
  20. private _rootBabylonMesh: Mesh;
  21. private _defaultSampler = {} as ILoaderSampler;
  22. private _defaultBabylonMaterials: { [drawMode: number]: PBRMaterial } = {};
  23. private _progressCallback?: (event: SceneLoaderProgressEvent) => void;
  24. private _requests = new Array<IFileRequestInfo>();
  25. private static _Names = new Array<string>();
  26. private static _Factories: { [name: string]: (loader: GLTFLoader) => GLTFLoaderExtension } = {};
  27. public static _Register(name: string, factory: (loader: GLTFLoader) => GLTFLoaderExtension): void {
  28. if (GLTFLoader._Factories[name]) {
  29. Tools.Error(`Extension with the name '${name}' already exists`);
  30. return;
  31. }
  32. GLTFLoader._Factories[name] = factory;
  33. // Keep the order of registration so that extensions registered first are called first.
  34. GLTFLoader._Names.push(name);
  35. }
  36. public coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  37. public animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  38. public compileMaterials = false;
  39. public useClipPlane = false;
  40. public compileShadowGenerators = false;
  41. public readonly onDisposeObservable = new Observable<IGLTFLoader>();
  42. public readonly onMeshLoadedObservable = new Observable<AbstractMesh>();
  43. public readonly onTextureLoadedObservable = new Observable<BaseTexture>();
  44. public readonly onMaterialLoadedObservable = new Observable<Material>();
  45. public readonly onExtensionLoadedObservable = new Observable<IGLTFLoaderExtension>();
  46. public readonly onCompleteObservable = new Observable<IGLTFLoader>();
  47. public get state(): Nullable<GLTFLoaderState> {
  48. return this._state;
  49. }
  50. public dispose(): void {
  51. if (this._disposed) {
  52. return;
  53. }
  54. this._disposed = true;
  55. this.onDisposeObservable.notifyObservers(this);
  56. this.onDisposeObservable.clear();
  57. this._clear();
  58. }
  59. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }> {
  60. return Promise.resolve().then(() => {
  61. let nodes: Nullable<Array<ILoaderNode>> = null;
  62. if (meshesNames) {
  63. const nodeMap: { [name: string]: ILoaderNode } = {};
  64. if (this._gltf.nodes) {
  65. for (const node of this._gltf.nodes) {
  66. if (node.name) {
  67. nodeMap[node.name] = node;
  68. }
  69. }
  70. }
  71. const names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  72. nodes = names.map(name => {
  73. const node = nodeMap[name];
  74. if (!node) {
  75. throw new Error(`Failed to find node '${name}'`);
  76. }
  77. return node;
  78. });
  79. }
  80. return this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(() => {
  81. return {
  82. meshes: this._getMeshes(),
  83. particleSystems: [],
  84. skeletons: this._getSkeletons(),
  85. animationGroups: this._getAnimationGroups()
  86. };
  87. });
  88. });
  89. }
  90. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void> {
  91. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  92. }
  93. private _loadAsync(nodes: Nullable<Array<ILoaderNode>>, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void> {
  94. return Promise.resolve().then(() => {
  95. this._loadExtensions();
  96. this._babylonScene = scene;
  97. this._rootUrl = rootUrl;
  98. this._progressCallback = onProgress;
  99. this._state = GLTFLoaderState.Loading;
  100. this._loadData(data);
  101. this._checkExtensions();
  102. const promises = new Array<Promise<void>>();
  103. if (nodes) {
  104. promises.push(this._loadNodesAsync(nodes));
  105. }
  106. else {
  107. const scene = GLTFLoader._GetProperty(`#/scene`, this._gltf.scenes, this._gltf.scene || 0);
  108. promises.push(this._loadSceneAsync(`#/scenes/${scene._index}`, scene));
  109. }
  110. if (this.compileMaterials) {
  111. promises.push(this._compileMaterialsAsync());
  112. }
  113. if (this.compileShadowGenerators) {
  114. promises.push(this._compileShadowGeneratorsAsync());
  115. }
  116. const resultPromise = Promise.all(promises).then(() => {
  117. this._state = GLTFLoaderState.Ready;
  118. this._startAnimations();
  119. });
  120. resultPromise.then(() => {
  121. this._rootBabylonMesh.setEnabled(true);
  122. Tools.SetImmediate(() => {
  123. if (!this._disposed) {
  124. Promise.all(this._completePromises).then(() => {
  125. this._state = GLTFLoaderState.Complete;
  126. this.onCompleteObservable.notifyObservers(this);
  127. this.onCompleteObservable.clear();
  128. this._clear();
  129. }).catch(error => {
  130. Tools.Error(`glTF Loader: ${error.message}`);
  131. this._clear();
  132. });
  133. }
  134. });
  135. });
  136. return resultPromise;
  137. }).catch(error => {
  138. Tools.Error(`glTF Loader: ${error.message}`);
  139. this._clear();
  140. throw error;
  141. });
  142. }
  143. private _loadExtensions(): void {
  144. for (const name of GLTFLoader._Names) {
  145. const extension = GLTFLoader._Factories[name](this);
  146. this._extensions[name] = extension;
  147. this.onExtensionLoadedObservable.notifyObservers(extension);
  148. }
  149. this.onExtensionLoadedObservable.clear();
  150. }
  151. private _loadData(data: IGLTFLoaderData): void {
  152. this._gltf = data.json as ILoaderGLTF;
  153. this._setupData();
  154. if (data.bin) {
  155. const buffers = this._gltf.buffers;
  156. if (buffers && buffers[0] && !buffers[0].uri) {
  157. const binaryBuffer = buffers[0];
  158. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  159. Tools.Warn(`Binary buffer length (${binaryBuffer.byteLength}) from JSON does not match chunk length (${data.bin.byteLength})`);
  160. }
  161. binaryBuffer._data = Promise.resolve(data.bin);
  162. }
  163. else {
  164. Tools.Warn("Unexpected BIN chunk");
  165. }
  166. }
  167. }
  168. private _setupData(): void {
  169. ArrayItem.Assign(this._gltf.accessors);
  170. ArrayItem.Assign(this._gltf.animations);
  171. ArrayItem.Assign(this._gltf.buffers);
  172. ArrayItem.Assign(this._gltf.bufferViews);
  173. ArrayItem.Assign(this._gltf.cameras);
  174. ArrayItem.Assign(this._gltf.images);
  175. ArrayItem.Assign(this._gltf.materials);
  176. ArrayItem.Assign(this._gltf.meshes);
  177. ArrayItem.Assign(this._gltf.nodes);
  178. ArrayItem.Assign(this._gltf.samplers);
  179. ArrayItem.Assign(this._gltf.scenes);
  180. ArrayItem.Assign(this._gltf.skins);
  181. ArrayItem.Assign(this._gltf.textures);
  182. if (this._gltf.nodes) {
  183. const nodeParents: { [index: number]: number } = {};
  184. for (const node of this._gltf.nodes) {
  185. if (node.children) {
  186. for (const index of node.children) {
  187. nodeParents[index] = node._index;
  188. }
  189. }
  190. }
  191. const rootNode = this._createRootNode();
  192. for (const node of this._gltf.nodes) {
  193. const parentIndex = nodeParents[node._index];
  194. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  195. }
  196. }
  197. }
  198. private _checkExtensions(): void {
  199. if (this._gltf.extensionsRequired) {
  200. for (const name of this._gltf.extensionsRequired) {
  201. const extension = this._extensions[name];
  202. if (!extension || !extension.enabled) {
  203. throw new Error(`Require extension ${name} is not available`);
  204. }
  205. }
  206. }
  207. }
  208. private _createRootNode(): ILoaderNode {
  209. this._rootBabylonMesh = new Mesh("__root__", this._babylonScene);
  210. this._rootBabylonMesh.setEnabled(false);
  211. const rootNode = { _babylonMesh: this._rootBabylonMesh } as ILoaderNode;
  212. switch (this.coordinateSystemMode) {
  213. case GLTFLoaderCoordinateSystemMode.AUTO: {
  214. if (!this._babylonScene.useRightHandedSystem) {
  215. rootNode.rotation = [0, 1, 0, 0];
  216. rootNode.scale = [1, 1, -1];
  217. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  218. }
  219. break;
  220. }
  221. case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  222. this._babylonScene.useRightHandedSystem = true;
  223. break;
  224. }
  225. default: {
  226. throw new Error(`Invalid coordinate system mode (${this.coordinateSystemMode})`);
  227. }
  228. }
  229. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  230. return rootNode;
  231. }
  232. private _loadNodesAsync(nodes: ILoaderNode[], ): Promise<void> {
  233. const promises = new Array<Promise<void>>();
  234. for (let node of nodes) {
  235. promises.push(this._loadNodeAsync(`#/nodes/${node._index}`, node));
  236. }
  237. promises.push(this._loadAnimationsAsync());
  238. return Promise.all(promises).then(() => {});
  239. }
  240. public _loadSceneAsync(context: string, scene: ILoaderScene): Promise<void> {
  241. const promise = GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  242. if (promise) {
  243. return promise;
  244. }
  245. const promises = new Array<Promise<void>>();
  246. for (let index of scene.nodes) {
  247. const node = GLTFLoader._GetProperty(`${context}/nodes/${index}`, this._gltf.nodes, index);
  248. promises.push(this._loadNodeAsync(`#/nodes/${node._index}`, node));
  249. }
  250. promises.push(this._loadAnimationsAsync());
  251. return Promise.all(promises).then(() => {});
  252. }
  253. private _forEachPrimitive(node: ILoaderNode, callback: (babylonMesh: Mesh) => void): void {
  254. if (node._primitiveBabylonMeshes) {
  255. for (const babylonMesh of node._primitiveBabylonMeshes) {
  256. callback(babylonMesh);
  257. }
  258. }
  259. else {
  260. callback(node._babylonMesh!);
  261. }
  262. }
  263. private _getMeshes(): Mesh[] {
  264. const meshes = new Array<Mesh>();
  265. // Root mesh is always first.
  266. meshes.push(this._rootBabylonMesh);
  267. const nodes = this._gltf.nodes;
  268. if (nodes) {
  269. for (const node of nodes) {
  270. if (node._babylonMesh) {
  271. meshes.push(node._babylonMesh);
  272. }
  273. if (node._primitiveBabylonMeshes) {
  274. for (const babylonMesh of node._primitiveBabylonMeshes) {
  275. meshes.push(babylonMesh);
  276. }
  277. }
  278. }
  279. }
  280. return meshes;
  281. }
  282. private _getSkeletons(): Skeleton[] {
  283. const skeletons = new Array<Skeleton>();
  284. const skins = this._gltf.skins;
  285. if (skins) {
  286. for (const skin of skins) {
  287. if (skin._babylonSkeleton) {
  288. skeletons.push(skin._babylonSkeleton);
  289. }
  290. }
  291. }
  292. return skeletons;
  293. }
  294. private _getAnimationGroups(): AnimationGroup[] {
  295. const animationGroups = new Array<AnimationGroup>();
  296. const animations = this._gltf.animations;
  297. if (animations) {
  298. for (const animation of animations) {
  299. if (animation._babylonAnimationGroup) {
  300. animationGroups.push(animation._babylonAnimationGroup);
  301. }
  302. }
  303. }
  304. return animationGroups;
  305. }
  306. private _startAnimations(): void {
  307. switch (this.animationStartMode) {
  308. case GLTFLoaderAnimationStartMode.NONE: {
  309. // do nothing
  310. break;
  311. }
  312. case GLTFLoaderAnimationStartMode.FIRST: {
  313. const babylonAnimationGroups = this._getAnimationGroups();
  314. if (babylonAnimationGroups.length !== 0) {
  315. babylonAnimationGroups[0].start(true);
  316. }
  317. break;
  318. }
  319. case GLTFLoaderAnimationStartMode.ALL: {
  320. const babylonAnimationGroups = this._getAnimationGroups();
  321. for (const babylonAnimationGroup of babylonAnimationGroups) {
  322. babylonAnimationGroup.start(true);
  323. }
  324. break;
  325. }
  326. default: {
  327. Tools.Error(`Invalid animation start mode (${this.animationStartMode})`);
  328. return;
  329. }
  330. }
  331. }
  332. public _loadNodeAsync(context: string, node: ILoaderNode): Promise<void> {
  333. const promise = GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  334. if (promise) {
  335. return promise;
  336. }
  337. if (node._babylonMesh) {
  338. throw new Error(`${context}: Invalid recursive node hierarchy`);
  339. }
  340. const promises = new Array<Promise<void>>();
  341. const babylonMesh = new Mesh(node.name || `node${node._index}`, this._babylonScene, node._parent._babylonMesh);
  342. node._babylonMesh = babylonMesh;
  343. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  344. node._babylonAnimationTargets.push(babylonMesh);
  345. GLTFLoader._LoadTransform(node, babylonMesh);
  346. if (node.mesh != undefined) {
  347. const mesh = GLTFLoader._GetProperty(`${context}/mesh`, this._gltf.meshes, node.mesh);
  348. promises.push(this._loadMeshAsync(`#/meshes/${mesh._index}`, node, mesh, babylonMesh));
  349. }
  350. if (node.children) {
  351. for (const index of node.children) {
  352. const childNode = GLTFLoader._GetProperty(`${context}/children/${index}`, this._gltf.nodes, index);
  353. promises.push(this._loadNodeAsync(`#/nodes/${index}`, childNode));
  354. }
  355. }
  356. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  357. return Promise.all(promises).then(() => {});
  358. }
  359. private _loadMeshAsync(context: string, node: ILoaderNode, mesh: ILoaderMesh, babylonMesh: Mesh): Promise<void> {
  360. // TODO: instancing
  361. const promises = new Array<Promise<void>>();
  362. const primitives = mesh.primitives;
  363. if (!primitives || primitives.length === 0) {
  364. throw new Error(`${context}: Primitives are missing`);
  365. }
  366. ArrayItem.Assign(primitives);
  367. if (primitives.length === 1) {
  368. const primitive = primitives[0];
  369. promises.push(this._loadPrimitiveAsync(`${context}/primitives/${primitive._index}`, node, mesh, primitive, babylonMesh));
  370. }
  371. else {
  372. node._primitiveBabylonMeshes = [];
  373. for (const primitive of primitives) {
  374. const primitiveBabylonMesh = new Mesh(`${mesh.name || babylonMesh.name}_${primitive._index}`, this._babylonScene, babylonMesh);
  375. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  376. promises.push(this._loadPrimitiveAsync(`${context}/primitives/${primitive._index}`, node, mesh, primitive, primitiveBabylonMesh));
  377. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  378. }
  379. }
  380. if (node.skin != undefined) {
  381. const skin = GLTFLoader._GetProperty(`${context}/skin`, this._gltf.skins, node.skin);
  382. promises.push(this._loadSkinAsync(`#/skins/${skin._index}`, node, mesh, skin));
  383. }
  384. return Promise.all(promises).then(() => {
  385. this._forEachPrimitive(node, babylonMesh => {
  386. babylonMesh._refreshBoundingInfo(true);
  387. });
  388. });
  389. }
  390. private _loadPrimitiveAsync(context: string, node: ILoaderNode, mesh: ILoaderMesh, primitive: ILoaderMeshPrimitive, babylonMesh: Mesh): Promise<void> {
  391. const promises = new Array<Promise<void>>();
  392. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  393. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(babylonGeometry => {
  394. return this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(() => {
  395. babylonGeometry.applyToMesh(babylonMesh);
  396. });
  397. }));
  398. const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  399. if (primitive.material == undefined) {
  400. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  401. }
  402. else {
  403. const material = GLTFLoader._GetProperty(`${context}/material}`, this._gltf.materials, primitive.material);
  404. promises.push(this._loadMaterialAsync(`#/materials/${material._index}`, material, babylonMesh, babylonDrawMode, babylonMaterial => {
  405. babylonMesh.material = babylonMaterial;
  406. }));
  407. }
  408. return Promise.all(promises).then(() => {});
  409. }
  410. private _loadVertexDataAsync(context: string, primitive: ILoaderMeshPrimitive, babylonMesh: Mesh): Promise<Geometry> {
  411. const promise = GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  412. if (promise) {
  413. return promise;
  414. }
  415. const attributes = primitive.attributes;
  416. if (!attributes) {
  417. throw new Error(`${context}: Attributes are missing`);
  418. }
  419. const promises = new Array<Promise<void>>();
  420. const babylonGeometry = new Geometry(babylonMesh.name, this._babylonScene);
  421. if (primitive.indices == undefined) {
  422. babylonMesh.isUnIndexed = true;
  423. }
  424. else {
  425. const accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  426. promises.push(this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(data => {
  427. babylonGeometry.setIndices(data as IndicesArray);
  428. }));
  429. }
  430. const loadAttribute = (attribute: string, kind: string) => {
  431. if (attributes[attribute] == undefined) {
  432. return;
  433. }
  434. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  435. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  436. babylonMesh._delayInfo.push(kind);
  437. }
  438. const accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, this._gltf.accessors, attributes[attribute]);
  439. promises.push(this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(babylonVertexBuffer => {
  440. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  441. }));
  442. };
  443. loadAttribute("POSITION", VertexBuffer.PositionKind);
  444. loadAttribute("NORMAL", VertexBuffer.NormalKind);
  445. loadAttribute("TANGENT", VertexBuffer.TangentKind);
  446. loadAttribute("TEXCOORD_0", VertexBuffer.UVKind);
  447. loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind);
  448. loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind);
  449. loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind);
  450. loadAttribute("COLOR_0", VertexBuffer.ColorKind);
  451. return Promise.all(promises).then(() => {
  452. return babylonGeometry;
  453. });
  454. }
  455. private _createMorphTargets(context: string, node: ILoaderNode, mesh: ILoaderMesh, primitive: IMeshPrimitive, babylonMesh: Mesh): void {
  456. if (!primitive.targets) {
  457. return;
  458. }
  459. if (node._numMorphTargets == undefined) {
  460. node._numMorphTargets = primitive.targets.length;
  461. }
  462. else if (primitive.targets.length !== node._numMorphTargets) {
  463. throw new Error(`${context}: Primitives do not have the same number of targets`);
  464. }
  465. babylonMesh.morphTargetManager = new MorphTargetManager();
  466. for (let index = 0; index < primitive.targets.length; index++) {
  467. const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  468. babylonMesh.morphTargetManager.addTarget(new MorphTarget(`morphTarget${index}`, weight));
  469. // TODO: tell the target whether it has positions, normals, tangents
  470. }
  471. }
  472. private _loadMorphTargetsAsync(context: string, primitive: IMeshPrimitive, babylonMesh: Mesh, babylonGeometry: Geometry): Promise<void> {
  473. if (!primitive.targets) {
  474. return Promise.resolve();
  475. }
  476. const promises = new Array<Promise<void>>();
  477. const morphTargetManager = babylonMesh.morphTargetManager!;
  478. for (let index = 0; index < morphTargetManager.numTargets; index++) {
  479. const babylonMorphTarget = morphTargetManager.getTarget(index);
  480. promises.push(this._loadMorphTargetVertexDataAsync(`${context}/targets/${index}`, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  481. }
  482. return Promise.all(promises).then(() => {});
  483. }
  484. private _loadMorphTargetVertexDataAsync(context: string, babylonGeometry: Geometry, attributes: { [name: string]: number }, babylonMorphTarget: MorphTarget): Promise<void> {
  485. const promises = new Array<Promise<void>>();
  486. const loadAttribute = (attribute: string, kind: string, setData: (babylonVertexBuffer: VertexBuffer, data: Float32Array) => void) => {
  487. if (attributes[attribute] == undefined) {
  488. return;
  489. }
  490. const babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  491. if (!babylonVertexBuffer) {
  492. return;
  493. }
  494. const accessor = GLTFLoader._GetProperty(`${context}/${attribute}`, this._gltf.accessors, attributes[attribute]);
  495. promises.push(this._loadAccessorAsync(`#/accessors/${accessor._index}`, accessor).then(data => {
  496. if (!(data instanceof Float32Array)) {
  497. throw new Error(`${context}: Morph target accessor must have float data`);
  498. }
  499. setData(babylonVertexBuffer, data);
  500. }));
  501. };
  502. loadAttribute("POSITION", VertexBuffer.PositionKind, (babylonVertexBuffer, data) => {
  503. babylonVertexBuffer.forEach(data.length, (value, index) => {
  504. data[index] += value;
  505. });
  506. babylonMorphTarget.setPositions(data);
  507. });
  508. loadAttribute("NORMAL", VertexBuffer.NormalKind, (babylonVertexBuffer, data) => {
  509. babylonVertexBuffer.forEach(data.length, (value, index) => {
  510. data[index] += value;
  511. });
  512. babylonMorphTarget.setNormals(data);
  513. });
  514. loadAttribute("TANGENT", VertexBuffer.TangentKind, (babylonVertexBuffer, data) => {
  515. let dataIndex = 0;
  516. babylonVertexBuffer.forEach(data.length, (value, index) => {
  517. // Tangent data for morph targets is stored as xyz delta.
  518. // The vertexData.tangent is stored as xyzw.
  519. // So we need to skip every fourth vertexData.tangent.
  520. if (((index + 1) % 4) !== 0) {
  521. data[dataIndex++] += value;
  522. }
  523. });
  524. babylonMorphTarget.setTangents(data);
  525. });
  526. return Promise.all(promises).then(() => {});
  527. }
  528. private static _LoadTransform(node: ILoaderNode, babylonNode: TransformNode): void {
  529. let position = Vector3.Zero();
  530. let rotation = Quaternion.Identity();
  531. let scaling = Vector3.One();
  532. if (node.matrix) {
  533. const matrix = Matrix.FromArray(node.matrix);
  534. matrix.decompose(scaling, rotation, position);
  535. }
  536. else {
  537. if (node.translation) position = Vector3.FromArray(node.translation);
  538. if (node.rotation) rotation = Quaternion.FromArray(node.rotation);
  539. if (node.scale) scaling = Vector3.FromArray(node.scale);
  540. }
  541. babylonNode.position = position;
  542. babylonNode.rotationQuaternion = rotation;
  543. babylonNode.scaling = scaling;
  544. }
  545. private _loadSkinAsync(context: string, node: ILoaderNode, mesh: ILoaderMesh, skin: ILoaderSkin): Promise<void> {
  546. const assignSkeleton = () => {
  547. this._forEachPrimitive(node, babylonMesh => {
  548. babylonMesh.skeleton = skin._babylonSkeleton!;
  549. });
  550. // Ignore the TRS of skinned nodes.
  551. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  552. node._babylonMesh!.parent = this._rootBabylonMesh;
  553. node._babylonMesh!.position = Vector3.Zero();
  554. node._babylonMesh!.rotationQuaternion = Quaternion.Identity();
  555. node._babylonMesh!.scaling = Vector3.One();
  556. };
  557. if (skin._loaded) {
  558. return skin._loaded.then(() => {
  559. assignSkeleton();
  560. });
  561. }
  562. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  563. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(inverseBindMatricesData => {
  564. const skeletonId = `skeleton${skin._index}`;
  565. const babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  566. skin._babylonSkeleton = babylonSkeleton;
  567. this._loadBones(context, skin, inverseBindMatricesData);
  568. assignSkeleton();
  569. }));
  570. }
  571. private _loadSkinInverseBindMatricesDataAsync(context: string, skin: ILoaderSkin): Promise<Nullable<Float32Array>> {
  572. if (skin.inverseBindMatrices == undefined) {
  573. return Promise.resolve(null);
  574. }
  575. const accessor = GLTFLoader._GetProperty(`${context}/inverseBindMatrices`, this._gltf.accessors, skin.inverseBindMatrices);
  576. return this._loadAccessorAsync(`#/accessors/${accessor._index}`, accessor).then(data => {
  577. return data as Float32Array;
  578. });
  579. }
  580. private _createBone(node: ILoaderNode, skin: ILoaderSkin, parent: Nullable<Bone>, localMatrix: Matrix, baseMatrix: Matrix, index: number): Bone {
  581. const babylonBone = new Bone(node.name || `joint${node._index}`, skin._babylonSkeleton!, parent, localMatrix, null, baseMatrix, index);
  582. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  583. node._babylonAnimationTargets.push(babylonBone);
  584. return babylonBone;
  585. }
  586. private _loadBones(context: string, skin: ILoaderSkin, inverseBindMatricesData: Nullable<Float32Array>): void {
  587. const babylonBones: { [index: number]: Bone } = {};
  588. for (const index of skin.joints) {
  589. const node = GLTFLoader._GetProperty(`${context}/joints/${index}`, this._gltf.nodes, index);
  590. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  591. }
  592. }
  593. private _loadBone(node: ILoaderNode, skin: ILoaderSkin, inverseBindMatricesData: Nullable<Float32Array>, babylonBones: { [index: number]: Bone }): Bone {
  594. let babylonBone = babylonBones[node._index];
  595. if (babylonBone) {
  596. return babylonBone;
  597. }
  598. const boneIndex = skin.joints.indexOf(node._index);
  599. let baseMatrix = Matrix.Identity();
  600. if (inverseBindMatricesData && boneIndex !== -1) {
  601. baseMatrix = Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  602. baseMatrix.invertToRef(baseMatrix);
  603. }
  604. let babylonParentBone: Nullable<Bone> = null;
  605. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  606. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  607. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  608. }
  609. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  610. babylonBones[node._index] = babylonBone;
  611. return babylonBone;
  612. }
  613. private _getNodeMatrix(node: ILoaderNode): Matrix {
  614. return node.matrix ?
  615. Matrix.FromArray(node.matrix) :
  616. Matrix.Compose(
  617. node.scale ? Vector3.FromArray(node.scale) : Vector3.One(),
  618. node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(),
  619. node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());
  620. }
  621. private _loadAnimationsAsync(): Promise<void> {
  622. const animations = this._gltf.animations;
  623. if (!animations) {
  624. return Promise.resolve();
  625. }
  626. const promises = new Array<Promise<void>>();
  627. for (let index = 0; index < animations.length; index++) {
  628. const animation = animations[index];
  629. promises.push(this._loadAnimationAsync(`#/animations/${index}`, animation));
  630. }
  631. return Promise.all(promises).then(() => {});
  632. }
  633. private _loadAnimationAsync(context: string, animation: ILoaderAnimation): Promise<void> {
  634. const babylonAnimationGroup = new AnimationGroup(animation.name || `animation${animation._index}`, this._babylonScene);
  635. animation._babylonAnimationGroup = babylonAnimationGroup;
  636. const promises = new Array<Promise<void>>();
  637. ArrayItem.Assign(animation.channels);
  638. ArrayItem.Assign(animation.samplers);
  639. for (const channel of animation.channels) {
  640. promises.push(this._loadAnimationChannelAsync(`${context}/channels/${channel._index}`, context, animation, channel, babylonAnimationGroup));
  641. }
  642. return Promise.all(promises).then(() => {
  643. babylonAnimationGroup.normalize();
  644. });
  645. }
  646. private _loadAnimationChannelAsync(context: string, animationContext: string, animation: ILoaderAnimation, channel: ILoaderAnimationChannel, babylonAnimationGroup: AnimationGroup): Promise<void> {
  647. const targetNode = GLTFLoader._GetProperty(`${context}/target/node`, this._gltf.nodes, channel.target.node);
  648. if (!targetNode._babylonMesh) {
  649. return Promise.resolve();
  650. }
  651. // Ignore animations targeting TRS of skinned nodes.
  652. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  653. if (targetNode.skin != undefined && channel.target.path !== AnimationChannelTargetPath.WEIGHTS) {
  654. return Promise.resolve();
  655. }
  656. const sampler = GLTFLoader._GetProperty(`${context}/sampler`, animation.samplers, channel.sampler);
  657. return this._loadAnimationSamplerAsync(`${animationContext}/samplers/${channel.sampler}`, sampler).then(data => {
  658. let targetPath: string;
  659. let animationType: number;
  660. switch (channel.target.path) {
  661. case AnimationChannelTargetPath.TRANSLATION: {
  662. targetPath = "position";
  663. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  664. break;
  665. }
  666. case AnimationChannelTargetPath.ROTATION: {
  667. targetPath = "rotationQuaternion";
  668. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  669. break;
  670. }
  671. case AnimationChannelTargetPath.SCALE: {
  672. targetPath = "scaling";
  673. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  674. break;
  675. }
  676. case AnimationChannelTargetPath.WEIGHTS: {
  677. targetPath = "influence";
  678. animationType = Animation.ANIMATIONTYPE_FLOAT;
  679. break;
  680. }
  681. default: {
  682. throw new Error(`${context}: Invalid target path (${channel.target.path})`);
  683. }
  684. }
  685. let outputBufferOffset = 0;
  686. let getNextOutputValue: () => Vector3 | Quaternion | Array<number>;
  687. switch (targetPath) {
  688. case "position": {
  689. getNextOutputValue = () => {
  690. const value = Vector3.FromArray(data.output, outputBufferOffset);
  691. outputBufferOffset += 3;
  692. return value;
  693. };
  694. break;
  695. }
  696. case "rotationQuaternion": {
  697. getNextOutputValue = () => {
  698. const value = Quaternion.FromArray(data.output, outputBufferOffset);
  699. outputBufferOffset += 4;
  700. return value;
  701. };
  702. break;
  703. }
  704. case "scaling": {
  705. getNextOutputValue = () => {
  706. const value = Vector3.FromArray(data.output, outputBufferOffset);
  707. outputBufferOffset += 3;
  708. return value;
  709. };
  710. break;
  711. }
  712. case "influence": {
  713. getNextOutputValue = () => {
  714. const value = new Array<number>(targetNode._numMorphTargets!);
  715. for (let i = 0; i < targetNode._numMorphTargets!; i++) {
  716. value[i] = data.output[outputBufferOffset++];
  717. }
  718. return value;
  719. };
  720. break;
  721. }
  722. }
  723. let getNextKey: (frameIndex: number) => IAnimationKey;
  724. switch (data.interpolation) {
  725. case AnimationSamplerInterpolation.STEP: {
  726. getNextKey = frameIndex => ({
  727. frame: data.input[frameIndex],
  728. value: getNextOutputValue(),
  729. interpolation: AnimationKeyInterpolation.STEP
  730. });
  731. break;
  732. }
  733. case AnimationSamplerInterpolation.LINEAR: {
  734. getNextKey = frameIndex => ({
  735. frame: data.input[frameIndex],
  736. value: getNextOutputValue()
  737. });
  738. break;
  739. }
  740. case AnimationSamplerInterpolation.CUBICSPLINE: {
  741. getNextKey = frameIndex => ({
  742. frame: data.input[frameIndex],
  743. inTangent: getNextOutputValue(),
  744. value: getNextOutputValue(),
  745. outTangent: getNextOutputValue()
  746. });
  747. break;
  748. }
  749. }
  750. const keys = new Array(data.input.length);
  751. for (let frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  752. keys[frameIndex] = getNextKey!(frameIndex);
  753. }
  754. if (targetPath === "influence") {
  755. for (let targetIndex = 0; targetIndex < targetNode._numMorphTargets!; targetIndex++) {
  756. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  757. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  758. babylonAnimation.setKeys(keys.map(key => ({
  759. frame: key.frame,
  760. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  761. value: key.value[targetIndex],
  762. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  763. })));
  764. const multiTarget = new AnimationMultiTarget();
  765. this._forEachPrimitive(targetNode, babylonMesh => {
  766. const morphTarget = babylonMesh.morphTargetManager!.getTarget(targetIndex);
  767. multiTarget.subTargets.push(morphTarget);
  768. });
  769. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, multiTarget);
  770. }
  771. }
  772. else {
  773. const animationName = `${babylonAnimationGroup.name}_channel${babylonAnimationGroup.targetedAnimations.length}`;
  774. const babylonAnimation = new Animation(animationName, targetPath, 1, animationType);
  775. babylonAnimation.setKeys(keys);
  776. if (targetNode._babylonAnimationTargets) {
  777. const multiTarget = new AnimationMultiTarget();
  778. for (const target of targetNode._babylonAnimationTargets) {
  779. multiTarget.subTargets.push(target);
  780. }
  781. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, multiTarget);
  782. }
  783. }
  784. });
  785. }
  786. private _loadAnimationSamplerAsync(context: string, sampler: ILoaderAnimationSampler): Promise<ILoaderAnimationSamplerData> {
  787. if (sampler._data) {
  788. return sampler._data;
  789. }
  790. const interpolation = sampler.interpolation || AnimationSamplerInterpolation.LINEAR;
  791. switch (interpolation) {
  792. case AnimationSamplerInterpolation.STEP:
  793. case AnimationSamplerInterpolation.LINEAR:
  794. case AnimationSamplerInterpolation.CUBICSPLINE: {
  795. break;
  796. }
  797. default: {
  798. throw new Error(`${context}: Invalid interpolation (${sampler.interpolation})`);
  799. }
  800. }
  801. let inputData: Nullable<Float32Array>;
  802. let outputData: Nullable<Float32Array>;
  803. const inputAccessor = GLTFLoader._GetProperty(`${context}/input`, this._gltf.accessors, sampler.input);
  804. const outputAccessor = GLTFLoader._GetProperty(`${context}/output`, this._gltf.accessors, sampler.output);
  805. sampler._data = Promise.all([
  806. this._loadAccessorAsync(`#/accessors/${inputAccessor._index}`, inputAccessor).then(data => {
  807. inputData = data as Float32Array;
  808. }),
  809. this._loadAccessorAsync(`#/accessors/${outputAccessor._index}`, outputAccessor).then(data => {
  810. outputData = data as Float32Array;
  811. })
  812. ]).then(() => {
  813. return {
  814. input: inputData!,
  815. interpolation: interpolation,
  816. output: outputData!,
  817. };
  818. });
  819. return sampler._data;
  820. }
  821. private _loadBufferAsync(context: string, buffer: ILoaderBuffer): Promise<ArrayBufferView> {
  822. if (buffer._data) {
  823. return buffer._data;
  824. }
  825. if (!buffer.uri) {
  826. throw new Error(`${context}: Uri is missing`);
  827. }
  828. buffer._data = this._loadUriAsync(context, buffer.uri);
  829. return buffer._data;
  830. }
  831. public _loadBufferViewAsync(context: string, bufferView: ILoaderBufferView): Promise<ArrayBufferView> {
  832. if (bufferView._data) {
  833. return bufferView._data;
  834. }
  835. const buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  836. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(data => {
  837. try {
  838. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  839. }
  840. catch (e) {
  841. throw new Error(`${context}: ${e.message}`);
  842. }
  843. });
  844. return bufferView._data;
  845. }
  846. private _loadAccessorAsync(context: string, accessor: ILoaderAccessor): Promise<ArrayBufferView> {
  847. if (accessor.sparse) {
  848. throw new Error(`${context}: Sparse accessors are not currently supported`);
  849. }
  850. if (accessor._data) {
  851. return accessor._data;
  852. }
  853. const bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  854. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(data => {
  855. const buffer = data.buffer;
  856. const byteOffset = data.byteOffset + (accessor.byteOffset || 0);
  857. const length = GLTFLoader._GetNumComponents(context, accessor.type) * accessor.count;
  858. try {
  859. switch (accessor.componentType) {
  860. case AccessorComponentType.BYTE: {
  861. return new Int8Array(buffer, byteOffset, length);
  862. }
  863. case AccessorComponentType.UNSIGNED_BYTE: {
  864. return new Uint8Array(buffer, byteOffset, length);
  865. }
  866. case AccessorComponentType.SHORT: {
  867. return new Int16Array(buffer, byteOffset, length);
  868. }
  869. case AccessorComponentType.UNSIGNED_SHORT: {
  870. return new Uint16Array(buffer, byteOffset, length);
  871. }
  872. case AccessorComponentType.UNSIGNED_INT: {
  873. return new Uint32Array(buffer, byteOffset, length);
  874. }
  875. case AccessorComponentType.FLOAT: {
  876. return new Float32Array(buffer, byteOffset, length);
  877. }
  878. default: {
  879. throw new Error(`${context}: Invalid accessor component type ${accessor.componentType}`);
  880. }
  881. }
  882. }
  883. catch (e) {
  884. throw new Error(`${context}: ${e}`);
  885. }
  886. });
  887. return accessor._data;
  888. }
  889. public _loadVertexBufferViewAsync(context: string, bufferView: ILoaderBufferView, kind: string): Promise<Buffer> {
  890. if (bufferView._babylonBuffer) {
  891. return bufferView._babylonBuffer;
  892. }
  893. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(data => {
  894. return new Buffer(this._babylonScene.getEngine(), data, false);
  895. });
  896. return bufferView._babylonBuffer;
  897. }
  898. private _loadVertexAccessorAsync(context: string, accessor: ILoaderAccessor, kind: string): Promise<VertexBuffer> {
  899. if (accessor.sparse) {
  900. throw new Error(`${context}: Sparse accessors are not currently supported`);
  901. }
  902. if (accessor._babylonVertexBuffer) {
  903. return accessor._babylonVertexBuffer;
  904. }
  905. const bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  906. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(buffer => {
  907. const size = GLTFLoader._GetNumComponents(context, accessor.type);
  908. return new VertexBuffer(this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride,
  909. false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  910. });
  911. return accessor._babylonVertexBuffer;
  912. }
  913. private _getDefaultMaterial(drawMode: number): Material {
  914. let babylonMaterial = this._defaultBabylonMaterials[drawMode];
  915. if (!babylonMaterial) {
  916. babylonMaterial = this._createMaterial(PBRMaterial, "__gltf_default", drawMode);
  917. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  918. babylonMaterial.metallic = 1;
  919. babylonMaterial.roughness = 1;
  920. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  921. }
  922. return babylonMaterial;
  923. }
  924. private _loadMaterialMetallicRoughnessPropertiesAsync(context: string, material: ILoaderMaterial, babylonMaterial: PBRMaterial): Promise<void> {
  925. const promises = new Array<Promise<void>>();
  926. // Ensure metallic workflow
  927. babylonMaterial.metallic = 1;
  928. babylonMaterial.roughness = 1;
  929. const properties = material.pbrMetallicRoughness;
  930. if (properties) {
  931. if (properties.baseColorFactor) {
  932. babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);
  933. babylonMaterial.alpha = properties.baseColorFactor[3];
  934. }
  935. else {
  936. babylonMaterial.albedoColor = Color3.White();
  937. }
  938. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  939. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  940. if (properties.baseColorTexture) {
  941. promises.push(this._loadTextureAsync(`${context}/baseColorTexture`, properties.baseColorTexture, texture => {
  942. babylonMaterial.albedoTexture = texture;
  943. }));
  944. }
  945. if (properties.metallicRoughnessTexture) {
  946. promises.push(this._loadTextureAsync(`${context}/metallicRoughnessTexture`, properties.metallicRoughnessTexture, texture => {
  947. babylonMaterial.metallicTexture = texture;
  948. }));
  949. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  950. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  951. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  952. }
  953. }
  954. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  955. return Promise.all(promises).then(() => {});
  956. }
  957. public _loadMaterialAsync(context: string, material: ILoaderMaterial, babylonMesh: Mesh, babylonDrawMode: number, assign: (babylonMaterial: Material) => void): Promise<void> {
  958. const promise = GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  959. if (promise) {
  960. return promise;
  961. }
  962. material._babylonData = material._babylonData || {};
  963. let babylonData = material._babylonData[babylonDrawMode];
  964. if (!babylonData) {
  965. const promises = new Array<Promise<void>>();
  966. const name = material.name || `materialSG_${material._index}`;
  967. const babylonMaterial = this._createMaterial(PBRMaterial, name, babylonDrawMode);
  968. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  969. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  970. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  971. babylonData = {
  972. material: babylonMaterial,
  973. meshes: [],
  974. loaded: Promise.all(promises).then(() => {})
  975. };
  976. material._babylonData[babylonDrawMode] = babylonData;
  977. }
  978. babylonData.meshes.push(babylonMesh);
  979. assign(babylonData.material);
  980. return babylonData.loaded;
  981. }
  982. public _createMaterial<T extends Material>(type: MaterialConstructor<T>, name: string, drawMode: number): T {
  983. const babylonMaterial = new type(name, this._babylonScene);
  984. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
  985. babylonMaterial.fillMode = drawMode;
  986. return babylonMaterial;
  987. }
  988. public _loadMaterialBasePropertiesAsync(context: string, material: ILoaderMaterial, babylonMaterial: PBRMaterial): Promise<void> {
  989. const promises = new Array<Promise<void>>();
  990. babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  991. if (material.doubleSided) {
  992. babylonMaterial.backFaceCulling = false;
  993. babylonMaterial.twoSidedLighting = true;
  994. }
  995. if (material.normalTexture) {
  996. promises.push(this._loadTextureAsync(`${context}/normalTexture`, material.normalTexture, texture => {
  997. babylonMaterial.bumpTexture = texture;
  998. }));
  999. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1000. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1001. if (material.normalTexture.scale != undefined) {
  1002. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1003. }
  1004. }
  1005. if (material.occlusionTexture) {
  1006. promises.push(this._loadTextureAsync(`${context}/occlusionTexture`, material.occlusionTexture, texture => {
  1007. babylonMaterial.ambientTexture = texture;
  1008. }));
  1009. babylonMaterial.useAmbientInGrayScale = true;
  1010. if (material.occlusionTexture.strength != undefined) {
  1011. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1012. }
  1013. }
  1014. if (material.emissiveTexture) {
  1015. promises.push(this._loadTextureAsync(`${context}/emissiveTexture`, material.emissiveTexture, texture => {
  1016. babylonMaterial.emissiveTexture = texture;
  1017. }));
  1018. }
  1019. return Promise.all(promises).then(() => {});
  1020. }
  1021. public _loadMaterialAlphaProperties(context: string, material: ILoaderMaterial, babylonMaterial: PBRMaterial): void {
  1022. const alphaMode = material.alphaMode || MaterialAlphaMode.OPAQUE;
  1023. switch (alphaMode) {
  1024. case MaterialAlphaMode.OPAQUE: {
  1025. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;
  1026. break;
  1027. }
  1028. case MaterialAlphaMode.MASK: {
  1029. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;
  1030. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  1031. if (babylonMaterial.albedoTexture) {
  1032. babylonMaterial.albedoTexture.hasAlpha = true;
  1033. }
  1034. break;
  1035. }
  1036. case MaterialAlphaMode.BLEND: {
  1037. babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1038. if (babylonMaterial.albedoTexture) {
  1039. babylonMaterial.albedoTexture.hasAlpha = true;
  1040. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1041. }
  1042. break;
  1043. }
  1044. default: {
  1045. throw new Error(`${context}: Invalid alpha mode (${material.alphaMode})`);
  1046. }
  1047. }
  1048. }
  1049. public _loadTextureAsync(context: string, textureInfo: ITextureInfo, assign: (texture: Texture) => void): Promise<void> {
  1050. const texture = GLTFLoader._GetProperty(`${context}/index`, this._gltf.textures, textureInfo.index);
  1051. context = `#/textures/${textureInfo.index}`;
  1052. const promises = new Array<Promise<void>>();
  1053. const sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(`${context}/sampler`, this._gltf.samplers, texture.sampler));
  1054. const samplerData = this._loadSampler(`#/samplers/${sampler._index}`, sampler);
  1055. const deferred = new Deferred<void>();
  1056. const babylonTexture = new Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, () => {
  1057. if (!this._disposed) {
  1058. deferred.resolve();
  1059. }
  1060. }, (message, exception) => {
  1061. if (!this._disposed) {
  1062. deferred.reject(new Error(`${context}: ${(exception && exception.message) ? exception.message : message || "Failed to load texture"}`));
  1063. }
  1064. });
  1065. promises.push(deferred.promise);
  1066. babylonTexture.name = texture.name || `texture${texture._index}`;
  1067. babylonTexture.wrapU = samplerData.wrapU;
  1068. babylonTexture.wrapV = samplerData.wrapV;
  1069. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  1070. const image = GLTFLoader._GetProperty(`${context}/source`, this._gltf.images, texture.source);
  1071. promises.push(this._loadImageAsync(`#/images/${image._index}`, image).then(objectURL => {
  1072. babylonTexture.updateURL(objectURL);
  1073. }));
  1074. assign(babylonTexture);
  1075. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1076. return Promise.all(promises).then(() => {});
  1077. }
  1078. private _loadSampler(context: string, sampler: ILoaderSampler): ILoaderSamplerData {
  1079. if (!sampler._data) {
  1080. sampler._data = {
  1081. noMipMaps: (sampler.minFilter === TextureMinFilter.NEAREST || sampler.minFilter === TextureMinFilter.LINEAR),
  1082. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  1083. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  1084. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  1085. };
  1086. };
  1087. return sampler._data;
  1088. }
  1089. private _loadImageAsync(context: string, image: ILoaderImage): Promise<string> {
  1090. if (image._objectURL) {
  1091. return image._objectURL;
  1092. }
  1093. let promise: Promise<ArrayBufferView>;
  1094. if (image.uri) {
  1095. promise = this._loadUriAsync(context, image.uri);
  1096. }
  1097. else {
  1098. const bufferView = GLTFLoader._GetProperty(`${context}/bufferView`, this._gltf.bufferViews, image.bufferView);
  1099. promise = this._loadBufferViewAsync(`#/bufferViews/${bufferView._index}`, bufferView);
  1100. }
  1101. image._objectURL = promise.then(data => {
  1102. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  1103. });
  1104. return image._objectURL;
  1105. }
  1106. public _loadUriAsync(context: string, uri: string): Promise<ArrayBufferView> {
  1107. const promise = GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  1108. if (promise) {
  1109. return promise;
  1110. }
  1111. if (!GLTFLoader._ValidateUri(uri)) {
  1112. throw new Error(`${context}: Uri '${uri}' is invalid`);
  1113. }
  1114. if (Tools.IsBase64(uri)) {
  1115. return Promise.resolve(new Uint8Array(Tools.DecodeBase64(uri)));
  1116. }
  1117. return new Promise((resolve, reject) => {
  1118. const request = Tools.LoadFile(this._rootUrl + uri, data => {
  1119. if (!this._disposed) {
  1120. resolve(new Uint8Array(data as ArrayBuffer));
  1121. }
  1122. }, event => {
  1123. if (!this._disposed) {
  1124. try {
  1125. if (request && this._state === GLTFLoaderState.Loading) {
  1126. request._lengthComputable = event.lengthComputable;
  1127. request._loaded = event.loaded;
  1128. request._total = event.total;
  1129. this._onProgress();
  1130. }
  1131. }
  1132. catch (e) {
  1133. reject(e);
  1134. }
  1135. }
  1136. }, this._babylonScene.database, true, (request, exception) => {
  1137. if (!this._disposed) {
  1138. reject(new LoadFileError(`${context}: Failed to load '${uri}'${request ? ": " + request.status + " " + request.statusText : ""}`, request));
  1139. }
  1140. }) as IFileRequestInfo;
  1141. this._requests.push(request);
  1142. })
  1143. }
  1144. private _onProgress(): void {
  1145. if (!this._progressCallback) {
  1146. return;
  1147. }
  1148. let lengthComputable = true;
  1149. let loaded = 0;
  1150. let total = 0;
  1151. for (let request of this._requests) {
  1152. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  1153. return;
  1154. }
  1155. lengthComputable = lengthComputable && request._lengthComputable;
  1156. loaded += request._loaded;
  1157. total += request._total;
  1158. }
  1159. this._progressCallback(new SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  1160. }
  1161. public static _GetProperty<T>(context: string, array: ArrayLike<T> | undefined, index: number | undefined): T {
  1162. if (!array || index == undefined || !array[index]) {
  1163. throw new Error(`${context}: Failed to find index (${index})`);
  1164. }
  1165. return array[index];
  1166. }
  1167. private static _GetTextureWrapMode(context: string, mode: TextureWrapMode | undefined): number {
  1168. // Set defaults if undefined
  1169. mode = mode == undefined ? TextureWrapMode.REPEAT : mode;
  1170. switch (mode) {
  1171. case TextureWrapMode.CLAMP_TO_EDGE: return Texture.CLAMP_ADDRESSMODE;
  1172. case TextureWrapMode.MIRRORED_REPEAT: return Texture.MIRROR_ADDRESSMODE;
  1173. case TextureWrapMode.REPEAT: return Texture.WRAP_ADDRESSMODE;
  1174. default:
  1175. Tools.Warn(`${context}: Invalid texture wrap mode (${mode})`);
  1176. return Texture.WRAP_ADDRESSMODE;
  1177. }
  1178. }
  1179. private static _GetTextureSamplingMode(context: string, magFilter?: TextureMagFilter, minFilter?: TextureMinFilter): number {
  1180. // Set defaults if undefined
  1181. magFilter = magFilter == undefined ? TextureMagFilter.LINEAR : magFilter;
  1182. minFilter = minFilter == undefined ? TextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  1183. if (magFilter === TextureMagFilter.LINEAR) {
  1184. switch (minFilter) {
  1185. case TextureMinFilter.NEAREST: return Texture.LINEAR_NEAREST;
  1186. case TextureMinFilter.LINEAR: return Texture.LINEAR_LINEAR;
  1187. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.LINEAR_NEAREST_MIPNEAREST;
  1188. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.LINEAR_LINEAR_MIPNEAREST;
  1189. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.LINEAR_NEAREST_MIPLINEAR;
  1190. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.LINEAR_LINEAR_MIPLINEAR;
  1191. default:
  1192. Tools.Warn(`${context}: Invalid texture minification filter (${minFilter})`);
  1193. return Texture.LINEAR_LINEAR_MIPLINEAR;
  1194. }
  1195. }
  1196. else {
  1197. if (magFilter !== TextureMagFilter.NEAREST) {
  1198. Tools.Warn(`${context}: Invalid texture magnification filter (${magFilter})`);
  1199. }
  1200. switch (minFilter) {
  1201. case TextureMinFilter.NEAREST: return Texture.NEAREST_NEAREST;
  1202. case TextureMinFilter.LINEAR: return Texture.NEAREST_LINEAR;
  1203. case TextureMinFilter.NEAREST_MIPMAP_NEAREST: return Texture.NEAREST_NEAREST_MIPNEAREST;
  1204. case TextureMinFilter.LINEAR_MIPMAP_NEAREST: return Texture.NEAREST_LINEAR_MIPNEAREST;
  1205. case TextureMinFilter.NEAREST_MIPMAP_LINEAR: return Texture.NEAREST_NEAREST_MIPLINEAR;
  1206. case TextureMinFilter.LINEAR_MIPMAP_LINEAR: return Texture.NEAREST_LINEAR_MIPLINEAR;
  1207. default:
  1208. Tools.Warn(`${context}: Invalid texture minification filter (${minFilter})`);
  1209. return Texture.NEAREST_NEAREST_MIPNEAREST;
  1210. }
  1211. }
  1212. }
  1213. private static _GetNumComponents(context: string, type: string): number {
  1214. switch (type) {
  1215. case "SCALAR": return 1;
  1216. case "VEC2": return 2;
  1217. case "VEC3": return 3;
  1218. case "VEC4": return 4;
  1219. case "MAT2": return 4;
  1220. case "MAT3": return 9;
  1221. case "MAT4": return 16;
  1222. }
  1223. throw new Error(`${context}: Invalid type (${type})`);
  1224. }
  1225. private static _ValidateUri(uri: string): boolean {
  1226. return (Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  1227. }
  1228. private static _GetDrawMode(context: string, mode: number | undefined): number {
  1229. if (mode == undefined) {
  1230. mode = MeshPrimitiveMode.TRIANGLES;
  1231. }
  1232. switch (mode) {
  1233. case MeshPrimitiveMode.POINTS: return Material.PointListDrawMode;
  1234. case MeshPrimitiveMode.LINES: return Material.LineListDrawMode;
  1235. case MeshPrimitiveMode.LINE_LOOP: return Material.LineLoopDrawMode;
  1236. case MeshPrimitiveMode.LINE_STRIP: return Material.LineStripDrawMode;
  1237. case MeshPrimitiveMode.TRIANGLES: return Material.TriangleFillMode;
  1238. case MeshPrimitiveMode.TRIANGLE_STRIP: return Material.TriangleStripDrawMode;
  1239. case MeshPrimitiveMode.TRIANGLE_FAN: return Material.TriangleFanDrawMode;
  1240. }
  1241. throw new Error(`${context}: Invalid mesh primitive mode (${mode})`);
  1242. }
  1243. private _compileMaterialsAsync(): Promise<void> {
  1244. const promises = new Array<Promise<void>>();
  1245. if (this._gltf.materials) {
  1246. for (const material of this._gltf.materials) {
  1247. if (material._babylonData) {
  1248. for (const babylonDrawMode in material._babylonData) {
  1249. const babylonData = material._babylonData[babylonDrawMode];
  1250. for (const babylonMesh of babylonData.meshes) {
  1251. // Ensure nonUniformScaling is set if necessary.
  1252. babylonMesh.computeWorldMatrix(true);
  1253. const babylonMaterial = babylonData.material;
  1254. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  1255. if (this.useClipPlane) {
  1256. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  1257. }
  1258. }
  1259. }
  1260. }
  1261. }
  1262. }
  1263. return Promise.all(promises).then(() => {});
  1264. }
  1265. private _compileShadowGeneratorsAsync(): Promise<void> {
  1266. const promises = new Array<Promise<void>>();
  1267. const lights = this._babylonScene.lights;
  1268. for (let light of lights) {
  1269. let generator = light.getShadowGenerator();
  1270. if (generator) {
  1271. promises.push(generator.forceCompilationAsync());
  1272. }
  1273. }
  1274. return Promise.all(promises).then(() => {});
  1275. }
  1276. private _clear(): void {
  1277. for (const request of this._requests) {
  1278. request.abort();
  1279. }
  1280. this._requests.length = 0;
  1281. if (this._gltf && this._gltf.images) {
  1282. for (const image of this._gltf.images) {
  1283. if (image._objectURL) {
  1284. image._objectURL.then(value => {
  1285. URL.revokeObjectURL(value);
  1286. });
  1287. image._objectURL = undefined;
  1288. }
  1289. }
  1290. }
  1291. delete this._gltf;
  1292. delete this._babylonScene;
  1293. this._completePromises.length = 0;
  1294. for (const name in this._extensions) {
  1295. this._extensions[name].dispose();
  1296. }
  1297. this._extensions = {};
  1298. delete this._rootBabylonMesh;
  1299. delete this._progressCallback;
  1300. this.onMeshLoadedObservable.clear();
  1301. this.onTextureLoadedObservable.clear();
  1302. this.onMaterialLoadedObservable.clear();
  1303. }
  1304. public _applyExtensions<T>(actionAsync: (extension: GLTFLoaderExtension) => Nullable<Promise<T>>) {
  1305. for (const name of GLTFLoader._Names) {
  1306. const extension = this._extensions[name];
  1307. if (extension.enabled) {
  1308. const promise = actionAsync(extension);
  1309. if (promise) {
  1310. return promise;
  1311. }
  1312. }
  1313. }
  1314. return null;
  1315. }
  1316. }
  1317. GLTFFileLoader.CreateGLTFLoaderV2 = () => new GLTFLoader();
  1318. }