index.js 38 KB

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