main.js 48 KB

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