main.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. var engine = null;
  2. var canas = null;
  3. var scene = null;
  4. var globalParent = null;
  5. handleException = function(parent, e) {
  6. parent.utils.showError(e.message, e);
  7. // Also log error in console to help debug playgrounds
  8. console.error(e);
  9. }
  10. fastEval = function(code) {
  11. var head = document.getElementsByTagName('head')[0];
  12. var script = document.createElement('script');
  13. script.setAttribute('type', 'text/javascript');
  14. script.innerHTML = `try {${code};}
  15. catch(e) {
  16. handleException(globalParent, e);
  17. }`;
  18. head.appendChild(script);
  19. }
  20. /**
  21. * Compile the script in the editor, and run the preview in the canvas
  22. */
  23. compileAndRun = function(parent, fpsLabel) {
  24. // If we need to change the version, don't do this
  25. if (parent.settingsPG.mustModifyBJSversion()) return;
  26. try {
  27. parent.menuPG.hideWaitDiv();
  28. globalParent = parent;
  29. if (!BABYLON.Engine.isSupported()) {
  30. parent.utils.showError("Your browser does not support WebGL. Please, try to update it, or install a compatible one.", null);
  31. return;
  32. }
  33. var showInspector = false;
  34. parent.menuPG.showBJSPGMenu();
  35. parent.monacoCreator.JsEditor.updateOptions({ readOnly: false });
  36. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.debugLayer.isVisible()) {
  37. showInspector = true;
  38. }
  39. if (engine) {
  40. try {
  41. engine.dispose();
  42. }
  43. catch (ex) { }
  44. engine = null;
  45. }
  46. canvas = document.getElementById("renderCanvas");
  47. document.getElementById("errorZone").style.display = 'none';
  48. document.getElementById("errorZone").innerHTML = "";
  49. document.getElementById("statusBar").innerHTML = "Loading assets... Please wait.";
  50. var checkCamera = true;
  51. var checkSceneCount = true;
  52. var createEngineFunction = "createDefaultEngine";
  53. var createSceneFunction;
  54. parent.monacoCreator.getRunCode().then(code => {
  55. createDefaultEngine = function () {
  56. return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  57. }
  58. var defaultEngineZip = "new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true })";
  59. if (code.indexOf("createEngine") !== -1) {
  60. createEngineFunction = "createEngine";
  61. }
  62. // Check for different typos
  63. if (code.indexOf("delayCreateScene") !== -1) { // delayCreateScene
  64. createSceneFunction = "delayCreateScene";
  65. checkCamera = false;
  66. } else if (code.indexOf("createScene") !== -1) { // createScene
  67. createSceneFunction = "createScene";
  68. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  69. createSceneFunction = "CreateScene";
  70. } else if (code.indexOf("createscene") !== -1) { // createscene
  71. createSceneFunction = "createscene";
  72. }
  73. if (!createSceneFunction) {
  74. // Just pasted code.
  75. engine = createDefaultEngine();
  76. scene = new BABYLON.Scene(engine);
  77. var runScript = null;
  78. fastEval("runScript = function(scene, canvas) {" + code + "}");
  79. runScript(scene, canvas);
  80. parent.zipTool.ZipCode = "var engine = " + defaultEngineZip + ";\r\nvar scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  81. } else {
  82. if (parent.settingsPG.ScriptLanguage == "JS") {
  83. code += "\n" + "scene = " + createSceneFunction + "();";
  84. }
  85. else {
  86. var startCar = code.search('var ' + createSceneFunction);
  87. code = code.substr(0, startCar) + code.substr(startCar + 4);
  88. code += "\n" + "scene = " + createSceneFunction + "();";
  89. }
  90. // Create engine
  91. fastEval("engine = " + createEngineFunction + "()");
  92. if (!engine) {
  93. parent.utils.showError("createEngine function must return an engine.", null);
  94. return;
  95. }
  96. // Execute the code
  97. fastEval(code);
  98. if (!scene) {
  99. parent.utils.showError(createSceneFunction + " function must return a scene.", null);
  100. return;
  101. }
  102. // if scene returns a promise avoid checks
  103. if (scene.then) {
  104. checkCamera = false;
  105. checkSceneCount = false;
  106. }
  107. var createEngineZip = (createEngineFunction === "createEngine")
  108. ? "createEngine()"
  109. : defaultEngineZip;
  110. parent.zipTool.zipCode =
  111. "var engine = " + createEngineZip + ";\r\n" +
  112. code + "\r\n\r\n";
  113. }
  114. engine = engine;
  115. engine.runRenderLoop(function () {
  116. if (engine.scenes.length === 0) {
  117. return;
  118. }
  119. if (canvas.width !== canvas.clientWidth) {
  120. engine.resize();
  121. }
  122. var scene = engine.scenes[0];
  123. if (scene.activeCamera || scene.activeCameras.length > 0) {
  124. scene.render();
  125. }
  126. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  127. }.bind(this));
  128. if (checkSceneCount && engine.scenes.length === 0) {
  129. parent.utils.showError("You must at least create a scene.", null);
  130. return;
  131. }
  132. if (checkCamera && engine.scenes[0].activeCamera == null) {
  133. parent.utils.showError("You must at least create a camera.", null);
  134. return;
  135. } else if (scene.then) {
  136. scene.then(function () {
  137. document.getElementById("statusBar").innerHTML = "";
  138. });
  139. } else {
  140. engine.scenes[0].executeWhenReady(function () {
  141. document.getElementById("statusBar").innerHTML = "";
  142. });
  143. }
  144. if (scene) {
  145. if (showInspector) {
  146. if (scene.then) {
  147. // Handle if scene is a promise
  148. scene.then(function (s) {
  149. if (!s.debugLayer.isVisible()) {
  150. s.debugLayer.show({ embedMode: true });
  151. }
  152. })
  153. } else {
  154. if (!scene.debugLayer.isVisible()) {
  155. scene.debugLayer.show({ embedMode: true });
  156. }
  157. }
  158. }
  159. }
  160. }).catch(e => {
  161. handleException(parent, e);
  162. });
  163. } catch (e) {
  164. handleException(parent, e);
  165. }
  166. };
  167. /**
  168. * This JS file contains the main function
  169. */
  170. class Main {
  171. constructor(parent) {
  172. this.parent = parent;
  173. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  174. this.snippetV3Url = "https://snippet.babylonjs.com"
  175. this.currentSnippetToken;
  176. this.currentSnippetTitle = null;
  177. this.currentSnippetDescription = null;
  178. this.currentSnippetTags = null;
  179. this.fpsLabel = document.getElementById("fpsLabel");
  180. this.scripts;
  181. this.previousHash = "";
  182. }
  183. /**
  184. * First function to initialize the script
  185. */
  186. initialize() {
  187. this.parent.monacoCreator.loadMonaco();
  188. };
  189. /**
  190. * Main function of the app
  191. */
  192. run() {
  193. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  194. document.getElementById("saveLayer").style.display = "none";
  195. this.save();
  196. }.bind(this));
  197. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  198. document.getElementById("saveLayer").style.display = "none";
  199. });
  200. document.getElementById("diffFormButtonOk").addEventListener("click", function () {
  201. document.getElementById("diffLayer").style.display = "none";
  202. this.diff();
  203. }.bind(this));
  204. document.getElementById("diffFormButtonCancel").addEventListener("click", function () {
  205. document.getElementById("diffLayer").style.display = "none";
  206. });
  207. // Resize the render view when resizing the window
  208. window.addEventListener("resize",
  209. function () {
  210. if (engine) {
  211. engine.resize();
  212. }
  213. }.bind(this)
  214. );
  215. // Restore BJS version if needed
  216. var restoreVersionResult = true;
  217. if (this.parent.settingsPG.restoreVersion() == false) {
  218. // Check if there a hash in the URL
  219. this.checkHash();
  220. restoreVersionResult = false;
  221. }
  222. // Load scripts list
  223. this.loadScriptsList(restoreVersionResult);
  224. // -------------------- UI --------------------
  225. // Display BJS version
  226. if (BABYLON) this.parent.utils.setToMultipleID("mainTitle", "innerHTML", "v" + BABYLON.Engine.Version);
  227. // Run
  228. this.parent.utils.setToMultipleID("runButton", "click", () => compileAndRun(this.parent, this.fpsLabel));
  229. // New
  230. this.parent.utils.setToMultipleID("newButton", "click", function () {
  231. this.parent.menuPG.removeAllOptions();
  232. this.createNewScript.call(this);
  233. }.bind(this));
  234. // Clear
  235. this.parent.utils.setToMultipleID("clearButton", "click", function () {
  236. this.parent.menuPG.removeAllOptions();
  237. this.clear.call(this);
  238. }.bind(this));
  239. // Save
  240. this.parent.utils.setToMultipleID("saveButton", "click", this.askForSave.bind(this));
  241. // Diff
  242. this.parent.utils.setToMultipleID("diffButton", "click", this.askForDiff.bind(this));
  243. this.parent.utils.setToMultipleID("previousButton", "click", this.navigateToPrevious.bind(this));
  244. this.parent.utils.setToMultipleID("nextButton", "click", this.navigateToNext.bind(this));
  245. this.parent.utils.setToMultipleID("exitButton", "click", function() {
  246. this.toggleDiffEditor(this.parent.monacoCreator, this.parent.menuPG)
  247. }.bind(this));
  248. // Zip
  249. this.parent.utils.setToMultipleID("zipButton", "click", function () {
  250. this.parent.zipTool.getZip(engine);
  251. }.bind(this));
  252. // Themes
  253. this.parent.utils.setToMultipleID("darkTheme", "click", function () {
  254. this.parent.menuPG.removeAllOptions();
  255. this.parent.settingsPG.setTheme.call(this.parent.settingsPG, 'dark');
  256. }.bind(this));
  257. this.parent.utils.setToMultipleID("lightTheme", "click", function () {
  258. this.parent.menuPG.removeAllOptions();
  259. this.parent.settingsPG.setTheme.call(this.parent.settingsPG, 'light');
  260. }.bind(this));
  261. // Size
  262. var displayFontSize = document.getElementsByClassName('displayFontSize');
  263. for (var i = 0; i < displayFontSize.length; i++) {
  264. var options = displayFontSize[i].querySelectorAll('.option');
  265. for (var j = 0; j < options.length; j++) {
  266. options[j].addEventListener('click', function (evt) {
  267. this.parent.menuPG.removeAllOptions();
  268. this.parent.settingsPG.setFontSize.call(this.parent.settingsPG, evt.target.innerText)
  269. }.bind(this));
  270. }
  271. }
  272. // Footer links
  273. var displayFontSize = document.getElementsByClassName('displayFooterLinks');
  274. for (var i = 0; i < displayFontSize.length; i++) {
  275. var options = displayFontSize[i].querySelectorAll('.option');
  276. for (var j = 0; j < options.length; j++) {
  277. options[j].addEventListener('click', this.parent.menuPG.clickOptionSub.bind(this));
  278. }
  279. }
  280. // Language (JS / TS)
  281. this.parent.utils.setToMultipleID("toTSbutton", "click", function () {
  282. if(location.hash != null && location.hash != ""){
  283. this.parent.settingsPG.ScriptLanguage = "TS";
  284. window.location = "./";
  285. }else{
  286. if (this.parent.settingsPG.ScriptLanguage == "JS") {
  287. //revert in case the reload is cancel due to safe mode
  288. if(document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()).classList.contains('checked')){
  289. // Message before unload
  290. var languageTSswapper = function () {
  291. this.parent.settingsPG.ScriptLanguage = "TS";
  292. window.removeEventListener('unload', languageTSswapper.bind(this));
  293. };
  294. window.addEventListener('unload',languageTSswapper.bind(this));
  295. location.reload();
  296. }
  297. else {
  298. this.parent.settingsPG.ScriptLanguage = "TS";
  299. location.reload();
  300. }
  301. }
  302. }
  303. }.bind(this));
  304. this.parent.utils.setToMultipleID("toJSbutton", "click", function () {
  305. if(location.hash != null && location.hash != ""){
  306. this.parent.settingsPG.ScriptLanguage = "JS";
  307. window.location = "./";
  308. }else{
  309. if (this.parent.settingsPG.ScriptLanguage == "TS") {
  310. //revert in case the reload is cancel due to safe mode
  311. if(document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()).classList.contains('checked')){
  312. // Message before unload
  313. var LanguageJSswapper = function () {
  314. this.parent.settingsPG.ScriptLanguage = "JS";
  315. window.removeEventListener('unload', LanguageJSswapper.bind(this));
  316. };
  317. window.addEventListener('unload',LanguageJSswapper.bind(this));
  318. location.reload();
  319. }
  320. else {
  321. this.parent.settingsPG.ScriptLanguage = "JS";
  322. location.reload();
  323. }
  324. }
  325. }
  326. }.bind(this));
  327. // Safe mode
  328. this.parent.utils.setToMultipleID("safemodeToggle", 'click', function () {
  329. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  330. if (document.getElementById("safemodeToggle1280").classList.contains('checked')) {
  331. this.parent.utils.setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  332. } else {
  333. this.parent.utils.setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square" aria-hidden="true"></i>');
  334. }
  335. }.bind(this));
  336. // Editor
  337. this.parent.utils.setToMultipleID("editorButton", "click", this.toggleEditor.bind(this));
  338. // FullScreen
  339. this.parent.utils.setToMultipleID("fullscreenButton", "click", function () {
  340. this.parent.menuPG.removeAllOptions();
  341. this.parent.menuPG.goFullscreen(engine);
  342. }.bind(this));
  343. // Editor fullScreen
  344. this.parent.utils.setToMultipleID("editorFullscreenButton", "click", function () {
  345. this.parent.menuPG.removeAllOptions();
  346. this.parent.menuPG.editorGoFullscreen.call(this.parent.menuPG)
  347. }.bind(this));
  348. // Format
  349. this.parent.utils.setToMultipleID("formatButton", "click", function () {
  350. this.parent.menuPG.removeAllOptions();
  351. this.parent.monacoCreator.formatCode.call(this.parent.monacoCreator)
  352. }.bind(this));
  353. // Minimap
  354. this.parent.utils.setToMultipleID("minimapToggle", "click", this.parent.monacoCreator.toggleMinimap.bind(this.parent.monacoCreator));
  355. // Inspector
  356. this.parent.utils.setToMultipleID("debugButton", "click", function () {
  357. this.parent.menuPG.removeAllOptions();
  358. this.toggleDebug.call(this);
  359. }.bind(this));
  360. // Metadata
  361. this.parent.utils.setToMultipleID("metadataButton", "click", function () {
  362. this.parent.menuPG.removeAllOptions();
  363. this.parent.menuPG.displayMetadata.call(this.parent.menuPG)
  364. }.bind(this));
  365. // Initialize the metadata form
  366. this.showNoMetadata();
  367. // Restore theme
  368. this.parent.settingsPG.restoreTheme();
  369. // Restore font size
  370. this.parent.settingsPG.restoreFont();
  371. // Restore language
  372. this.parent.settingsPG.setScriptLanguage();
  373. // Check if it's mobile mode. If true, switch to full canvas by default
  374. this.parent.menuPG.resizeBigCanvas();
  375. };
  376. /**
  377. * Check if we're in the correct language for the selected script
  378. * @param {*} xhr
  379. */
  380. checkTypescriptSupport(xhr) {
  381. // If we're loading TS content and it's JS page
  382. if (xhr.responseText.indexOf("class Playground") !== -1) {
  383. if (this.parent.settingsPG.ScriptLanguage == "JS") {
  384. this.parent.settingsPG.ScriptLanguage = "TS";
  385. location.reload();
  386. return false;
  387. }
  388. } else { // If we're loading JS content and it's TS page
  389. if (this.parent.settingsPG.ScriptLanguage == "TS") {
  390. this.parent.settingsPG.ScriptLanguage = "JS";
  391. location.reload();
  392. return false;
  393. }
  394. }
  395. return true;
  396. };
  397. /**
  398. * Load a script in the database
  399. * @param {*} scriptURL
  400. * @param {*} title
  401. */
  402. loadScript(scriptURL, title) {
  403. var xhr = new XMLHttpRequest();
  404. xhr.open('GET', scriptURL, true);
  405. xhr.onreadystatechange = function () {
  406. if (xhr.readyState === 4) {
  407. if (xhr.status === 200) {
  408. if (!this.checkTypescriptSupport(xhr)) return;
  409. xhr.onreadystatechange = null;
  410. this.parent.monacoCreator.BlockEditorChange = true;
  411. this.parent.monacoCreator.JsEditor.setValue(xhr.responseText);
  412. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  413. this.parent.monacoCreator.BlockEditorChange = false;
  414. compileAndRun(this.parent, this.fpsLabel);
  415. this.currentSnippetToken = null;
  416. }
  417. }
  418. }.bind(this);
  419. xhr.send(null);
  420. };
  421. /**
  422. * Load the examples scripts list in the database
  423. */
  424. loadScriptsList(restoreVersionResult) {
  425. var exampleList = document.getElementById("exampleList");
  426. var xhr = new XMLHttpRequest();
  427. // Open Typescript or Javascript examples
  428. if (exampleList.className != 'typescript') {
  429. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list.json', true);
  430. }
  431. else {
  432. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list_ts.json', true);
  433. }
  434. xhr.onreadystatechange = function () {
  435. if (xhr.readyState === 4) {
  436. if (xhr.status === 200) {
  437. this.scripts = JSON.parse(xhr.response)["examples"];
  438. function sortScriptsList(a, b) {
  439. if (a.title < b.title) return -1;
  440. else return 1;
  441. }
  442. this.scripts.sort(sortScriptsList);
  443. if (exampleList) {
  444. for (var i = 0; i < this.scripts.length; i++) {
  445. this.scripts[i].samples.sort(sortScriptsList);
  446. var exampleCategory = document.createElement("div");
  447. exampleCategory.classList.add("categoryContainer");
  448. var exampleCategoryTitle = document.createElement("p");
  449. exampleCategoryTitle.innerText = this.scripts[i].title;
  450. exampleCategory.appendChild(exampleCategoryTitle);
  451. for (var ii = 0; ii < this.scripts[i].samples.length; ii++) {
  452. var example = document.createElement("div");
  453. example.classList.add("itemLine");
  454. example.id = ii;
  455. var exampleImg = document.createElement("img");
  456. exampleImg.src = this.scripts[i].samples[ii].icon.replace("icons", "https://doc.babylonjs.com/examples/icons");
  457. exampleImg.setAttribute("onClick", "document.getElementById('PGLink_" + this.scripts[i].samples[ii].PGID + "').click();");
  458. var exampleContent = document.createElement("div");
  459. exampleContent.classList.add("itemContent");
  460. exampleContent.setAttribute("onClick", "document.getElementById('PGLink_" + this.scripts[i].samples[ii].PGID + "').click();");
  461. var exampleContentLink = document.createElement("div");
  462. exampleContentLink.classList.add("itemContentLink");
  463. var exampleTitle = document.createElement("h3");
  464. exampleTitle.classList.add("exampleCategoryTitle");
  465. exampleTitle.innerText = this.scripts[i].samples[ii].title;
  466. var exampleDescr = document.createElement("div");
  467. exampleDescr.classList.add("itemLineChild");
  468. exampleDescr.innerText = this.scripts[i].samples[ii].description;
  469. var exampleDocLink = document.createElement("a");
  470. exampleDocLink.classList.add("itemLineDocLink");
  471. exampleDocLink.innerText = "Documentation";
  472. exampleDocLink.href = this.scripts[i].samples[ii].doc;
  473. exampleDocLink.target = "_blank";
  474. var examplePGLink = document.createElement("a");
  475. examplePGLink.id = "PGLink_" + this.scripts[i].samples[ii].PGID;
  476. examplePGLink.classList.add("itemLinePGLink");
  477. examplePGLink.innerText = "Display";
  478. examplePGLink.href = this.scripts[i].samples[ii].PGID;
  479. examplePGLink.addEventListener("click", function() {
  480. location.href = this.href;
  481. location.reload();
  482. });
  483. exampleContentLink.appendChild(exampleTitle);
  484. exampleContentLink.appendChild(exampleDescr);
  485. exampleContent.appendChild(exampleContentLink);
  486. exampleContent.appendChild(exampleDocLink);
  487. exampleContent.appendChild(examplePGLink);
  488. example.appendChild(exampleImg);
  489. example.appendChild(exampleContent);
  490. exampleCategory.appendChild(example);
  491. }
  492. exampleList.appendChild(exampleCategory);
  493. }
  494. var noResultContainer = document.createElement("div");
  495. noResultContainer.id = "noResultsContainer";
  496. noResultContainer.classList.add("categoryContainer");
  497. noResultContainer.style.display = "none";
  498. noResultContainer.innerHTML = "<p id='noResults'>No results found.</p>";
  499. exampleList.appendChild(noResultContainer);
  500. }
  501. if (!location.hash && restoreVersionResult == false) {
  502. // Query string
  503. var queryString = window.location.search;
  504. if (queryString) {
  505. var query = queryString.replace("?", "");
  506. index = parseInt(query);
  507. if (!isNaN(index)) {
  508. var newPG = "";
  509. switch (index) {
  510. case 1: newPG = "#TAZ2CB#0"; break; // Basic scene
  511. case 2: newPG = "#A1210C#0"; break; // Basic elements
  512. case 3: newPG = "#CURCZC#0"; break; // Rotation and scaling
  513. case 4: newPG = "#DXARSP#0"; break; // Materials
  514. case 5: newPG = "#1A3M5C#0"; break; // Cameras
  515. case 6: newPG = "#AQRDKW#0"; break; // Lights
  516. case 7: newPG = "#QYFDDP#1"; break; // Animations
  517. case 8: newPG = "#9RI8CG#0"; break; // Sprites
  518. case 9: newPG = "#U8MEB0#0"; break; // Collisions
  519. case 10: newPG = "#KQV9SA#0"; break; // Intersections
  520. case 11: newPG = "#NU4F6Y#0"; break; // Picking
  521. case 12: newPG = "#EF9X5R#0"; break; // Particles
  522. case 13: newPG = "#7G0IQW#0"; break; // Environment
  523. case 14: newPG = "#95PXRY#0"; break; // Height map
  524. case 15: newPG = "#IFYDRS#0"; break; // Shadows
  525. case 16: newPG = "#AQZJ4C#0"; break; // Import meshes
  526. case 17: newPG = "#J19GYK#0"; break; // Actions
  527. case 18: newPG = "#UZ23UH#0"; break; // Drag and drop
  528. case 19: newPG = "#AQZJ4C#0"; break; // Fresnel
  529. case 20: newPG = "#8ZNVGR#0"; break; // Easing functions
  530. case 21: newPG = "#B2ZXG6#0"; break; // Procedural texture
  531. case 22: newPG = "#DXAEUY#0"; break; // Basic sounds
  532. case 23: newPG = "#EDVU95#0"; break; // Sound on mesh
  533. case 24: newPG = "#N96NXC#0"; break; // SSAO rendering pipeline
  534. case 25: newPG = "#7D2QDD#0"; break; // SSAO 2
  535. case 26: newPG = "#V2DAKC#0"; break; // Volumetric light scattering
  536. case 27: newPG = "#XH85A9#0"; break; // Refraction and reflection
  537. case 28: newPG = "#8MGKWK#0"; break; // PBR
  538. case 29: newPG = "#0K8EYN#0"; break; // Instanced bones
  539. case 30: newPG = "#C245A1#0"; break; // Pointer events handling
  540. case 31: newPG = "#TAFSN0#2"; break; // WebVR
  541. case 32: newPG = "#3VMTI9#0"; break; // GUI
  542. case 33: newPG = "#7149G4#0"; break; // Physics
  543. default: newPG = ""; break;
  544. }
  545. window.location.href = location.protocol + "//" + location.host + location.pathname + "#" + newPG;
  546. } else if (query.indexOf("=") === -1) {
  547. this.loadScript("scripts/" + query + ".js", query);
  548. } else {
  549. this.loadScript(this.parent.settingsPG.DefaultScene, "Basic scene");
  550. }
  551. } else {
  552. this.loadScript(this.parent.settingsPG.DefaultScene, "Basic scene");
  553. }
  554. }
  555. // Restore language
  556. this.parent.settingsPG.setScriptLanguage();
  557. }
  558. }
  559. }.bind(this);
  560. xhr.send(null);
  561. };
  562. createNewScript() {
  563. // Check if safe mode is on, and ask if it is
  564. if (!this.checkSafeMode("Are you sure you want to create a new playground?")) return;
  565. location.hash = "";
  566. this.currentSnippetToken = null;
  567. this.currentSnippetTitle = null;
  568. this.currentSnippetDescription = null;
  569. this.currentSnippetTags = null;
  570. this.showNoMetadata();
  571. if (this.parent.monacoCreator.monacoMode === "javascript") {
  572. this.parent.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};');
  573. } else {
  574. this.parent.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}');
  575. }
  576. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 11, column: 0 });
  577. this.parent.monacoCreator.JsEditor.focus();
  578. compileAndRun(this.parent, this.fpsLabel);
  579. };
  580. clear() {
  581. // Check if safe mode is on, and ask if it is
  582. if (!this.checkSafeMode("Are you sure you want to clear the playground?")) return;
  583. location.hash = "";
  584. this.currentSnippetToken = null;
  585. this.parent.monacoCreator.JsEditor.setValue('');
  586. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  587. this.parent.monacoCreator.JsEditor.focus();
  588. };
  589. compileAndRunFromOutside() {
  590. compileAndRun(this.parent, this.fpsLabel);
  591. };
  592. checkSafeMode(message) {
  593. if (document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()) &&
  594. document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()).classList.contains('checked')) {
  595. let confirm = window.confirm(message);
  596. if (!confirm) {
  597. return false;
  598. } else {
  599. for (var i = 0; i < this.parent.utils.multipleSize.length; i++) {
  600. document.getElementById("safemodeToggle" + this.parent.utils.multipleSize[i]).classList.toggle('checked');
  601. }
  602. return true;
  603. }
  604. } else {
  605. return true;
  606. }
  607. };
  608. /**
  609. * Metadatas form
  610. */
  611. showNoMetadata() {
  612. if (this.currentSnippetTitle) {
  613. document.getElementById("saveFormTitle").value = this.currentSnippetTitle;
  614. document.getElementById("saveFormTitle").readOnly = true;
  615. }
  616. else {
  617. document.getElementById("saveFormTitle").value = '';
  618. document.getElementById("saveFormTitle").readOnly = false;
  619. }
  620. if (this.currentSnippetDescription) {
  621. document.getElementById("saveFormDescription").value = this.currentSnippetDescription;
  622. document.getElementById("saveFormDescription").readOnly = true;
  623. }
  624. else {
  625. document.getElementById("saveFormDescription").value = '';
  626. document.getElementById("saveFormDescription").readOnly = false;
  627. }
  628. if (this.currentSnippetTags) {
  629. document.getElementById("saveFormTags").value = this.currentSnippetTags;
  630. document.getElementById("saveFormTags").readOnly = true;
  631. }
  632. else {
  633. document.getElementById("saveFormTags").value = '';
  634. document.getElementById("saveFormTags").readOnly = false;
  635. }
  636. document.getElementById("saveFormButtons").style.display = "block";
  637. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  638. };
  639. hideNoMetadata() {
  640. document.getElementById("saveFormTitle").readOnly = true;
  641. document.getElementById("saveFormDescription").readOnly = true;
  642. document.getElementById("saveFormTags").readOnly = true;
  643. document.getElementById("saveFormButtonOk").style.display = "none";
  644. };
  645. /*
  646. * Metadatas save
  647. */
  648. save() {
  649. // Retrieve title if necessary
  650. if (document.getElementById("saveLayer")) {
  651. this.currentSnippetTitle = document.getElementById("saveFormTitle").value;
  652. this.currentSnippetDescription = document.getElementById("saveFormDescription").value;
  653. this.currentSnippetTags = document.getElementById("saveFormTags").value;
  654. }
  655. var xmlHttp = new XMLHttpRequest();
  656. xmlHttp.onreadystatechange = function () {
  657. if (xmlHttp.readyState === 4) {
  658. if (xmlHttp.status === 200) {
  659. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  660. var snippet = JSON.parse(xmlHttp.responseText);
  661. var newUrl = baseUrl + "#" + snippet.id;
  662. this.currentSnippetToken = snippet.id;
  663. if (snippet.version && snippet.version !== "0") {
  664. newUrl += "#" + snippet.version;
  665. }
  666. location.href = newUrl;
  667. // Hide the complete title & co message
  668. this.hideNoMetadata();
  669. compileAndRun(this.parent, this.fpsLabel);
  670. } else {
  671. this.parent.utils.showError("Unable to save your code. It may be too long.", null);
  672. }
  673. }
  674. }.bind(this);
  675. xmlHttp.open("POST", this.snippetV3Url + (this.currentSnippetToken ? "/" + this.currentSnippetToken : ""), true);
  676. xmlHttp.setRequestHeader("Content-Type", "application/json");
  677. var dataToSend = {
  678. payload: JSON.stringify({
  679. code: this.parent.monacoCreator.JsEditor.getValue()
  680. }),
  681. name: this.currentSnippetTitle,
  682. description: this.currentSnippetDescription,
  683. tags: this.currentSnippetTags
  684. };
  685. xmlHttp.send(JSON.stringify(dataToSend));
  686. };
  687. askForSave() {
  688. if (this.currentSnippetTitle == null
  689. || this.currentSnippetDescription == null
  690. || this.currentSnippetTags == null) {
  691. document.getElementById("saveLayer").style.display = "block";
  692. }
  693. else {
  694. this.save();
  695. }
  696. };
  697. askForDiff() {
  698. const diffLayer = document.getElementById("diffLayer");
  699. const right = document.getElementById("diffFormCompareTo");
  700. if (this.previousHash && right.value === "") {
  701. // Use the previous snippet hash for right comparison, if present
  702. right.value = this.previousHash;
  703. }
  704. diffLayer.style.display = "block";
  705. }
  706. async loadSnippetCode(snippetid) {
  707. if (!snippetid || snippetid === "")
  708. return "";
  709. let response = await fetch(`${this.snippetV3Url}/${snippetid.replace(/#/g, "/")}`);
  710. if (!response.ok)
  711. throw new Error(`Unable to load snippet ${snippetid}`)
  712. let result = await response.json();
  713. return JSON.parse(result.jsonPayload).code.toString();
  714. }
  715. async getSnippetCode(value) {
  716. if (!value || value === "") {
  717. // use current snippet
  718. return this.parent.monacoCreator.JsEditor.getValue();
  719. } else {
  720. // load script
  721. return await this.loadSnippetCode(value);
  722. }
  723. }
  724. async diff() {
  725. try {
  726. const leftText = await this.getSnippetCode(document.getElementById("diffFormSource").value);
  727. const rightText = await this.getSnippetCode(document.getElementById("diffFormCompareTo").value);
  728. this.toggleDiffEditor(this.parent.monacoCreator, this.parent.menuPG, leftText, rightText);
  729. } catch(e) {
  730. // only pass the message, we don't want to inspect the stacktrace in this case
  731. this.parent.utils.showError(e.message, null);
  732. }
  733. }
  734. toggleDiffEditor(monacoCreator, menuPG, leftText, rightText) {
  735. const diffView = document.getElementById("diffView");
  736. if (leftText && rightText) {
  737. menuPG.resizeForDiff();
  738. diffView.style.display = "block";
  739. monacoCreator.createDiff(leftText, rightText, diffView);
  740. } else {
  741. monacoCreator.disposeDiff();
  742. diffView.style.display = "none";
  743. if (menuPG.navBarMobile.offsetHeight > 0) {
  744. menuPG.resizeBigJsEditor();
  745. } else {
  746. menuPG.resizeSplitted();
  747. }
  748. }
  749. }
  750. navigateToPrevious() {
  751. var dn = this.parent.monacoCreator.diffNavigator;
  752. if (!dn)
  753. return;
  754. if (dn.canNavigate())
  755. dn.previous();
  756. }
  757. navigateToNext() {
  758. var dn = this.parent.monacoCreator.diffNavigator;
  759. if (!dn)
  760. return;
  761. if (dn.canNavigate())
  762. dn.next();
  763. }
  764. /**
  765. * Toggle the code editor
  766. */
  767. toggleEditor() {
  768. var editorButton = document.getElementById("editorButton1280");
  769. var scene = engine.scenes[0];
  770. // If the editor is present
  771. if (editorButton.classList.contains('checked')) {
  772. this.parent.utils.setToMultipleID("editorButton", "removeClass", 'checked');
  773. this.parent.splitInstance.collapse(0);
  774. this.parent.utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square" aria-hidden="true"></i>');
  775. } else {
  776. this.parent.utils.setToMultipleID("editorButton", "addClass", 'checked');
  777. this.parent.splitInstance.setSizes([50, 50]); // Reset
  778. this.parent.utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  779. }
  780. engine.resize();
  781. if (scene.debugLayer.isVisible()) {
  782. scene.debugLayer.show({ embedMode: true });
  783. }
  784. };
  785. /**
  786. * Toggle the BJS debug layer
  787. */
  788. toggleDebug() {
  789. // Always showing the debug layer, because you can close it by itself
  790. var scene = engine.scenes[0];
  791. if (scene.debugLayer.isVisible()) {
  792. scene.debugLayer.hide();
  793. }
  794. else {
  795. scene.debugLayer.show({ embedMode: true });
  796. }
  797. };
  798. /**
  799. * HASH part
  800. */
  801. cleanHash() {
  802. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  803. if (splits.length > 2) {
  804. splits.splice(2, splits.length - 2);
  805. }
  806. location.hash = splits.join("#");
  807. };
  808. checkHash() {
  809. if (location.hash) {
  810. if (this.previousHash !== location.hash) {
  811. this.cleanHash();
  812. this.previousHash = location.hash;
  813. try {
  814. var xmlHttp = new XMLHttpRequest();
  815. xmlHttp.onreadystatechange = function () {
  816. if (xmlHttp.readyState === 4) {
  817. if (xmlHttp.status === 200) {
  818. if (!this.checkTypescriptSupport(xmlHttp)) {
  819. return;
  820. }
  821. var snippet = JSON.parse(xmlHttp.responseText);
  822. this.parent.monacoCreator.BlockEditorChange = true;
  823. this.parent.monacoCreator.JsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  824. // Check if title / descr / tags are already set
  825. if (snippet.name != null && snippet.name != "") {
  826. this.currentSnippetTitle = snippet.name;
  827. }
  828. else this.currentSnippetTitle = null;
  829. if (snippet.description != null && snippet.description != "") {
  830. this.currentSnippetDescription = snippet.description;
  831. }
  832. else this.currentSnippetDescription = null;
  833. if (snippet.tags != null && snippet.tags != "") {
  834. this.currentSnippetTags = snippet.tags;
  835. }
  836. else this.currentSnippetTags = null;
  837. if (this.currentSnippetTitle != null && this.currentSnippetTags != null && this.currentSnippetDescription) {
  838. if (document.getElementById("saveLayer")) {
  839. document.getElementById("saveFormTitle").value = this.currentSnippetTitle;
  840. document.getElementById("saveFormDescription").value = this.currentSnippetDescription;
  841. document.getElementById("saveFormTags").value = this.currentSnippetTags;
  842. this.hideNoMetadata();
  843. }
  844. }
  845. else {
  846. this.showNoMetadata();
  847. }
  848. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  849. this.parent.monacoCreator.BlockEditorChange = false;
  850. compileAndRun(this.parent, this.fpsLabel);
  851. }
  852. }
  853. }.bind(this);
  854. var hash = location.hash.substr(1);
  855. this.currentSnippetToken = hash.split("#")[0];
  856. if (!hash.split("#")[1]) hash += "#0";
  857. xmlHttp.open("GET", this.snippetV3Url + "/" + hash.replace("#", "/"));
  858. xmlHttp.send();
  859. } catch (e) {
  860. }
  861. }
  862. }
  863. setTimeout(this.checkHash.bind(this), 200);
  864. };
  865. }