index.js 16 KB

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