main.js 40 KB

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