filesInput.ts 11 KB

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