sceneLoader.ts 40 KB

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