sceneLoader.ts 41 KB

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