main.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. /**
  2. * This JS file contains the main function
  3. */
  4. class Main {
  5. constructor(parent) {
  6. this.parent = parent;
  7. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  8. this.snippetV3Url = "https://snippet.babylonjs.com"
  9. this.currentSnippetToken;
  10. this.currentSnippetTitle = null;
  11. this.currentSnippetDescription = null;
  12. this.currentSnippetTags = null;
  13. this.engine = null;
  14. this.fpsLabel = document.getElementById("fpsLabel");
  15. this.scripts;
  16. this.previousHash = "";
  17. }
  18. /**
  19. * First function to initialize the script
  20. */
  21. initialize() {
  22. this.parent.monacoCreator.loadMonaco();
  23. };
  24. /**
  25. * Main function of the app
  26. */
  27. run() {
  28. // TO DO - Rewrite this with unpkg.com
  29. if (location.href.indexOf("indexStable") !== -1) {
  30. this.parent.utils.setToMultipleID("currentVersion", "innerHTML", "v.3.0");
  31. } else {
  32. this.parent.utils.setToMultipleID("currentVersion", "innerHTML", "v.4.0");
  33. }
  34. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  35. document.getElementById("saveLayer").style.display = "none";
  36. this.save();
  37. }.bind(this));
  38. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  39. document.getElementById("saveLayer").style.display = "none";
  40. });
  41. // Resize the render view when resizing the window
  42. window.addEventListener("resize",
  43. function () {
  44. if (this.engine) {
  45. this.engine.resize();
  46. }
  47. }.bind(this)
  48. );
  49. // Load scripts list
  50. this.loadScriptsList();
  51. // Check if there a hash in the URL
  52. this.checkHash();
  53. // -------------------- UI --------------------
  54. // TO DO - A proper UI class ?
  55. // Display BJS version
  56. this.parent.utils.setToMultipleID("mainTitle", "innerHTML", "v" + BABYLON.Engine.Version);
  57. // Run
  58. this.parent.utils.setToMultipleID("runButton", "click", this.compileAndRun.bind(this));
  59. // New
  60. this.parent.utils.setToMultipleID("newButton", "click", this.createNewScript.bind(this));
  61. // Clear
  62. this.parent.utils.setToMultipleID("clearButton", "click", this.clear.bind(this));
  63. // Save
  64. this.parent.utils.setToMultipleID("saveButton", "click", this.askForSave.bind(this));
  65. // Zip
  66. this.parent.utils.setToMultipleID("zipButton", "click", function () {
  67. this.parent.zipTool.getZip(this.engine);
  68. }.bind(this));
  69. // Themes
  70. this.parent.utils.setToMultipleID("darkTheme", "click", [this.parent.settingsPG.setTheme.bind(this.parent.settingsPG, 'dark'), this.parent.menuPG.clickOptionSub.bind(this.parent.menuPG)]);
  71. this.parent.utils.setToMultipleID("lightTheme", "click", [this.parent.settingsPG.setTheme.bind(this.parent.settingsPG, 'light'), this.parent.menuPG.clickOptionSub.bind(this.parent.menuPG)]);
  72. // Size
  73. var displayFontSize = document.getElementsByClassName('displayFontSize');
  74. for (var i = 0; i < displayFontSize.length; i++) {
  75. var options = displayFontSize[i].querySelectorAll('.option');
  76. for (var j = 0; j < options.length; j++) {
  77. options[j].addEventListener('click', this.parent.menuPG.clickOptionSub.bind(this.parent.menuPG));
  78. options[j].addEventListener('click', this.parent.settingsPG.setFontSize.bind(this.parent.settingsPG, options[j].innerText));
  79. }
  80. }
  81. // Footer links
  82. var displayFontSize = document.getElementsByClassName('displayFooterLinks');
  83. for (var i = 0; i < displayFontSize.length; i++) {
  84. var options = displayFontSize[i].querySelectorAll('.option');
  85. for (var j = 0; j < options.length; j++) {
  86. options[j].addEventListener('click', this.parent.menuPG.clickOptionSub.bind(this));
  87. }
  88. }
  89. // Language (JS / TS)
  90. this.parent.utils.setToMultipleID("toTSbutton", "click", function () {
  91. this.parent.settingsPG.ScriptLanguage = "TS";
  92. location.reload();
  93. }.bind(this));
  94. this.parent.utils.setToMultipleID("toJSbutton", "click", function () {
  95. this.parent.settingsPG.ScriptLanguage = "JS";
  96. location.reload();
  97. }.bind(this));
  98. // Safe mode
  99. this.parent.utils.setToMultipleID("safemodeToggle", 'click', function () {
  100. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  101. if (document.getElementById("safemodeToggle1280").classList.contains('checked')) {
  102. this.parent.utils.setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  103. } else {
  104. this.parent.utils.setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square" aria-hidden="true"></i>');
  105. }
  106. }.bind(this));
  107. // Editor
  108. this.parent.utils.setToMultipleID("editorButton", "click", this.toggleEditor.bind(this));
  109. // FullScreen
  110. this.parent.utils.setToMultipleID("fullscreenButton", "click", function () {
  111. this.parent.menuPG.goFullscreen(this.engine);
  112. }.bind(this));
  113. // Editor fullScreen
  114. this.parent.utils.setToMultipleID("editorFullscreenButton", "click", this.parent.menuPG.editorGoFullscreen.bind(this.parent.menuPG));
  115. // Format
  116. this.parent.utils.setToMultipleID("formatButton", "click", this.parent.monacoCreator.formatCode.bind(this.parent.monacoCreator));
  117. // Minimap
  118. this.parent.utils.setToMultipleID("minimapToggle", "click", this.parent.monacoCreator.toggleMinimap.bind(this.parent.monacoCreator));
  119. // Debug
  120. this.parent.utils.setToMultipleID("debugButton", "click", this.toggleDebug.bind(this));
  121. // Metadata
  122. this.parent.utils.setToMultipleID("metadataButton", "click", this.parent.menuPG.displayMetadata.bind(this.parent.menuPG));
  123. // Initialize the metadata form
  124. this.showNoMetadata();
  125. // Restore theme
  126. this.parent.settingsPG.restoreTheme();
  127. // Restore font size
  128. this.parent.settingsPG.restoreFont();
  129. // Restore language
  130. this.parent.settingsPG.setScriptLanguage();
  131. // Check if it's mobile mode. If true, switch to full canvas by default
  132. this.parent.menuPG.resizeBigCanvas();
  133. };
  134. /**
  135. * Check if we're in the correct language for the selected script
  136. * @param {*} xhr
  137. */
  138. checkTypescriptSupport(xhr) {
  139. // If we're loading TS content and it's JS page
  140. if (xhr.responseText.indexOf("class Playground") !== -1) {
  141. if (this.parent.settingsPG.ScriptLanguage == "JS") {
  142. this.parent.settingsPG.ScriptLanguage = "TS";
  143. location.reload();
  144. return false;
  145. }
  146. } else { // If we're loading JS content and it's TS page
  147. if (this.parent.settingsPG.ScriptLanguage == "TS") {
  148. this.parent.settingsPG.ScriptLanguage = "JS";
  149. location.reload();
  150. return false;
  151. }
  152. }
  153. return true;
  154. };
  155. /**
  156. * Load a script in the database
  157. * @param {*} scriptURL
  158. * @param {*} title
  159. */
  160. loadScript(scriptURL, title) {
  161. var xhr = new XMLHttpRequest();
  162. xhr.open('GET', scriptURL, true);
  163. xhr.onreadystatechange = function () {
  164. if (xhr.readyState === 4) {
  165. if (xhr.status === 200) {
  166. if (!this.checkTypescriptSupport(xhr)) return;
  167. xhr.onreadystatechange = null;
  168. this.parent.monacoCreator.BlockEditorChange = true;
  169. this.parent.monacoCreator.JsEditor.setValue(xhr.responseText);
  170. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  171. this.parent.monacoCreator.BlockEditorChange = false;
  172. this.compileAndRun();
  173. this.currentSnippetToken = null;
  174. }
  175. }
  176. }.bind(this);
  177. xhr.send(null);
  178. };
  179. /**
  180. * Load the examples scripts list in the database
  181. */
  182. loadScriptsList() {
  183. var exampleList = document.getElementById("exampleList");
  184. var xhr = new XMLHttpRequest();
  185. //Open Typescript or Javascript examples
  186. if (exampleList.className != 'typescript') {
  187. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list.json', true);
  188. }
  189. else {
  190. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list_ts.json', true);
  191. }
  192. xhr.onreadystatechange = function () {
  193. if (xhr.readyState === 4) {
  194. if (xhr.status === 200) {
  195. this.scripts = JSON.parse(xhr.response)["examples"];
  196. function sortScriptsList(a, b) {
  197. if (a.title < b.title) return -1;
  198. else return 1;
  199. }
  200. this.scripts.sort(sortScriptsList);
  201. if (exampleList) {
  202. for (var i = 0; i < this.scripts.length; i++) {
  203. this.scripts[i].samples.sort(sortScriptsList);
  204. var exampleCategory = document.createElement("div");
  205. exampleCategory.classList.add("categoryContainer");
  206. var exampleCategoryTitle = document.createElement("p");
  207. exampleCategoryTitle.innerText = this.scripts[i].title;
  208. exampleCategory.appendChild(exampleCategoryTitle);
  209. for (var ii = 0; ii < this.scripts[i].samples.length; ii++) {
  210. var example = document.createElement("div");
  211. example.classList.add("itemLine");
  212. example.id = ii;
  213. var exampleImg = document.createElement("img");
  214. exampleImg.src = this.scripts[i].samples[ii].icon.replace("icons", "https://doc.babylonjs.com/examples/icons");
  215. exampleImg.setAttribute("onClick", "document.getElementById('PGLink_" + this.scripts[i].samples[ii].PGID + "').click();");
  216. var exampleContent = document.createElement("div");
  217. exampleContent.classList.add("itemContent");
  218. exampleContent.setAttribute("onClick", "document.getElementById('PGLink_" + this.scripts[i].samples[ii].PGID + "').click();");
  219. var exampleContentLink = document.createElement("div");
  220. exampleContentLink.classList.add("itemContentLink");
  221. var exampleTitle = document.createElement("h3");
  222. exampleTitle.classList.add("exampleCategoryTitle");
  223. exampleTitle.innerText = this.scripts[i].samples[ii].title;
  224. var exampleDescr = document.createElement("div");
  225. exampleDescr.classList.add("itemLineChild");
  226. exampleDescr.innerText = this.scripts[i].samples[ii].description;
  227. var exampleDocLink = document.createElement("a");
  228. exampleDocLink.classList.add("itemLineDocLink");
  229. exampleDocLink.innerText = "Documentation";
  230. exampleDocLink.href = this.scripts[i].samples[ii].doc;
  231. exampleDocLink.target = "_blank";
  232. var examplePGLink = document.createElement("a");
  233. examplePGLink.id = "PGLink_" + this.scripts[i].samples[ii].PGID;
  234. examplePGLink.classList.add("itemLinePGLink");
  235. examplePGLink.innerText = "Display";
  236. examplePGLink.href = this.scripts[i].samples[ii].PGID;
  237. exampleContentLink.appendChild(exampleTitle);
  238. exampleContentLink.appendChild(exampleDescr);
  239. exampleContent.appendChild(exampleContentLink);
  240. exampleContent.appendChild(exampleDocLink);
  241. exampleContent.appendChild(examplePGLink);
  242. example.appendChild(exampleImg);
  243. example.appendChild(exampleContent);
  244. exampleCategory.appendChild(example);
  245. }
  246. exampleList.appendChild(exampleCategory);
  247. }
  248. var noResultContainer = document.createElement("div");
  249. noResultContainer.id = "noResultsContainer";
  250. noResultContainer.classList.add("categoryContainer");
  251. noResultContainer.style.display = "none";
  252. noResultContainer.innerHTML = "<p id='noResults'>No results found.</p>";
  253. exampleList.appendChild(noResultContainer);
  254. }
  255. if (!location.hash) {
  256. // Query string
  257. var queryString = window.location.search;
  258. if (queryString) {
  259. var query = queryString.replace("?", "");
  260. index = parseInt(query);
  261. if (!isNaN(index)) {
  262. var newPG = "";
  263. switch (index) {
  264. case 1: newPG = "#TAZ2CB#0"; break; // Basic scene
  265. case 2: newPG = "#A1210C#0"; break; // Basic elements
  266. case 3: newPG = "#CURCZC#0"; break; // Rotation and scaling
  267. case 4: newPG = "#DXARSP#0"; break; // Materials
  268. case 5: newPG = "#1A3M5C#0"; break; // Cameras
  269. case 6: newPG = "#AQRDKW#0"; break; // Lights
  270. case 7: newPG = "#QYFDDP#1"; break; // Animations
  271. case 8: newPG = "#9RI8CG#0"; break; // Sprites
  272. case 9: newPG = "#U8MEB0#0"; break; // Collisions
  273. case 10: newPG = "#KQV9SA#0"; break; // Intersections
  274. case 11: newPG = "#NU4F6Y#0"; break; // Picking
  275. case 12: newPG = "#EF9X5R#0"; break; // Particles
  276. case 13: newPG = "#7G0IQW#0"; break; // Environment
  277. case 14: newPG = "#95PXRY#0"; break; // Height map
  278. case 15: newPG = "#IFYDRS#0"; break; // Shadows
  279. case 16: newPG = "#AQZJ4C#0"; break; // Import meshes
  280. case 17: newPG = "#J19GYK#0"; break; // Actions
  281. case 18: newPG = "#UZ23UH#0"; break; // Drag and drop
  282. case 19: newPG = "#AQZJ4C#0"; break; // Fresnel
  283. case 20: newPG = "#8ZNVGR#0"; break; // Easing functions
  284. case 21: newPG = "#B2ZXG6#0"; break; // Procedural texture
  285. case 22: newPG = "#DXAEUY#0"; break; // Basic sounds
  286. case 23: newPG = "#EDVU95#0"; break; // Sound on mesh
  287. case 24: newPG = "#N96NXC#0"; break; // SSAO rendering pipeline
  288. case 25: newPG = "#7D2QDD#0"; break; // SSAO 2
  289. case 26: newPG = "#V2DAKC#0"; break; // Volumetric light scattering
  290. case 27: newPG = "#XH85A9#0"; break; // Refraction and reflection
  291. case 28: newPG = "#8MGKWK#0"; break; // PBR
  292. case 29: newPG = "#0K8EYN#0"; break; // Instanced bones
  293. case 30: newPG = "#C245A1#0"; break; // Pointer events handling
  294. case 31: newPG = "#TAFSN0#2"; break; // WebVR
  295. case 32: newPG = "#3VMTI9#0"; break; // GUI
  296. case 33: newPG = "#7149G4#0"; break; // Physics
  297. default: newPG = ""; break;
  298. }
  299. window.location.href = location.protocol + "//" + location.host + location.pathname + "#" + newPG;
  300. } else if (query.indexOf("=") === -1) {
  301. this.loadScript("scripts/" + query + ".js", query);
  302. } else {
  303. this.loadScript(this.parent.settingsPG.DefaultScene, "Basic scene");
  304. }
  305. } else {
  306. this.loadScript(this.parent.settingsPG.DefaultScene, "Basic scene");
  307. }
  308. }
  309. // Restore theme
  310. this.parent.settingsPG.restoreTheme(this.parent.monacoCreator);
  311. // Restore language
  312. this.parent.settingsPG.setScriptLanguage();
  313. }
  314. }
  315. }.bind(this);
  316. xhr.send(null);
  317. };
  318. createNewScript() {
  319. // Check if safe mode is on, and ask if it is
  320. if (!this.checkSafeMode("Are you sure you want to create a new playground?")) return;
  321. location.hash = "";
  322. this.currentSnippetToken = null;
  323. this.currentSnippetTitle = null;
  324. this.currentSnippetDescription = null;
  325. this.currentSnippetTags = null;
  326. this.showNoMetadata();
  327. if (this.parent.monacoCreator.monacoMode === "javascript") {
  328. 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};');
  329. } else {
  330. 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}');
  331. }
  332. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 11, column: 0 });
  333. this.parent.monacoCreator.JsEditor.focus();
  334. this.compileAndRun();
  335. };
  336. clear() {
  337. // Check if safe mode is on, and ask if it is
  338. if (!this.checkSafeMode("Are you sure you want to clear the playground?")) return;
  339. location.hash = "";
  340. this.currentSnippetToken = null;
  341. this.parent.monacoCreator.JsEditor.setValue('');
  342. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  343. this.parent.monacoCreator.JsEditor.focus();
  344. };
  345. checkSafeMode(message) {
  346. if (document.getElementById("safemodeToggle" + this.parent.getCurrentSize).classList.contains('checked')) {
  347. let confirm = window.confirm(message);
  348. if (!confirm) {
  349. return false;
  350. } else {
  351. for (var i = 0; i < this.parent.utils.multipleSize.length; i++) {
  352. document.getElementById("safemodeToggle" + this.parent.utils.multipleSize[i]).classList.toggle('checked');
  353. }
  354. return true;
  355. }
  356. } else {
  357. return true;
  358. }
  359. };
  360. /**
  361. * Metadatas form
  362. */
  363. showNoMetadata() {
  364. if (this.currentSnippetTitle) {
  365. document.getElementById("saveFormTitle").value = this.currentSnippetTitle;
  366. document.getElementById("saveFormTitle").readOnly = true;
  367. }
  368. else {
  369. document.getElementById("saveFormTitle").value = '';
  370. document.getElementById("saveFormTitle").readOnly = false;
  371. }
  372. if (this.currentSnippetDescription) {
  373. document.getElementById("saveFormDescription").value = this.currentSnippetDescription;
  374. document.getElementById("saveFormDescription").readOnly = true;
  375. }
  376. else {
  377. document.getElementById("saveFormDescription").value = '';
  378. document.getElementById("saveFormDescription").readOnly = false;
  379. }
  380. if (this.currentSnippetTags) {
  381. document.getElementById("saveFormTags").value = this.currentSnippetTags;
  382. document.getElementById("saveFormTags").readOnly = true;
  383. }
  384. else {
  385. document.getElementById("saveFormTags").value = '';
  386. document.getElementById("saveFormTags").readOnly = false;
  387. }
  388. document.getElementById("saveFormButtons").style.display = "block";
  389. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  390. };
  391. hideNoMetadata() {
  392. document.getElementById("saveFormTitle").readOnly = true;
  393. document.getElementById("saveFormDescription").readOnly = true;
  394. document.getElementById("saveFormTags").readOnly = true;
  395. document.getElementById("saveFormButtonOk").style.display = "none";
  396. this.parent.utils.setToMultipleID("metadataButton", "display", "inline-block");
  397. };
  398. /*
  399. * Metadatas save
  400. */
  401. save() {
  402. // Retrieve title if necessary
  403. if (document.getElementById("saveLayer")) {
  404. this.currentSnippetTitle = document.getElementById("saveFormTitle").value;
  405. this.currentSnippetDescription = document.getElementById("saveFormDescription").value;
  406. this.currentSnippetTags = document.getElementById("saveFormTags").value;
  407. }
  408. var xmlHttp = new XMLHttpRequest();
  409. xmlHttp.onreadystatechange = function () {
  410. if (xmlHttp.readyState === 4) {
  411. if (xmlHttp.status === 200) {
  412. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  413. var snippet = JSON.parse(xmlHttp.responseText);
  414. var newUrl = baseUrl + "#" + snippet.id;
  415. this.currentSnippetToken = snippet.id;
  416. if (snippet.version && snippet.version !== "0") {
  417. newUrl += "#" + snippet.version;
  418. }
  419. location.href = newUrl;
  420. // Hide the complete title & co message
  421. this.hideNoMetadata();
  422. this.compileAndRun();
  423. } else {
  424. this.parent.utils.showError("Unable to save your code. It may be too long.", null);
  425. }
  426. }
  427. }.bind(this);
  428. xmlHttp.open("POST", this.snippetV3Url + (this.currentSnippetToken ? "/" + this.currentSnippetToken : ""), true);
  429. xmlHttp.setRequestHeader("Content-Type", "application/json");
  430. var dataToSend = {
  431. payload: JSON.stringify({
  432. code: this.parent.monacoCreator.JsEditor.getValue()
  433. }),
  434. name: this.currentSnippetTitle,
  435. description: this.currentSnippetDescription,
  436. tags: this.currentSnippetTags
  437. };
  438. xmlHttp.send(JSON.stringify(dataToSend));
  439. };
  440. askForSave() {
  441. if (this.currentSnippetTitle == null
  442. || this.currentSnippetDescription == null
  443. || this.currentSnippetTags == null) {
  444. document.getElementById("saveLayer").style.display = "block";
  445. }
  446. else {
  447. this.save();
  448. }
  449. };
  450. /**
  451. * Compile the script in the editor, and run the preview in the canvas
  452. */
  453. compileAndRun() {
  454. try {
  455. this.parent.menuPG.hideWaitDiv();
  456. if (!BABYLON.Engine.isSupported()) {
  457. this.parent.utils.showError("Your browser does not support WebGL. Please, try to update it, or install a compatible one.", null);
  458. return;
  459. }
  460. var showInspector = false;
  461. this.parent.menuPG.showBJSPGMenu();
  462. this.parent.monacoCreator.JsEditor.updateOptions({ readOnly: false });
  463. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.debugLayer.isVisible()) {
  464. showInspector = true;
  465. }
  466. if (this.engine) {
  467. this.engine.dispose();
  468. this.engine = null;
  469. }
  470. var canvas = document.getElementById("renderCanvas");
  471. document.getElementById("errorZone").style.display = 'none';
  472. document.getElementById("errorZone").innerHTML = "";
  473. document.getElementById("statusBar").innerHTML = "Loading assets... Please wait.";
  474. var checkCamera = true;
  475. var checkSceneCount = true;
  476. var createEngineFunction = "createDefaultEngine";
  477. var createSceneFunction;
  478. this.parent.monacoCreator.getRunCode(function (code) {
  479. // Need these variables for "eval" purpose
  480. var engine = this.engine;
  481. var delayCreateScene = null;
  482. var createScene = null;
  483. var CreateScene = null;
  484. var createscene = null;
  485. var createDefaultEngine = function () {
  486. return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  487. }
  488. var scene;
  489. var defaultEngineZip = "new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true })";
  490. if (code.indexOf("createEngine") !== -1) {
  491. createEngineFunction = "createEngine";
  492. }
  493. // Check for different typos
  494. if (code.indexOf("delayCreateScene") !== -1) { // createScene
  495. createSceneFunction = "delayCreateScene";
  496. checkCamera = false;
  497. } else if (code.indexOf("createScene") !== -1) { // createScene
  498. createSceneFunction = "createScene";
  499. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  500. createSceneFunction = "CreateScene";
  501. } else if (code.indexOf("createscene") !== -1) { // createscene
  502. createSceneFunction = "createscene";
  503. }
  504. if (!createSceneFunction) {
  505. // Just pasted code.
  506. engine = createDefaultEngine();
  507. scene = new BABYLON.Scene(engine);
  508. eval("runScript = function(scene, canvas) {" + code + "}");
  509. runScript(scene, canvas);
  510. this.parent.zipTool.ZipCode = "var engine = " + defaultEngineZip + ";\r\nvar scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  511. } else {
  512. var startCar = code.search('var ' + createSceneFunction);
  513. code = code.substr(0, startCar) + code.substr(startCar + 4);
  514. // Execute the code
  515. eval(code);
  516. // Create engine
  517. eval("engine = " + createEngineFunction + "()");
  518. if (!engine) {
  519. this.parent.utils.showError("createEngine function must return an engine.", null);
  520. return;
  521. }
  522. // Create scene
  523. eval("scene = " + createSceneFunction + "()");
  524. if (!scene) {
  525. this.parent.utils.showError(createSceneFunction + " function must return a scene.", null);
  526. return;
  527. }
  528. // if scene returns a promise avoid checks
  529. if (scene.then) {
  530. checkCamera = false;
  531. checkSceneCount = false;
  532. }
  533. var createEngineZip = (createEngineFunction === "createEngine")
  534. ? "createEngine()"
  535. : defaultEngineZip;
  536. this.parent.zipTool.zipCode =
  537. code + "\r\n\r\n" +
  538. "var engine = " + createEngineZip + ";\r\n" +
  539. "var scene = " + createSceneFunction + "();";
  540. }
  541. this.engine = engine;
  542. this.engine.runRenderLoop(function () {
  543. if (this.engine.scenes.length === 0) {
  544. return;
  545. }
  546. if (canvas.width !== canvas.clientWidth) {
  547. this.engine.resize();
  548. }
  549. var scene = this.engine.scenes[0];
  550. if (scene.activeCamera || scene.activeCameras.length > 0) {
  551. scene.render();
  552. }
  553. this.fpsLabel.innerHTML = this.engine.getFps().toFixed() + " fps";
  554. }.bind(this));
  555. if (checkSceneCount && this.engine.scenes.length === 0) {
  556. this.parent.utils.showError("You must at least create a scene.", null);
  557. return;
  558. }
  559. if (checkCamera && this.engine.scenes[0].activeCamera == null) {
  560. this.parent.utils.showError("You must at least create a camera.", null);
  561. return;
  562. } else if (scene.then) {
  563. scene.then(function () {
  564. document.getElementById("statusBar").innerHTML = "";
  565. });
  566. } else {
  567. this.engine.scenes[0].executeWhenReady(function () {
  568. document.getElementById("statusBar").innerHTML = "";
  569. });
  570. }
  571. if (scene) {
  572. if (showInspector) {
  573. if (scene.then) {
  574. // Handle if scene is a promise
  575. scene.then(function (s) {
  576. if (!s.debugLayer.isVisible()) {
  577. s.debugLayer.show({ embedMode: true });
  578. }
  579. })
  580. } else {
  581. if (!scene.debugLayer.isVisible()) {
  582. scene.debugLayer.show({ embedMode: true });
  583. }
  584. }
  585. }
  586. }
  587. }.bind(this));
  588. } catch (e) {
  589. this.parent.utils.showError(e.message, e);
  590. // Also log error in console to help debug playgrounds
  591. console.error(e);
  592. }
  593. };
  594. /**
  595. * BJS version
  596. */
  597. // TO DO - Rewrite this with unpkg.com
  598. setVersion(version) {
  599. // switch (version) {
  600. // case "stable":
  601. // location.href = "indexStable.html" + location.hash;
  602. // break;
  603. // default:
  604. // location.href = "index.html" + location.hash;
  605. // break;
  606. // }
  607. };
  608. /**
  609. * Toggle the code editor
  610. */
  611. toggleEditor() {
  612. var editorButton = document.getElementById("editorButton1280");
  613. var scene = this.engine.scenes[0];
  614. // If the editor is present
  615. if (editorButton.classList.contains('checked')) {
  616. this.parent.utils.setToMultipleID("editorButton", "removeClass", 'checked');
  617. this.parent.splitInstance.collapse(0);
  618. this.parent.utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square" aria-hidden="true"></i>');
  619. } else {
  620. this.parent.utils.setToMultipleID("editorButton", "addClass", 'checked');
  621. this.parent.splitInstance.setSizes([50, 50]); // Reset
  622. this.parent.utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  623. }
  624. this.engine.resize();
  625. if (scene.debugLayer.isVisible()) {
  626. scene.debugLayer.show({ embedMode: true });
  627. }
  628. };
  629. /**
  630. * Toggle the BJS debug layer
  631. */
  632. toggleDebug() {
  633. // Always showing the debug layer, because you can close it by itself
  634. var scene = this.engine.scenes[0];
  635. if (scene.debugLayer.isVisible()) {
  636. scene.debugLayer.hide();
  637. }
  638. else {
  639. scene.debugLayer.show({ embedMode: true });
  640. }
  641. };
  642. /**
  643. * HASH part
  644. */
  645. cleanHash() {
  646. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  647. if (splits.length > 2) {
  648. splits.splice(2, splits.length - 2);
  649. }
  650. location.hash = splits.join("#");
  651. };
  652. checkHash() {
  653. if (location.hash) {
  654. if (this.previousHash !== location.hash) {
  655. this.cleanHash();
  656. this.previousHash = location.hash;
  657. try {
  658. var xmlHttp = new XMLHttpRequest();
  659. xmlHttp.onreadystatechange = function () {
  660. if (xmlHttp.readyState === 4) {
  661. if (xmlHttp.status === 200) {
  662. if (!this.checkTypescriptSupport(xmlHttp)) {
  663. return;
  664. }
  665. var snippet = JSON.parse(xmlHttp.responseText);
  666. this.parent.monacoCreator.BlockEditorChange = true;
  667. this.parent.monacoCreator.JsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  668. // Check if title / descr / tags are already set
  669. if (snippet.name != null && snippet.name != "") {
  670. this.currentSnippetTitle = snippet.name;
  671. }
  672. else this.currentSnippetTitle = null;
  673. if (snippet.description != null && snippet.description != "") {
  674. this.currentSnippetDescription = snippet.description;
  675. }
  676. else this.currentSnippetDescription = null;
  677. if (snippet.tags != null && snippet.tags != "") {
  678. this.currentSnippetTags = snippet.tags;
  679. }
  680. else this.currentSnippetTags = null;
  681. if (this.currentSnippetTitle != null && this.currentSnippetTags != null && this.currentSnippetDescription) {
  682. if (document.getElementById("saveLayer")) {
  683. document.getElementById("saveFormTitle").value = this.currentSnippetTitle;
  684. document.getElementById("saveFormDescription").value = this.currentSnippetDescription;
  685. document.getElementById("saveFormTags").value = this.currentSnippetTags;
  686. this.hideNoMetadata();
  687. }
  688. }
  689. else {
  690. this.showNoMetadata();
  691. }
  692. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  693. this.parent.monacoCreator.BlockEditorChange = false;
  694. this.compileAndRun();
  695. }
  696. }
  697. }.bind(this);
  698. var hash = location.hash.substr(1);
  699. this.currentSnippetToken = hash.split("#")[0];
  700. if (!hash.split("#")[1]) hash += "#0";
  701. xmlHttp.open("GET", this.snippetV3Url + "/" + hash.replace("#", "/"));
  702. xmlHttp.send();
  703. } catch (e) {
  704. }
  705. }
  706. }
  707. setTimeout(this.checkHash.bind(this), 200);
  708. };
  709. }