index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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) {
  107. var targetedAnimations = currentGroup.targetedAnimations;
  108. if (targetedAnimations.length > 0) {
  109. var runtimeAnimations = currentGroup.targetedAnimations[0].animation.runtimeAnimations;
  110. if (runtimeAnimations.length > 0) {
  111. slider.value = runtimeAnimations[0].currentFrame;
  112. }
  113. }
  114. }
  115. });
  116. // Clear the error
  117. errorZone.style.display = 'none';
  118. btnInspector.classList.remove("hidden");
  119. currentScene = babylonScene;
  120. document.title = "Babylon.js - " + sceneFile.name;
  121. // Fix for IE, otherwise it will change the default filter for files selection after first use
  122. htmlInput.value = "";
  123. // Attach camera to canvas inputs
  124. if (!currentScene.activeCamera || currentScene.lights.length === 0) {
  125. currentScene.createDefaultCamera(true);
  126. if (cameraPosition) {
  127. currentScene.activeCamera.setPosition(cameraPosition);
  128. }
  129. else {
  130. if (currentPluginName === "gltf") {
  131. // glTF assets use a +Z forward convention while the default camera faces +Z. Rotate the camera to look at the front of the asset.
  132. currentScene.activeCamera.alpha += Math.PI;
  133. }
  134. // Enable camera's behaviors
  135. currentScene.activeCamera.useFramingBehavior = true;
  136. var framingBehavior = currentScene.activeCamera.getBehaviorByName("Framing");
  137. framingBehavior.framingTime = 0;
  138. framingBehavior.elevationReturnTime = -1;
  139. if (currentScene.meshes.length) {
  140. var worldExtends = currentScene.getWorldExtends();
  141. currentScene.activeCamera.lowerRadiusLimit = null;
  142. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  143. }
  144. }
  145. currentScene.activeCamera.pinchPrecision = 200 / currentScene.activeCamera.radius;
  146. currentScene.activeCamera.upperRadiusLimit = 5 * currentScene.activeCamera.radius;
  147. currentScene.activeCamera.wheelDeltaPercentage = 0.01;
  148. currentScene.activeCamera.pinchDeltaPercentage = 0.01;
  149. }
  150. currentScene.activeCamera.attachControl(canvas);
  151. // Lighting
  152. if (currentPluginName === "gltf") {
  153. if (!currentScene.environmentTexture) {
  154. currentScene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(skyboxPath, currentScene);
  155. }
  156. currentSkybox = currentScene.createDefaultSkybox(currentScene.environmentTexture, true, (currentScene.activeCamera.maxZ - currentScene.activeCamera.minZ) / 2, 0.3, false);
  157. }
  158. else {
  159. currentScene.createDefaultLight();
  160. }
  161. // In case of error during loading, meshes will be empty and clearColor is set to red
  162. if (currentScene.meshes.length === 0 && currentScene.clearColor.r === 1 && currentScene.clearColor.g === 0 && currentScene.clearColor.b === 0) {
  163. document.getElementById("logo").className = "";
  164. canvas.style.opacity = 0;
  165. debugLayerEnabled = true;
  166. }
  167. else {
  168. if (BABYLON.Tools.errorsCount > 0) {
  169. debugLayerEnabled = true;
  170. }
  171. document.getElementById("logo").className = "hidden";
  172. document.getElementById("droptext").className = "hidden";
  173. canvas.style.opacity = 1;
  174. if (currentScene.activeCamera.keysUp) {
  175. currentScene.activeCamera.keysUp.push(90); // Z
  176. currentScene.activeCamera.keysUp.push(87); // W
  177. currentScene.activeCamera.keysDown.push(83); // S
  178. currentScene.activeCamera.keysLeft.push(65); // A
  179. currentScene.activeCamera.keysLeft.push(81); // Q
  180. currentScene.activeCamera.keysRight.push(69); // E
  181. currentScene.activeCamera.keysRight.push(68); // D
  182. }
  183. }
  184. if (debugLayerEnabled) {
  185. currentScene.debugLayer.show({ initialTab: debugLayerLastActiveTab });
  186. }
  187. };
  188. var sceneError = function(sceneFile, babylonScene, message) {
  189. document.title = "Babylon.js - " + sceneFile.name;
  190. document.getElementById("logo").className = "";
  191. canvas.style.opacity = 0;
  192. 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>';
  193. errorZone.style.display = 'block';
  194. errorZone.innerHTML = errorContent;
  195. // Close button error
  196. errorZone.querySelector('.close').addEventListener('click', function() {
  197. errorZone.style.display = 'none';
  198. });
  199. };
  200. var loadFromAssetUrl = function() {
  201. var rootUrl = BABYLON.Tools.GetFolderPath(assetUrl);
  202. var fileName = BABYLON.Tools.GetFilename(assetUrl);
  203. BABYLON.SceneLoader.LoadAsync(rootUrl, fileName, engine).then(function(scene) {
  204. if (currentScene) {
  205. currentScene.dispose();
  206. }
  207. sceneLoaded({ name: fileName }, scene);
  208. scene.whenReadyAsync().then(function() {
  209. engine.runRenderLoop(function() {
  210. scene.render();
  211. });
  212. });
  213. }).catch(function(reason) {
  214. sceneError({ name: fileName }, null, reason.message || reason);
  215. });
  216. };
  217. if (assetUrl) {
  218. loadFromAssetUrl();
  219. }
  220. else {
  221. var startProcessingFiles = function() {
  222. BABYLON.Tools.ClearLogCache();
  223. if (currentScene) {
  224. debugLayerLastActiveTab = currentScene.debugLayer.getActiveTab();
  225. }
  226. };
  227. filesInput = new BABYLON.FilesInput(engine, null, sceneLoaded, null, null, null, startProcessingFiles, null, sceneError);
  228. filesInput.onProcessFileCallback = (function(file, name, extension) {
  229. if (filesInput._filesToLoad && filesInput._filesToLoad.length === 1 && extension) {
  230. if (extension.toLowerCase() === "dds" || extension.toLowerCase() === "env") {
  231. BABYLON.FilesInput.FilesToLoad[name] = file;
  232. skyboxPath = "file:" + file.correctName;
  233. return false;
  234. }
  235. }
  236. return true;
  237. }).bind(this);
  238. filesInput.monitorElementForDragNDrop(canvas);
  239. htmlInput.addEventListener('change', function(event) {
  240. var filestoLoad;
  241. // Handling data transfer via drag'n'drop
  242. if (event && event.dataTransfer && event.dataTransfer.files) {
  243. filesToLoad = event.dataTransfer.files;
  244. }
  245. // Handling files from input files
  246. if (event && event.target && event.target.files) {
  247. filesToLoad = event.target.files;
  248. }
  249. filesInput.loadFiles(event);
  250. }, false);
  251. }
  252. window.addEventListener("keydown", function(event) {
  253. // Press R to reload
  254. if (event.keyCode === 82 && event.target.nodeName !== "INPUT" && currentScene) {
  255. debugLayerLastActiveTab = currentScene.debugLayer.getActiveTab();
  256. if (assetUrl) {
  257. loadFromAssetUrl();
  258. }
  259. else {
  260. filesInput.reload();
  261. }
  262. }
  263. });
  264. btnInspector.addEventListener('click', function() {
  265. if (currentScene) {
  266. if (currentScene.debugLayer.isVisible()) {
  267. debugLayerEnabled = false;
  268. debugLayerLastActiveTab = currentScene.debugLayer.getActiveTab();
  269. currentScene.debugLayer.hide();
  270. }
  271. else {
  272. currentScene.debugLayer.show({ initialTab: debugLayerLastActiveTab });
  273. debugLayerEnabled = true;
  274. }
  275. }
  276. }, false);
  277. window.addEventListener("keydown", function(event) {
  278. // Press space to toggle footer
  279. if (event.keyCode === 32 && event.target.nodeName !== "INPUT") {
  280. if (footer.style.display === "none") {
  281. footer.style.display = "block";
  282. canvas.style.height = "calc(100% - 56px)";
  283. engine.resize();
  284. }
  285. else {
  286. footer.style.display = "none";
  287. canvas.style.height = "100%";
  288. errorZone.style.display = "none";
  289. engine.resize();
  290. if (debugLayerEnabled) {
  291. currentScene.debugLayer.hide();
  292. debugLayerEnabled = false;
  293. }
  294. }
  295. }
  296. });
  297. sizeScene();
  298. window.onresize = function() {
  299. sizeScene();
  300. }
  301. }
  302. function sizeScene() {
  303. let divInspWrapper = document.getElementsByClassName('insp-wrapper')[0];
  304. if (divInspWrapper) {
  305. let divFooter = document.getElementsByClassName('footer')[0];
  306. divInspWrapper.style.height = (document.body.clientHeight - divFooter.clientHeight) + "px";
  307. divInspWrapper.style['max-width'] = document.body.clientWidth + "px";
  308. }
  309. }
  310. // animation
  311. // event on the dropdown
  312. function formatId(name) {
  313. return "data-" + name.replace(/\s/g, '');
  314. }
  315. function displayDropdownContent(display) {
  316. if (display) {
  317. dropdownContent.style.display = "flex";
  318. chevronDown.style.display = "inline";
  319. chevronUp.style.display = "none";
  320. }
  321. else {
  322. dropdownContent.style.display = "none";
  323. chevronDown.style.display = "none";
  324. chevronUp.style.display = "inline";
  325. }
  326. }
  327. dropdownBtn.addEventListener("click", function() {
  328. if (dropdownContent.style.display === "flex") {
  329. displayDropdownContent(false);
  330. }
  331. else {
  332. displayDropdownContent(true);
  333. }
  334. });
  335. function createDropdownLink(group, index) {
  336. var animation = document.createElement("a");
  337. animation.innerHTML = group.name;
  338. animation.title = group.name;
  339. animation.setAttribute("id", formatId(group.name + "-" + index));
  340. animation.addEventListener("click", function() {
  341. // stop the current animation group
  342. currentGroup.reset();
  343. currentGroup.stop();
  344. document.getElementById(formatId(currentGroup.name + "-" + currentGroupIndex)).classList.remove("active");
  345. playBtn.classList.remove("play");
  346. playBtn.classList.add("pause");
  347. // start the new animation group
  348. currentGroup = group;
  349. currentGroupIndex = index;
  350. currentGroup.start(true);
  351. this.classList.add("active");
  352. dropdownLabel.innerHTML = currentGroup.name;
  353. dropdownLabel.title = currentGroup.name;
  354. // set the slider
  355. slider.setAttribute("min", currentGroup.from);
  356. slider.setAttribute("max", currentGroup.to);
  357. currentSliderValue = currentGroup.from;
  358. slider.value = currentGroup.from;
  359. // hide the content of the dropdown
  360. displayDropdownContent(false);
  361. });
  362. dropdownContent.appendChild(animation);
  363. }
  364. // event on the play/pause button
  365. playBtn.addEventListener("click", function() {
  366. // click on the button to run the animation
  367. if (this.classList.contains("play")) {
  368. this.classList.remove("play");
  369. this.classList.add("pause");
  370. var currentFrame = slider.value;
  371. currentGroup.play(true);
  372. }
  373. // click on the button to pause the animation
  374. else {
  375. this.classList.add("play");
  376. this.classList.remove("pause");
  377. currentGroup.pause();
  378. }
  379. });
  380. // event on the slider
  381. slider.addEventListener("input", function() {
  382. if (playBtn.classList.contains("play")) {
  383. currentGroup.play(true);
  384. currentGroup.goToFrame(this.value);
  385. currentGroup.pause();
  386. } else {
  387. currentGroup.goToFrame(this.value);
  388. }
  389. });
  390. var sliderPause = false;
  391. slider.addEventListener("mousedown", function() {
  392. if (playBtn.classList.contains("pause")) {
  393. sliderPause = true;
  394. playBtn.click();
  395. }
  396. });
  397. slider.addEventListener("mouseup", function() {
  398. if (sliderPause) {
  399. sliderPause = false;
  400. playBtn.click();
  401. }
  402. });