index.js 40 KB

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