sceneLoader.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. import { Tools } from "../Misc/tools";
  2. import { Observable } from "../Misc/observable";
  3. import { FilesInputStore } from "../Misc/filesInputStore";
  4. import { Nullable } from "../types";
  5. import { Scene } from "../scene";
  6. import { Engine } from "../Engines/engine";
  7. import { EngineStore } from "../Engines/engineStore";
  8. import { AbstractMesh } from "../Meshes/abstractMesh";
  9. import { AnimationGroup } from "../Animations/animationGroup";
  10. import { _TimeToken } from "../Instrumentation/timeToken";
  11. import { AssetContainer } from "../assetContainer";
  12. import { IParticleSystem } from "../Particles/IParticleSystem";
  13. import { Skeleton } from "../Bones/skeleton";
  14. import { Logger } from "../Misc/logger";
  15. import { Constants } from "../Engines/constants";
  16. import { SceneLoaderFlags } from "./sceneLoaderFlags";
  17. import { IFileRequest } from "../Misc/fileRequest";
  18. import { WebRequest } from "../Misc/webRequest";
  19. import { RequestFileError, ReadFileError } from '../Misc/fileTools';
  20. /**
  21. * Class used to represent data loading progression
  22. */
  23. export class SceneLoaderProgressEvent {
  24. /**
  25. * Create a new progress event
  26. * @param lengthComputable defines if data length to load can be evaluated
  27. * @param loaded defines the loaded data length
  28. * @param total defines the data length to load
  29. */
  30. constructor(
  31. /** defines if data length to load can be evaluated */
  32. public readonly lengthComputable: boolean,
  33. /** defines the loaded data length */
  34. public readonly loaded: number,
  35. /** defines the data length to load */
  36. public readonly total: number) {
  37. }
  38. /**
  39. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  40. * @param event defines the source event
  41. * @returns a new SceneLoaderProgressEvent
  42. */
  43. public static FromProgressEvent(event: ProgressEvent): SceneLoaderProgressEvent {
  44. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  45. }
  46. }
  47. /**
  48. * Interface used by SceneLoader plugins to define supported file extensions
  49. */
  50. export interface ISceneLoaderPluginExtensions {
  51. /**
  52. * Defines the list of supported extensions
  53. */
  54. [extension: string]: {
  55. isBinary: boolean;
  56. };
  57. }
  58. /**
  59. * Interface used by SceneLoader plugin factory
  60. */
  61. export interface ISceneLoaderPluginFactory {
  62. /**
  63. * Defines the name of the factory
  64. */
  65. name: string;
  66. /**
  67. * Function called to create a new plugin
  68. * @return the new plugin
  69. */
  70. createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  71. /**
  72. * The callback that returns true if the data can be directly loaded.
  73. * @param data string containing the file data
  74. * @returns if the data can be loaded directly
  75. */
  76. canDirectLoad?(data: string): boolean;
  77. }
  78. /**
  79. * Interface used to define the base of ISceneLoaderPlugin and ISceneLoaderPluginAsync
  80. */
  81. export interface ISceneLoaderPluginBase {
  82. /**
  83. * The friendly name of this plugin.
  84. */
  85. name: string;
  86. /**
  87. * The file extensions supported by this plugin.
  88. */
  89. extensions: string | ISceneLoaderPluginExtensions;
  90. /**
  91. * The callback called when loading from a url.
  92. * @param scene scene loading this url
  93. * @param url url to load
  94. * @param onSuccess callback called when the file successfully loads
  95. * @param onProgress callback called while file is loading (if the server supports this mode)
  96. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  97. * @param onError callback called when the file fails to load
  98. * @returns a file request object
  99. */
  100. requestFile?(scene: Scene, url: string, onSuccess: (data: any, request?: WebRequest) => void, onProgress?: (ev: ProgressEvent) => void, useArrayBuffer?: boolean, onError?: (error: any) => void): IFileRequest;
  101. /**
  102. * The callback called when loading from a file object.
  103. * @param scene scene loading this file
  104. * @param file defines the file to load
  105. * @param onSuccess defines the callback to call when data is loaded
  106. * @param onProgress defines the callback to call during loading process
  107. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  108. * @param onError defines the callback to call when an error occurs
  109. * @returns a file request object
  110. */
  111. readFile?(scene: Scene, file: File, onSuccess: (data: any) => void, onProgress?: (ev: ProgressEvent) => any, useArrayBuffer?: boolean, onError?: (error: any) => void): IFileRequest;
  112. /**
  113. * The callback that returns true if the data can be directly loaded.
  114. * @param data string containing the file data
  115. * @returns if the data can be loaded directly
  116. */
  117. canDirectLoad?(data: string): boolean;
  118. /**
  119. * The callback that returns the data to pass to the plugin if the data can be directly loaded.
  120. * @param scene scene loading this data
  121. * @param data string containing the data
  122. * @returns data to pass to the plugin
  123. */
  124. directLoad?(scene: Scene, data: string): any;
  125. /**
  126. * The callback that allows custom handling of the root url based on the response url.
  127. * @param rootUrl the original root url
  128. * @param responseURL the response url if available
  129. * @returns the new root url
  130. */
  131. rewriteRootURL?(rootUrl: string, responseURL?: string): string;
  132. }
  133. /**
  134. * Interface used to define a SceneLoader plugin
  135. */
  136. export interface ISceneLoaderPlugin extends ISceneLoaderPluginBase {
  137. /**
  138. * Import meshes into a scene.
  139. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  140. * @param scene The scene to import into
  141. * @param data The data to import
  142. * @param rootUrl The root url for scene and resources
  143. * @param meshes The meshes array to import into
  144. * @param particleSystems The particle systems array to import into
  145. * @param skeletons The skeletons array to import into
  146. * @param onError The callback when import fails
  147. * @returns True if successful or false otherwise
  148. */
  149. importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], onError?: (message: string, exception?: any) => void): boolean;
  150. /**
  151. * Load into a scene.
  152. * @param scene The scene to load into
  153. * @param data The data to import
  154. * @param rootUrl The root url for scene and resources
  155. * @param onError The callback when import fails
  156. * @returns True if successful or false otherwise
  157. */
  158. load(scene: Scene, data: any, rootUrl: string, onError?: (message: string, exception?: any) => void): boolean;
  159. /**
  160. * Load into an asset container.
  161. * @param scene The scene to load into
  162. * @param data The data to import
  163. * @param rootUrl The root url for scene and resources
  164. * @param onError The callback when import fails
  165. * @returns The loaded asset container
  166. */
  167. loadAssetContainer(scene: Scene, data: any, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer;
  168. }
  169. /**
  170. * Interface used to define an async SceneLoader plugin
  171. */
  172. export interface ISceneLoaderPluginAsync extends ISceneLoaderPluginBase {
  173. /**
  174. * Import meshes into a scene.
  175. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  176. * @param scene The scene to import into
  177. * @param data The data to import
  178. * @param rootUrl The root url for scene and resources
  179. * @param onProgress The callback when the load progresses
  180. * @param fileName Defines the name of the file to load
  181. * @returns The loaded meshes, particle systems, skeletons, and animation groups
  182. */
  183. importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<{ meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }>;
  184. /**
  185. * Load into a scene.
  186. * @param scene The scene to load into
  187. * @param data The data to import
  188. * @param rootUrl The root url for scene and resources
  189. * @param onProgress The callback when the load progresses
  190. * @param fileName Defines the name of the file to load
  191. * @returns Nothing
  192. */
  193. loadAsync(scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<void>;
  194. /**
  195. * Load into an asset container.
  196. * @param scene The scene to load into
  197. * @param data The data to import
  198. * @param rootUrl The root url for scene and resources
  199. * @param onProgress The callback when the load progresses
  200. * @param fileName Defines the name of the file to load
  201. * @returns The loaded asset container
  202. */
  203. loadAssetContainerAsync(scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<AssetContainer>;
  204. }
  205. /**
  206. * Defines a plugin registered by the SceneLoader
  207. */
  208. interface IRegisteredPlugin {
  209. /**
  210. * Defines the plugin to use
  211. */
  212. plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory;
  213. /**
  214. * Defines if the plugin supports binary data
  215. */
  216. isBinary: boolean;
  217. }
  218. /**
  219. * Defines file information
  220. */
  221. interface IFileInfo {
  222. /**
  223. * Gets the file url
  224. */
  225. url: string;
  226. /**
  227. * Gets the root url
  228. */
  229. rootUrl: string;
  230. /**
  231. * Gets filename
  232. */
  233. name: string;
  234. /**
  235. * Gets the file
  236. */
  237. file: Nullable<File>;
  238. }
  239. /**
  240. * Class used to load scene from various file formats using registered plugins
  241. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  242. */
  243. export class SceneLoader {
  244. /**
  245. * No logging while loading
  246. */
  247. public static readonly NO_LOGGING = Constants.SCENELOADER_NO_LOGGING;
  248. /**
  249. * Minimal logging while loading
  250. */
  251. public static readonly MINIMAL_LOGGING = Constants.SCENELOADER_MINIMAL_LOGGING;
  252. /**
  253. * Summary logging while loading
  254. */
  255. public static readonly SUMMARY_LOGGING = Constants.SCENELOADER_SUMMARY_LOGGING;
  256. /**
  257. * Detailled logging while loading
  258. */
  259. public static readonly DETAILED_LOGGING = Constants.SCENELOADER_DETAILED_LOGGING;
  260. /**
  261. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  262. */
  263. public static get ForceFullSceneLoadingForIncremental() {
  264. return SceneLoaderFlags.ForceFullSceneLoadingForIncremental;
  265. }
  266. public static set ForceFullSceneLoadingForIncremental(value: boolean) {
  267. SceneLoaderFlags.ForceFullSceneLoadingForIncremental = value;
  268. }
  269. /**
  270. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  271. */
  272. public static get ShowLoadingScreen(): boolean {
  273. return SceneLoaderFlags.ShowLoadingScreen;
  274. }
  275. public static set ShowLoadingScreen(value: boolean) {
  276. SceneLoaderFlags.ShowLoadingScreen = value;
  277. }
  278. /**
  279. * Defines the current logging level (while loading the scene)
  280. * @ignorenaming
  281. */
  282. public static get loggingLevel(): number {
  283. return SceneLoaderFlags.loggingLevel;
  284. }
  285. public static set loggingLevel(value: number) {
  286. SceneLoaderFlags.loggingLevel = value;
  287. }
  288. /**
  289. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  290. */
  291. public static get CleanBoneMatrixWeights(): boolean {
  292. return SceneLoaderFlags.CleanBoneMatrixWeights;
  293. }
  294. public static set CleanBoneMatrixWeights(value: boolean) {
  295. SceneLoaderFlags.CleanBoneMatrixWeights = value;
  296. }
  297. // Members
  298. /**
  299. * Event raised when a plugin is used to load a scene
  300. */
  301. public static OnPluginActivatedObservable = new Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>();
  302. private static _registeredPlugins: { [extension: string]: IRegisteredPlugin } = {};
  303. private static _getDefaultPlugin(): IRegisteredPlugin {
  304. return SceneLoader._registeredPlugins[".babylon"];
  305. }
  306. private static _getPluginForExtension(extension: string): IRegisteredPlugin {
  307. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  308. if (registeredPlugin) {
  309. return registeredPlugin;
  310. }
  311. Logger.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  312. return SceneLoader._getDefaultPlugin();
  313. }
  314. private static _getPluginForDirectLoad(data: string): IRegisteredPlugin {
  315. for (var extension in SceneLoader._registeredPlugins) {
  316. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  317. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  318. return SceneLoader._registeredPlugins[extension];
  319. }
  320. }
  321. return SceneLoader._getDefaultPlugin();
  322. }
  323. private static _getPluginForFilename(sceneFilename: string): IRegisteredPlugin {
  324. var queryStringPosition = sceneFilename.indexOf("?");
  325. if (queryStringPosition !== -1) {
  326. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  327. }
  328. var dotPosition = sceneFilename.lastIndexOf(".");
  329. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  330. return SceneLoader._getPluginForExtension(extension);
  331. }
  332. private static _getDirectLoad(sceneFilename: string): Nullable<string> {
  333. if (sceneFilename.substr(0, 5) === "data:") {
  334. return sceneFilename.substr(5);
  335. }
  336. return null;
  337. }
  338. private static _loadData(fileInfo: IFileInfo, scene: Scene, onSuccess: (plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync, data: any, responseURL?: string) => void, onProgress: ((event: SceneLoaderProgressEvent) => void) | undefined, onError: (message: string, exception?: any) => void, onDispose: () => void, pluginExtension: Nullable<string>): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  339. const directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  340. const registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  341. let plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  342. if ((registeredPlugin.plugin as ISceneLoaderPluginFactory).createPlugin) {
  343. plugin = (registeredPlugin.plugin as ISceneLoaderPluginFactory).createPlugin();
  344. }
  345. else {
  346. plugin = <any>registeredPlugin.plugin;
  347. }
  348. if (!plugin) {
  349. throw "The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";
  350. }
  351. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  352. if (directLoad) {
  353. onSuccess(plugin, plugin.directLoad ? plugin.directLoad(scene, directLoad) : directLoad);
  354. return plugin;
  355. }
  356. const useArrayBuffer = registeredPlugin.isBinary;
  357. const dataCallback = (data: any, responseURL?: string) => {
  358. if (scene.isDisposed) {
  359. onError("Scene has been disposed");
  360. return;
  361. }
  362. onSuccess(plugin, data, responseURL);
  363. };
  364. let request: Nullable<IFileRequest> = null;
  365. let pluginDisposed = false;
  366. const onDisposeObservable = (plugin as any).onDisposeObservable as Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>;
  367. if (onDisposeObservable) {
  368. onDisposeObservable.add(() => {
  369. pluginDisposed = true;
  370. if (request) {
  371. request.abort();
  372. request = null;
  373. }
  374. onDispose();
  375. });
  376. }
  377. const progressCallback = onProgress ? (event: ProgressEvent) => {
  378. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  379. } : undefined;
  380. const manifestChecked = () => {
  381. if (pluginDisposed) {
  382. return;
  383. }
  384. const successCallback = (data: string | ArrayBuffer, request?: WebRequest) => {
  385. dataCallback(data, request ? request.responseURL : undefined);
  386. };
  387. const errorCallback = (error: RequestFileError) => {
  388. onError(error.message, error);
  389. };
  390. request = plugin.requestFile
  391. ? plugin.requestFile(scene, fileInfo.url, successCallback, progressCallback, useArrayBuffer, errorCallback)
  392. : scene._requestFile(fileInfo.url, successCallback, progressCallback, true, useArrayBuffer, errorCallback);
  393. };
  394. const file = fileInfo.file || FilesInputStore.FilesToLoad[fileInfo.name.toLowerCase()];
  395. if (fileInfo.rootUrl.indexOf("file:") === -1 || (fileInfo.rootUrl.indexOf("file:") !== -1 && !file)) {
  396. const engine = scene.getEngine();
  397. let canUseOfflineSupport = engine.enableOfflineSupport;
  398. if (canUseOfflineSupport) {
  399. // Also check for exceptions
  400. let exceptionFound = false;
  401. for (var regex of scene.disableOfflineSupportExceptionRules) {
  402. if (regex.test(fileInfo.url)) {
  403. exceptionFound = true;
  404. break;
  405. }
  406. }
  407. canUseOfflineSupport = !exceptionFound;
  408. }
  409. if (canUseOfflineSupport && Engine.OfflineProviderFactory) {
  410. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  411. scene.offlineProvider = Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  412. }
  413. else {
  414. manifestChecked();
  415. }
  416. }
  417. // Loading file from disk via input file or drag'n'drop
  418. else {
  419. if (file) {
  420. const errorCallback = (error: ReadFileError) => {
  421. onError(error.message, error);
  422. };
  423. request = plugin.readFile
  424. ? plugin.readFile(scene, file, dataCallback, progressCallback, useArrayBuffer, errorCallback)
  425. : scene._readFile(file, dataCallback, progressCallback, useArrayBuffer, errorCallback);
  426. } else {
  427. onError("Unable to find file named " + fileInfo.name);
  428. }
  429. }
  430. return plugin;
  431. }
  432. private static _getFileInfo(rootUrl: string, sceneFilename: string | File): Nullable<IFileInfo> {
  433. let url: string;
  434. let name: string;
  435. let file: Nullable<File> = null;
  436. if (!sceneFilename) {
  437. url = rootUrl;
  438. name = Tools.GetFilename(rootUrl);
  439. rootUrl = Tools.GetFolderPath(rootUrl);
  440. }
  441. else if ((sceneFilename as File).name) {
  442. const sceneFile = sceneFilename as File;
  443. url = rootUrl + sceneFile.name;
  444. name = sceneFile.name;
  445. file = sceneFile;
  446. }
  447. else {
  448. const filename = sceneFilename as string;
  449. if (filename.substr(0, 1) === "/") {
  450. Tools.Error("Wrong sceneFilename parameter");
  451. return null;
  452. }
  453. url = rootUrl + filename;
  454. name = filename;
  455. }
  456. return {
  457. url: url,
  458. rootUrl: rootUrl,
  459. name: name,
  460. file: file
  461. };
  462. }
  463. // Public functions
  464. /**
  465. * Gets a plugin that can load the given extension
  466. * @param extension defines the extension to load
  467. * @returns a plugin or null if none works
  468. */
  469. public static GetPluginForExtension(extension: string): ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory {
  470. return SceneLoader._getPluginForExtension(extension).plugin;
  471. }
  472. /**
  473. * Gets a boolean indicating that the given extension can be loaded
  474. * @param extension defines the extension to load
  475. * @returns true if the extension is supported
  476. */
  477. public static IsPluginForExtensionAvailable(extension: string): boolean {
  478. return !!SceneLoader._registeredPlugins[extension];
  479. }
  480. /**
  481. * Adds a new plugin to the list of registered plugins
  482. * @param plugin defines the plugin to add
  483. */
  484. public static RegisterPlugin(plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync): void {
  485. if (typeof plugin.extensions === "string") {
  486. var extension = <string>plugin.extensions;
  487. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  488. plugin: plugin,
  489. isBinary: false
  490. };
  491. }
  492. else {
  493. var extensions = <ISceneLoaderPluginExtensions>plugin.extensions;
  494. Object.keys(extensions).forEach((extension) => {
  495. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  496. plugin: plugin,
  497. isBinary: extensions[extension].isBinary
  498. };
  499. });
  500. }
  501. }
  502. /**
  503. * Import meshes into a scene
  504. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  505. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  506. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  507. * @param scene the instance of BABYLON.Scene to append to
  508. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  509. * @param onProgress a callback with a progress event for each file being loaded
  510. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  511. * @param pluginExtension the extension used to determine the plugin
  512. * @returns The loaded plugin
  513. */
  514. public static ImportMesh(meshNames: any, rootUrl: string, sceneFilename: string | File = "", scene: Nullable<Scene> = EngineStore.LastCreatedScene, onSuccess: Nullable<(meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[]) => void> = null, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null, pluginExtension: Nullable<string> = null): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  515. if (!scene) {
  516. Logger.Error("No scene available to import mesh to");
  517. return null;
  518. }
  519. const fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  520. if (!fileInfo) {
  521. return null;
  522. }
  523. var loadingToken = {};
  524. scene._addPendingData(loadingToken);
  525. var disposeHandler = () => {
  526. scene._removePendingData(loadingToken);
  527. };
  528. var errorHandler = (message: string, exception?: any) => {
  529. let errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  530. if (onError) {
  531. onError(scene, errorMessage, exception);
  532. } else {
  533. Logger.Error(errorMessage);
  534. // should the exception be thrown?
  535. }
  536. disposeHandler();
  537. };
  538. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  539. try {
  540. onProgress(event);
  541. }
  542. catch (e) {
  543. errorHandler("Error in onProgress callback: " + e, e);
  544. }
  545. } : undefined;
  546. var successHandler = (meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[]) => {
  547. scene.importedMeshesFiles.push(fileInfo.url);
  548. if (onSuccess) {
  549. try {
  550. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  551. }
  552. catch (e) {
  553. errorHandler("Error in onSuccess callback: " + e, e);
  554. }
  555. }
  556. scene._removePendingData(loadingToken);
  557. };
  558. return SceneLoader._loadData(fileInfo, scene, (plugin, data, responseURL) => {
  559. if (plugin.rewriteRootURL) {
  560. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  561. }
  562. if ((<any>plugin).importMesh) {
  563. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  564. var meshes = new Array<AbstractMesh>();
  565. var particleSystems = new Array<IParticleSystem>();
  566. var skeletons = new Array<Skeleton>();
  567. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  568. return;
  569. }
  570. scene.loadingPluginName = plugin.name;
  571. successHandler(meshes, particleSystems, skeletons, []);
  572. }
  573. else {
  574. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  575. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then((result) => {
  576. scene.loadingPluginName = plugin.name;
  577. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  578. }).catch((error) => {
  579. errorHandler(error.message, error);
  580. });
  581. }
  582. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  583. }
  584. /**
  585. * Import meshes into a scene
  586. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  587. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  588. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  589. * @param scene the instance of BABYLON.Scene to append to
  590. * @param onProgress a callback with a progress event for each file being loaded
  591. * @param pluginExtension the extension used to determine the plugin
  592. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  593. */
  594. public static ImportMeshAsync(meshNames: any, rootUrl: string, sceneFilename: string | File = "", scene: Nullable<Scene> = EngineStore.LastCreatedScene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<{ meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }> {
  595. return new Promise((resolve, reject) => {
  596. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups) => {
  597. resolve({
  598. meshes: meshes,
  599. particleSystems: particleSystems,
  600. skeletons: skeletons,
  601. animationGroups: animationGroups
  602. });
  603. }, onProgress, (scene, message, exception) => {
  604. reject(exception || new Error(message));
  605. },
  606. pluginExtension);
  607. });
  608. }
  609. /**
  610. * Load a scene
  611. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  612. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  613. * @param engine is the instance of BABYLON.Engine to use to create the scene
  614. * @param onSuccess a callback with the scene when import succeeds
  615. * @param onProgress a callback with a progress event for each file being loaded
  616. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  617. * @param pluginExtension the extension used to determine the plugin
  618. * @returns The loaded plugin
  619. */
  620. public static Load(rootUrl: string, sceneFilename: string | File = "", engine: Nullable<Engine> = EngineStore.LastCreatedEngine, onSuccess: Nullable<(scene: Scene) => void> = null, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null, pluginExtension: Nullable<string> = null): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  621. if (!engine) {
  622. Tools.Error("No engine available");
  623. return null;
  624. }
  625. return SceneLoader.Append(rootUrl, sceneFilename, new Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  626. }
  627. /**
  628. * Load a scene
  629. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  630. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  631. * @param engine is the instance of BABYLON.Engine to use to create the scene
  632. * @param onProgress a callback with a progress event for each file being loaded
  633. * @param pluginExtension the extension used to determine the plugin
  634. * @returns The loaded scene
  635. */
  636. public static LoadAsync(rootUrl: string, sceneFilename: string | File = "", engine: Nullable<Engine> = EngineStore.LastCreatedEngine, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<Scene> {
  637. return new Promise((resolve, reject) => {
  638. SceneLoader.Load(rootUrl, sceneFilename, engine, (scene) => {
  639. resolve(scene);
  640. }, onProgress, (scene, message, exception) => {
  641. reject(exception || new Error(message));
  642. }, pluginExtension);
  643. });
  644. }
  645. /**
  646. * Append a scene
  647. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  648. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  649. * @param scene is the instance of BABYLON.Scene to append to
  650. * @param onSuccess a callback with the scene when import succeeds
  651. * @param onProgress a callback with a progress event for each file being loaded
  652. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  653. * @param pluginExtension the extension used to determine the plugin
  654. * @returns The loaded plugin
  655. */
  656. public static Append(rootUrl: string, sceneFilename: string | File = "", scene: Nullable<Scene> = EngineStore.LastCreatedScene, onSuccess: Nullable<(scene: Scene) => void> = null, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null, pluginExtension: Nullable<string> = null): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  657. if (!scene) {
  658. Logger.Error("No scene available to append to");
  659. return null;
  660. }
  661. const fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  662. if (!fileInfo) {
  663. return null;
  664. }
  665. if (SceneLoader.ShowLoadingScreen) {
  666. scene.getEngine().displayLoadingUI();
  667. }
  668. var loadingToken = {};
  669. scene._addPendingData(loadingToken);
  670. var disposeHandler = () => {
  671. scene._removePendingData(loadingToken);
  672. scene.getEngine().hideLoadingUI();
  673. };
  674. var errorHandler = (message: Nullable<string>, exception?: any) => {
  675. let errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  676. if (onError) {
  677. onError(scene, errorMessage, exception);
  678. } else {
  679. Logger.Error(errorMessage);
  680. // should the exception be thrown?
  681. }
  682. disposeHandler();
  683. };
  684. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  685. try {
  686. onProgress(event);
  687. }
  688. catch (e) {
  689. errorHandler("Error in onProgress callback", e);
  690. }
  691. } : undefined;
  692. var successHandler = () => {
  693. if (onSuccess) {
  694. try {
  695. onSuccess(scene);
  696. }
  697. catch (e) {
  698. errorHandler("Error in onSuccess callback", e);
  699. }
  700. }
  701. scene._removePendingData(loadingToken);
  702. };
  703. return SceneLoader._loadData(fileInfo, scene, (plugin, data) => {
  704. if ((<any>plugin).load) {
  705. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  706. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  707. return;
  708. }
  709. scene.loadingPluginName = plugin.name;
  710. successHandler();
  711. } else {
  712. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  713. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(() => {
  714. scene.loadingPluginName = plugin.name;
  715. successHandler();
  716. }).catch((error) => {
  717. errorHandler(error.message, error);
  718. });
  719. }
  720. if (SceneLoader.ShowLoadingScreen) {
  721. scene.executeWhenReady(() => {
  722. scene.getEngine().hideLoadingUI();
  723. });
  724. }
  725. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  726. }
  727. /**
  728. * Append a scene
  729. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  730. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  731. * @param scene is the instance of BABYLON.Scene to append to
  732. * @param onProgress a callback with a progress event for each file being loaded
  733. * @param pluginExtension the extension used to determine the plugin
  734. * @returns The given scene
  735. */
  736. public static AppendAsync(rootUrl: string, sceneFilename: string | File = "", scene: Nullable<Scene> = EngineStore.LastCreatedScene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<Scene> {
  737. return new Promise((resolve, reject) => {
  738. SceneLoader.Append(rootUrl, sceneFilename, scene, (scene) => {
  739. resolve(scene);
  740. }, onProgress, (scene, message, exception) => {
  741. reject(exception || new Error(message));
  742. }, pluginExtension);
  743. });
  744. }
  745. /**
  746. * Load a scene into an asset container
  747. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  748. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  749. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  750. * @param onSuccess a callback with the scene when import succeeds
  751. * @param onProgress a callback with a progress event for each file being loaded
  752. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  753. * @param pluginExtension the extension used to determine the plugin
  754. * @returns The loaded plugin
  755. */
  756. public static LoadAssetContainer(
  757. rootUrl: string,
  758. sceneFilename: string | File = "",
  759. scene: Nullable<Scene> = EngineStore.LastCreatedScene,
  760. onSuccess: Nullable<(assets: AssetContainer) => void> = null,
  761. onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null,
  762. onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null,
  763. pluginExtension: Nullable<string> = null
  764. ): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  765. if (!scene) {
  766. Logger.Error("No scene available to load asset container to");
  767. return null;
  768. }
  769. const fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  770. if (!fileInfo) {
  771. return null;
  772. }
  773. var loadingToken = {};
  774. scene._addPendingData(loadingToken);
  775. var disposeHandler = () => {
  776. scene._removePendingData(loadingToken);
  777. };
  778. var errorHandler = (message: Nullable<string>, exception?: any) => {
  779. let errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  780. if (onError) {
  781. onError(scene, errorMessage, exception);
  782. } else {
  783. Logger.Error(errorMessage);
  784. // should the exception be thrown?
  785. }
  786. disposeHandler();
  787. };
  788. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  789. try {
  790. onProgress(event);
  791. }
  792. catch (e) {
  793. errorHandler("Error in onProgress callback", e);
  794. }
  795. } : undefined;
  796. var successHandler = (assets: AssetContainer) => {
  797. if (onSuccess) {
  798. try {
  799. onSuccess(assets);
  800. }
  801. catch (e) {
  802. errorHandler("Error in onSuccess callback", e);
  803. }
  804. }
  805. scene._removePendingData(loadingToken);
  806. };
  807. return SceneLoader._loadData(fileInfo, scene, (plugin, data) => {
  808. if ((<any>plugin).loadAssetContainer) {
  809. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  810. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  811. if (!assetContainer) {
  812. return;
  813. }
  814. scene.loadingPluginName = plugin.name;
  815. successHandler(assetContainer);
  816. } else if ((<any>plugin).loadAssetContainerAsync) {
  817. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  818. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then((assetContainer) => {
  819. scene.loadingPluginName = plugin.name;
  820. successHandler(assetContainer);
  821. }).catch((error) => {
  822. errorHandler(error.message, error);
  823. });
  824. } else {
  825. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  826. }
  827. if (SceneLoader.ShowLoadingScreen) {
  828. scene.executeWhenReady(() => {
  829. scene.getEngine().hideLoadingUI();
  830. });
  831. }
  832. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  833. }
  834. /**
  835. * Load a scene into an asset container
  836. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  837. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  838. * @param scene is the instance of Scene to append to
  839. * @param onProgress a callback with a progress event for each file being loaded
  840. * @param pluginExtension the extension used to determine the plugin
  841. * @returns The loaded asset container
  842. */
  843. public static LoadAssetContainerAsync(rootUrl: string, sceneFilename: string = "", scene: Nullable<Scene> = EngineStore.LastCreatedScene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<AssetContainer> {
  844. return new Promise((resolve, reject) => {
  845. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, (assetContainer) => {
  846. resolve(assetContainer);
  847. }, onProgress, (scene, message, exception) => {
  848. reject(exception || new Error(message));
  849. }, pluginExtension);
  850. });
  851. }
  852. }