sceneLoader.ts 43 KB

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