babylon.filesInput.ts 12 KB

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