main.js 40 KB

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