index.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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. var run = function () {
  12. var snippetV3Url = "https://snippet.babylonjs.com"
  13. var currentSnippetToken;
  14. var currentSnippetTitle = null;
  15. var currentSnippetDescription = null;
  16. var currentSnippetTags = null;
  17. var engine;
  18. var fpsLabel = document.getElementById("fpsLabel");
  19. var scripts;
  20. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  21. window.addEventListener("resize",
  22. function () {
  23. if (engine) {
  24. engine.resize();
  25. }
  26. }
  27. );
  28. // TO DO : Rewrite this with unpkg.com
  29. if (location.href.indexOf("indexStable") !== -1) {
  30. utils.setToMultipleID("currentVersion", "innerHTML", "v.3.0");
  31. } else {
  32. utils.setToMultipleID("currentVersion", "innerHTML", "v.4.0");
  33. }
  34. var checkTypescriptSupport = function (xhr) {
  35. // If we're loading TS content and it's JS page
  36. if (xhr.responseText.indexOf("class Playground") !== -1) {
  37. if (settingsPG.ScriptLanguage == "JS") {
  38. settingsPG.ScriptLanguage = "TS";
  39. location.reload();
  40. return false;
  41. }
  42. } else { // If we're loading JS content and it's TS page
  43. if (settingsPG.ScriptLanguage == "TS") {
  44. settingsPG.ScriptLanguage = "JS";
  45. location.reload();
  46. return false;
  47. }
  48. }
  49. return true;
  50. };
  51. var loadScript = function (scriptURL, title) {
  52. var xhr = new XMLHttpRequest();
  53. xhr.open('GET', scriptURL, true);
  54. xhr.onreadystatechange = function () {
  55. if (xhr.readyState === 4) {
  56. if (xhr.status === 200) {
  57. if (!checkTypescriptSupport(xhr)) return;
  58. xhr.onreadystatechange = null;
  59. monacoCreator.BlockEditorChange = true;
  60. monacoCreator.JsEditor.setValue(xhr.responseText);
  61. monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  62. monacoCreator.BlockEditorChange = false;
  63. compileAndRun();
  64. currentSnippetToken = null;
  65. }
  66. }
  67. };
  68. xhr.send(null);
  69. };
  70. var loadScriptsList = function () {
  71. var exampleList = document.getElementById("exampleList");
  72. var xhr = new XMLHttpRequest();
  73. //Open Typescript or Javascript examples
  74. // TO DO - Check why it's always javascript ? Is it hard coded in html page ?
  75. // Should we merge both lists ?
  76. if (exampleList.className != 'typescript') {
  77. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list.json', true);
  78. }
  79. else {
  80. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list_ts.json', true);
  81. }
  82. xhr.onreadystatechange = function () {
  83. if (xhr.readyState === 4) {
  84. if (xhr.status === 200) {
  85. scripts = JSON.parse(xhr.response)["examples"];
  86. function sortScriptsList(a, b) {
  87. if (a.title < b.title) return -1;
  88. else return 1;
  89. }
  90. scripts.sort(sortScriptsList);
  91. if (exampleList) {
  92. for (var i = 0; i < scripts.length; i++) {
  93. scripts[i].samples.sort(sortScriptsList);
  94. var exampleCategory = document.createElement("div");
  95. exampleCategory.classList.add("categoryContainer");
  96. var exampleCategoryTitle = document.createElement("p");
  97. exampleCategoryTitle.innerText = scripts[i].title;
  98. exampleCategory.appendChild(exampleCategoryTitle);
  99. for (var ii = 0; ii < scripts[i].samples.length; ii++) {
  100. var example = document.createElement("div");
  101. example.classList.add("itemLine");
  102. example.id = ii;
  103. var exampleImg = document.createElement("img");
  104. exampleImg.src = scripts[i].samples[ii].icon.replace("icons", "https://doc.babylonjs.com/examples/icons");
  105. exampleImg.setAttribute("onClick", "document.getElementById('PGLink_" + scripts[i].samples[ii].PGID + "').click();");
  106. var exampleContent = document.createElement("div");
  107. exampleContent.classList.add("itemContent");
  108. exampleContent.setAttribute("onClick", "document.getElementById('PGLink_" + scripts[i].samples[ii].PGID + "').click();");
  109. var exampleContentLink = document.createElement("div");
  110. exampleContentLink.classList.add("itemContentLink");
  111. var exampleTitle = document.createElement("h3");
  112. exampleTitle.classList.add("exampleCategoryTitle");
  113. exampleTitle.innerText = scripts[i].samples[ii].title;
  114. var exampleDescr = document.createElement("div");
  115. exampleDescr.classList.add("itemLineChild");
  116. exampleDescr.innerText = scripts[i].samples[ii].description;
  117. var exampleDocLink = document.createElement("a");
  118. exampleDocLink.classList.add("itemLineDocLink");
  119. exampleDocLink.innerText = "Documentation";
  120. exampleDocLink.href = scripts[i].samples[ii].doc;
  121. exampleDocLink.target = "_blank";
  122. var examplePGLink = document.createElement("a");
  123. examplePGLink.id = "PGLink_" + scripts[i].samples[ii].PGID;
  124. examplePGLink.classList.add("itemLinePGLink");
  125. examplePGLink.innerText = "Display";
  126. examplePGLink.href = scripts[i].samples[ii].PGID;
  127. exampleContentLink.appendChild(exampleTitle);
  128. exampleContentLink.appendChild(exampleDescr);
  129. exampleContent.appendChild(exampleContentLink);
  130. exampleContent.appendChild(exampleDocLink);
  131. exampleContent.appendChild(examplePGLink);
  132. example.appendChild(exampleImg);
  133. example.appendChild(exampleContent);
  134. exampleCategory.appendChild(example);
  135. }
  136. exampleList.appendChild(exampleCategory);
  137. }
  138. var noResultContainer = document.createElement("div");
  139. noResultContainer.id = "noResultsContainer";
  140. noResultContainer.classList.add("categoryContainer");
  141. noResultContainer.style.display = "none";
  142. noResultContainer.innerHTML = "<p id='noResults'>No results found.</p>";
  143. exampleList.appendChild(noResultContainer);
  144. }
  145. if (!location.hash) {
  146. // Query string
  147. var queryString = window.location.search;
  148. if (queryString) {
  149. var query = queryString.replace("?", "");
  150. index = parseInt(query);
  151. if (!isNaN(index)) {
  152. // TO DO - Should we remove this deprecated code ?
  153. var newPG = "";
  154. switch (index) {
  155. case 1: newPG = "#TAZ2CB#0"; break; // Basic scene
  156. case 2: newPG = "#A1210C#0"; break; // Basic elements
  157. case 3: newPG = "#CURCZC#0"; break; // Rotation and scaling
  158. case 4: newPG = "#DXARSP#0"; break; // Materials
  159. case 5: newPG = "#1A3M5C#0"; break; // Cameras
  160. case 6: newPG = "#AQRDKW#0"; break; // Lights
  161. case 7: newPG = "#QYFDDP#1"; break; // Animations
  162. case 8: newPG = "#9RI8CG#0"; break; // Sprites
  163. case 9: newPG = "#U8MEB0#0"; break; // Collisions
  164. case 10: newPG = "#KQV9SA#0"; break; // Intersections
  165. case 11: newPG = "#NU4F6Y#0"; break; // Picking
  166. case 12: newPG = "#EF9X5R#0"; break; // Particles
  167. case 13: newPG = "#7G0IQW#0"; break; // Environment
  168. case 14: newPG = "#95PXRY#0"; break; // Height map
  169. case 15: newPG = "#IFYDRS#0"; break; // Shadows
  170. case 16: newPG = "#AQZJ4C#0"; break; // Import meshes
  171. case 17: newPG = "#J19GYK#0"; break; // Actions
  172. case 18: newPG = "#UZ23UH#0"; break; // Drag and drop
  173. case 19: newPG = "#AQZJ4C#0"; break; // Fresnel
  174. case 20: newPG = "#8ZNVGR#0"; break; // Easing functions
  175. case 21: newPG = "#B2ZXG6#0"; break; // Procedural texture
  176. case 22: newPG = "#DXAEUY#0"; break; // Basic sounds
  177. case 23: newPG = "#EDVU95#0"; break; // Sound on mesh
  178. case 24: newPG = "#N96NXC#0"; break; // SSAO rendering pipeline
  179. case 25: newPG = "#7D2QDD#0"; break; // SSAO 2
  180. case 26: newPG = "#V2DAKC#0"; break; // Volumetric light scattering
  181. case 27: newPG = "#XH85A9#0"; break; // Refraction and reflection
  182. case 28: newPG = "#8MGKWK#0"; break; // PBR
  183. case 29: newPG = "#0K8EYN#0"; break; // Instanced bones
  184. case 30: newPG = "#C245A1#0"; break; // Pointer events handling
  185. case 31: newPG = "#TAFSN0#2"; break; // WebVR
  186. case 32: newPG = "#3VMTI9#0"; break; // GUI
  187. case 33: newPG = "#7149G4#0"; break; // Physics
  188. default: newPG = ""; break;
  189. }
  190. window.location.href = location.protocol + "//" + location.host + location.pathname + "#" + newPG;
  191. } else if (query.indexOf("=") === -1) {
  192. loadScript("scripts/" + query + ".js", query);
  193. } else {
  194. loadScript(settingsPG.DefaultScene, "Basic scene");
  195. }
  196. } else {
  197. loadScript(settingsPG.DefaultScene, "Basic scene");
  198. }
  199. }
  200. // Restore theme
  201. settingsPG.restoreTheme(monacoCreator);
  202. // Restore language
  203. settingsPG.setScriptLanguage();
  204. }
  205. }
  206. };
  207. xhr.send(null);
  208. };
  209. var createNewScript = function () {
  210. // check if checked is on
  211. let iCanClear = checkSafeMode("Are you sure you want to create a new playground?");
  212. if (!iCanClear) return;
  213. location.hash = "";
  214. currentSnippetToken = null;
  215. currentSnippetTitle = null;
  216. currentSnippetDescription = null;
  217. currentSnippetTags = null;
  218. showNoMetadata();
  219. if (monacoCreator.monacoMode === "javascript") {
  220. 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};');
  221. } else {
  222. 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}');
  223. }
  224. monacoCreator.JsEditor.setPosition({ lineNumber: 11, column: 0 });
  225. monacoCreator.JsEditor.focus();
  226. compileAndRun();
  227. };
  228. var clear = function () {
  229. // check if checked is on
  230. let iCanClear = checkSafeMode("Are you sure you want to clear the playground?");
  231. if (!iCanClear) return;
  232. location.hash = "";
  233. currentSnippetToken = null;
  234. monacoCreator.JsEditor.setValue('');
  235. monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  236. monacoCreator.JsEditor.focus();
  237. };
  238. // TO DO - Is this really usefull ? Safe mode only available in full HD screen, not for small screen ? Why ?!
  239. var checkSafeMode = function (message) {
  240. var safeToggle = document.getElementById("safemodeToggle1280");
  241. if (safeToggle.classList.contains('checked')) {
  242. let confirm = window.confirm(message);
  243. if (!confirm) {
  244. return false;
  245. } else {
  246. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  247. return true;
  248. }
  249. } else {
  250. return true;
  251. }
  252. };
  253. /**
  254. * Metadatas form
  255. */
  256. var showNoMetadata = function () {
  257. if (currentSnippetTitle) {
  258. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  259. document.getElementById("saveFormTitle").readOnly = true;
  260. }
  261. else {
  262. document.getElementById("saveFormTitle").value = '';
  263. document.getElementById("saveFormTitle").readOnly = false;
  264. }
  265. if (currentSnippetDescription) {
  266. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  267. document.getElementById("saveFormDescription").readOnly = true;
  268. }
  269. else {
  270. document.getElementById("saveFormDescription").value = '';
  271. document.getElementById("saveFormDescription").readOnly = false;
  272. }
  273. if (currentSnippetTags) {
  274. document.getElementById("saveFormTags").value = currentSnippetTags;
  275. document.getElementById("saveFormTags").readOnly = true;
  276. }
  277. else {
  278. document.getElementById("saveFormTags").value = '';
  279. document.getElementById("saveFormTags").readOnly = false;
  280. }
  281. document.getElementById("saveFormButtons").style.display = "block";
  282. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  283. };
  284. var hideNoMetadata = function () {
  285. document.getElementById("saveFormTitle").readOnly = true;
  286. document.getElementById("saveFormDescription").readOnly = true;
  287. document.getElementById("saveFormTags").readOnly = true;
  288. document.getElementById("saveFormButtonOk").style.display = "none";
  289. utils.setToMultipleID("metadataButton", "display", "inline-block");
  290. };
  291. showNoMetadata();
  292. /*
  293. * Metadatas save
  294. */
  295. // TO DO - Search what is the appropriate place for this code
  296. var save = function () {
  297. // Retrieve title if necessary
  298. if (document.getElementById("saveLayer")) {
  299. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  300. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  301. currentSnippetTags = document.getElementById("saveFormTags").value;
  302. }
  303. var xmlHttp = new XMLHttpRequest();
  304. xmlHttp.onreadystatechange = function () {
  305. if (xmlHttp.readyState === 4) {
  306. if (xmlHttp.status === 200) {
  307. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  308. var snippet = JSON.parse(xmlHttp.responseText);
  309. var newUrl = baseUrl + "#" + snippet.id;
  310. currentSnippetToken = snippet.id;
  311. if (snippet.version && snippet.version !== "0") {
  312. newUrl += "#" + snippet.version;
  313. }
  314. location.href = newUrl;
  315. // Hide the complete title & co message
  316. hideNoMetadata();
  317. compileAndRun();
  318. } else {
  319. utils.showError("Unable to save your code. It may be too long.", null);
  320. }
  321. }
  322. }
  323. xmlHttp.open("POST", snippetV3Url + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  324. xmlHttp.setRequestHeader("Content-Type", "application/json");
  325. var dataToSend = {
  326. payload: JSON.stringify({
  327. code: monacoCreator.JsEditor.getValue()
  328. }),
  329. name: currentSnippetTitle,
  330. description: currentSnippetDescription,
  331. tags: currentSnippetTags
  332. };
  333. xmlHttp.send(JSON.stringify(dataToSend));
  334. };
  335. var askForSave = function () {
  336. if (currentSnippetTitle == null
  337. || currentSnippetDescription == null
  338. || currentSnippetTags == null) {
  339. document.getElementById("saveLayer").style.display = "block";
  340. }
  341. else {
  342. save();
  343. }
  344. };
  345. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  346. document.getElementById("saveLayer").style.display = "none";
  347. save();
  348. });
  349. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  350. document.getElementById("saveLayer").style.display = "none";
  351. });
  352. /**
  353. * Compile the script in the editor, and run the preview in the canvas
  354. */
  355. var compileAndRun = function () {
  356. try {
  357. var waitRing = document.getElementById("waitDiv");
  358. if (waitRing) {
  359. waitRing.style.display = "none";
  360. }
  361. if (!BABYLON.Engine.isSupported()) {
  362. utils.showError("Your browser does not support WebGL. Please, try to update it, or install a compatible one.", null);
  363. return;
  364. }
  365. var showInspector = false;
  366. showBJSPGMenu();
  367. monacoCreator.JsEditor.updateOptions({ readOnly: false });
  368. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.debugLayer.isVisible()) {
  369. showInspector = true;
  370. }
  371. if (engine) {
  372. engine.dispose();
  373. engine = null;
  374. }
  375. var canvas = document.getElementById("renderCanvas");
  376. document.getElementById("errorZone").style.display = 'none';
  377. document.getElementById("errorZone").innerHTML = "";
  378. document.getElementById("statusBar").innerHTML = "Loading assets... Please wait.";
  379. var checkCamera = true;
  380. var checkSceneCount = true;
  381. var createEngineFunction = "createDefaultEngine";
  382. var createSceneFunction;
  383. monacoCreator.getRunCode(function (code) {
  384. var createDefaultEngine = function () {
  385. return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  386. }
  387. var scene;
  388. var defaultEngineZip = "new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true })";
  389. if (code.indexOf("createEngine") !== -1) {
  390. createEngineFunction = "createEngine";
  391. }
  392. // Check for different typos
  393. if (code.indexOf("delayCreateScene") !== -1) { // createScene
  394. createSceneFunction = "delayCreateScene";
  395. checkCamera = false;
  396. } else if (code.indexOf("createScene") !== -1) { // createScene
  397. createSceneFunction = "createScene";
  398. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  399. createSceneFunction = "CreateScene";
  400. } else if (code.indexOf("createscene") !== -1) { // createscene
  401. createSceneFunction = "createscene";
  402. }
  403. if (!createSceneFunction) {
  404. // just pasted code.
  405. engine = createDefaultEngine();
  406. scene = new BABYLON.Scene(engine);
  407. eval("runScript = function(scene, canvas) {" + code + "}");
  408. runScript(scene, canvas);
  409. zipTool.ZipCode = "var engine = " + defaultEngineZip + ";\r\nvar scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  410. } else {
  411. //execute the code
  412. eval(code);
  413. //create engine
  414. eval("engine = " + createEngineFunction + "()");
  415. if (!engine) {
  416. utils.showError("createEngine function must return an engine.", null);
  417. return;
  418. }
  419. //create scene
  420. eval("scene = " + createSceneFunction + "()");
  421. if (!scene) {
  422. utils.showError(createSceneFunction + " function must return a scene.", null);
  423. return;
  424. }
  425. // if scene returns a promise avoid checks
  426. if (scene.then) {
  427. checkCamera = false;
  428. checkSceneCount = false;
  429. }
  430. var createEngineZip = (createEngineFunction === "createEngine")
  431. ? "createEngine()"
  432. : defaultEngineZip;
  433. zipTool.zipCode =
  434. code + "\r\n\r\n" +
  435. "var engine = " + createEngineZip + ";\r\n" +
  436. "var scene = " + createSceneFunction + "();";
  437. }
  438. engine.runRenderLoop(function () {
  439. if (engine.scenes.length === 0) {
  440. return;
  441. }
  442. if (canvas.width !== canvas.clientWidth) {
  443. engine.resize();
  444. }
  445. var scene = engine.scenes[0];
  446. if (scene.activeCamera || scene.activeCameras.length > 0) {
  447. scene.render();
  448. }
  449. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  450. });
  451. if (checkSceneCount && engine.scenes.length === 0) {
  452. utils.showError("You must at least create a scene.", null);
  453. return;
  454. }
  455. if (checkCamera && engine.scenes[0].activeCamera == null) {
  456. utils.showError("You must at least create a camera.", null);
  457. return;
  458. } else if (scene.then) {
  459. scene.then(function () {
  460. document.getElementById("statusBar").innerHTML = "";
  461. });
  462. } else {
  463. engine.scenes[0].executeWhenReady(function () {
  464. document.getElementById("statusBar").innerHTML = "";
  465. });
  466. }
  467. if (scene) {
  468. if (showInspector) {
  469. if (scene.then) {
  470. // Handle if scene is a promise
  471. scene.then(function (s) {
  472. if (!s.debugLayer.isVisible()) {
  473. s.debugLayer.show({ embedMode: true });
  474. }
  475. })
  476. } else {
  477. if (!scene.debugLayer.isVisible()) {
  478. scene.debugLayer.show({ embedMode: true });
  479. }
  480. }
  481. }
  482. }
  483. });
  484. } catch (e) {
  485. utils.showError(e.message, e);
  486. // Also log error in console to help debug playgrounds
  487. console.error(e);
  488. }
  489. };
  490. /**
  491. * BJS version
  492. */
  493. // TO DO - Rewrite that
  494. var setVersion = function (version) {
  495. // switch (version) {
  496. // case "stable":
  497. // location.href = "indexStable.html" + location.hash;
  498. // break;
  499. // default:
  500. // location.href = "index.html" + location.hash;
  501. // break;
  502. // }
  503. }
  504. utils.setToMultipleID("mainTitle", "innerHTML", "v" + BABYLON.Engine.Version);
  505. // TO DO - Make it work on small screens and mobile
  506. var showQRCode = function () {
  507. $("#qrCodeImage").empty();
  508. var playgroundCode = window.location.href.split("#");
  509. playgroundCode.shift();
  510. $("#qrCodeImage").qrcode({ text: "https://playground.babylonjs.com/frame.html#" + (playgroundCode.join("#")) });
  511. };
  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. }