mainWebGPU.js 42 KB

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