index.js 15 KB

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