filesInput.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import { Engine } from "../Engines/engine";
  2. import { Scene } from "../scene";
  3. import { ISceneLoaderProgressEvent, SceneLoader } from "../Loading/sceneLoader";
  4. import { Logger } from "../Misc/logger";
  5. import { FilesInputStore } from "./filesInputStore";
  6. import { Nullable } from '../types';
  7. /**
  8. * Class used to help managing file picking and drag'n'drop
  9. */
  10. export class FilesInput {
  11. /**
  12. * List of files ready to be loaded
  13. */
  14. public static get FilesToLoad() {
  15. return FilesInputStore.FilesToLoad;
  16. }
  17. /**
  18. * Callback called when a file is processed
  19. */
  20. public onProcessFileCallback: (file: File, name: string, extension: string) => boolean = () => { return true; };
  21. private _engine: Engine;
  22. private _currentScene: Nullable<Scene>;
  23. private _sceneLoadedCallback: Nullable<(sceneFile: File, scene: Scene) => void>;
  24. private _progressCallback: Nullable<(progress: ISceneLoaderProgressEvent) => void>;
  25. private _additionalRenderLoopLogicCallback: Nullable<() => void>;
  26. private _textureLoadingCallback: Nullable<(remaining: number) => void>;
  27. private _startingProcessingFilesCallback: Nullable<(files?: File[]) => void>;
  28. private _onReloadCallback: Nullable<(sceneFile: File) => void>;
  29. private _errorCallback: Nullable<(sceneFile: File, scene: Nullable<Scene>, message: string) => void>;
  30. private _elementToMonitor: HTMLElement;
  31. private _sceneFileToLoad: File;
  32. private _filesToLoad: File[];
  33. /**
  34. * Creates a new FilesInput
  35. * @param engine defines the rendering engine
  36. * @param scene defines the hosting scene
  37. * @param sceneLoadedCallback callback called when scene is loaded
  38. * @param progressCallback callback called to track progress
  39. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  40. * @param textureLoadingCallback callback called when a texture is loading
  41. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  42. * @param onReloadCallback callback called when a reload is requested
  43. * @param errorCallback callback call if an error occurs
  44. */
  45. constructor(engine: Engine, scene: Nullable<Scene>,
  46. sceneLoadedCallback: Nullable<(sceneFile: File, scene: Scene) => void>,
  47. progressCallback: Nullable<(progress: ISceneLoaderProgressEvent) => void>,
  48. additionalRenderLoopLogicCallback: Nullable<() => void>,
  49. textureLoadingCallback: Nullable<(remaining: number) => void>,
  50. startingProcessingFilesCallback: Nullable<(files?: File[]) => void>,
  51. onReloadCallback: Nullable<(sceneFile: File) => void>,
  52. errorCallback: Nullable<(sceneFile: File, scene: Nullable<Scene>, message: string) => void>) {
  53. this._engine = engine;
  54. this._currentScene = scene;
  55. this._sceneLoadedCallback = sceneLoadedCallback;
  56. this._progressCallback = progressCallback;
  57. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  58. this._textureLoadingCallback = textureLoadingCallback;
  59. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60. this._onReloadCallback = onReloadCallback;
  61. this._errorCallback = errorCallback;
  62. }
  63. private _dragEnterHandler: (e: any) => void;
  64. private _dragOverHandler: (e: any) => void;
  65. private _dropHandler: (e: any) => void;
  66. /**
  67. * Calls this function to listen to drag'n'drop events on a specific DOM element
  68. * @param elementToMonitor defines the DOM element to track
  69. */
  70. public monitorElementForDragNDrop(elementToMonitor: HTMLElement): void {
  71. if (elementToMonitor) {
  72. this._elementToMonitor = elementToMonitor;
  73. this._dragEnterHandler = (e) => { this.drag(e); };
  74. this._dragOverHandler = (e) => { this.drag(e); };
  75. this._dropHandler = (e) => { this.drop(e); };
  76. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  77. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  78. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  79. }
  80. }
  81. /** Gets the current list of files to load */
  82. public get filesToLoad() {
  83. return this._filesToLoad;
  84. }
  85. /**
  86. * Release all associated resources
  87. */
  88. public dispose() {
  89. if (!this._elementToMonitor) {
  90. return;
  91. }
  92. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  93. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  94. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  95. }
  96. private renderFunction(): void {
  97. if (this._additionalRenderLoopLogicCallback) {
  98. this._additionalRenderLoopLogicCallback();
  99. }
  100. if (this._currentScene) {
  101. if (this._textureLoadingCallback) {
  102. var remaining = this._currentScene.getWaitingItemsCount();
  103. if (remaining > 0) {
  104. this._textureLoadingCallback(remaining);
  105. }
  106. }
  107. this._currentScene.render();
  108. }
  109. }
  110. private drag(e: DragEvent): void {
  111. e.stopPropagation();
  112. e.preventDefault();
  113. }
  114. private drop(eventDrop: DragEvent): void {
  115. eventDrop.stopPropagation();
  116. eventDrop.preventDefault();
  117. this.loadFiles(eventDrop);
  118. }
  119. private _traverseFolder(folder: any, files: Array<any>, remaining: { count: number }, callback: () => void) {
  120. var reader = folder.createReader();
  121. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  122. reader.readEntries((entries: any) => {
  123. remaining.count += entries.length;
  124. for (let entry of entries) {
  125. if (entry.isFile) {
  126. entry.file((file: any) => {
  127. file.correctName = relativePath + file.name;
  128. files.push(file);
  129. if (--remaining.count === 0) {
  130. callback();
  131. }
  132. });
  133. }
  134. else if (entry.isDirectory) {
  135. this._traverseFolder(entry, files, remaining, callback);
  136. }
  137. }
  138. if (--remaining.count === 0) {
  139. callback();
  140. }
  141. });
  142. }
  143. private _processFiles(files: Array<any>): void {
  144. for (var i = 0; i < files.length; i++) {
  145. var name = files[i].correctName.toLowerCase();
  146. var extension = name.split('.').pop();
  147. if (!this.onProcessFileCallback(files[i], name, extension)) {
  148. continue;
  149. }
  150. if (SceneLoader.IsPluginForExtensionAvailable("." + extension)) {
  151. this._sceneFileToLoad = files[i];
  152. }
  153. FilesInput.FilesToLoad[name] = files[i];
  154. }
  155. }
  156. /**
  157. * Load files from a drop event
  158. * @param event defines the drop event to use as source
  159. */
  160. public loadFiles(event: any): void {
  161. // Handling data transfer via drag'n'drop
  162. if (event && event.dataTransfer && event.dataTransfer.files) {
  163. this._filesToLoad = event.dataTransfer.files;
  164. }
  165. // Handling files from input files
  166. if (event && event.target && event.target.files) {
  167. this._filesToLoad = event.target.files;
  168. }
  169. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  170. return;
  171. }
  172. if (this._startingProcessingFilesCallback) {
  173. this._startingProcessingFilesCallback(this._filesToLoad);
  174. }
  175. if (this._filesToLoad && this._filesToLoad.length > 0) {
  176. let files = new Array<File>();
  177. let folders = [];
  178. var items = event.dataTransfer ? event.dataTransfer.items : null;
  179. for (var i = 0; i < this._filesToLoad.length; i++) {
  180. let fileToLoad: any = this._filesToLoad[i];
  181. let name = fileToLoad.name.toLowerCase();
  182. let entry;
  183. fileToLoad.correctName = name;
  184. if (items) {
  185. let item = items[i];
  186. if (item.getAsEntry) {
  187. entry = item.getAsEntry();
  188. } else if (item.webkitGetAsEntry) {
  189. entry = item.webkitGetAsEntry();
  190. }
  191. }
  192. if (!entry) {
  193. files.push(fileToLoad);
  194. } else {
  195. if (entry.isDirectory) {
  196. folders.push(entry);
  197. } else {
  198. files.push(fileToLoad);
  199. }
  200. }
  201. }
  202. if (folders.length === 0) {
  203. this._processFiles(files);
  204. this._processReload();
  205. } else {
  206. var remaining = { count: folders.length };
  207. for (var folder of folders) {
  208. this._traverseFolder(folder, files, remaining, () => {
  209. this._processFiles(files);
  210. if (remaining.count === 0) {
  211. this._processReload();
  212. }
  213. });
  214. }
  215. }
  216. }
  217. }
  218. private _processReload() {
  219. if (this._onReloadCallback) {
  220. this._onReloadCallback(this._sceneFileToLoad);
  221. }
  222. else {
  223. this.reload();
  224. }
  225. }
  226. /**
  227. * Reload the current scene from the loaded files
  228. */
  229. public reload() {
  230. // If a scene file has been provided
  231. if (this._sceneFileToLoad) {
  232. if (this._currentScene) {
  233. if (Logger.errorsCount > 0) {
  234. Logger.ClearLogCache();
  235. }
  236. this._engine.stopRenderLoop();
  237. }
  238. SceneLoader.ShowLoadingScreen = false;
  239. this._engine.displayLoadingUI();
  240. SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, (progress) => {
  241. if (this._progressCallback) {
  242. this._progressCallback(progress);
  243. }
  244. }).then((scene) => {
  245. if (this._currentScene) {
  246. this._currentScene.dispose();
  247. }
  248. this._currentScene = scene;
  249. if (this._sceneLoadedCallback) {
  250. this._sceneLoadedCallback(this._sceneFileToLoad, this._currentScene);
  251. }
  252. // Wait for textures and shaders to be ready
  253. this._currentScene.executeWhenReady(() => {
  254. this._engine.hideLoadingUI();
  255. this._engine.runRenderLoop(() => {
  256. this.renderFunction();
  257. });
  258. });
  259. }).catch((error) => {
  260. this._engine.hideLoadingUI();
  261. if (this._errorCallback) {
  262. this._errorCallback(this._sceneFileToLoad, this._currentScene, error.message);
  263. }
  264. });
  265. }
  266. else {
  267. Logger.Error("Please provide a valid .babylon file.");
  268. }
  269. }
  270. }