index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /// <reference path="../dist/preview release/babylon.d.ts" />
  2. var assetUrl;
  3. var cameraPosition;
  4. var kiosk;
  5. var currentGroup; // animation group
  6. var currentGroupIndex;
  7. var currentScene;
  8. // html tags
  9. var footer = document.getElementById("footer");
  10. var canvas = document.getElementById("renderCanvas");
  11. var canvasZone = document.getElementById("canvasZone");
  12. // Check URL
  13. var indexOf = location.href.indexOf("?");
  14. if (indexOf !== -1) {
  15. var params = location.href.substr(indexOf + 1).split("&");
  16. for (var index = 0; index < params.length; index++) {
  17. var param = params[index].split("=");
  18. var name = param[0];
  19. var value = param[1];
  20. switch (name) {
  21. case "assetUrl": {
  22. assetUrl = value;
  23. break;
  24. }
  25. case "cameraPosition": {
  26. cameraPosition = BABYLON.Vector3.FromArray(value.split(",").map(function(component) { return +component; }));
  27. break;
  28. }
  29. case "kiosk": {
  30. kiosk = value === "true" ? true : false;
  31. break;
  32. }
  33. }
  34. }
  35. }
  36. if (kiosk) {
  37. footer.style.display = "none";
  38. canvasZone.style.height = "100%";
  39. }
  40. if (BABYLON.Engine.isSupported()) {
  41. var engine = new BABYLON.Engine(canvas, true, { premultipliedAlpha: false, preserveDrawingBuffer: true });
  42. var htmlInput = document.getElementById("files");
  43. var htmlInputAnimation = document.getElementById("animationFiles");
  44. var btnInspector = document.getElementById("btnInspector");
  45. var errorZone = document.getElementById("errorZone");
  46. var filesInput;
  47. var filesInputAnimation;
  48. var currentScene;
  49. var currentSkybox;
  50. var currentPluginName;
  51. var skyboxPath = skyboxes[defaultSkyboxIndex];
  52. var debugLayerEnabled = false;
  53. engine.loadingUIBackgroundColor = "#2A2342";
  54. btnInspector.classList.add("hidden");
  55. btnEnvironment.classList.add("hidden");
  56. // htmlInputAnimation.classList.add("hidden");
  57. canvas.addEventListener("contextmenu", function(evt) {
  58. evt.preventDefault();
  59. }, false);
  60. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  61. // This is really important to tell Babylon.js to use decomposeLerp and matrix interpolation
  62. BABYLON.Animation.AllowMatricesInterpolation = true;
  63. // Setting up some GLTF values
  64. BABYLON.GLTFFileLoader.IncrementalLoading = false;
  65. BABYLON.SceneLoader.OnPluginActivatedObservable.add(function(plugin) {
  66. currentPluginName = plugin.name;
  67. if (currentPluginName === "gltf") {
  68. plugin.onValidatedObservable.add(function(results) {
  69. if (results.issues.numErrors > 0) {
  70. debugLayerEnabled = true;
  71. }
  72. });
  73. }
  74. });
  75. // Resize
  76. window.addEventListener("resize", function() {
  77. engine.resize();
  78. });
  79. var anyLoaded = function(sceneFile, babylonScene) {
  80. engine.clearInternalTexturesCache();
  81. // Clear dropdown that contains animation names
  82. dropdownContent.innerHTML = "";
  83. animationBar.style.display = "none";
  84. currentGroup = null;
  85. if (babylonScene.animationGroups.length > 0) {
  86. animationBar.style.display = "flex";
  87. for (var index = 0; index < babylonScene.animationGroups.length; index++) {
  88. var group = babylonScene.animationGroups[index];
  89. createDropdownLink(group, index);
  90. }
  91. currentGroup = babylonScene.animationGroups[0];
  92. currentGroupIndex = 0;
  93. currentGroup.play(true);
  94. }
  95. // Sync the slider with the current frame
  96. babylonScene.registerBeforeRender(function() {
  97. if (currentGroup) {
  98. var targetedAnimations = currentGroup.targetedAnimations;
  99. if (targetedAnimations.length > 0) {
  100. var runtimeAnimations = currentGroup.targetedAnimations[0].animation.runtimeAnimations;
  101. if (runtimeAnimations.length > 0) {
  102. slider.value = runtimeAnimations[0].currentFrame;
  103. }
  104. }
  105. }
  106. });
  107. // Clear the error
  108. errorZone.style.display = 'none';
  109. btnInspector.classList.remove("hidden");
  110. btnEnvironment.classList.remove("hidden");
  111. currentScene = babylonScene;
  112. document.title = "Babylon.js - " + sceneFile.name;
  113. htmlInputAnimation.value = "";
  114. }
  115. var assetContainerLoaded = function(sceneFile, babylonScene) {
  116. anyLoaded(sceneFile, babylonScene);
  117. // Fix for IE, otherwise it will change the default filter for files selection after first use
  118. htmlInputAnimation.value = "";
  119. }
  120. var sceneLoaded = function(sceneFile, babylonScene) {
  121. anyLoaded(sceneFile, babylonScene);
  122. // Fix for IE, otherwise it will change the default filter for files selection after first use
  123. htmlInput.value = "";
  124. // Attach camera to canvas inputs
  125. if (!currentScene.activeCamera || currentScene.lights.length === 0) {
  126. currentScene.createDefaultCamera(true);
  127. if (cameraPosition) {
  128. currentScene.activeCamera.setPosition(cameraPosition);
  129. }
  130. else {
  131. if (currentPluginName === "gltf") {
  132. // glTF assets use a +Z forward convention while the default camera faces +Z. Rotate the camera to look at the front of the asset.
  133. currentScene.activeCamera.alpha += Math.PI;
  134. }
  135. // Enable camera's behaviors
  136. currentScene.activeCamera.useFramingBehavior = true;
  137. var framingBehavior = currentScene.activeCamera.getBehaviorByName("Framing");
  138. framingBehavior.framingTime = 0;
  139. framingBehavior.elevationReturnTime = -1;
  140. if (currentScene.meshes.length) {
  141. var worldExtends = currentScene.getWorldExtends();
  142. currentScene.activeCamera.lowerRadiusLimit = null;
  143. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  144. }
  145. }
  146. currentScene.activeCamera.pinchPrecision = 200 / currentScene.activeCamera.radius;
  147. currentScene.activeCamera.upperRadiusLimit = 5 * currentScene.activeCamera.radius;
  148. currentScene.activeCamera.wheelDeltaPercentage = 0.01;
  149. currentScene.activeCamera.pinchDeltaPercentage = 0.01;
  150. }
  151. currentScene.activeCamera.attachControl(canvas);
  152. // Lighting
  153. if (currentPluginName === "gltf") {
  154. if (!currentScene.environmentTexture) {
  155. currentScene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(skyboxPath, currentScene);
  156. }
  157. currentSkybox = currentScene.createDefaultSkybox(currentScene.environmentTexture, true, (currentScene.activeCamera.maxZ - currentScene.activeCamera.minZ) / 2, 0.3, false);
  158. }
  159. else {
  160. var pbrPresent = false;
  161. for (var i = 0; i < currentScene.materials.length; i++) {
  162. if (currentScene.materials[i]._transparencyMode !== undefined) {
  163. pbrPresent = true;
  164. break;
  165. }
  166. }
  167. if (pbrPresent) {
  168. if (!currentScene.environmentTexture) {
  169. currentScene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(skyboxPath, currentScene);
  170. }
  171. }
  172. else {
  173. currentScene.createDefaultLight();
  174. }
  175. }
  176. // In case of error during loading, meshes will be empty and clearColor is set to red
  177. if (currentScene.meshes.length === 0 && currentScene.clearColor.r === 1 && currentScene.clearColor.g === 0 && currentScene.clearColor.b === 0) {
  178. document.getElementById("logo").className = "";
  179. canvas.style.opacity = 0;
  180. debugLayerEnabled = true;
  181. }
  182. else {
  183. if (BABYLON.Tools.errorsCount > 0) {
  184. debugLayerEnabled = true;
  185. }
  186. document.getElementById("logo").className = "hidden";
  187. document.getElementById("droptext").className = "hidden";
  188. canvas.style.opacity = 1;
  189. if (currentScene.activeCamera.keysUp) {
  190. currentScene.activeCamera.keysUp.push(90); // Z
  191. currentScene.activeCamera.keysUp.push(87); // W
  192. currentScene.activeCamera.keysDown.push(83); // S
  193. currentScene.activeCamera.keysLeft.push(65); // A
  194. currentScene.activeCamera.keysLeft.push(81); // Q
  195. currentScene.activeCamera.keysRight.push(69); // E
  196. currentScene.activeCamera.keysRight.push(68); // D
  197. }
  198. }
  199. if (debugLayerEnabled) {
  200. currentScene.debugLayer.show();
  201. }
  202. };
  203. var sceneError = function(sceneFile, babylonScene, message) {
  204. document.title = "Babylon.js - " + sceneFile.name;
  205. document.getElementById("logo").className = "";
  206. canvas.style.opacity = 0;
  207. var errorContent = '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button>' + message.replace("file:[object File]", "'" + sceneFile.name + "'") + '</div>';
  208. errorZone.style.display = 'block';
  209. errorZone.innerHTML = errorContent;
  210. // Close button error
  211. errorZone.querySelector('.close').addEventListener('click', function() {
  212. errorZone.style.display = 'none';
  213. });
  214. };
  215. var loadFromAssetUrl = function() {
  216. var rootUrl = BABYLON.Tools.GetFolderPath(assetUrl);
  217. var fileName = BABYLON.Tools.GetFilename(assetUrl);
  218. BABYLON.SceneLoader.LoadAsync(rootUrl, fileName, engine).then(function(scene) {
  219. if (currentScene) {
  220. currentScene.dispose();
  221. }
  222. sceneLoaded({ name: fileName }, scene);
  223. scene.whenReadyAsync().then(function() {
  224. engine.runRenderLoop(function() {
  225. scene.render();
  226. });
  227. });
  228. }).catch(function(reason) {
  229. sceneError({ name: fileName }, null, reason.message || reason);
  230. });
  231. };
  232. if (assetUrl) {
  233. loadFromAssetUrl();
  234. }
  235. else {
  236. var startProcessingFiles = function() {
  237. BABYLON.Tools.ClearLogCache();
  238. };
  239. filesInput = new BABYLON.FilesInput(engine, null, sceneLoaded, null, null, null, startProcessingFiles, null, sceneError);
  240. filesInput.onProcessFileCallback = (function(file, name, extension) {
  241. if (filesInput._filesToLoad && filesInput._filesToLoad.length === 1 && extension) {
  242. if (extension.toLowerCase() === "dds" || extension.toLowerCase() === "env") {
  243. BABYLON.FilesInput.FilesToLoad[name] = file;
  244. skyboxPath = "file:" + file.correctName;
  245. return false;
  246. }
  247. }
  248. return true;
  249. }).bind(this);
  250. filesInput.monitorElementForDragNDrop(canvas);
  251. htmlInput.addEventListener('change', function(event) {
  252. // Handling data transfer via drag'n'drop
  253. if (event && event.dataTransfer && event.dataTransfer.files) {
  254. filesToLoad = event.dataTransfer.files;
  255. }
  256. // Handling files from input files
  257. if (event && event.target && event.target.files) {
  258. filesToLoad = event.target.files;
  259. }
  260. filesInput.loadFiles(event);
  261. }, false);
  262. var reload = function (sceneFile) {
  263. // If a scene file has been provided
  264. if (sceneFile) {
  265. var onSuccess = function (scene) {
  266. assetContainerLoaded(sceneFile, scene);
  267. };
  268. BABYLON.SceneLoader.ImportAnimations("file:", sceneFile, currentScene, null, onSuccess);
  269. }
  270. else {
  271. Logger.Error("Please provide a valid .babylon file.");
  272. }
  273. };
  274. filesInputAnimation = new BABYLON.FilesInput(engine, null, null, null, null, null, startProcessingFiles, reload, sceneError);
  275. htmlInputAnimation.addEventListener('change', function (event) {
  276. // Handling data transfer via drag'n'drop
  277. if (event && event.dataTransfer && event.dataTransfer.files) {
  278. filesToLoad = event.dataTransfer.files;
  279. }
  280. // Handling files from input files
  281. if (event && event.target && event.target.files) {
  282. filesToLoad = event.target.files;
  283. }
  284. filesInputAnimation.loadFiles(event);
  285. }, false);
  286. }
  287. window.addEventListener("keydown", function (event) {
  288. // Press R to reload
  289. if (event.keyCode === 82 && event.target.nodeName !== "INPUT" && currentScene) {
  290. if (assetUrl) {
  291. loadFromAssetUrl();
  292. }
  293. else {
  294. filesInput.reload();
  295. }
  296. }
  297. });
  298. btnInspector.addEventListener('click', function() {
  299. if (currentScene) {
  300. if (currentScene.debugLayer.isVisible()) {
  301. debugLayerEnabled = false;
  302. currentScene.debugLayer.hide();
  303. }
  304. else {
  305. currentScene.debugLayer.show();
  306. debugLayerEnabled = true;
  307. }
  308. }
  309. }, false);
  310. window.addEventListener("keydown", function(event) {
  311. // Press space to toggle footer
  312. if (event.keyCode === 32 && event.target.nodeName !== "INPUT") {
  313. if (footer.style.display === "none") {
  314. footer.style.display = "block";
  315. canvasZone.style.height = "calc(100% - 56px)";
  316. if (debugLayerEnabled) {
  317. currentScene.debugLayer.show();
  318. }
  319. engine.resize();
  320. }
  321. else {
  322. footer.style.display = "none";
  323. canvasZone.style.height = "100%";
  324. errorZone.style.display = "none";
  325. engine.resize();
  326. if (currentScene.debugLayer.isVisible()) {
  327. currentScene.debugLayer.hide();
  328. }
  329. }
  330. }
  331. });
  332. sizeScene();
  333. window.onresize = function() {
  334. sizeScene();
  335. }
  336. }
  337. function sizeScene() {
  338. let divInspWrapper = document.getElementsByClassName('insp-wrapper')[0];
  339. if (divInspWrapper) {
  340. let divFooter = document.getElementsByClassName('footer')[0];
  341. divInspWrapper.style.height = (document.body.clientHeight - divFooter.clientHeight) + "px";
  342. divInspWrapper.style['max-width'] = document.body.clientWidth + "px";
  343. }
  344. }