index.js 17 KB

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