index.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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. // Fullscreen
  465. document.getElementById("renderCanvas").addEventListener("webkitfullscreenchange", function () {
  466. if(document.webkitIsFullScreen) goFullPage();
  467. else exitFullPage();
  468. }, false);
  469. var goFullPage = function () {
  470. var canvasElement = document.getElementById("renderCanvas");
  471. canvasElement.style.position = "absolute";
  472. canvasElement.style.top = 0;
  473. canvasElement.style.left = 0;
  474. canvasElement.style.zIndex = 100;
  475. }
  476. var exitFullPage = function () {
  477. document.getElementById("renderCanvas").style.position = "relative";
  478. document.getElementById("renderCanvas").style.zIndex = 0;
  479. }
  480. var goFullscreen = function () {
  481. if (engine) {
  482. engine.switchFullscreen(true);
  483. }
  484. }
  485. var toggleEditor = function () {
  486. var editorButton = document.getElementById("editorButton1600");
  487. var scene = engine.scenes[0];
  488. // If the editor is present
  489. if (editorButton.classList.contains('checked')) {
  490. setToMultipleID("editorButton", "removeClass", 'checked');
  491. splitInstance.collapse(0);
  492. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square-o" aria-hidden="true"></i>');
  493. } else {
  494. setToMultipleID("editorButton", "addClass", 'checked');
  495. splitInstance.setSizes([50, 50]); // Reset
  496. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  497. }
  498. engine.resize();
  499. if (scene.debugLayer.isVisible()) {
  500. scene.debugLayer.hide();
  501. scene.debugLayer.show();
  502. }
  503. }
  504. /**
  505. * Toggle the dark theme
  506. */
  507. var toggleTheme = function (theme) {
  508. // Monaco
  509. var vsTheme;
  510. if (theme == 'dark') {
  511. vsTheme = 'vs-dark'
  512. } else {
  513. vsTheme = 'vs'
  514. }
  515. let oldCode = jsEditor.getValue();
  516. jsEditor.dispose();
  517. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), {
  518. value: "",
  519. language: "javascript",
  520. lineNumbers: true,
  521. tabSize: "auto",
  522. insertSpaces: "auto",
  523. roundedSelection: true,
  524. scrollBeyondLastLine: false,
  525. automaticLayout: true,
  526. readOnly: false,
  527. theme: vsTheme,
  528. contextmenu: false
  529. });
  530. jsEditor.setValue(oldCode);
  531. setFontSize(fontSize);
  532. jsEditor.onKeyUp(function (evt) {
  533. markDirty();
  534. });
  535. for (var index = 0; index < elementToTheme.length; index++) {
  536. var obj = elementToTheme[index];
  537. let domObjArr = document.querySelectorAll(obj);
  538. for (var domObjIndex = 0; domObjIndex < domObjArr.length; domObjIndex++) {
  539. var domObj = domObjArr[domObjIndex];
  540. domObj.classList.remove('light');
  541. domObj.classList.remove('dark');
  542. domObj.classList.add(theme);
  543. }
  544. }
  545. localStorage.setItem("bjs-playground-theme", theme);
  546. }
  547. var toggleDebug = function () {
  548. var debugButton = document.getElementById("debugButton1600");
  549. var scene = engine.scenes[0];
  550. if (debugButton.classList.contains('uncheck')) {
  551. setToMultipleID("debugButton", "removeClass", 'uncheck');
  552. setToMultipleID("debugButton", "innerHTML", 'Debug layer<i class="fa fa-check-square" aria-hidden="true"></i>');
  553. scene.debugLayer.show();
  554. } else {
  555. setToMultipleID("debugButton", "addClass", 'uncheck');
  556. setToMultipleID("debugButton", "innerHTML", 'Debug layer<i class="fa fa-square-o" aria-hidden="true"></i>');
  557. scene.debugLayer.hide();
  558. }
  559. }
  560. var toggleMetadata = function () {
  561. var scene = engine.scenes[0];
  562. document.getElementById("saveLayer").style.display = "block";
  563. }
  564. var formatCode = function () {
  565. jsEditor.getAction('editor.action.format').run();
  566. }
  567. //Navigation Overwrites
  568. var exitPrompt = function (e) {
  569. var safeToggle = document.getElementById("safemodeToggle1600");
  570. if (safeToggle.classList.contains('checked')) {
  571. e = e || window.event;
  572. var message =
  573. 'This page is asking you to confirm that you want to leave - data you have entered may not be saved.';
  574. if (e) {
  575. e.returnValue = message;
  576. }
  577. return message;
  578. }
  579. };
  580. window.onbeforeunload = exitPrompt;
  581. // Snippet
  582. var save = function () {
  583. // Retrieve title if necessary
  584. if (document.getElementById("saveLayer")) {
  585. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  586. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  587. currentSnippetTags = document.getElementById("saveFormTags").value;
  588. }
  589. var xmlHttp = new XMLHttpRequest();
  590. xmlHttp.onreadystatechange = function () {
  591. if (xmlHttp.readyState === 4) {
  592. if (xmlHttp.status === 201) {
  593. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  594. var snippet = JSON.parse(xmlHttp.responseText);
  595. var newUrl = baseUrl + "#" + snippet.id;
  596. currentSnippetToken = snippet.id;
  597. if (snippet.version && snippet.version !== "0") {
  598. newUrl += "#" + snippet.version;
  599. }
  600. location.href = newUrl;
  601. // Hide the complete title & co message
  602. hideNoMetadata();
  603. compileAndRun();
  604. } else {
  605. showError("Unable to save your code. It may be too long.", null);
  606. }
  607. }
  608. }
  609. xmlHttp.open("POST", snippetUrl + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  610. xmlHttp.setRequestHeader("Content-Type", "application/json");
  611. var dataToSend = {
  612. payload: {
  613. code: jsEditor.getValue()
  614. },
  615. name: currentSnippetTitle,
  616. description: currentSnippetDescription,
  617. tags: currentSnippetTags
  618. };
  619. xmlHttp.send(JSON.stringify(dataToSend));
  620. }
  621. var askForSave = function () {
  622. if (currentSnippetTitle == null
  623. || currentSnippetDescription == null
  624. || currentSnippetTags == null) {
  625. document.getElementById("saveLayer").style.display = "block";
  626. }
  627. else {
  628. save();
  629. }
  630. };
  631. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  632. document.getElementById("saveLayer").style.display = "none";
  633. save();
  634. });
  635. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  636. document.getElementById("saveLayer").style.display = "none";
  637. });
  638. document.getElementById("saveMessage").addEventListener("click", function () {
  639. document.getElementById("saveMessage").style.display = "none";
  640. });
  641. document.getElementById("mainTitle").innerHTML = "v" + BABYLON.Engine.Version;
  642. var previousHash = "";
  643. var cleanHash = function () {
  644. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  645. if (splits.length > 2) {
  646. splits.splice(2, splits.length - 2);
  647. }
  648. location.hash = splits.join("#");
  649. }
  650. var checkHash = function (firstTime) {
  651. if (location.hash) {
  652. if (previousHash !== location.hash) {
  653. cleanHash();
  654. previousHash = location.hash;
  655. try {
  656. var xmlHttp = new XMLHttpRequest();
  657. xmlHttp.onreadystatechange = function () {
  658. if (xmlHttp.readyState === 4) {
  659. if (xmlHttp.status === 200) {
  660. var snippet = JSON.parse(xmlHttp.responseText)[0];
  661. blockEditorChange = true;
  662. jsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  663. // Check if title / descr / tags are already set
  664. if (snippet.name != null && snippet.name != "") {
  665. currentSnippetTitle = snippet.name;
  666. }
  667. else currentSnippetTitle = null;
  668. if (snippet.description != null && snippet.description != "") {
  669. currentSnippetDescription = snippet.description;
  670. }
  671. else currentSnippetDescription = null;
  672. if (snippet.tags != null && snippet.tags != "") {
  673. currentSnippetTags = snippet.tags;
  674. }
  675. else currentSnippetTags = null;
  676. if (currentSnippetTitle != null && currentSnippetTags != null && currentSnippetDescription) {
  677. if (document.getElementById("saveLayer")) {
  678. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  679. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  680. document.getElementById("saveFormTags").value = currentSnippetTags;
  681. hideNoMetadata();
  682. }
  683. }
  684. else {
  685. showNoMetadata();
  686. }
  687. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  688. blockEditorChange = false;
  689. compileAndRun();
  690. setToMultipleID("currentScript", "innerHTML", "Custom");
  691. } else if (firstTime) {
  692. location.href = location.href.replace(location.hash, "");
  693. if (scripts) {
  694. loadScriptFromIndex(0);
  695. }
  696. }
  697. }
  698. };
  699. var hash = location.hash.substr(1);
  700. currentSnippetToken = hash.split("#")[0];
  701. if (!hash.split("#")[1]) hash += "#0";
  702. xmlHttp.open("GET", snippetUrl + "/" + hash.replace("#", "/"));
  703. xmlHttp.send();
  704. } catch (e) {
  705. }
  706. }
  707. }
  708. setTimeout(checkHash, 200);
  709. }
  710. checkHash(true);
  711. // ---------- UI
  712. // Run
  713. setToMultipleID("runButton", "click", compileAndRun);
  714. // New
  715. setToMultipleID("newButton", "click", createNewScript);
  716. // Clear
  717. setToMultipleID("clearButton", "click", clear);
  718. // Save
  719. setToMultipleID("saveButton", "click", askForSave);
  720. // Zip
  721. setToMultipleID("zipButton", "click", getZip);
  722. // Themes
  723. setToMultipleID("darkTheme", "click", toggleTheme.bind(this, 'dark'));
  724. setToMultipleID("lightTheme", "click", toggleTheme.bind(this, 'light'));
  725. // Safe mode
  726. setToMultipleID("safemodeToggle", 'click', function () {
  727. document.getElementById("safemodeToggle1600").classList.toggle('checked');
  728. if (document.getElementById("safemodeToggle1600").classList.contains('checked')) {
  729. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  730. } else {
  731. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square-o" aria-hidden="true"></i>');
  732. }
  733. });
  734. // Editor
  735. setToMultipleID("editorButton", "click", toggleEditor);
  736. // FullScreen
  737. setToMultipleID("fullscreenButton", "click", goFullscreen);
  738. // Format
  739. setToMultipleID("formatButton", "click", formatCode);
  740. // Debug
  741. setToMultipleID("debugButton", "click", toggleDebug);
  742. // Metadata
  743. setToMultipleID("metadataButton", "click", toggleMetadata);
  744. // Restore theme
  745. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  746. toggleTheme(theme);
  747. }
  748. // Monaco
  749. var xhr = new XMLHttpRequest();
  750. xhr.open('GET', "babylon.d.txt", true);
  751. xhr.onreadystatechange = function () {
  752. if (xhr.readyState === 4) {
  753. if (xhr.status === 200) {
  754. require.config({ paths: { 'vs': 'node_modules/monaco-editor/min/vs' } });
  755. require(['vs/editor/editor.main'], function () {
  756. monaco.languages.typescript.javascriptDefaults.addExtraLib(xhr.responseText, 'babylon.d.ts');
  757. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), {
  758. value: "",
  759. language: "javascript",
  760. lineNumbers: true,
  761. tabSize: "auto",
  762. insertSpaces: "auto",
  763. roundedSelection: true,
  764. scrollBeyondLastLine: false,
  765. automaticLayout: true,
  766. readOnly: false,
  767. theme: "vs",
  768. contextmenu: false
  769. });
  770. run();
  771. });
  772. }
  773. }
  774. };
  775. xhr.send(null);
  776. })();