index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. canvasZone.style.height = "calc(100% - 56px)";
  276. if (debugLayerEnabled) {
  277. currentScene.debugLayer.show();
  278. }
  279. engine.resize();
  280. }
  281. else {
  282. footer.style.display = "none";
  283. canvasZone.style.height = "100%";
  284. errorZone.style.display = "none";
  285. engine.resize();
  286. if (currentScene.debugLayer.isVisible()) {
  287. currentScene.debugLayer.hide();
  288. }
  289. }
  290. }
  291. });
  292. sizeScene();
  293. window.onresize = function() {
  294. sizeScene();
  295. }
  296. }
  297. function sizeScene() {
  298. let divInspWrapper = document.getElementsByClassName('insp-wrapper')[0];
  299. if (divInspWrapper) {
  300. let divFooter = document.getElementsByClassName('footer')[0];
  301. divInspWrapper.style.height = (document.body.clientHeight - divFooter.clientHeight) + "px";
  302. divInspWrapper.style['max-width'] = document.body.clientWidth + "px";
  303. }
  304. }
  305. // animation
  306. // event on the dropdown
  307. function formatId(name) {
  308. return "data-" + name.replace(/\s/g, '');
  309. }
  310. function displayDropdownContent(display) {
  311. if (display) {
  312. dropdownContent.style.display = "flex";
  313. chevronDown.style.display = "inline";
  314. chevronUp.style.display = "none";
  315. }
  316. else {
  317. dropdownContent.style.display = "none";
  318. chevronDown.style.display = "none";
  319. chevronUp.style.display = "inline";
  320. }
  321. }
  322. dropdownBtn.addEventListener("click", function() {
  323. if (dropdownContent.style.display === "flex") {
  324. displayDropdownContent(false);
  325. }
  326. else {
  327. displayDropdownContent(true);
  328. }
  329. });
  330. function selectCurrentGroup(group, index, animation) {
  331. if (currentGroupIndex !== undefined) {
  332. document.getElementById(formatId(currentGroup.name + "-" + currentGroupIndex)).classList.remove("active");
  333. }
  334. playBtn.classList.remove("play");
  335. playBtn.classList.add("pause");
  336. // start the new animation group
  337. currentGroup = group;
  338. currentGroupIndex = index;
  339. animation.classList.add("active");
  340. dropdownLabel.innerHTML = currentGroup.name;
  341. dropdownLabel.title = currentGroup.name;
  342. // set the slider
  343. slider.setAttribute("min", currentGroup.from);
  344. slider.setAttribute("max", currentGroup.to);
  345. currentSliderValue = currentGroup.from;
  346. slider.value = currentGroup.from;
  347. }
  348. function createDropdownLink(group, index) {
  349. var animation = document.createElement("a");
  350. animation.innerHTML = group.name;
  351. animation.title = group.name;
  352. animation.setAttribute("id", formatId(group.name + "-" + index));
  353. animation.addEventListener("click", function() {
  354. // stop the current animation group
  355. currentGroup.reset();
  356. currentGroup.stop();
  357. group.play(true);
  358. // hide the content of the dropdown
  359. displayDropdownContent(false);
  360. });
  361. dropdownContent.appendChild(animation);
  362. group.onAnimationGroupPlayObservable.add(function(grp) {
  363. selectCurrentGroup(grp, index, animation);
  364. });
  365. group.onAnimationGroupPauseObservable.add(function(grp) {
  366. playBtn.classList.add("play");
  367. playBtn.classList.remove("pause");
  368. });
  369. }
  370. // event on the play/pause button
  371. playBtn.addEventListener("click", function() {
  372. // click on the button to run the animation
  373. if (this.classList.contains("play")) {
  374. currentGroup.play(true);
  375. }
  376. // click on the button to pause the animation
  377. else {
  378. currentGroup.pause();
  379. }
  380. });
  381. // event on the slider
  382. slider.addEventListener("input", function() {
  383. var value = parseFloat(this.value);
  384. if (playBtn.classList.contains("play")) {
  385. currentGroup.play(true);
  386. currentGroup.goToFrame(value);
  387. currentGroup.pause();
  388. } else {
  389. currentGroup.goToFrame(value);
  390. }
  391. });
  392. var sliderPause = false;
  393. slider.addEventListener("mousedown", function() {
  394. if (playBtn.classList.contains("pause")) {
  395. sliderPause = true;
  396. playBtn.click();
  397. }
  398. });
  399. slider.addEventListener("mouseup", function() {
  400. if (sliderPause) {
  401. sliderPause = false;
  402. playBtn.click();
  403. }
  404. });