babylon.sceneLoader.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. module BABYLON {
  2. export class SceneLoaderProgressEvent {
  3. constructor(public readonly lengthComputable: boolean, public readonly loaded: number, public readonly total: number) {
  4. }
  5. public static FromProgressEvent(event: ProgressEvent): SceneLoaderProgressEvent {
  6. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  7. }
  8. }
  9. export interface ISceneLoaderPluginExtensions {
  10. [extension: string]: {
  11. isBinary: boolean;
  12. };
  13. }
  14. export interface ISceneLoaderPluginFactory {
  15. name: string;
  16. createPlugin(): ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  17. canDirectLoad?: (data: string) => boolean;
  18. }
  19. export interface ISceneLoaderPlugin {
  20. /**
  21. * The friendly name of this plugin.
  22. */
  23. name: string;
  24. /**
  25. * The file extensions supported by this plugin.
  26. */
  27. extensions: string | ISceneLoaderPluginExtensions;
  28. /**
  29. * Import meshes into a scene.
  30. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  31. * @param scene The scene to import into
  32. * @param data The data to import
  33. * @param rootUrl The root url for scene and resources
  34. * @param meshes The meshes array to import into
  35. * @param particleSystems The particle systems array to import into
  36. * @param skeletons The skeletons array to import into
  37. * @param onError The callback when import fails
  38. * @returns True if successful or false otherwise
  39. */
  40. importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[], onError?: (message: string, exception?: any) => void): boolean;
  41. /**
  42. * Load into a scene.
  43. * @param scene The scene to load into
  44. * @param data The data to import
  45. * @param rootUrl The root url for scene and resources
  46. * @param onError The callback when import fails
  47. * @returns true if successful or false otherwise
  48. */
  49. load(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): boolean;
  50. /**
  51. * The callback that returns true if the data can be directly loaded.
  52. */
  53. canDirectLoad?: (data: string) => boolean;
  54. /**
  55. * The callback that allows custom handling of the root url based on the response url.
  56. */
  57. rewriteRootURL?: (rootUrl: string, responseURL?: string) => string;
  58. /**
  59. * Load into an asset container.
  60. * @param scene The scene to load into
  61. * @param data The data to import
  62. * @param rootUrl The root url for scene and resources
  63. * @param onError The callback when import fails
  64. * @returns The loaded asset container
  65. */
  66. loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer;
  67. }
  68. export interface ISceneLoaderPluginAsync {
  69. /**
  70. * The friendly name of this plugin.
  71. */
  72. name: string;
  73. /**
  74. * The file extensions supported by this plugin.
  75. */
  76. extensions: string | ISceneLoaderPluginExtensions;
  77. /**
  78. * Import meshes into a scene.
  79. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  80. * @param scene The scene to import into
  81. * @param data The data to import
  82. * @param rootUrl The root url for scene and resources
  83. * @param onProgress The callback when the load progresses
  84. * @returns The loaded meshes, particle systems, skeletons, and animation groups
  85. */
  86. importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }>;
  87. /**
  88. * Load into a scene.
  89. * @param scene The scene to load into
  90. * @param data The data to import
  91. * @param rootUrl The root url for scene and resources
  92. * @param onProgress The callback when the load progresses
  93. * @returns Nothing
  94. */
  95. loadAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<void>;
  96. /**
  97. * The callback that returns true if the data can be directly loaded.
  98. */
  99. canDirectLoad?: (data: string) => boolean;
  100. /**
  101. * The callback that allows custom handling of the root url based on the response url.
  102. */
  103. rewriteRootURL?: (rootUrl: string, responseURL?: string) => string;
  104. /**
  105. * Load into an asset container.
  106. * @param scene The scene to load into
  107. * @param data The data to import
  108. * @param rootUrl The root url for scene and resources
  109. * @param onProgress The callback when the load progresses
  110. * @returns The loaded asset container
  111. */
  112. loadAssetContainerAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void): Promise<AssetContainer>;
  113. }
  114. interface IRegisteredPlugin {
  115. plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory;
  116. isBinary: boolean;
  117. }
  118. export class SceneLoader {
  119. // Flags
  120. private static _ForceFullSceneLoadingForIncremental = false;
  121. private static _ShowLoadingScreen = true;
  122. private static _CleanBoneMatrixWeights = false;
  123. public static get NO_LOGGING(): number {
  124. return 0;
  125. }
  126. public static get MINIMAL_LOGGING(): number {
  127. return 1;
  128. }
  129. public static get SUMMARY_LOGGING(): number {
  130. return 2;
  131. }
  132. public static get DETAILED_LOGGING(): number {
  133. return 3;
  134. }
  135. private static _loggingLevel = SceneLoader.NO_LOGGING;
  136. public static get ForceFullSceneLoadingForIncremental() {
  137. return SceneLoader._ForceFullSceneLoadingForIncremental;
  138. }
  139. public static set ForceFullSceneLoadingForIncremental(value: boolean) {
  140. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  141. }
  142. public static get ShowLoadingScreen(): boolean {
  143. return SceneLoader._ShowLoadingScreen;
  144. }
  145. public static set ShowLoadingScreen(value: boolean) {
  146. SceneLoader._ShowLoadingScreen = value;
  147. }
  148. public static get loggingLevel(): number {
  149. return SceneLoader._loggingLevel;
  150. }
  151. public static set loggingLevel(value: number) {
  152. SceneLoader._loggingLevel = value;
  153. }
  154. public static get CleanBoneMatrixWeights(): boolean {
  155. return SceneLoader._CleanBoneMatrixWeights;
  156. }
  157. public static set CleanBoneMatrixWeights(value: boolean) {
  158. SceneLoader._CleanBoneMatrixWeights = value;
  159. }
  160. // Members
  161. public static OnPluginActivatedObservable = new Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>();
  162. private static _registeredPlugins: { [extension: string]: IRegisteredPlugin } = {};
  163. private static _getDefaultPlugin(): IRegisteredPlugin {
  164. return SceneLoader._registeredPlugins[".babylon"];
  165. }
  166. private static _getPluginForExtension(extension: string): IRegisteredPlugin {
  167. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  168. if (registeredPlugin) {
  169. return registeredPlugin;
  170. }
  171. Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  172. return SceneLoader._getDefaultPlugin();
  173. }
  174. private static _getPluginForDirectLoad(data: string): IRegisteredPlugin {
  175. for (var extension in SceneLoader._registeredPlugins) {
  176. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  177. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  178. return SceneLoader._registeredPlugins[extension];
  179. }
  180. }
  181. return SceneLoader._getDefaultPlugin();
  182. }
  183. private static _getPluginForFilename(sceneFilename: any): IRegisteredPlugin {
  184. if (sceneFilename.name) {
  185. sceneFilename = sceneFilename.name;
  186. }
  187. var queryStringPosition = sceneFilename.indexOf("?");
  188. if (queryStringPosition !== -1) {
  189. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  190. }
  191. var dotPosition = sceneFilename.lastIndexOf(".");
  192. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  193. return SceneLoader._getPluginForExtension(extension);
  194. }
  195. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  196. private static _getDirectLoad(sceneFilename: string): Nullable<string> {
  197. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  198. return sceneFilename.substr(5);
  199. }
  200. return null;
  201. }
  202. private static _loadData(rootUrl: string, sceneFilename: string, 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 {
  203. let directLoad = SceneLoader._getDirectLoad(sceneFilename);
  204. let registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  205. let plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  206. if ((registeredPlugin.plugin as ISceneLoaderPluginFactory).createPlugin) {
  207. plugin = (registeredPlugin.plugin as ISceneLoaderPluginFactory).createPlugin();
  208. }
  209. else {
  210. plugin = <any>registeredPlugin.plugin;
  211. }
  212. let useArrayBuffer = registeredPlugin.isBinary;
  213. let database: Database;
  214. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  215. let dataCallback = (data: any, responseURL?: string) => {
  216. if (scene.isDisposed) {
  217. onError("Scene has been disposed");
  218. return;
  219. }
  220. scene.database = database;
  221. onSuccess(plugin, data, responseURL);
  222. };
  223. let request: Nullable<IFileRequest> = null;
  224. let pluginDisposed = false;
  225. let onDisposeObservable = (plugin as any).onDisposeObservable as Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>;
  226. if (onDisposeObservable) {
  227. onDisposeObservable.add(() => {
  228. pluginDisposed = true;
  229. if (request) {
  230. request.abort();
  231. request = null;
  232. }
  233. onDispose();
  234. });
  235. }
  236. let manifestChecked = () => {
  237. if (pluginDisposed) {
  238. return;
  239. }
  240. let url = rootUrl + sceneFilename;
  241. request = Tools.LoadFile(url, dataCallback, onProgress ? event => {
  242. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  243. } : undefined, database, useArrayBuffer, (request, exception) => {
  244. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  245. });
  246. };
  247. if (directLoad) {
  248. dataCallback(directLoad);
  249. return plugin;
  250. }
  251. if (rootUrl.indexOf("file:") === -1) {
  252. let engine = scene.getEngine();
  253. let canUseOfflineSupport = engine.enableOfflineSupport;
  254. if (canUseOfflineSupport) {
  255. // Also check for exceptions
  256. let exceptionFound = false;
  257. for (var regex of scene.disableOfflineSupportExceptionRules) {
  258. if (regex.test(rootUrl + sceneFilename)) {
  259. exceptionFound = true;
  260. break;
  261. }
  262. }
  263. canUseOfflineSupport = !exceptionFound;
  264. }
  265. if (canUseOfflineSupport) {
  266. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  267. database = new Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  268. }
  269. else {
  270. manifestChecked();
  271. }
  272. }
  273. // Loading file from disk via input file or drag'n'drop
  274. else {
  275. let fileOrString = <any>sceneFilename;
  276. if (fileOrString.name) { // File
  277. request = Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  278. } else if (FilesInput.FilesToLoad[sceneFilename]) {
  279. request = Tools.ReadFile(FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  280. } else {
  281. onError("Unable to find file named " + sceneFilename);
  282. }
  283. }
  284. return plugin;
  285. }
  286. // Public functions
  287. public static GetPluginForExtension(extension: string): ISceneLoaderPlugin | ISceneLoaderPluginAsync | ISceneLoaderPluginFactory {
  288. return SceneLoader._getPluginForExtension(extension).plugin;
  289. }
  290. public static IsPluginForExtensionAvailable(extension: string): boolean {
  291. return !!SceneLoader._registeredPlugins[extension];
  292. }
  293. public static RegisterPlugin(plugin: ISceneLoaderPlugin | ISceneLoaderPluginAsync): void {
  294. if (typeof plugin.extensions === "string") {
  295. var extension = <string>plugin.extensions;
  296. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  297. plugin: plugin,
  298. isBinary: false
  299. };
  300. }
  301. else {
  302. var extensions = <ISceneLoaderPluginExtensions>plugin.extensions;
  303. Object.keys(extensions).forEach(extension => {
  304. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  305. plugin: plugin,
  306. isBinary: extensions[extension].isBinary
  307. };
  308. });
  309. }
  310. }
  311. /**
  312. * Import meshes into a scene
  313. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  314. * @param rootUrl a string that defines the root url for scene and resources
  315. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  316. * @param scene the instance of BABYLON.Scene to append to
  317. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  318. * @param onProgress a callback with a progress event for each file being loaded
  319. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  320. * @param pluginExtension the extension used to determine the plugin
  321. * @returns The loaded plugin
  322. */
  323. public static ImportMesh(meshNames: any, rootUrl: string, sceneFilename: string, scene: Scene, onSuccess: Nullable<(meshes: AbstractMesh[], particleSystems: ParticleSystem[], 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> {
  324. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  325. Tools.Error("Wrong sceneFilename parameter");
  326. return null;
  327. }
  328. var loadingToken = {};
  329. scene._addPendingData(loadingToken);
  330. var disposeHandler = () => {
  331. scene._removePendingData(loadingToken);
  332. };
  333. var errorHandler = (message: string, exception?: any) => {
  334. let errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  335. if (onError) {
  336. onError(scene, errorMessage, exception);
  337. } else {
  338. Tools.Error(errorMessage);
  339. // should the exception be thrown?
  340. }
  341. disposeHandler();
  342. };
  343. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  344. try {
  345. onProgress(event);
  346. }
  347. catch (e) {
  348. errorHandler("Error in onProgress callback", e);
  349. }
  350. } : undefined;
  351. var successHandler = (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[]) => {
  352. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  353. if (onSuccess) {
  354. try {
  355. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  356. }
  357. catch (e) {
  358. errorHandler("Error in onSuccess callback", e);
  359. }
  360. }
  361. scene._removePendingData(loadingToken);
  362. };
  363. return SceneLoader._loadData(rootUrl, sceneFilename, scene, (plugin, data, responseURL) => {
  364. if (plugin.rewriteRootURL) {
  365. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  366. }
  367. if (sceneFilename === "") {
  368. if (sceneFilename === "") {
  369. rootUrl = Tools.GetFolderPath(rootUrl, true);
  370. }
  371. }
  372. if ((<any>plugin).importMesh) {
  373. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  374. var meshes = new Array<AbstractMesh>();
  375. var particleSystems = new Array<ParticleSystem>();
  376. var skeletons = new Array<Skeleton>();
  377. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  378. return;
  379. }
  380. scene.loadingPluginName = plugin.name;
  381. successHandler(meshes, particleSystems, skeletons, []);
  382. }
  383. else {
  384. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  385. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(result => {
  386. scene.loadingPluginName = plugin.name;
  387. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  388. }).catch(error => {
  389. errorHandler(error.message, error);
  390. });
  391. }
  392. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  393. }
  394. /**
  395. * Import meshes into a scene
  396. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  397. * @param rootUrl a string that defines the root url for scene and resources
  398. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  399. * @param scene the instance of BABYLON.Scene to append to
  400. * @param onProgress a callback with a progress event for each file being loaded
  401. * @param pluginExtension the extension used to determine the plugin
  402. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  403. */
  404. public static ImportMeshAsync(meshNames: any, rootUrl: string, sceneFilename: string, scene: Scene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<{ meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }> {
  405. return new Promise((resolve, reject) => {
  406. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups) => {
  407. resolve({
  408. meshes: meshes,
  409. particleSystems: particleSystems,
  410. skeletons: skeletons,
  411. animationGroups: animationGroups
  412. });
  413. }, onProgress, (scene, message, exception) => {
  414. reject(exception || new Error(message));
  415. },
  416. pluginExtension);
  417. });
  418. }
  419. /**
  420. * Load a scene
  421. * @param rootUrl a string that defines the root url for scene and resources
  422. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  423. * @param engine is the instance of BABYLON.Engine to use to create the scene
  424. * @param onSuccess a callback with the scene when import succeeds
  425. * @param onProgress a callback with a progress event for each file being loaded
  426. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  427. * @param pluginExtension the extension used to determine the plugin
  428. * @returns The loaded plugin
  429. */
  430. public static Load(rootUrl: string, sceneFilename: any, 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> {
  431. return SceneLoader.Append(rootUrl, sceneFilename, new Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  432. }
  433. /**
  434. * Load a scene
  435. * @param rootUrl a string that defines the root url for scene and resources
  436. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  437. * @param engine is the instance of BABYLON.Engine to use to create the scene
  438. * @param onProgress a callback with a progress event for each file being loaded
  439. * @param pluginExtension the extension used to determine the plugin
  440. * @returns The loaded scene
  441. */
  442. public static LoadAsync(rootUrl: string, sceneFilename: any, engine: Engine, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<Scene> {
  443. return new Promise((resolve, reject) => {
  444. SceneLoader.Load(rootUrl, sceneFilename, engine, scene => {
  445. resolve(scene);
  446. }, onProgress, (scene, message, exception) => {
  447. reject(exception || new Error(message));
  448. }, pluginExtension);
  449. });
  450. }
  451. /**
  452. * Append a scene
  453. * @param rootUrl a string that defines the root url for scene and resources
  454. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  455. * @param scene is the instance of BABYLON.Scene to append to
  456. * @param onSuccess a callback with the scene when import succeeds
  457. * @param onProgress a callback with a progress event for each file being loaded
  458. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  459. * @param pluginExtension the extension used to determine the plugin
  460. * @returns The loaded plugin
  461. */
  462. public static Append(rootUrl: string, sceneFilename: any, scene: Scene, 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> {
  463. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  464. Tools.Error("Wrong sceneFilename parameter");
  465. return null;
  466. }
  467. if (SceneLoader.ShowLoadingScreen) {
  468. scene.getEngine().displayLoadingUI();
  469. }
  470. var loadingToken = {};
  471. scene._addPendingData(loadingToken);
  472. var disposeHandler = () => {
  473. scene._removePendingData(loadingToken);
  474. scene.getEngine().hideLoadingUI();
  475. };
  476. var errorHandler = (message: Nullable<string>, exception?: any) => {
  477. let errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  478. if (onError) {
  479. onError(scene, errorMessage, exception);
  480. } else {
  481. Tools.Error(errorMessage);
  482. // should the exception be thrown?
  483. }
  484. disposeHandler();
  485. };
  486. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  487. try {
  488. onProgress(event);
  489. }
  490. catch (e) {
  491. errorHandler("Error in onProgress callback", e);
  492. }
  493. } : undefined;
  494. var successHandler = () => {
  495. if (onSuccess) {
  496. try {
  497. onSuccess(scene);
  498. }
  499. catch (e) {
  500. errorHandler("Error in onSuccess callback", e);
  501. }
  502. }
  503. scene._removePendingData(loadingToken);
  504. };
  505. return SceneLoader._loadData(rootUrl, sceneFilename, scene, (plugin, data, responseURL) => {
  506. if (sceneFilename === "") {
  507. rootUrl = Tools.GetFolderPath(rootUrl, true);
  508. }
  509. if ((<any>plugin).load) {
  510. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  511. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  512. return;
  513. }
  514. scene.loadingPluginName = plugin.name;
  515. successHandler();
  516. } else {
  517. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  518. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(() => {
  519. scene.loadingPluginName = plugin.name;
  520. successHandler();
  521. }).catch(error => {
  522. errorHandler(error.message, error);
  523. });
  524. }
  525. if (SceneLoader.ShowLoadingScreen) {
  526. scene.executeWhenReady(() => {
  527. scene.getEngine().hideLoadingUI();
  528. });
  529. }
  530. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  531. }
  532. /**
  533. * Append a scene
  534. * @param rootUrl a string that defines the root url for scene and resources
  535. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  536. * @param scene is the instance of BABYLON.Scene to append to
  537. * @param onProgress a callback with a progress event for each file being loaded
  538. * @param pluginExtension the extension used to determine the plugin
  539. * @returns The given scene
  540. */
  541. public static AppendAsync(rootUrl: string, sceneFilename: any, scene: Scene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<Scene> {
  542. return new Promise((resolve, reject) => {
  543. SceneLoader.Append(rootUrl, sceneFilename, scene, scene => {
  544. resolve(scene);
  545. }, onProgress, (scene, message, exception) => {
  546. reject(exception || new Error(message));
  547. }, pluginExtension);
  548. });
  549. }
  550. /**
  551. * Load a scene into an asset container
  552. * @param rootUrl a string that defines the root url for scene and resources
  553. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  554. * @param scene is the instance of BABYLON.Scene to append to
  555. * @param onSuccess a callback with the scene when import succeeds
  556. * @param onProgress a callback with a progress event for each file being loaded
  557. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  558. * @param pluginExtension the extension used to determine the plugin
  559. * @returns The loaded plugin
  560. */
  561. public static LoadAssetContainer(
  562. rootUrl: string,
  563. sceneFilename: any,
  564. scene: Scene,
  565. onSuccess: Nullable<(assets: AssetContainer) => void> = null,
  566. onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null,
  567. onError: Nullable<(scene: Scene, message: string, exception?: any) => void> = null,
  568. pluginExtension: Nullable<string> = null
  569. ): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  570. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  571. Tools.Error("Wrong sceneFilename parameter");
  572. return null;
  573. }
  574. var loadingToken = {};
  575. scene._addPendingData(loadingToken);
  576. var disposeHandler = () => {
  577. scene._removePendingData(loadingToken);
  578. };
  579. var errorHandler = (message: Nullable<string>, exception?: any) => {
  580. let errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  581. if (onError) {
  582. onError(scene, errorMessage, exception);
  583. } else {
  584. Tools.Error(errorMessage);
  585. // should the exception be thrown?
  586. }
  587. disposeHandler();
  588. };
  589. var progressHandler = onProgress ? (event: SceneLoaderProgressEvent) => {
  590. try {
  591. onProgress(event);
  592. }
  593. catch (e) {
  594. errorHandler("Error in onProgress callback", e);
  595. }
  596. } : undefined;
  597. var successHandler = (assets: AssetContainer) => {
  598. if (onSuccess) {
  599. try {
  600. onSuccess(assets);
  601. }
  602. catch (e) {
  603. errorHandler("Error in onSuccess callback", e);
  604. }
  605. }
  606. scene._removePendingData(loadingToken);
  607. };
  608. return SceneLoader._loadData(rootUrl, sceneFilename, scene, (plugin, data, responseURL) => {
  609. if ((<any>plugin).loadAssetContainer) {
  610. var syncedPlugin = <ISceneLoaderPlugin>plugin;
  611. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  612. if (!assetContainer) {
  613. return;
  614. }
  615. scene.loadingPluginName = plugin.name;
  616. successHandler(assetContainer);
  617. } else if ((<any>plugin).loadAssetContainerAsync) {
  618. var asyncedPlugin = <ISceneLoaderPluginAsync>plugin;
  619. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(assetContainer => {
  620. scene.loadingPluginName = plugin.name;
  621. successHandler(assetContainer);
  622. }).catch(error => {
  623. errorHandler(error.message, error);
  624. });
  625. } else {
  626. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")
  627. }
  628. if (SceneLoader.ShowLoadingScreen) {
  629. scene.executeWhenReady(() => {
  630. scene.getEngine().hideLoadingUI();
  631. });
  632. }
  633. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  634. }
  635. /**
  636. * Load a scene into an asset container
  637. * @param rootUrl a string that defines the root url for scene and resources
  638. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  639. * @param scene is the instance of BABYLON.Scene to append to
  640. * @param onProgress a callback with a progress event for each file being loaded
  641. * @param pluginExtension the extension used to determine the plugin
  642. * @returns The loaded asset container
  643. */
  644. public static LoadAssetContainerAsync(rootUrl: string, sceneFilename: any, scene: Scene, onProgress: Nullable<(event: SceneLoaderProgressEvent) => void> = null, pluginExtension: Nullable<string> = null): Promise<AssetContainer> {
  645. return new Promise((resolve, reject) => {
  646. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, assetContainer => {
  647. resolve(assetContainer);
  648. }, onProgress, (scene, message, exception) => {
  649. reject(exception || new Error(message));
  650. }, pluginExtension);
  651. });
  652. }
  653. };
  654. }