index.js 17 KB

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