main.js 51 KB

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