main.js 52 KB

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