index.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. examples = new Examples();
  2. utils = new Utils();
  3. monacoCreator = new MonacoCreator();
  4. settingsPG = new SettingsPG(monacoCreator);
  5. menuPG = new MenuPG();
  6. zipTool = new zipTool();
  7. /**
  8. * View split
  9. */
  10. var splitInstance = Split(['#jsEditor', '#canvasZone']);
  11. // TO DO - Make it work on small screens and mobile
  12. showQRCode = function () {
  13. $("#qrCodeImage").empty();
  14. var playgroundCode = window.location.href.split("#");
  15. playgroundCode.shift();
  16. $("#qrCodeImage").qrcode({ text: "https://playground.babylonjs.com/frame.html#" + (playgroundCode.join("#")) });
  17. };
  18. var run = function () {
  19. var snippetV3Url = "https://snippet.babylonjs.com"
  20. var currentSnippetToken;
  21. var currentSnippetTitle = null;
  22. var currentSnippetDescription = null;
  23. var currentSnippetTags = null;
  24. var engine;
  25. var fpsLabel = document.getElementById("fpsLabel");
  26. var scripts;
  27. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  28. window.addEventListener("resize",
  29. function () {
  30. if (engine) {
  31. engine.resize();
  32. }
  33. }
  34. );
  35. // TO DO : Rewrite this with unpkg.com
  36. if (location.href.indexOf("indexStable") !== -1) {
  37. utils.setToMultipleID("currentVersion", "innerHTML", "v.3.0");
  38. } else {
  39. utils.setToMultipleID("currentVersion", "innerHTML", "v.4.0");
  40. }
  41. var checkTypescriptSupport = function (xhr) {
  42. // If we're loading TS content and it's JS page
  43. if (xhr.responseText.indexOf("class Playground") !== -1) {
  44. if (settingsPG.ScriptLanguage == "JS") {
  45. settingsPG.ScriptLanguage = "TS";
  46. location.reload();
  47. return false;
  48. }
  49. } else { // If we're loading JS content and it's TS page
  50. if (settingsPG.ScriptLanguage == "TS") {
  51. settingsPG.ScriptLanguage = "JS";
  52. location.reload();
  53. return false;
  54. }
  55. }
  56. return true;
  57. };
  58. var loadScript = function (scriptURL, title) {
  59. var xhr = new XMLHttpRequest();
  60. xhr.open('GET', scriptURL, true);
  61. xhr.onreadystatechange = function () {
  62. if (xhr.readyState === 4) {
  63. if (xhr.status === 200) {
  64. if (!checkTypescriptSupport(xhr)) return;
  65. xhr.onreadystatechange = null;
  66. monacoCreator.BlockEditorChange = true;
  67. monacoCreator.JsEditor.setValue(xhr.responseText);
  68. monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  69. monacoCreator.BlockEditorChange = false;
  70. compileAndRun();
  71. currentSnippetToken = null;
  72. }
  73. }
  74. };
  75. xhr.send(null);
  76. };
  77. var loadScriptsList = function () {
  78. var exampleList = document.getElementById("exampleList");
  79. var xhr = new XMLHttpRequest();
  80. //Open Typescript or Javascript examples
  81. // TO DO - Check why it's always javascript ? Is it hard coded in html page ?
  82. // Should we merge both lists ?
  83. if (exampleList.className != 'typescript') {
  84. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list.json', true);
  85. }
  86. else {
  87. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list_ts.json', true);
  88. }
  89. xhr.onreadystatechange = function () {
  90. if (xhr.readyState === 4) {
  91. if (xhr.status === 200) {
  92. scripts = JSON.parse(xhr.response)["examples"];
  93. function sortScriptsList(a, b) {
  94. if (a.title < b.title) return -1;
  95. else return 1;
  96. }
  97. scripts.sort(sortScriptsList);
  98. if (exampleList) {
  99. for (var i = 0; i < scripts.length; i++) {
  100. scripts[i].samples.sort(sortScriptsList);
  101. var exampleCategory = document.createElement("div");
  102. exampleCategory.classList.add("categoryContainer");
  103. var exampleCategoryTitle = document.createElement("p");
  104. exampleCategoryTitle.innerText = scripts[i].title;
  105. exampleCategory.appendChild(exampleCategoryTitle);
  106. for (var ii = 0; ii < scripts[i].samples.length; ii++) {
  107. var example = document.createElement("div");
  108. example.classList.add("itemLine");
  109. example.id = ii;
  110. var exampleImg = document.createElement("img");
  111. exampleImg.src = scripts[i].samples[ii].icon.replace("icons", "https://doc.babylonjs.com/examples/icons");
  112. exampleImg.setAttribute("onClick", "document.getElementById('PGLink_" + scripts[i].samples[ii].PGID + "').click();");
  113. var exampleContent = document.createElement("div");
  114. exampleContent.classList.add("itemContent");
  115. exampleContent.setAttribute("onClick", "document.getElementById('PGLink_" + scripts[i].samples[ii].PGID + "').click();");
  116. var exampleContentLink = document.createElement("div");
  117. exampleContentLink.classList.add("itemContentLink");
  118. var exampleTitle = document.createElement("h3");
  119. exampleTitle.classList.add("exampleCategoryTitle");
  120. exampleTitle.innerText = scripts[i].samples[ii].title;
  121. var exampleDescr = document.createElement("div");
  122. exampleDescr.classList.add("itemLineChild");
  123. exampleDescr.innerText = scripts[i].samples[ii].description;
  124. var exampleDocLink = document.createElement("a");
  125. exampleDocLink.classList.add("itemLineDocLink");
  126. exampleDocLink.innerText = "Documentation";
  127. exampleDocLink.href = scripts[i].samples[ii].doc;
  128. exampleDocLink.target = "_blank";
  129. var examplePGLink = document.createElement("a");
  130. examplePGLink.id = "PGLink_" + scripts[i].samples[ii].PGID;
  131. examplePGLink.classList.add("itemLinePGLink");
  132. examplePGLink.innerText = "Display";
  133. examplePGLink.href = scripts[i].samples[ii].PGID;
  134. exampleContentLink.appendChild(exampleTitle);
  135. exampleContentLink.appendChild(exampleDescr);
  136. exampleContent.appendChild(exampleContentLink);
  137. exampleContent.appendChild(exampleDocLink);
  138. exampleContent.appendChild(examplePGLink);
  139. example.appendChild(exampleImg);
  140. example.appendChild(exampleContent);
  141. exampleCategory.appendChild(example);
  142. }
  143. exampleList.appendChild(exampleCategory);
  144. }
  145. var noResultContainer = document.createElement("div");
  146. noResultContainer.id = "noResultsContainer";
  147. noResultContainer.classList.add("categoryContainer");
  148. noResultContainer.style.display = "none";
  149. noResultContainer.innerHTML = "<p id='noResults'>No results found.</p>";
  150. exampleList.appendChild(noResultContainer);
  151. }
  152. if (!location.hash) {
  153. // Query string
  154. var queryString = window.location.search;
  155. if (queryString) {
  156. var query = queryString.replace("?", "");
  157. index = parseInt(query);
  158. if (!isNaN(index)) {
  159. // TO DO - Should we remove this deprecated code ?
  160. var newPG = "";
  161. switch (index) {
  162. case 1: newPG = "#TAZ2CB#0"; break; // Basic scene
  163. case 2: newPG = "#A1210C#0"; break; // Basic elements
  164. case 3: newPG = "#CURCZC#0"; break; // Rotation and scaling
  165. case 4: newPG = "#DXARSP#0"; break; // Materials
  166. case 5: newPG = "#1A3M5C#0"; break; // Cameras
  167. case 6: newPG = "#AQRDKW#0"; break; // Lights
  168. case 7: newPG = "#QYFDDP#1"; break; // Animations
  169. case 8: newPG = "#9RI8CG#0"; break; // Sprites
  170. case 9: newPG = "#U8MEB0#0"; break; // Collisions
  171. case 10: newPG = "#KQV9SA#0"; break; // Intersections
  172. case 11: newPG = "#NU4F6Y#0"; break; // Picking
  173. case 12: newPG = "#EF9X5R#0"; break; // Particles
  174. case 13: newPG = "#7G0IQW#0"; break; // Environment
  175. case 14: newPG = "#95PXRY#0"; break; // Height map
  176. case 15: newPG = "#IFYDRS#0"; break; // Shadows
  177. case 16: newPG = "#AQZJ4C#0"; break; // Import meshes
  178. case 17: newPG = "#J19GYK#0"; break; // Actions
  179. case 18: newPG = "#UZ23UH#0"; break; // Drag and drop
  180. case 19: newPG = "#AQZJ4C#0"; break; // Fresnel
  181. case 20: newPG = "#8ZNVGR#0"; break; // Easing functions
  182. case 21: newPG = "#B2ZXG6#0"; break; // Procedural texture
  183. case 22: newPG = "#DXAEUY#0"; break; // Basic sounds
  184. case 23: newPG = "#EDVU95#0"; break; // Sound on mesh
  185. case 24: newPG = "#N96NXC#0"; break; // SSAO rendering pipeline
  186. case 25: newPG = "#7D2QDD#0"; break; // SSAO 2
  187. case 26: newPG = "#V2DAKC#0"; break; // Volumetric light scattering
  188. case 27: newPG = "#XH85A9#0"; break; // Refraction and reflection
  189. case 28: newPG = "#8MGKWK#0"; break; // PBR
  190. case 29: newPG = "#0K8EYN#0"; break; // Instanced bones
  191. case 30: newPG = "#C245A1#0"; break; // Pointer events handling
  192. case 31: newPG = "#TAFSN0#2"; break; // WebVR
  193. case 32: newPG = "#3VMTI9#0"; break; // GUI
  194. case 33: newPG = "#7149G4#0"; break; // Physics
  195. default: newPG = ""; break;
  196. }
  197. window.location.href = location.protocol + "//" + location.host + location.pathname + "#" + newPG;
  198. } else if (query.indexOf("=") === -1) {
  199. loadScript("scripts/" + query + ".js", query);
  200. } else {
  201. loadScript(settingsPG.DefaultScene, "Basic scene");
  202. }
  203. } else {
  204. loadScript(settingsPG.DefaultScene, "Basic scene");
  205. }
  206. }
  207. // Restore theme
  208. settingsPG.restoreTheme(monacoCreator);
  209. // Restore language
  210. settingsPG.setScriptLanguage();
  211. }
  212. }
  213. };
  214. xhr.send(null);
  215. };
  216. var createNewScript = function () {
  217. // check if checked is on
  218. let iCanClear = checkSafeMode("Are you sure you want to create a new playground?");
  219. if (!iCanClear) return;
  220. location.hash = "";
  221. currentSnippetToken = null;
  222. currentSnippetTitle = null;
  223. currentSnippetDescription = null;
  224. currentSnippetTags = null;
  225. showNoMetadata();
  226. if (monacoCreator.monacoMode === "javascript") {
  227. monacoCreator.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\r\nvar createScene = function() {\r\n\tvar scene = new BABYLON.Scene(engine);\r\n\tvar camera = new BABYLON.ArcRotateCamera("Camera", -Math.PI / 2, 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};');
  228. } else {
  229. monacoCreator.JsEditor.setValue('// You have to create a class called Playground. This class must provide a static function named CreateScene(engine, canvas) which must return a BABYLON.Scene object\r\n// You must at least define a camera inside the CreateScene function\r\n\r\nclass Playground {\r\n\tpublic static CreateScene(engine: BABYLON.Engine, canvas: HTMLCanvasElement): BABYLON.Scene {\r\n\t\tvar scene = new BABYLON.Scene(engine);\r\n\r\n\t\tvar camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);\r\n\t\tcamera.setTarget(BABYLON.Vector3.Zero());\r\n\t\tcamera.attachControl(canvas, true);\r\n\r\n\t\treturn scene;\r\n\t}\r\n}');
  230. }
  231. monacoCreator.JsEditor.setPosition({ lineNumber: 11, column: 0 });
  232. monacoCreator.JsEditor.focus();
  233. compileAndRun();
  234. };
  235. var clear = function () {
  236. // check if checked is on
  237. let iCanClear = checkSafeMode("Are you sure you want to clear the playground?");
  238. if (!iCanClear) return;
  239. location.hash = "";
  240. currentSnippetToken = null;
  241. monacoCreator.JsEditor.setValue('');
  242. monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  243. monacoCreator.JsEditor.focus();
  244. };
  245. // TO DO - Is this really usefull ? Safe mode only available in full HD screen, not for small screen ? Why ?!
  246. var checkSafeMode = function (message) {
  247. var safeToggle = document.getElementById("safemodeToggle1280");
  248. if (safeToggle.classList.contains('checked')) {
  249. let confirm = window.confirm(message);
  250. if (!confirm) {
  251. return false;
  252. } else {
  253. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  254. return true;
  255. }
  256. } else {
  257. return true;
  258. }
  259. };
  260. /**
  261. * Metadatas form
  262. */
  263. var showNoMetadata = function () {
  264. if (currentSnippetTitle) {
  265. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  266. document.getElementById("saveFormTitle").readOnly = true;
  267. }
  268. else {
  269. document.getElementById("saveFormTitle").value = '';
  270. document.getElementById("saveFormTitle").readOnly = false;
  271. }
  272. if (currentSnippetDescription) {
  273. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  274. document.getElementById("saveFormDescription").readOnly = true;
  275. }
  276. else {
  277. document.getElementById("saveFormDescription").value = '';
  278. document.getElementById("saveFormDescription").readOnly = false;
  279. }
  280. if (currentSnippetTags) {
  281. document.getElementById("saveFormTags").value = currentSnippetTags;
  282. document.getElementById("saveFormTags").readOnly = true;
  283. }
  284. else {
  285. document.getElementById("saveFormTags").value = '';
  286. document.getElementById("saveFormTags").readOnly = false;
  287. }
  288. document.getElementById("saveFormButtons").style.display = "block";
  289. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  290. };
  291. var hideNoMetadata = function () {
  292. document.getElementById("saveFormTitle").readOnly = true;
  293. document.getElementById("saveFormDescription").readOnly = true;
  294. document.getElementById("saveFormTags").readOnly = true;
  295. document.getElementById("saveFormButtonOk").style.display = "none";
  296. utils.setToMultipleID("metadataButton", "display", "inline-block");
  297. };
  298. showNoMetadata();
  299. /*
  300. * Metadatas save
  301. */
  302. // TO DO - Search what is the appropriate place for this code
  303. var save = function () {
  304. // Retrieve title if necessary
  305. if (document.getElementById("saveLayer")) {
  306. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  307. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  308. currentSnippetTags = document.getElementById("saveFormTags").value;
  309. }
  310. var xmlHttp = new XMLHttpRequest();
  311. xmlHttp.onreadystatechange = function () {
  312. if (xmlHttp.readyState === 4) {
  313. if (xmlHttp.status === 200) {
  314. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  315. var snippet = JSON.parse(xmlHttp.responseText);
  316. var newUrl = baseUrl + "#" + snippet.id;
  317. currentSnippetToken = snippet.id;
  318. if (snippet.version && snippet.version !== "0") {
  319. newUrl += "#" + snippet.version;
  320. }
  321. location.href = newUrl;
  322. // Hide the complete title & co message
  323. hideNoMetadata();
  324. compileAndRun();
  325. } else {
  326. utils.showError("Unable to save your code. It may be too long.", null);
  327. }
  328. }
  329. }
  330. xmlHttp.open("POST", snippetV3Url + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  331. xmlHttp.setRequestHeader("Content-Type", "application/json");
  332. var dataToSend = {
  333. payload: JSON.stringify({
  334. code: monacoCreator.JsEditor.getValue()
  335. }),
  336. name: currentSnippetTitle,
  337. description: currentSnippetDescription,
  338. tags: currentSnippetTags
  339. };
  340. xmlHttp.send(JSON.stringify(dataToSend));
  341. };
  342. var askForSave = function () {
  343. if (currentSnippetTitle == null
  344. || currentSnippetDescription == null
  345. || currentSnippetTags == null) {
  346. document.getElementById("saveLayer").style.display = "block";
  347. }
  348. else {
  349. save();
  350. }
  351. };
  352. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  353. document.getElementById("saveLayer").style.display = "none";
  354. save();
  355. });
  356. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  357. document.getElementById("saveLayer").style.display = "none";
  358. });
  359. /**
  360. * Compile the script in the editor, and run the preview in the canvas
  361. */
  362. var compileAndRun = function () {
  363. try {
  364. var waitRing = document.getElementById("waitDiv");
  365. if (waitRing) {
  366. waitRing.style.display = "none";
  367. }
  368. if (!BABYLON.Engine.isSupported()) {
  369. utils.showError("Your browser does not support WebGL. Please, try to update it, or install a compatible one.", null);
  370. return;
  371. }
  372. var showInspector = false;
  373. showBJSPGMenu();
  374. monacoCreator.JsEditor.updateOptions({ readOnly: false });
  375. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.debugLayer.isVisible()) {
  376. showInspector = true;
  377. }
  378. if (engine) {
  379. engine.dispose();
  380. engine = null;
  381. }
  382. var canvas = document.getElementById("renderCanvas");
  383. document.getElementById("errorZone").style.display = 'none';
  384. document.getElementById("errorZone").innerHTML = "";
  385. document.getElementById("statusBar").innerHTML = "Loading assets... Please wait.";
  386. var checkCamera = true;
  387. var checkSceneCount = true;
  388. var createEngineFunction = "createDefaultEngine";
  389. var createSceneFunction;
  390. monacoCreator.getRunCode(function (code) {
  391. var createDefaultEngine = function () {
  392. return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  393. }
  394. var scene;
  395. var defaultEngineZip = "new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true })";
  396. if (code.indexOf("createEngine") !== -1) {
  397. createEngineFunction = "createEngine";
  398. }
  399. // Check for different typos
  400. if (code.indexOf("delayCreateScene") !== -1) { // createScene
  401. createSceneFunction = "delayCreateScene";
  402. checkCamera = false;
  403. } else if (code.indexOf("createScene") !== -1) { // createScene
  404. createSceneFunction = "createScene";
  405. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  406. createSceneFunction = "CreateScene";
  407. } else if (code.indexOf("createscene") !== -1) { // createscene
  408. createSceneFunction = "createscene";
  409. }
  410. if (!createSceneFunction) {
  411. // just pasted code.
  412. engine = createDefaultEngine();
  413. scene = new BABYLON.Scene(engine);
  414. eval("runScript = function(scene, canvas) {" + code + "}");
  415. runScript(scene, canvas);
  416. zipTool.ZipCode = "var engine = " + defaultEngineZip + ";\r\nvar scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  417. } else {
  418. //execute the code
  419. eval(code);
  420. //create engine
  421. eval("engine = " + createEngineFunction + "()");
  422. if (!engine) {
  423. utils.showError("createEngine function must return an engine.", null);
  424. return;
  425. }
  426. //create scene
  427. eval("scene = " + createSceneFunction + "()");
  428. if (!scene) {
  429. utils.showError(createSceneFunction + " function must return a scene.", null);
  430. return;
  431. }
  432. // if scene returns a promise avoid checks
  433. if (scene.then) {
  434. checkCamera = false;
  435. checkSceneCount = false;
  436. }
  437. var createEngineZip = (createEngineFunction === "createEngine")
  438. ? "createEngine()"
  439. : defaultEngineZip;
  440. zipTool.zipCode =
  441. code + "\r\n\r\n" +
  442. "var engine = " + createEngineZip + ";\r\n" +
  443. "var scene = " + createSceneFunction + "();";
  444. }
  445. engine.runRenderLoop(function () {
  446. if (engine.scenes.length === 0) {
  447. return;
  448. }
  449. if (canvas.width !== canvas.clientWidth) {
  450. engine.resize();
  451. }
  452. var scene = engine.scenes[0];
  453. if (scene.activeCamera || scene.activeCameras.length > 0) {
  454. scene.render();
  455. }
  456. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  457. });
  458. if (checkSceneCount && engine.scenes.length === 0) {
  459. utils.showError("You must at least create a scene.", null);
  460. return;
  461. }
  462. if (checkCamera && engine.scenes[0].activeCamera == null) {
  463. utils.showError("You must at least create a camera.", null);
  464. return;
  465. } else if (scene.then) {
  466. scene.then(function () {
  467. document.getElementById("statusBar").innerHTML = "";
  468. });
  469. } else {
  470. engine.scenes[0].executeWhenReady(function () {
  471. document.getElementById("statusBar").innerHTML = "";
  472. });
  473. }
  474. if (scene) {
  475. if (showInspector) {
  476. if (scene.then) {
  477. // Handle if scene is a promise
  478. scene.then(function (s) {
  479. if (!s.debugLayer.isVisible()) {
  480. s.debugLayer.show({ embedMode: true });
  481. }
  482. })
  483. } else {
  484. if (!scene.debugLayer.isVisible()) {
  485. scene.debugLayer.show({ embedMode: true });
  486. }
  487. }
  488. }
  489. }
  490. });
  491. } catch (e) {
  492. utils.showError(e.message, e);
  493. // Also log error in console to help debug playgrounds
  494. console.error(e);
  495. }
  496. };
  497. /**
  498. * BJS version
  499. */
  500. // TO DO - Rewrite that
  501. var setVersion = function (version) {
  502. // switch (version) {
  503. // case "stable":
  504. // location.href = "indexStable.html" + location.hash;
  505. // break;
  506. // default:
  507. // location.href = "index.html" + location.hash;
  508. // break;
  509. // }
  510. }
  511. utils.setToMultipleID("mainTitle", "innerHTML", "v" + BABYLON.Engine.Version);
  512. /**
  513. * Toggle the code editor
  514. */
  515. var toggleEditor = function () {
  516. var editorButton = document.getElementById("editorButton1280");
  517. var scene = engine.scenes[0];
  518. // If the editor is present
  519. if (editorButton.classList.contains('checked')) {
  520. utils.setToMultipleID("editorButton", "removeClass", 'checked');
  521. splitInstance.collapse(0);
  522. utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square" aria-hidden="true"></i>');
  523. } else {
  524. utils.setToMultipleID("editorButton", "addClass", 'checked');
  525. splitInstance.setSizes([50, 50]); // Reset
  526. utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  527. }
  528. engine.resize();
  529. if (scene.debugLayer.isVisible()) {
  530. scene.debugLayer.show({ embedMode: true });
  531. }
  532. }
  533. /**
  534. * Toggle the BJS debug layer
  535. */
  536. var toggleDebug = function () {
  537. // Always showing the debug layer, because you can close it by itself
  538. var scene = engine.scenes[0];
  539. if (scene.debugLayer.isVisible()) {
  540. scene.debugLayer.hide();
  541. }
  542. else {
  543. scene.debugLayer.show({ embedMode: true });
  544. }
  545. }
  546. // Load scripts list
  547. loadScriptsList();
  548. /**
  549. * HASH part
  550. */
  551. // TO DO - Rewrite / move this code
  552. var previousHash = "";
  553. var cleanHash = function () {
  554. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  555. if (splits.length > 2) {
  556. splits.splice(2, splits.length - 2);
  557. }
  558. location.hash = splits.join("#");
  559. }
  560. var checkHash = function (firstTime) {
  561. if (location.hash) {
  562. if (previousHash !== location.hash) {
  563. cleanHash();
  564. previousHash = location.hash;
  565. try {
  566. var xmlHttp = new XMLHttpRequest();
  567. xmlHttp.onreadystatechange = function () {
  568. if (xmlHttp.readyState === 4) {
  569. if (xmlHttp.status === 200) {
  570. if (!checkTypescriptSupport(xmlHttp)) {
  571. return;
  572. }
  573. var snippet = JSON.parse(xmlHttp.responseText);
  574. monacoCreator.BlockEditorChange = true;
  575. monacoCreator.JsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  576. // Check if title / descr / tags are already set
  577. if (snippet.name != null && snippet.name != "") {
  578. currentSnippetTitle = snippet.name;
  579. }
  580. else currentSnippetTitle = null;
  581. if (snippet.description != null && snippet.description != "") {
  582. currentSnippetDescription = snippet.description;
  583. }
  584. else currentSnippetDescription = null;
  585. if (snippet.tags != null && snippet.tags != "") {
  586. currentSnippetTags = snippet.tags;
  587. }
  588. else currentSnippetTags = null;
  589. if (currentSnippetTitle != null && currentSnippetTags != null && currentSnippetDescription) {
  590. if (document.getElementById("saveLayer")) {
  591. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  592. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  593. document.getElementById("saveFormTags").value = currentSnippetTags;
  594. hideNoMetadata();
  595. }
  596. }
  597. else {
  598. showNoMetadata();
  599. }
  600. monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  601. monacoCreator.BlockEditorChange = false;
  602. compileAndRun();
  603. // utils.setToMultipleID("currentScript", "innerHTML", "Custom");
  604. }
  605. }
  606. };
  607. var hash = location.hash.substr(1);
  608. currentSnippetToken = hash.split("#")[0];
  609. if (!hash.split("#")[1]) hash += "#0";
  610. xmlHttp.open("GET", snippetV3Url + "/" + hash.replace("#", "/"));
  611. xmlHttp.send();
  612. } catch (e) {
  613. }
  614. }
  615. }
  616. setTimeout(checkHash, 200);
  617. }
  618. checkHash(true);
  619. // ---------- UI
  620. // TO DO - A proper UI class
  621. // Run
  622. utils.setToMultipleID("runButton", "click", compileAndRun);
  623. // New
  624. utils.setToMultipleID("newButton", "click", createNewScript);
  625. // Clear
  626. utils.setToMultipleID("clearButton", "click", clear);
  627. // Save
  628. utils.setToMultipleID("saveButton", "click", askForSave);
  629. // Zip
  630. utils.setToMultipleID("zipButton", "click", function() {
  631. zipTool.getZip(engine);
  632. });
  633. // Themes
  634. utils.setToMultipleID("darkTheme", "click", [settingsPG.setTheme.bind(settingsPG, 'dark'), menuPG.clickOptionSub.bind(menuPG)]);
  635. utils.setToMultipleID("lightTheme", "click", [settingsPG.setTheme.bind(settingsPG, 'light'), menuPG.clickOptionSub.bind(menuPG)]);
  636. // Size
  637. var displayFontSize = document.getElementsByClassName('displayFontSize');
  638. for (var i = 0; i < displayFontSize.length; i++) {
  639. var options = displayFontSize[i].querySelectorAll('.option');
  640. for (var j = 0; j < options.length; j++) {
  641. options[j].addEventListener('click', menuPG.clickOptionSub.bind(menuPG));
  642. options[j].addEventListener('click', settingsPG.setFontSize.bind(settingsPG, options[j].innerText));
  643. }
  644. }
  645. // Footer links
  646. var displayFontSize = document.getElementsByClassName('displayFooterLinks');
  647. for (var i = 0; i < displayFontSize.length; i++) {
  648. var options = displayFontSize[i].querySelectorAll('.option');
  649. for (var j = 0; j < options.length; j++) {
  650. options[j].addEventListener('click', menuPG.clickOptionSub.bind(this));
  651. }
  652. }
  653. // Language (JS / TS)
  654. utils.setToMultipleID("toTSbutton", "click", function () {
  655. settingsPG.ScriptLanguage = "TS";
  656. location.reload();
  657. });
  658. utils.setToMultipleID("toJSbutton", "click", function () {
  659. settingsPG.ScriptLanguage = "JS";
  660. location.reload();
  661. });
  662. // Safe mode
  663. utils.setToMultipleID("safemodeToggle", 'click', function () {
  664. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  665. if (document.getElementById("safemodeToggle1280").classList.contains('checked')) {
  666. utils.setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  667. } else {
  668. utils.setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square" aria-hidden="true"></i>');
  669. }
  670. });
  671. // Editor
  672. utils.setToMultipleID("editorButton", "click", toggleEditor);
  673. // FullScreen
  674. utils.setToMultipleID("fullscreenButton", "click", menuPG.goFullscreen);
  675. // Editor fullScreen
  676. utils.setToMultipleID("editorFullscreenButton", "click", menuPG.editorGoFullscreen);
  677. // Format
  678. utils.setToMultipleID("formatButton", "click", monacoCreator.formatCode.bind(monacoCreator));
  679. // Format
  680. utils.setToMultipleID("minimapToggle", "click", monacoCreator.toggleMinimap.bind(monacoCreator));
  681. // Debug
  682. utils.setToMultipleID("debugButton", "click", toggleDebug);
  683. // Metadata
  684. utils.setToMultipleID("metadataButton", "click", menuPG.displayMetadata);
  685. // Restore theme
  686. settingsPG.restoreTheme(monacoCreator);
  687. // Restore language
  688. settingsPG.setScriptLanguage();
  689. //
  690. menuPG.resizeBigCanvas();
  691. }