index.js 15 KB

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