index.js 36 KB

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