index.js 17 KB

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