mainWebGPU.js 41 KB

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