index.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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.style.right = document.body.clientWidth - (jsEditor.domElement.clientWidth + canvas.clientWidth) + "px";
  287. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  288. });
  289. var code = jsEditor.getValue();
  290. var scene;
  291. if (code.indexOf("createScene") !== -1) { // createScene
  292. eval(code);
  293. scene = createScene();
  294. if (!scene) {
  295. showError("createScene function must return a scene.", null);
  296. return;
  297. }
  298. zipCode = code + "\r\n\r\nvar scene = createScene();";
  299. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  300. eval(code);
  301. scene = CreateScene();
  302. if (!scene) {
  303. showError("CreateScene function must return a scene.", null);
  304. return;
  305. }
  306. zipCode = code + "\r\n\r\nvar scene = CreateScene();";
  307. } else if (code.indexOf("createscene") !== -1) { // createscene
  308. eval(code);
  309. scene = createscene();
  310. if (!scene) {
  311. showError("createscene function must return a scene.", null);
  312. return;
  313. }
  314. zipCode = code + "\r\n\r\nvar scene = createscene();";
  315. } else { // Direct code
  316. scene = new BABYLON.Scene(engine);
  317. eval("runScript = function(scene, canvas) {" + code + "}");
  318. runScript(scene, canvas);
  319. zipCode = "var scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  320. }
  321. if (engine.scenes.length === 0) {
  322. showError("You must at least create a scene.", null);
  323. return;
  324. }
  325. if (engine.scenes[0].activeCamera == null) {
  326. showError("You must at least create a camera.", null);
  327. return;
  328. }
  329. engine.scenes[0].executeWhenReady(function () {
  330. document.getElementById("statusBar").innerHTML = "";
  331. });
  332. if(scene){
  333. if(showInspector){
  334. scene.debugLayer.show({initialTab:initialTabIndex});
  335. scene.executeWhenReady(function(){
  336. scene.debugLayer._inspector.refresh();
  337. })
  338. }else if(showDebugLayer){
  339. scene.debugLayer.show();
  340. }
  341. }
  342. } catch (e) {
  343. showError(e.message, e);
  344. }
  345. };
  346. window.addEventListener("resize",
  347. function () {
  348. if (engine) {
  349. engine.resize();
  350. }
  351. });
  352. // Load scripts list
  353. loadScriptsList();
  354. // Zip
  355. var addContentToZip = function (zip, name, url, replace, buffer, then) {
  356. var xhr = new XMLHttpRequest();
  357. xhr.open('GET', url, true);
  358. if (buffer) {
  359. xhr.responseType = "arraybuffer";
  360. }
  361. xhr.onreadystatechange = function () {
  362. if (xhr.readyState === 4) {
  363. if (xhr.status === 200) {
  364. var text;
  365. if (!buffer) {
  366. if (replace) {
  367. var splits = replace.split("\r\n");
  368. for (var index = 0; index < splits.length; index++) {
  369. splits[index] = " " + splits[index];
  370. }
  371. replace = splits.join("\r\n");
  372. text = xhr.responseText.replace("####INJECT####", replace);
  373. } else {
  374. text = xhr.responseText;
  375. }
  376. }
  377. zip.file(name, buffer ? xhr.response : text);
  378. then();
  379. }
  380. }
  381. };
  382. xhr.send(null);
  383. }
  384. var addTexturesToZip = function (zip, index, textures, folder, then) {
  385. if (index === textures.length) {
  386. then();
  387. return;
  388. }
  389. if (textures[index].isRenderTarget || textures[index] instanceof BABYLON.DynamicTexture) {
  390. addTexturesToZip(zip, index + 1, textures, folder, then);
  391. return;
  392. }
  393. if (textures[index].isCube) {
  394. if (textures[index]._extensions) {
  395. for (var i = 0; i < 6; i++) {
  396. textures.push({ name: textures[index].name + textures[index]._extensions[i] });
  397. }
  398. }
  399. else {
  400. textures.push({ name: textures[index].name });
  401. }
  402. addTexturesToZip(zip, index + 1, textures, folder, then);
  403. return;
  404. }
  405. if (folder == null) {
  406. folder = zip.folder("textures");
  407. }
  408. var url;
  409. if (textures[index].video) {
  410. url = textures[index].video.currentSrc;
  411. } else {
  412. // url = textures[index].name;
  413. url = textures[index].url;
  414. }
  415. var name = textures[index].name;
  416. // var name = url.substr(url.lastIndexOf("/") + 1);
  417. if (url != null) {
  418. addContentToZip(folder,
  419. name,
  420. url,
  421. null,
  422. true,
  423. function () {
  424. addTexturesToZip(zip, index + 1, textures, folder, then);
  425. });
  426. }
  427. else {
  428. addTexturesToZip(zip, index + 1, textures, folder, then);
  429. }
  430. }
  431. var addImportedFilesToZip = function (zip, index, importedFiles, folder, then) {
  432. if (index === importedFiles.length) {
  433. then();
  434. return;
  435. }
  436. if (!folder) {
  437. folder = zip.folder("scenes");
  438. }
  439. var url = importedFiles[index];
  440. var name = url.substr(url.lastIndexOf("/") + 1);
  441. addContentToZip(folder,
  442. name,
  443. url,
  444. null,
  445. true,
  446. function () {
  447. addImportedFilesToZip(zip, index + 1, importedFiles, folder, then);
  448. });
  449. }
  450. var getZip = function () {
  451. if (engine.scenes.length === 0) {
  452. return;
  453. }
  454. var zip = new JSZip();
  455. var scene = engine.scenes[0];
  456. var textures = scene.textures;
  457. var importedFiles = scene.importedMeshesFiles;
  458. document.getElementById("statusBar").innerHTML = "Creating archive...Please wait";
  459. if (zipCode.indexOf("textures/worldHeightMap.jpg") !== -1) {
  460. textures.push({ name: "textures/worldHeightMap.jpg" });
  461. }
  462. addContentToZip(zip,
  463. "index.html",
  464. "zipContent/index.html",
  465. zipCode,
  466. false,
  467. function () {
  468. addTexturesToZip(zip,
  469. 0,
  470. textures,
  471. null,
  472. function () {
  473. addImportedFilesToZip(zip,
  474. 0,
  475. importedFiles,
  476. null,
  477. function () {
  478. var blob = zip.generate({ type: "blob" });
  479. saveAs(blob, "sample.zip");
  480. document.getElementById("statusBar").innerHTML = "";
  481. });
  482. });
  483. });
  484. }
  485. // Versions
  486. setVersion = function (version) {
  487. switch (version) {
  488. case "2.5":
  489. location.href = "index2_5.html" + location.hash;
  490. break;
  491. default:
  492. location.href = "index.html" + location.hash;
  493. break;
  494. }
  495. }
  496. // Fonts
  497. setFontSize = function (size) {
  498. fontSize = size;
  499. document.querySelector(".view-lines").style.fontSize = size + "px";
  500. setToMultipleID("currentFontSize", "innerHTML", "Font: " + size);
  501. };
  502. // Fullscreen
  503. document.getElementById("renderCanvas").addEventListener("webkitfullscreenchange", function () {
  504. if(document.webkitIsFullScreen) goFullPage();
  505. else exitFullPage();
  506. }, false);
  507. var goFullPage = function () {
  508. var canvasElement = document.getElementById("renderCanvas");
  509. canvasElement.style.position = "absolute";
  510. canvasElement.style.top = 0;
  511. canvasElement.style.left = 0;
  512. canvasElement.style.zIndex = 100;
  513. }
  514. var exitFullPage = function () {
  515. document.getElementById("renderCanvas").style.position = "relative";
  516. document.getElementById("renderCanvas").style.zIndex = 0;
  517. }
  518. var goFullscreen = function () {
  519. if (engine) {
  520. engine.switchFullscreen(true);
  521. }
  522. }
  523. var editorGoFullscreen = function () {
  524. var editorDiv = document.getElementById("jsEditor");
  525. if (editorDiv.requestFullscreen) {
  526. editorDiv.requestFullscreen();
  527. } else if (editorDiv.mozRequestFullScreen) {
  528. editorDiv.mozRequestFullScreen();
  529. } else if (editorDiv.webkitRequestFullscreen) {
  530. editorDiv.webkitRequestFullscreen();
  531. }
  532. }
  533. var toggleEditor = function () {
  534. var editorButton = document.getElementById("editorButton1600");
  535. var scene = engine.scenes[0];
  536. // If the editor is present
  537. if (editorButton.classList.contains('checked')) {
  538. setToMultipleID("editorButton", "removeClass", 'checked');
  539. splitInstance.collapse(0);
  540. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square-o" aria-hidden="true"></i>');
  541. } else {
  542. setToMultipleID("editorButton", "addClass", 'checked');
  543. splitInstance.setSizes([50, 50]); // Reset
  544. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  545. }
  546. engine.resize();
  547. if (scene.debugLayer.isVisible()) {
  548. scene.debugLayer.hide();
  549. scene.debugLayer.show();
  550. }
  551. }
  552. /**
  553. * Toggle the dark theme
  554. */
  555. var toggleTheme = function (theme) {
  556. // Monaco
  557. var vsTheme;
  558. if (theme == 'dark') {
  559. vsTheme = 'vs-dark'
  560. } else {
  561. vsTheme = 'vs'
  562. }
  563. let oldCode = jsEditor.getValue();
  564. jsEditor.dispose();
  565. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), {
  566. value: "",
  567. language: "javascript",
  568. lineNumbers: true,
  569. tabSize: "auto",
  570. insertSpaces: "auto",
  571. roundedSelection: true,
  572. scrollBeyondLastLine: false,
  573. automaticLayout: true,
  574. readOnly: false,
  575. theme: vsTheme,
  576. contextmenu: false
  577. });
  578. jsEditor.setValue(oldCode);
  579. setFontSize(fontSize);
  580. jsEditor.onKeyUp(function (evt) {
  581. markDirty();
  582. });
  583. for (var index = 0; index < elementToTheme.length; index++) {
  584. var obj = elementToTheme[index];
  585. let domObjArr = document.querySelectorAll(obj);
  586. for (var domObjIndex = 0; domObjIndex < domObjArr.length; domObjIndex++) {
  587. var domObj = domObjArr[domObjIndex];
  588. domObj.classList.remove('light');
  589. domObj.classList.remove('dark');
  590. domObj.classList.add(theme);
  591. }
  592. }
  593. localStorage.setItem("bjs-playground-theme", theme);
  594. }
  595. var toggleDebug = function () {
  596. var debugButton = document.getElementById("debugButton1600");
  597. var scene = engine.scenes[0];
  598. if (debugButton.classList.contains('uncheck')) {
  599. setToMultipleID("debugButton", "removeClass", 'uncheck');
  600. setToMultipleID("debugButton", "innerHTML", 'Debug layer<i class="fa fa-check-square" aria-hidden="true"></i>');
  601. scene.debugLayer.show();
  602. } else {
  603. setToMultipleID("debugButton", "addClass", 'uncheck');
  604. setToMultipleID("debugButton", "innerHTML", 'Debug layer<i class="fa fa-square-o" aria-hidden="true"></i>');
  605. scene.debugLayer.hide();
  606. }
  607. }
  608. var toggleMetadata = function () {
  609. var scene = engine.scenes[0];
  610. document.getElementById("saveLayer").style.display = "block";
  611. }
  612. var formatCode = function () {
  613. jsEditor.getAction('editor.action.format').run();
  614. }
  615. //Navigation Overwrites
  616. var exitPrompt = function (e) {
  617. var safeToggle = document.getElementById("safemodeToggle1600");
  618. if (safeToggle.classList.contains('checked')) {
  619. e = e || window.event;
  620. var message =
  621. 'This page is asking you to confirm that you want to leave - data you have entered may not be saved.';
  622. if (e) {
  623. e.returnValue = message;
  624. }
  625. return message;
  626. }
  627. };
  628. window.onbeforeunload = exitPrompt;
  629. // Snippet
  630. var save = function () {
  631. // Retrieve title if necessary
  632. if (document.getElementById("saveLayer")) {
  633. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  634. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  635. currentSnippetTags = document.getElementById("saveFormTags").value;
  636. }
  637. var xmlHttp = new XMLHttpRequest();
  638. xmlHttp.onreadystatechange = function () {
  639. if (xmlHttp.readyState === 4) {
  640. if (xmlHttp.status === 201) {
  641. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  642. var snippet = JSON.parse(xmlHttp.responseText);
  643. var newUrl = baseUrl + "#" + snippet.id;
  644. currentSnippetToken = snippet.id;
  645. if (snippet.version && snippet.version !== "0") {
  646. newUrl += "#" + snippet.version;
  647. }
  648. location.href = newUrl;
  649. // Hide the complete title & co message
  650. hideNoMetadata();
  651. compileAndRun();
  652. } else {
  653. showError("Unable to save your code. It may be too long.", null);
  654. }
  655. }
  656. }
  657. xmlHttp.open("POST", snippetUrl + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  658. xmlHttp.setRequestHeader("Content-Type", "application/json");
  659. var dataToSend = {
  660. payload: {
  661. code: jsEditor.getValue()
  662. },
  663. name: currentSnippetTitle,
  664. description: currentSnippetDescription,
  665. tags: currentSnippetTags
  666. };
  667. xmlHttp.send(JSON.stringify(dataToSend));
  668. }
  669. var askForSave = function () {
  670. if (currentSnippetTitle == null
  671. || currentSnippetDescription == null
  672. || currentSnippetTags == null) {
  673. document.getElementById("saveLayer").style.display = "block";
  674. }
  675. else {
  676. save();
  677. }
  678. };
  679. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  680. document.getElementById("saveLayer").style.display = "none";
  681. save();
  682. });
  683. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  684. document.getElementById("saveLayer").style.display = "none";
  685. });
  686. document.getElementById("saveMessage").addEventListener("click", function () {
  687. document.getElementById("saveMessage").style.display = "none";
  688. });
  689. document.getElementById("mainTitle").innerHTML = "v" + BABYLON.Engine.Version;
  690. var previousHash = "";
  691. var cleanHash = function () {
  692. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  693. if (splits.length > 2) {
  694. splits.splice(2, splits.length - 2);
  695. }
  696. location.hash = splits.join("#");
  697. }
  698. var checkHash = function (firstTime) {
  699. if (location.hash) {
  700. if (previousHash !== location.hash) {
  701. cleanHash();
  702. previousHash = location.hash;
  703. try {
  704. var xmlHttp = new XMLHttpRequest();
  705. xmlHttp.onreadystatechange = function () {
  706. if (xmlHttp.readyState === 4) {
  707. if (xmlHttp.status === 200) {
  708. var snippet = JSON.parse(xmlHttp.responseText)[0];
  709. blockEditorChange = true;
  710. jsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  711. // Check if title / descr / tags are already set
  712. if (snippet.name != null && snippet.name != "") {
  713. currentSnippetTitle = snippet.name;
  714. }
  715. else currentSnippetTitle = null;
  716. if (snippet.description != null && snippet.description != "") {
  717. currentSnippetDescription = snippet.description;
  718. }
  719. else currentSnippetDescription = null;
  720. if (snippet.tags != null && snippet.tags != "") {
  721. currentSnippetTags = snippet.tags;
  722. }
  723. else currentSnippetTags = null;
  724. if (currentSnippetTitle != null && currentSnippetTags != null && currentSnippetDescription) {
  725. if (document.getElementById("saveLayer")) {
  726. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  727. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  728. document.getElementById("saveFormTags").value = currentSnippetTags;
  729. hideNoMetadata();
  730. }
  731. }
  732. else {
  733. showNoMetadata();
  734. }
  735. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  736. blockEditorChange = false;
  737. compileAndRun();
  738. setToMultipleID("currentScript", "innerHTML", "Custom");
  739. } else if (firstTime) {
  740. location.href = location.href.replace(location.hash, "");
  741. if (scripts) {
  742. loadScriptFromIndex(0);
  743. }
  744. }
  745. }
  746. };
  747. var hash = location.hash.substr(1);
  748. currentSnippetToken = hash.split("#")[0];
  749. if (!hash.split("#")[1]) hash += "#0";
  750. xmlHttp.open("GET", snippetUrl + "/" + hash.replace("#", "/"));
  751. xmlHttp.send();
  752. } catch (e) {
  753. }
  754. }
  755. }
  756. setTimeout(checkHash, 200);
  757. }
  758. checkHash(true);
  759. // ---------- UI
  760. // Run
  761. setToMultipleID("runButton", "click", compileAndRun);
  762. // New
  763. setToMultipleID("newButton", "click", createNewScript);
  764. // Clear
  765. setToMultipleID("clearButton", "click", clear);
  766. // Save
  767. setToMultipleID("saveButton", "click", askForSave);
  768. // Zip
  769. setToMultipleID("zipButton", "click", getZip);
  770. // Themes
  771. setToMultipleID("darkTheme", "click", toggleTheme.bind(this, 'dark'));
  772. setToMultipleID("lightTheme", "click", toggleTheme.bind(this, 'light'));
  773. // Safe mode
  774. setToMultipleID("safemodeToggle", 'click', function () {
  775. document.getElementById("safemodeToggle1600").classList.toggle('checked');
  776. if (document.getElementById("safemodeToggle1600").classList.contains('checked')) {
  777. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  778. } else {
  779. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square-o" aria-hidden="true"></i>');
  780. }
  781. });
  782. // Editor
  783. setToMultipleID("editorButton", "click", toggleEditor);
  784. // FullScreen
  785. setToMultipleID("fullscreenButton", "click", goFullscreen);
  786. // Editor fullScreen
  787. setToMultipleID("editorFullscreenButton", "click", editorGoFullscreen);
  788. // Format
  789. setToMultipleID("formatButton", "click", formatCode);
  790. // Debug
  791. setToMultipleID("debugButton", "click", toggleDebug);
  792. // Metadata
  793. setToMultipleID("metadataButton", "click", toggleMetadata);
  794. // Restore theme
  795. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  796. toggleTheme(theme);
  797. }
  798. // Monaco
  799. var xhr = new XMLHttpRequest();
  800. xhr.open('GET', "babylon.d.txt", true);
  801. xhr.onreadystatechange = function () {
  802. if (xhr.readyState === 4) {
  803. if (xhr.status === 200) {
  804. require.config({ paths: { 'vs': 'node_modules/monaco-editor/min/vs' } });
  805. require(['vs/editor/editor.main'], function () {
  806. monaco.languages.typescript.javascriptDefaults.addExtraLib(xhr.responseText, 'babylon.d.ts');
  807. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), {
  808. value: "",
  809. language: "javascript",
  810. lineNumbers: true,
  811. tabSize: "auto",
  812. insertSpaces: "auto",
  813. roundedSelection: true,
  814. scrollBeyondLastLine: false,
  815. automaticLayout: true,
  816. readOnly: false,
  817. theme: "vs",
  818. contextmenu: false
  819. });
  820. run();
  821. });
  822. }
  823. }
  824. };
  825. xhr.send(null);
  826. })();