index.js 37 KB

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