index.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. var jsEditor;
  2. (function () {
  3. var multipleSize = [1600, 1475, 1030, 750];
  4. var setToMultipleID = function (id, thingToDo, param) {
  5. multipleSize.forEach(function (size) {
  6. if (thingToDo == "innerHTML") {
  7. document.getElementById(id + size).innerHTML = param
  8. }
  9. else if (thingToDo == "click") {
  10. document.getElementById(id + size).addEventListener("click", param);
  11. }
  12. else if (thingToDo == "addClass") {
  13. document.getElementById(id + size).classList.add(param);
  14. }
  15. else if (thingToDo == "removeClass") {
  16. document.getElementById(id + size).classList.remove(param);
  17. }
  18. else if (thingToDo == "display") {
  19. document.getElementById(id + size).style.display = param;
  20. }
  21. });
  22. };
  23. var fontSize = 14;
  24. var splitInstance = Split(['#jsEditor', '#canvasZone']);
  25. var elementToTheme = [
  26. '.wrapper .gutter',
  27. '.wrapper #jsEditor',
  28. '.navbar',
  29. '.navbar .select .toDisplay .option',
  30. '.navbar .select .toDisplayBig',
  31. '.navbar .select .toDisplayBig a',
  32. '.navbar .select .toDisplayBig ul li',
  33. '.navbarBottom',
  34. '.navbarBottom .links .link',
  35. '.save-message'];
  36. var run = function () {
  37. var blockEditorChange = false;
  38. var markDirty = function () {
  39. if (blockEditorChange) {
  40. return;
  41. }
  42. setToMultipleID("currentScript", "innerHTML", "Custom");
  43. setToMultipleID("safemodeToggle", "addClass", "checked");
  44. setToMultipleID('safemodeToggle', 'innerHTML', 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  45. }
  46. jsEditor.onKeyUp(function (evt) {
  47. markDirty();
  48. });
  49. var snippetUrl = "https://babylonjs-api2.azurewebsites.net/snippets";
  50. var currentSnippetToken;
  51. var currentSnippetTitle = null;
  52. var currentSnippetDescription = null;
  53. var currentSnippetTags = null;
  54. var engine;
  55. var fpsLabel = document.getElementById("fpsLabel");
  56. var scripts;
  57. var zipCode;
  58. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  59. if (location.href.indexOf("Stable") !== -1) {
  60. setToMultipleID("currentVersion", "innerHTML", "Version: Stable");
  61. } else {
  62. setToMultipleID("currentVersion", "innerHTML", "Version: Latest");
  63. }
  64. var loadScript = function (scriptURL, title) {
  65. var xhr = new XMLHttpRequest();
  66. xhr.open('GET', scriptURL, true);
  67. xhr.onreadystatechange = function () {
  68. if (xhr.readyState === 4) {
  69. if (xhr.status === 200) {
  70. xhr.onreadystatechange = null;
  71. blockEditorChange = true;
  72. jsEditor.setValue(xhr.responseText);
  73. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  74. blockEditorChange = false;
  75. compileAndRun();
  76. setToMultipleID("currentScript", "innerHTML", title);
  77. currentSnippetToken = null;
  78. }
  79. }
  80. };
  81. xhr.send(null);
  82. };
  83. var loadScriptFromIndex = function (index) {
  84. if (index === 0) {
  85. index = 1;
  86. }
  87. var script = scripts[index - 1].trim();
  88. loadScript("scripts/" + script + ".js", script);
  89. }
  90. var onScriptClick = function (evt) {
  91. loadScriptFromIndex(evt.target.scriptLinkIndex);
  92. };
  93. var loadScriptsList = function () {
  94. var xhr = new XMLHttpRequest();
  95. xhr.open('GET', 'scripts/scripts.txt', true);
  96. xhr.onreadystatechange = function () {
  97. if (xhr.readyState === 4) {
  98. if (xhr.status === 200) {
  99. scripts = xhr.responseText.split("\n");
  100. for (var i = 0; i < multipleSize.length; i++) {
  101. var ul = document.getElementById("scriptsList" + multipleSize[i]);
  102. var index;
  103. for (index = 0; index < scripts.length; index++) {
  104. var option = document.createElement("li");
  105. var a = document.createElement("a");
  106. a.href = "#";
  107. a.innerHTML = (index + 1) + " - " + scripts[index];
  108. a.scriptLinkIndex = index + 1;
  109. //a.onclick = onScriptClick;
  110. option.scriptLinkIndex = index + 1;
  111. option.onclick = onScriptClick;
  112. option.appendChild(a);
  113. ul.appendChild(option);
  114. }
  115. }
  116. if (!location.hash) {
  117. // Query string
  118. var queryString = window.location.search;
  119. if (queryString) {
  120. var query = queryString.replace("?", "");
  121. index = parseInt(query);
  122. if (!isNaN(index)) {
  123. loadScriptFromIndex(index);
  124. } else {
  125. loadScript("scripts/" + query + ".js", query);
  126. }
  127. } else {
  128. loadScript("scripts/basic scene.js", "Basic scene");
  129. }
  130. }
  131. // Restore theme
  132. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  133. toggleTheme(theme);
  134. // Remove editor if window size is less than 850px
  135. var removeEditorForSmallScreen = function () {
  136. if (mq.matches) {
  137. splitInstance.collapse(0);
  138. } else {
  139. splitInstance.setSizes([50, 50]);
  140. }
  141. }
  142. var mq = window.matchMedia("(max-width: 850px)");
  143. mq.addListener(removeEditorForSmallScreen);
  144. }
  145. }
  146. };
  147. xhr.send(null);
  148. }
  149. var createNewScript = function () {
  150. location.hash = "";
  151. currentSnippetToken = null;
  152. currentSnippetTitle = null;
  153. currentSnippetDescription = null;
  154. currentSnippetTags = null;
  155. showNoMetadata();
  156. jsEditor.setValue('// You have to create a function called createScene. This function must return a BABYLON.Scene object\r\n// You can reference the following variables: scene, canvas\r\n// You must at least define a camera\r\n// More info here: https://doc.babylonjs.com/generals/The_Playground_Tutorial\r\n\r\nvar createScene = function() {\r\n\tvar scene = new BABYLON.Scene(engine);\r\n\tvar camera = new BABYLON.ArcRotateCamera("Camera", 0, Math.PI / 2, 12, BABYLON.Vector3.Zero(), scene);\r\n\tcamera.attachControl(canvas, true);\r\n\r\n\r\n\r\n\treturn scene;\r\n};');
  157. jsEditor.setPosition({ lineNumber: 11, column: 0 });
  158. jsEditor.focus();
  159. compileAndRun();
  160. }
  161. var clear = function () {
  162. location.hash = "";
  163. currentSnippetToken = null;
  164. jsEditor.setValue('');
  165. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  166. jsEditor.focus();
  167. }
  168. var showError = function (errorMessage, errorEvent) {
  169. var errorContent =
  170. '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button>';
  171. if (errorEvent) {
  172. var regEx = /\(.+:(\d+):(\d+)\)\n/g;
  173. var match = regEx.exec(errorEvent.stack);
  174. if (match) {
  175. errorContent += "Line ";
  176. var lineNumber = match[1];
  177. var columnNumber = match[2];
  178. errorContent += lineNumber + ':' + columnNumber + ' - ';
  179. }
  180. }
  181. errorContent += errorMessage + '</div>';
  182. document.getElementById("errorZone").style.display = 'block';
  183. document.getElementById("errorZone").innerHTML = errorContent;
  184. // Close button error
  185. document.getElementById("errorZone").querySelector('.close').addEventListener('click', function () {
  186. document.getElementById("errorZone").style.display = 'none';
  187. });
  188. }
  189. var showNoMetadata = function () {
  190. if (currentSnippetTitle) {
  191. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  192. document.getElementById("saveFormTitle").readOnly = true;
  193. }
  194. else {
  195. document.getElementById("saveFormTitle").value = '';
  196. document.getElementById("saveFormTitle").readOnly = false;
  197. }
  198. if (currentSnippetDescription) {
  199. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  200. document.getElementById("saveFormDescription").readOnly = true;
  201. }
  202. else {
  203. document.getElementById("saveFormDescription").value = '';
  204. document.getElementById("saveFormDescription").readOnly = false;
  205. }
  206. if (currentSnippetTags) {
  207. document.getElementById("saveFormTags").value = currentSnippetTags;
  208. document.getElementById("saveFormTags").readOnly = true;
  209. }
  210. else {
  211. document.getElementById("saveFormTags").value = '';
  212. document.getElementById("saveFormTags").readOnly = false;
  213. }
  214. document.getElementById("saveFormButtons").style.display = "block";
  215. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  216. document.getElementById("saveMessage").style.display = "block";
  217. };
  218. showNoMetadata();
  219. document.getElementById("saveMessage").style.display = "none";
  220. var hideNoMetadata = function () {
  221. document.getElementById("saveFormTitle").readOnly = true;
  222. document.getElementById("saveFormDescription").readOnly = true;
  223. document.getElementById("saveFormTags").readOnly = true;
  224. document.getElementById("saveFormButtonOk").style.display = "none";
  225. document.getElementById("saveMessage").style.display = "none";
  226. setToMultipleID("metadataButton", "display", "inline-block");
  227. };
  228. compileAndRun = function () {
  229. try {
  230. var waitRing = document.getElementById("waitDiv");
  231. if (waitRing) {
  232. waitRing.style.display = "none";
  233. }
  234. if (!BABYLON.Engine.isSupported()) {
  235. showError("Your browser does not support WebGL", null);
  236. return;
  237. }
  238. var showInspector = false;
  239. var showDebugLayer = false;
  240. var initialTabIndex = 0;
  241. if(document.getElementsByClassName('insp-wrapper').length > 0){
  242. for(var i = 0; i < engine.scenes.length; i++){
  243. if(engine.scenes[i]._debugLayer){
  244. //TODO: once inspector is updated on netlify, use getActiveTabIndex instead of the following loop
  245. //initialTabIndex = engine.scenes[i]._debugLayer._inspector.getActiveTabIndex();
  246. var tabs = engine.scenes[i]._debugLayer._inspector._tabbar._tabs;
  247. for(var j = 0; j < tabs.length; j++){
  248. if(tabs[j].isActive()){
  249. initialTabIndex = j;
  250. break;
  251. }
  252. }
  253. break;
  254. }
  255. }
  256. showInspector = true;
  257. }else if(document.getElementById('DebugLayer')){
  258. showDebugLayer = true;
  259. }
  260. if (engine) {
  261. engine.dispose();
  262. engine = null;
  263. }
  264. var canvas = document.getElementById("renderCanvas");
  265. engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  266. document.getElementById("errorZone").style.display = 'none';
  267. document.getElementById("errorZone").innerHTML = "";
  268. document.getElementById("statusBar").innerHTML = "Loading assets...Please wait";
  269. engine.runRenderLoop(function () {
  270. if (engine.scenes.length === 0) {
  271. return;
  272. }
  273. if (canvas.width !== canvas.clientWidth) {
  274. engine.resize();
  275. }
  276. var scene = engine.scenes[0];
  277. if (scene.activeCamera || scene.activeCameras.length > 0) {
  278. scene.render();
  279. }
  280. fpsLabel.style.right = document.body.clientWidth - (jsEditor.domElement.clientWidth + canvas.clientWidth) + "px";
  281. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  282. });
  283. var code = jsEditor.getValue();
  284. var scene;
  285. if (code.indexOf("createScene") !== -1) { // createScene
  286. eval(code);
  287. scene = createScene();
  288. if (!scene) {
  289. showError("createScene function must return a scene.", null);
  290. return;
  291. }
  292. zipCode = code + "\r\n\r\nvar scene = createScene();";
  293. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  294. eval(code);
  295. scene = CreateScene();
  296. if (!scene) {
  297. showError("CreateScene function must return a scene.", null);
  298. return;
  299. }
  300. zipCode = code + "\r\n\r\nvar scene = CreateScene();";
  301. } else if (code.indexOf("createscene") !== -1) { // createscene
  302. eval(code);
  303. scene = createscene();
  304. if (!scene) {
  305. showError("createscene function must return a scene.", null);
  306. return;
  307. }
  308. zipCode = code + "\r\n\r\nvar scene = createscene();";
  309. } else { // Direct code
  310. scene = new BABYLON.Scene(engine);
  311. eval("runScript = function(scene, canvas) {" + code + "}");
  312. runScript(scene, canvas);
  313. zipCode = "var scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  314. }
  315. if (engine.scenes.length === 0) {
  316. showError("You must at least create a scene.", null);
  317. return;
  318. }
  319. if (engine.scenes[0].activeCamera == null) {
  320. showError("You must at least create a camera.", null);
  321. return;
  322. }
  323. engine.scenes[0].executeWhenReady(function () {
  324. document.getElementById("statusBar").innerHTML = "";
  325. });
  326. if(scene){
  327. if(showInspector){
  328. scene.debugLayer.show({initialTab:initialTabIndex});
  329. scene.executeWhenReady(function(){
  330. scene.debugLayer._inspector.refresh();
  331. })
  332. }else if(showDebugLayer){
  333. scene.debugLayer.show();
  334. }
  335. }
  336. } catch (e) {
  337. showError(e.message, e);
  338. }
  339. };
  340. window.addEventListener("resize",
  341. function () {
  342. if (engine) {
  343. engine.resize();
  344. }
  345. });
  346. // Load scripts list
  347. loadScriptsList();
  348. // Zip
  349. var addContentToZip = function (zip, name, url, replace, buffer, then) {
  350. var xhr = new XMLHttpRequest();
  351. xhr.open('GET', url, true);
  352. if (buffer) {
  353. xhr.responseType = "arraybuffer";
  354. }
  355. xhr.onreadystatechange = function () {
  356. if (xhr.readyState === 4) {
  357. if (xhr.status === 200) {
  358. var text;
  359. if (!buffer) {
  360. if (replace) {
  361. var splits = replace.split("\r\n");
  362. for (var index = 0; index < splits.length; index++) {
  363. splits[index] = " " + splits[index];
  364. }
  365. replace = splits.join("\r\n");
  366. text = xhr.responseText.replace("####INJECT####", replace);
  367. } else {
  368. text = xhr.responseText;
  369. }
  370. }
  371. zip.file(name, buffer ? xhr.response : text);
  372. then();
  373. }
  374. }
  375. };
  376. xhr.send(null);
  377. }
  378. var addTexturesToZip = function (zip, index, textures, folder, then) {
  379. if (index === textures.length) {
  380. then();
  381. return;
  382. }
  383. if (textures[index].isRenderTarget || textures[index] instanceof BABYLON.DynamicTexture || textures[index].name.indexOf("data:") !== -1) {
  384. addTexturesToZip(zip, index + 1, textures, folder, then);
  385. return;
  386. }
  387. if (textures[index].isCube) {
  388. if (textures[index]._extensions && textures[index].name.indexOf("dds") === -1) {
  389. for (var i = 0; i < 6; i++) {
  390. textures.push({ name: textures[index].name + textures[index]._extensions[i] });
  391. }
  392. }
  393. else {
  394. textures.push({ name: textures[index].name });
  395. }
  396. addTexturesToZip(zip, index + 1, textures, folder, then);
  397. return;
  398. }
  399. if (folder == null) {
  400. folder = zip.folder("textures");
  401. }
  402. var url;
  403. if (textures[index].video) {
  404. url = textures[index].video.currentSrc;
  405. } else {
  406. // url = textures[index].name;
  407. url = textures[index].url ? textures[index].url : textures[index].name;
  408. }
  409. var name = textures[index].name.replace("textures/", "");
  410. // var name = url.substr(url.lastIndexOf("/") + 1);
  411. if (url != null) {
  412. addContentToZip(folder,
  413. name,
  414. url,
  415. null,
  416. true,
  417. function () {
  418. addTexturesToZip(zip, index + 1, textures, folder, then);
  419. });
  420. }
  421. else {
  422. addTexturesToZip(zip, index + 1, textures, folder, then);
  423. }
  424. }
  425. var addImportedFilesToZip = function (zip, index, importedFiles, folder, then) {
  426. if (index === importedFiles.length) {
  427. then();
  428. return;
  429. }
  430. if (!folder) {
  431. folder = zip.folder("scenes");
  432. }
  433. var url = importedFiles[index];
  434. var name = url.substr(url.lastIndexOf("/") + 1);
  435. addContentToZip(folder,
  436. name,
  437. url,
  438. null,
  439. true,
  440. function () {
  441. addImportedFilesToZip(zip, index + 1, importedFiles, folder, then);
  442. });
  443. }
  444. var getZip = function () {
  445. if (engine.scenes.length === 0) {
  446. return;
  447. }
  448. var zip = new JSZip();
  449. var scene = engine.scenes[0];
  450. var textures = scene.textures;
  451. var importedFiles = scene.importedMeshesFiles;
  452. document.getElementById("statusBar").innerHTML = "Creating archive...Please wait";
  453. if (zipCode.indexOf("textures/worldHeightMap.jpg") !== -1) {
  454. textures.push({ name: "textures/worldHeightMap.jpg" });
  455. }
  456. addContentToZip(zip,
  457. "index.html",
  458. "zipContent/index.html",
  459. zipCode,
  460. false,
  461. function () {
  462. addTexturesToZip(zip,
  463. 0,
  464. textures,
  465. null,
  466. function () {
  467. addImportedFilesToZip(zip,
  468. 0,
  469. importedFiles,
  470. null,
  471. function () {
  472. var blob = zip.generate({ type: "blob" });
  473. saveAs(blob, "sample.zip");
  474. document.getElementById("statusBar").innerHTML = "";
  475. });
  476. });
  477. });
  478. }
  479. // Versions
  480. setVersion = function (version) {
  481. switch (version) {
  482. case "stable":
  483. location.href = "indexStable.html" + location.hash;
  484. break;
  485. default:
  486. location.href = "index.html" + location.hash;
  487. break;
  488. }
  489. }
  490. // Fonts
  491. setFontSize = function (size) {
  492. fontSize = size;
  493. document.querySelector(".view-lines").style.fontSize = size + "px";
  494. setToMultipleID("currentFontSize", "innerHTML", "Font: " + size);
  495. };
  496. // Fullscreen
  497. document.getElementById("renderCanvas").addEventListener("webkitfullscreenchange", function () {
  498. if(document.webkitIsFullScreen) goFullPage();
  499. else exitFullPage();
  500. }, false);
  501. var goFullPage = function () {
  502. var canvasElement = document.getElementById("renderCanvas");
  503. canvasElement.style.position = "absolute";
  504. canvasElement.style.top = 0;
  505. canvasElement.style.left = 0;
  506. canvasElement.style.zIndex = 100;
  507. }
  508. var exitFullPage = function () {
  509. document.getElementById("renderCanvas").style.position = "relative";
  510. document.getElementById("renderCanvas").style.zIndex = 0;
  511. }
  512. var goFullscreen = function () {
  513. if (engine) {
  514. engine.switchFullscreen(true);
  515. }
  516. }
  517. var editorGoFullscreen = function () {
  518. var editorDiv = document.getElementById("jsEditor");
  519. if (editorDiv.requestFullscreen) {
  520. editorDiv.requestFullscreen();
  521. } else if (editorDiv.mozRequestFullScreen) {
  522. editorDiv.mozRequestFullScreen();
  523. } else if (editorDiv.webkitRequestFullscreen) {
  524. editorDiv.webkitRequestFullscreen();
  525. }
  526. }
  527. var toggleEditor = function () {
  528. var editorButton = document.getElementById("editorButton1600");
  529. var scene = engine.scenes[0];
  530. // If the editor is present
  531. if (editorButton.classList.contains('checked')) {
  532. setToMultipleID("editorButton", "removeClass", 'checked');
  533. splitInstance.collapse(0);
  534. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square-o" aria-hidden="true"></i>');
  535. } else {
  536. setToMultipleID("editorButton", "addClass", 'checked');
  537. splitInstance.setSizes([50, 50]); // Reset
  538. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  539. }
  540. engine.resize();
  541. if (scene.debugLayer.isVisible()) {
  542. scene.debugLayer.hide();
  543. scene.debugLayer.show();
  544. }
  545. }
  546. /**
  547. * Toggle the dark theme
  548. */
  549. var toggleTheme = function (theme) {
  550. // Monaco
  551. var vsTheme;
  552. if (theme == 'dark') {
  553. vsTheme = 'vs-dark'
  554. } else {
  555. vsTheme = 'vs'
  556. }
  557. var oldCode = jsEditor.getValue();
  558. jsEditor.dispose();
  559. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), {
  560. value: "",
  561. language: "javascript",
  562. lineNumbers: true,
  563. tabSize: "auto",
  564. insertSpaces: "auto",
  565. roundedSelection: true,
  566. scrollBeyondLastLine: false,
  567. automaticLayout: true,
  568. readOnly: false,
  569. theme: vsTheme,
  570. contextmenu: false
  571. });
  572. jsEditor.setValue(oldCode);
  573. setFontSize(fontSize);
  574. jsEditor.onKeyUp(function (evt) {
  575. markDirty();
  576. });
  577. for (var index = 0; index < elementToTheme.length; index++) {
  578. var obj = elementToTheme[index];
  579. var domObjArr = document.querySelectorAll(obj);
  580. for (var domObjIndex = 0; domObjIndex < domObjArr.length; domObjIndex++) {
  581. var domObj = domObjArr[domObjIndex];
  582. domObj.classList.remove('light');
  583. domObj.classList.remove('dark');
  584. domObj.classList.add(theme);
  585. }
  586. }
  587. localStorage.setItem("bjs-playground-theme", theme);
  588. }
  589. var toggleDebug = function () {
  590. var debugButton = document.getElementById("debugButton1600");
  591. var scene = engine.scenes[0];
  592. if (debugButton.classList.contains('uncheck')) {
  593. setToMultipleID("debugButton", "removeClass", 'uncheck');
  594. setToMultipleID("debugButton", "innerHTML", 'Debug layer<i class="fa fa-check-square" aria-hidden="true"></i>');
  595. scene.debugLayer.show();
  596. } else {
  597. setToMultipleID("debugButton", "addClass", 'uncheck');
  598. setToMultipleID("debugButton", "innerHTML", 'Debug layer<i class="fa fa-square-o" aria-hidden="true"></i>');
  599. scene.debugLayer.hide();
  600. }
  601. }
  602. var toggleMetadata = function () {
  603. var scene = engine.scenes[0];
  604. document.getElementById("saveLayer").style.display = "block";
  605. }
  606. var formatCode = function () {
  607. jsEditor.getAction('editor.action.format').run();
  608. }
  609. //Navigation Overwrites
  610. var exitPrompt = function (e) {
  611. var safeToggle = document.getElementById("safemodeToggle1600");
  612. if (safeToggle.classList.contains('checked')) {
  613. e = e || window.event;
  614. var message =
  615. 'This page is asking you to confirm that you want to leave - data you have entered may not be saved.';
  616. if (e) {
  617. e.returnValue = message;
  618. }
  619. return message;
  620. }
  621. };
  622. window.onbeforeunload = exitPrompt;
  623. // Snippet
  624. var save = function () {
  625. // Retrieve title if necessary
  626. if (document.getElementById("saveLayer")) {
  627. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  628. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  629. currentSnippetTags = document.getElementById("saveFormTags").value;
  630. }
  631. var xmlHttp = new XMLHttpRequest();
  632. xmlHttp.onreadystatechange = function () {
  633. if (xmlHttp.readyState === 4) {
  634. if (xmlHttp.status === 201) {
  635. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  636. var snippet = JSON.parse(xmlHttp.responseText);
  637. var newUrl = baseUrl + "#" + snippet.id;
  638. currentSnippetToken = snippet.id;
  639. if (snippet.version && snippet.version !== "0") {
  640. newUrl += "#" + snippet.version;
  641. }
  642. location.href = newUrl;
  643. // Hide the complete title & co message
  644. hideNoMetadata();
  645. compileAndRun();
  646. } else {
  647. showError("Unable to save your code. It may be too long.", null);
  648. }
  649. }
  650. }
  651. xmlHttp.open("POST", snippetUrl + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  652. xmlHttp.setRequestHeader("Content-Type", "application/json");
  653. var dataToSend = {
  654. payload: {
  655. code: jsEditor.getValue()
  656. },
  657. name: currentSnippetTitle,
  658. description: currentSnippetDescription,
  659. tags: currentSnippetTags
  660. };
  661. xmlHttp.send(JSON.stringify(dataToSend));
  662. }
  663. var askForSave = function () {
  664. if (currentSnippetTitle == null
  665. || currentSnippetDescription == null
  666. || currentSnippetTags == null) {
  667. document.getElementById("saveLayer").style.display = "block";
  668. }
  669. else {
  670. save();
  671. }
  672. };
  673. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  674. document.getElementById("saveLayer").style.display = "none";
  675. save();
  676. });
  677. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  678. document.getElementById("saveLayer").style.display = "none";
  679. });
  680. document.getElementById("saveMessage").addEventListener("click", function () {
  681. document.getElementById("saveMessage").style.display = "none";
  682. });
  683. document.getElementById("mainTitle").innerHTML = "v" + BABYLON.Engine.Version;
  684. var previousHash = "";
  685. var cleanHash = function () {
  686. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  687. if (splits.length > 2) {
  688. splits.splice(2, splits.length - 2);
  689. }
  690. location.hash = splits.join("#");
  691. }
  692. var checkHash = function (firstTime) {
  693. if (location.hash) {
  694. if (previousHash !== location.hash) {
  695. cleanHash();
  696. previousHash = location.hash;
  697. try {
  698. var xmlHttp = new XMLHttpRequest();
  699. xmlHttp.onreadystatechange = function () {
  700. if (xmlHttp.readyState === 4) {
  701. if (xmlHttp.status === 200) {
  702. var snippet = JSON.parse(xmlHttp.responseText)[0];
  703. blockEditorChange = true;
  704. jsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  705. // Check if title / descr / tags are already set
  706. if (snippet.name != null && snippet.name != "") {
  707. currentSnippetTitle = snippet.name;
  708. }
  709. else currentSnippetTitle = null;
  710. if (snippet.description != null && snippet.description != "") {
  711. currentSnippetDescription = snippet.description;
  712. }
  713. else currentSnippetDescription = null;
  714. if (snippet.tags != null && snippet.tags != "") {
  715. currentSnippetTags = snippet.tags;
  716. }
  717. else currentSnippetTags = null;
  718. if (currentSnippetTitle != null && currentSnippetTags != null && currentSnippetDescription) {
  719. if (document.getElementById("saveLayer")) {
  720. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  721. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  722. document.getElementById("saveFormTags").value = currentSnippetTags;
  723. hideNoMetadata();
  724. }
  725. }
  726. else {
  727. showNoMetadata();
  728. }
  729. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  730. blockEditorChange = false;
  731. compileAndRun();
  732. setToMultipleID("currentScript", "innerHTML", "Custom");
  733. } else if (firstTime) {
  734. location.href = location.href.replace(location.hash, "");
  735. if (scripts) {
  736. loadScriptFromIndex(0);
  737. }
  738. }
  739. }
  740. };
  741. var hash = location.hash.substr(1);
  742. currentSnippetToken = hash.split("#")[0];
  743. if (!hash.split("#")[1]) hash += "#0";
  744. xmlHttp.open("GET", snippetUrl + "/" + hash.replace("#", "/"));
  745. xmlHttp.send();
  746. } catch (e) {
  747. }
  748. }
  749. }
  750. setTimeout(checkHash, 200);
  751. }
  752. checkHash(true);
  753. // ---------- UI
  754. // Run
  755. setToMultipleID("runButton", "click", compileAndRun);
  756. // New
  757. setToMultipleID("newButton", "click", createNewScript);
  758. // Clear
  759. setToMultipleID("clearButton", "click", clear);
  760. // Save
  761. setToMultipleID("saveButton", "click", askForSave);
  762. // Zip
  763. setToMultipleID("zipButton", "click", getZip);
  764. // Themes
  765. setToMultipleID("darkTheme", "click", toggleTheme.bind(this, 'dark'));
  766. setToMultipleID("lightTheme", "click", toggleTheme.bind(this, 'light'));
  767. // Safe mode
  768. setToMultipleID("safemodeToggle", 'click', function () {
  769. document.getElementById("safemodeToggle1600").classList.toggle('checked');
  770. if (document.getElementById("safemodeToggle1600").classList.contains('checked')) {
  771. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  772. } else {
  773. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square-o" aria-hidden="true"></i>');
  774. }
  775. });
  776. // Editor
  777. setToMultipleID("editorButton", "click", toggleEditor);
  778. // FullScreen
  779. setToMultipleID("fullscreenButton", "click", goFullscreen);
  780. // Editor fullScreen
  781. setToMultipleID("editorFullscreenButton", "click", editorGoFullscreen);
  782. // Format
  783. setToMultipleID("formatButton", "click", formatCode);
  784. // Debug
  785. setToMultipleID("debugButton", "click", toggleDebug);
  786. // Metadata
  787. setToMultipleID("metadataButton", "click", toggleMetadata);
  788. // Restore theme
  789. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  790. toggleTheme(theme);
  791. }
  792. // Monaco
  793. var xhr = new XMLHttpRequest();
  794. xhr.open('GET', "babylon.d.txt", true);
  795. xhr.onreadystatechange = function () {
  796. if (xhr.readyState === 4) {
  797. if (xhr.status === 200) {
  798. require.config({ paths: { 'vs': 'node_modules/monaco-editor/min/vs' } });
  799. require(['vs/editor/editor.main'], function () {
  800. monaco.languages.typescript.javascriptDefaults.addExtraLib(xhr.responseText, 'babylon.d.ts');
  801. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), {
  802. value: "",
  803. language: "javascript",
  804. lineNumbers: true,
  805. tabSize: "auto",
  806. insertSpaces: "auto",
  807. roundedSelection: true,
  808. scrollBeyondLastLine: false,
  809. automaticLayout: true,
  810. readOnly: false,
  811. theme: "vs",
  812. contextmenu: false,
  813. folding: true
  814. });
  815. run();
  816. });
  817. }
  818. }
  819. };
  820. xhr.send(null);
  821. })();