main.js 49 KB

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