index.js 17 KB

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