index.js 39 KB

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