index.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. var jsEditor;
  2. var defaultScene = "scripts/basic scene.js";
  3. var monacoMode = "javascript";
  4. var scriptLanguage = localStorage.getItem("bjs-playground-scriptLanguage") || 'JS';
  5. if (scriptLanguage == "JS") {
  6. defaultScene = "scripts/basic scene.js";
  7. monacoMode = "javascript";
  8. }
  9. else if (scriptLanguage == "TS") {
  10. defaultScene = "scripts/basic scene.txt";
  11. monacoMode = "typescript";
  12. var compilerTriggerTimeoutID;
  13. function triggerCompile(d, func) {
  14. if (compilerTriggerTimeoutID !== null) {
  15. window.clearTimeout(compilerTriggerTimeoutID);
  16. }
  17. compilerTriggerTimeoutID = window.setTimeout(function () {
  18. try {
  19. var output = transpileModule(d, {
  20. module: ts.ModuleKind.AMD,
  21. target: ts.ScriptTarget.ES5,
  22. noLib: true,
  23. noResolve: true,
  24. suppressOutputPathCheck: true
  25. });
  26. if (typeof output === "string") {
  27. func(output);
  28. }
  29. }
  30. catch (e) {
  31. showError(e.message, e);
  32. }
  33. }, 100);
  34. }
  35. function transpileModule(input, options) {
  36. var inputFileName = options.jsx ? "module.tsx" : "module.ts";
  37. var sourceFile = ts.createSourceFile(inputFileName, input, options.target || ts.ScriptTarget.ES5);
  38. // Output
  39. var outputText;
  40. var program = ts.createProgram([inputFileName], options, {
  41. getSourceFile: function (fileName) { return fileName.indexOf("module") === 0 ? sourceFile : undefined; },
  42. writeFile: function (_name, text) { outputText = text; },
  43. getDefaultLibFileName: function () { return "lib.d.ts"; },
  44. useCaseSensitiveFileNames: function () { return false; },
  45. getCanonicalFileName: function (fileName) { return fileName; },
  46. getCurrentDirectory: function () { return ""; },
  47. getNewLine: function () { return "\r\n"; },
  48. fileExists: function (fileName) { return fileName === inputFileName; },
  49. readFile: function () { return ""; },
  50. directoryExists: function () { return true; },
  51. getDirectories: function () { return []; }
  52. });
  53. // Emit
  54. program.emit();
  55. if (outputText === undefined) {
  56. throw new Error("Output generation failed");
  57. }
  58. return outputText;
  59. }
  60. function getRunCode(jsEditor, callBack) {
  61. triggerCompile(jsEditor.getValue(), function (result) {
  62. callBack(result + "var createScene = function() { return Playground.CreateScene(engine, engine.getRenderingCanvas()); }")
  63. });
  64. }
  65. }
  66. function getRunCode(jsEditor, callBack) {
  67. var code = jsEditor.getValue();
  68. callBack(code);
  69. }
  70. function showError(errorMessage, errorEvent) {
  71. var errorContent =
  72. '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button>';
  73. if (errorEvent) {
  74. var regEx = /\(.+:(\d+):(\d+)\)\n/g;
  75. var match = regEx.exec(errorEvent.stack);
  76. if (match) {
  77. errorContent += "Line ";
  78. var lineNumber = match[1];
  79. var columnNumber = match[2];
  80. errorContent += lineNumber + ':' + columnNumber + ' - ';
  81. }
  82. }
  83. errorContent += errorMessage + '</div>';
  84. document.getElementById("errorZone").style.display = 'block';
  85. document.getElementById("errorZone").innerHTML = errorContent;
  86. // Close button error
  87. document.getElementById("errorZone").querySelector('.close').addEventListener('click', function () {
  88. document.getElementById("errorZone").style.display = 'none';
  89. });
  90. }
  91. (function () {
  92. var multipleSize = [1280, 920, 710, 550];
  93. var setToMultipleID = function (id, thingToDo, param) {
  94. multipleSize.forEach(function (size) {
  95. if (thingToDo == "innerHTML") {
  96. document.getElementById(id + size).innerHTML = param
  97. }
  98. else if (thingToDo == "click") {
  99. if (param.length > 1) {
  100. for (var i = 0; i < param.length; i++) {
  101. document.getElementById(id + size).addEventListener("click", param[i]);
  102. }
  103. }
  104. else
  105. document.getElementById(id + size).addEventListener("click", param);
  106. }
  107. else if (thingToDo == "addClass") {
  108. document.getElementById(id + size).classList.add(param);
  109. }
  110. else if (thingToDo == "removeClass") {
  111. document.getElementById(id + size).classList.remove(param);
  112. }
  113. else if (thingToDo == "display") {
  114. document.getElementById(id + size).style.display = param;
  115. }
  116. });
  117. };
  118. var editorOptions;
  119. var fontSize = 14;
  120. var splitInstance = Split(['#jsEditor', '#canvasZone']);
  121. var elementForscriptLanguage = [
  122. '#exampleList #exampleBanner',
  123. '.navbar',
  124. '.navbar .category',
  125. '.navbar .select .toDisplay',
  126. '.navbar .select .toDisplay .subSelect .toDisplaySub',
  127. '#fpsLabel',
  128. '.save-form'
  129. ];
  130. var elementToTheme = [
  131. '.wrapper #jsEditor',
  132. '.wrapper .gutter'
  133. ];
  134. var run = function () {
  135. // #region - Examples playgrounds
  136. var examplesButton = document.getElementsByClassName("examplesButton");
  137. if (examplesButton && examplesButton.length > 0) {
  138. var isExamplesDisplayed = false;
  139. for (var i = 0; i < examplesButton.length; i++) {
  140. examplesButton[i].parentElement.onclick = function () {
  141. isExamplesDisplayed = !isExamplesDisplayed;
  142. if (isExamplesDisplayed) {
  143. document.getElementById("fpsLabel").style.display = "none";
  144. document.getElementById("exampleList").style.display = "block";
  145. document.getElementsByClassName("wrapper")[0].style.width = "calc(100% - 400px)";
  146. }
  147. else {
  148. document.getElementById("fpsLabel").style.display = "block";
  149. document.getElementById("exampleList").style.display = "none";
  150. document.getElementsByClassName("wrapper")[0].style.width = "100%";
  151. }
  152. }
  153. }
  154. }
  155. var filterBar = document.getElementById("filterBar");
  156. if (filterBar) {
  157. var filterBarClear = document.getElementById("filterBarClear");
  158. var filter = function () {
  159. var filterText = filterBar.value.toLowerCase();
  160. if (filterText == "") filterBarClear.style.display = "none";
  161. else filterBarClear.style.display = "inline-block";
  162. var lines = document.getElementsByClassName("itemLine");
  163. for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) {
  164. var line = lines[lineIndex];
  165. if (line.innerText.toLowerCase().indexOf(filterText) > -1) {
  166. line.style.display = "";
  167. } else {
  168. line.style.display = "none";
  169. }
  170. }
  171. var categories = document.getElementsByClassName("categoryContainer");
  172. var displayCount = categories.length;
  173. for (var categoryIndex = 0; categoryIndex < categories.length; categoryIndex++) {
  174. var category = categories[categoryIndex];
  175. category.style.display = "block";
  176. if (category.clientHeight < 25) {
  177. category.style.display = "none";
  178. displayCount--;
  179. }
  180. }
  181. if (displayCount == 0) document.getElementById("noResultsContainer").style.display = "block";
  182. else document.getElementById("noResultsContainer").style.display = "none";
  183. }
  184. filterBar.oninput = function () {
  185. filter();
  186. }
  187. filterBarClear.onclick = function () {
  188. filterBar.value = "";
  189. filter();
  190. }
  191. }
  192. // #endregion
  193. var blockEditorChange = false;
  194. var markDirty = function () {
  195. if (blockEditorChange) {
  196. return;
  197. }
  198. // setToMultipleID("currentScript", "innerHTML", "Custom");
  199. setToMultipleID("safemodeToggle", "addClass", "checked");
  200. // setToMultipleID("minimapToggle", "addClass", "checked"); // Why ?!
  201. setToMultipleID('safemodeToggle', 'innerHTML', 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  202. }
  203. jsEditor.onKeyUp(function (evt) {
  204. markDirty();
  205. });
  206. var snippetV3Url = "https://snippet.babylonjs.com"
  207. var currentSnippetToken;
  208. var currentSnippetTitle = null;
  209. var currentSnippetDescription = null;
  210. var currentSnippetTags = null;
  211. var engine;
  212. var fpsLabel = document.getElementById("fpsLabel");
  213. var scripts;
  214. var zipCode;
  215. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  216. // TO DO : Rewrite this with unpkg.com
  217. if (location.href.indexOf("indexStable") !== -1) {
  218. setToMultipleID("currentVersion", "innerHTML", "v.3.0");
  219. } else {
  220. setToMultipleID("currentVersion", "innerHTML", "v.4.0");
  221. }
  222. var checkTypescriptSupport = function (xhr) {
  223. // If we're loading TS content and it's JS page
  224. if (xhr.responseText.indexOf("class Playground") !== -1) {
  225. if (scriptLanguage == "JS") {
  226. localStorage.setItem("bjs-playground-scriptLanguage", "TS");
  227. if (confirm("You need to reload the page to switch to Typescript. Do you want to reload now ?"))
  228. location.reload();
  229. return false;
  230. }
  231. } else { // If we're loading JS content and it's TS page
  232. if (scriptLanguage == "TS") {
  233. localStorage.setItem("bjs-playground-scriptLanguage", "JS");
  234. if (confirm("You need to reload the page to switch to Javascript. Do you want to reload now ?"))
  235. location.reload();
  236. return false;
  237. }
  238. }
  239. return true;
  240. }
  241. var loadScript = function (scriptURL, title) {
  242. var xhr = new XMLHttpRequest();
  243. xhr.open('GET', scriptURL, true);
  244. xhr.onreadystatechange = function () {
  245. if (xhr.readyState === 4) {
  246. if (xhr.status === 200) {
  247. if (!checkTypescriptSupport(xhr)) {
  248. return;
  249. }
  250. xhr.onreadystatechange = null;
  251. blockEditorChange = true;
  252. jsEditor.setValue(xhr.responseText);
  253. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  254. blockEditorChange = false;
  255. compileAndRun();
  256. // setToMultipleID("currentScript", "innerHTML", title);
  257. currentSnippetToken = null;
  258. }
  259. }
  260. };
  261. xhr.send(null);
  262. };
  263. var loadScriptsList = function () {
  264. var exampleList = document.getElementById("exampleList");
  265. var xhr = new XMLHttpRequest();
  266. //Open Typescript or Javascript examples
  267. if (exampleList.className != 'typescript') {
  268. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list.json', true);
  269. }
  270. else {
  271. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list_ts.json', true);
  272. }
  273. xhr.onreadystatechange = function () {
  274. if (xhr.readyState === 4) {
  275. if (xhr.status === 200) {
  276. scripts = JSON.parse(xhr.response)["examples"];
  277. function sortScriptsList(a, b) {
  278. if (a.title < b.title) return -1;
  279. else return 1;
  280. return 0;
  281. }
  282. scripts.sort(sortScriptsList);
  283. if (exampleList) {
  284. for (var i = 0; i < scripts.length; i++) {
  285. scripts[i].samples.sort(sortScriptsList);
  286. var exampleCategory = document.createElement("div");
  287. exampleCategory.classList.add("categoryContainer");
  288. var exampleCategoryTitle = document.createElement("p");
  289. exampleCategoryTitle.innerText = scripts[i].title;
  290. exampleCategory.appendChild(exampleCategoryTitle);
  291. for (var ii = 0; ii < scripts[i].samples.length; ii++) {
  292. var example = document.createElement("div");
  293. example.classList.add("itemLine");
  294. example.id = ii;
  295. var exampleImg = document.createElement("img");
  296. exampleImg.src = scripts[i].samples[ii].icon.replace("icons", "https://doc.babylonjs.com/examples/icons");
  297. exampleImg.setAttribute("onClick", "document.getElementById('PGLink_" + scripts[i].samples[ii].PGID + "').click();");
  298. var exampleContent = document.createElement("div");
  299. exampleContent.classList.add("itemContent");
  300. exampleContent.setAttribute("onClick", "document.getElementById('PGLink_" + scripts[i].samples[ii].PGID + "').click();");
  301. var exampleContentLink = document.createElement("div");
  302. exampleContentLink.classList.add("itemContentLink");
  303. var exampleTitle = document.createElement("h3");
  304. exampleTitle.classList.add("exampleCategoryTitle");
  305. exampleTitle.innerText = scripts[i].samples[ii].title;
  306. var exampleDescr = document.createElement("div");
  307. exampleDescr.classList.add("itemLineChild");
  308. exampleDescr.innerText = scripts[i].samples[ii].description;
  309. var exampleDocLink = document.createElement("a");
  310. exampleDocLink.classList.add("itemLineDocLink");
  311. exampleDocLink.innerText = "Documentation";
  312. exampleDocLink.href = scripts[i].samples[ii].doc;
  313. exampleDocLink.target = "_blank";
  314. var examplePGLink = document.createElement("a");
  315. examplePGLink.id = "PGLink_" + scripts[i].samples[ii].PGID;
  316. examplePGLink.classList.add("itemLinePGLink");
  317. examplePGLink.innerText = "Display";
  318. examplePGLink.href = scripts[i].samples[ii].PGID;
  319. exampleContentLink.appendChild(exampleTitle);
  320. exampleContentLink.appendChild(exampleDescr);
  321. exampleContent.appendChild(exampleContentLink);
  322. exampleContent.appendChild(exampleDocLink);
  323. exampleContent.appendChild(examplePGLink);
  324. example.appendChild(exampleImg);
  325. example.appendChild(exampleContent);
  326. exampleCategory.appendChild(example);
  327. }
  328. exampleList.appendChild(exampleCategory);
  329. }
  330. var noResultContainer = document.createElement("div");
  331. noResultContainer.id = "noResultsContainer";
  332. noResultContainer.classList.add("categoryContainer");
  333. noResultContainer.style.display = "none";
  334. noResultContainer.innerHTML = "<p id='noResults'>No results found.</p>";
  335. exampleList.appendChild(noResultContainer);
  336. }
  337. if (!location.hash) {
  338. // Query string
  339. var queryString = window.location.search;
  340. if (queryString) {
  341. var query = queryString.replace("?", "");
  342. index = parseInt(query);
  343. if (!isNaN(index)) {
  344. var newPG = "";
  345. switch (index) {
  346. case 1: newPG = "#TAZ2CB#0"; break; // Basic scene
  347. case 2: newPG = "#A1210C#0"; break; // Basic elements
  348. case 3: newPG = "#CURCZC#0"; break; // Rotation and scaling
  349. case 4: newPG = "#DXARSP#0"; break; // Materials
  350. case 5: newPG = "#1A3M5C#0"; break; // Cameras
  351. case 6: newPG = "#AQRDKW#0"; break; // Lights
  352. case 7: newPG = "#QYFDDP#1"; break; // Animations
  353. case 8: newPG = "#9RI8CG#0"; break; // Sprites
  354. case 9: newPG = "#U8MEB0#0"; break; // Collisions
  355. case 10: newPG = "#KQV9SA#0"; break; // Intersections
  356. case 11: newPG = "#NU4F6Y#0"; break; // Picking
  357. case 12: newPG = "#EF9X5R#0"; break; // Particles
  358. case 13: newPG = "#7G0IQW#0"; break; // Environment
  359. case 14: newPG = "#95PXRY#0"; break; // Height map
  360. case 15: newPG = "#IFYDRS#0"; break; // Shadows
  361. case 16: newPG = "#AQZJ4C#0"; break; // Import meshes
  362. case 17: newPG = "#J19GYK#0"; break; // Actions
  363. case 18: newPG = "#UZ23UH#0"; break; // Drag and drop
  364. case 19: newPG = "#AQZJ4C#0"; break; // Fresnel
  365. case 20: newPG = "#8ZNVGR#0"; break; // Easing functions
  366. case 21: newPG = "#B2ZXG6#0"; break; // Procedural texture
  367. case 22: newPG = "#DXAEUY#0"; break; // Basic sounds
  368. case 23: newPG = "#EDVU95#0"; break; // Sound on mesh
  369. case 24: newPG = "#N96NXC#0"; break; // SSAO rendering pipeline
  370. case 25: newPG = "#7D2QDD#0"; break; // SSAO 2
  371. case 26: newPG = "#V2DAKC#0"; break; // Volumetric light scattering
  372. case 27: newPG = "#XH85A9#0"; break; // Refraction and reflection
  373. case 28: newPG = "#8MGKWK#0"; break; // PBR
  374. case 29: newPG = "#0K8EYN#0"; break; // Instanced bones
  375. case 30: newPG = "#C245A1#0"; break; // Pointer events handling
  376. case 31: newPG = "#TAFSN0#2"; break; // WebVR
  377. case 32: newPG = "#3VMTI9#0"; break; // GUI
  378. case 33: newPG = "#7149G4#0"; break; // Physics
  379. default: newPG = ""; break;
  380. }
  381. window.location.href = location.protocol + "//" + location.host + location.pathname + "#" + newPG;
  382. } else if (query.indexOf("=") === -1) {
  383. loadScript("scripts/" + query + ".js", query);
  384. } else {
  385. loadScript(defaultScene, "Basic scene");
  386. }
  387. } else {
  388. loadScript(defaultScene, "Basic scene");
  389. }
  390. }
  391. // Restore theme
  392. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  393. toggleTheme(theme);
  394. // Restore language
  395. scriptLanguage = localStorage.getItem("bjs-playground-scriptLanguage") || 'JS';
  396. togglescriptLanguage(scriptLanguage);
  397. // Remove editor if window size is less than 850px
  398. var removeEditorForSmallScreen = function () {
  399. if (mq.matches) {
  400. splitInstance.collapse(0);
  401. } else {
  402. splitInstance.setSizes([50, 50]);
  403. }
  404. }
  405. var mq = window.matchMedia("(max-width: 850px)");
  406. mq.addListener(removeEditorForSmallScreen);
  407. }
  408. }
  409. };
  410. xhr.send(null);
  411. }
  412. var createNewScript = function () {
  413. // check if checked is on
  414. let iCanClear = checkSafeMode("Are you sure you want to create a new playground?");
  415. if (!iCanClear) return;
  416. location.hash = "";
  417. currentSnippetToken = null;
  418. currentSnippetTitle = null;
  419. currentSnippetDescription = null;
  420. currentSnippetTags = null;
  421. showNoMetadata();
  422. if (monacoMode === "javascript") {
  423. 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};');
  424. } else {
  425. 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}');
  426. }
  427. jsEditor.setPosition({ lineNumber: 11, column: 0 });
  428. jsEditor.focus();
  429. compileAndRun();
  430. }
  431. var clear = function () {
  432. // check if checked is on
  433. let iCanClear = checkSafeMode("Are you sure you want to clear the playground?");
  434. if (!iCanClear) return;
  435. location.hash = "";
  436. currentSnippetToken = null;
  437. jsEditor.setValue('');
  438. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  439. jsEditor.focus();
  440. }
  441. var checkSafeMode = function (message) {
  442. var safeToggle = document.getElementById("safemodeToggle1280");
  443. if (safeToggle.classList.contains('checked')) {
  444. let confirm = window.confirm(message);
  445. if (!confirm) {
  446. return false;
  447. } else {
  448. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  449. return true;
  450. }
  451. } else {
  452. return true;
  453. }
  454. }
  455. var showNoMetadata = function () {
  456. if (currentSnippetTitle) {
  457. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  458. document.getElementById("saveFormTitle").readOnly = true;
  459. }
  460. else {
  461. document.getElementById("saveFormTitle").value = '';
  462. document.getElementById("saveFormTitle").readOnly = false;
  463. }
  464. if (currentSnippetDescription) {
  465. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  466. document.getElementById("saveFormDescription").readOnly = true;
  467. }
  468. else {
  469. document.getElementById("saveFormDescription").value = '';
  470. document.getElementById("saveFormDescription").readOnly = false;
  471. }
  472. if (currentSnippetTags) {
  473. document.getElementById("saveFormTags").value = currentSnippetTags;
  474. document.getElementById("saveFormTags").readOnly = true;
  475. }
  476. else {
  477. document.getElementById("saveFormTags").value = '';
  478. document.getElementById("saveFormTags").readOnly = false;
  479. }
  480. document.getElementById("saveFormButtons").style.display = "block";
  481. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  482. };
  483. showNoMetadata();
  484. var hideNoMetadata = function () {
  485. document.getElementById("saveFormTitle").readOnly = true;
  486. document.getElementById("saveFormDescription").readOnly = true;
  487. document.getElementById("saveFormTags").readOnly = true;
  488. document.getElementById("saveFormButtonOk").style.display = "none";
  489. setToMultipleID("metadataButton", "display", "inline-block");
  490. };
  491. compileAndRun = function () {
  492. try {
  493. var waitRing = document.getElementById("waitDiv");
  494. if (waitRing) {
  495. waitRing.style.display = "none";
  496. }
  497. if (!BABYLON.Engine.isSupported()) {
  498. showError("Your browser does not support WebGL", null);
  499. return;
  500. }
  501. var showInspector = false;
  502. showBJSPGMenu();
  503. jsEditor.updateOptions({ readOnly: false });
  504. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.debugLayer.isVisible()) {
  505. showInspector = true;
  506. }
  507. if (engine) {
  508. engine.dispose();
  509. engine = null;
  510. }
  511. var canvas = document.getElementById("renderCanvas");
  512. document.getElementById("errorZone").style.display = 'none';
  513. document.getElementById("errorZone").innerHTML = "";
  514. document.getElementById("statusBar").innerHTML = "Loading assets...Please wait";
  515. var checkCamera = true;
  516. var checkSceneCount = true;
  517. var wrappedEval = false;
  518. var createEngineFunction = "createDefaultEngine";
  519. var createSceneFunction;
  520. getRunCode(jsEditor, function (code) {
  521. var createDefaultEngine = function () {
  522. return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  523. }
  524. var scene;
  525. var defaultEngineZip = "new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true })";
  526. if (code.indexOf("createEngine") !== -1) {
  527. createEngineFunction = "createEngine";
  528. }
  529. if (code.indexOf("delayCreateScene") !== -1) { // createScene
  530. createSceneFunction = "delayCreateScene";
  531. checkCamera = false;
  532. } else if (code.indexOf("createScene") !== -1) { // createScene
  533. createSceneFunction = "createScene";
  534. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  535. createSceneFunction = "CreateScene";
  536. } else if (code.indexOf("createscene") !== -1) { // createscene
  537. createSceneFunction = "createscene";
  538. }
  539. if (!createSceneFunction) {
  540. // just pasted code.
  541. engine = createDefaultEngine();
  542. scene = new BABYLON.Scene(engine);
  543. eval("runScript = function(scene, canvas) {" + code + "}");
  544. runScript(scene, canvas);
  545. zipCode = "var engine = " + defaultEngineZip + ";\r\nvar scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  546. } else {
  547. //execute the code
  548. eval(code);
  549. //create engine
  550. eval("engine = " + createEngineFunction + "()");
  551. if (!engine) {
  552. showError("createEngine function must return an engine.", null);
  553. return;
  554. }
  555. //create scene
  556. eval("scene = " + createSceneFunction + "()");
  557. if (!scene) {
  558. showError(createSceneFunction + " function must return a scene.", null);
  559. return;
  560. }
  561. // if scene returns a promise avoid checks
  562. if (scene.then) {
  563. checkCamera = false;
  564. checkSceneCount = false;
  565. }
  566. var createEngineZip = (createEngineFunction === "createEngine")
  567. ? "createEngine()"
  568. : defaultEngineZip;
  569. zipCode =
  570. code + "\r\n\r\n" +
  571. "var engine = " + createEngineZip + ";\r\n" +
  572. "var scene = " + createSceneFunction + "();";
  573. }
  574. engine.runRenderLoop(function () {
  575. if (engine.scenes.length === 0) {
  576. return;
  577. }
  578. if (canvas.width !== canvas.clientWidth) {
  579. engine.resize();
  580. }
  581. var scene = engine.scenes[0];
  582. if (scene.activeCamera || scene.activeCameras.length > 0) {
  583. scene.render();
  584. }
  585. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  586. });
  587. if (checkSceneCount && engine.scenes.length === 0) {
  588. showError("You must at least create a scene.", null);
  589. return;
  590. }
  591. if (checkCamera && engine.scenes[0].activeCamera == null) {
  592. showError("You must at least create a camera.", null);
  593. return;
  594. } else if (scene.then) {
  595. scene.then(function () {
  596. document.getElementById("statusBar").innerHTML = "";
  597. });
  598. } else {
  599. engine.scenes[0].executeWhenReady(function () {
  600. document.getElementById("statusBar").innerHTML = "";
  601. });
  602. }
  603. if (scene) {
  604. if (showInspector) {
  605. if (scene.then) {
  606. // Handle if scene is a promise
  607. scene.then(function (s) {
  608. if (!s.debugLayer.isVisible()) {
  609. s.debugLayer.show({ embedMode: true });
  610. }
  611. })
  612. } else {
  613. if (!scene.debugLayer.isVisible()) {
  614. scene.debugLayer.show({ embedMode: true });
  615. }
  616. }
  617. }
  618. }
  619. });
  620. } catch (e) {
  621. showError(e.message, e);
  622. // Also log error in console to help debug playgrounds
  623. console.error(e);
  624. }
  625. };
  626. window.addEventListener("resize",
  627. function () {
  628. if (engine) {
  629. engine.resize();
  630. }
  631. });
  632. // Load scripts list
  633. loadScriptsList();
  634. // Zip
  635. var addContentToZip = function (zip, name, url, replace, buffer, then) {
  636. if (url.substring(0, 5) == "data:" || url.substring(0, 5) == "http:" || url.substring(0, 5) == "blob:" || url.substring(0, 6) == "https:") {
  637. then();
  638. return;
  639. }
  640. var xhr = new XMLHttpRequest();
  641. xhr.open('GET', url, true);
  642. if (buffer) {
  643. xhr.responseType = "arraybuffer";
  644. }
  645. xhr.onreadystatechange = function () {
  646. if (xhr.readyState === 4) {
  647. if (xhr.status === 200) {
  648. var text;
  649. if (!buffer) {
  650. if (replace) {
  651. var splits = replace.split("\r\n");
  652. for (var index = 0; index < splits.length; index++) {
  653. splits[index] = " " + splits[index];
  654. }
  655. replace = splits.join("\r\n");
  656. text = xhr.responseText.replace("####INJECT####", replace);
  657. } else {
  658. text = xhr.responseText;
  659. }
  660. }
  661. zip.file(name, buffer ? xhr.response : text);
  662. then();
  663. }
  664. }
  665. };
  666. xhr.send(null);
  667. }
  668. var addTexturesToZip = function (zip, index, textures, folder, then) {
  669. if (index === textures.length || !textures[index].name) {
  670. then();
  671. return;
  672. }
  673. if (textures[index].isRenderTarget || textures[index] instanceof BABYLON.DynamicTexture || textures[index].name.indexOf("data:") !== -1) {
  674. addTexturesToZip(zip, index + 1, textures, folder, then);
  675. return;
  676. }
  677. if (textures[index].isCube) {
  678. if (textures[index].name.indexOf("dds") === -1) {
  679. if (textures[index]._extensions) {
  680. for (var i = 0; i < 6; i++) {
  681. textures.push({ name: textures[index].name + textures[index]._extensions[i] });
  682. }
  683. } else if (textures[index]._files) {
  684. for (var i = 0; i < 6; i++) {
  685. textures.push({ name: textures[index]._files[i] });
  686. }
  687. }
  688. }
  689. else {
  690. textures.push({ name: textures[index].name });
  691. }
  692. addTexturesToZip(zip, index + 1, textures, folder, then);
  693. return;
  694. }
  695. if (folder == null) {
  696. folder = zip.folder("textures");
  697. }
  698. var url;
  699. if (textures[index].video) {
  700. url = textures[index].video.currentSrc;
  701. } else {
  702. // url = textures[index].name;
  703. url = textures[index].url ? textures[index].url : textures[index].name;
  704. }
  705. var name = textures[index].name.replace("textures/", "");
  706. // var name = url.substr(url.lastIndexOf("/") + 1);
  707. if (url != null) {
  708. addContentToZip(folder,
  709. name,
  710. url,
  711. null,
  712. true,
  713. function () {
  714. addTexturesToZip(zip, index + 1, textures, folder, then);
  715. });
  716. }
  717. else {
  718. addTexturesToZip(zip, index + 1, textures, folder, then);
  719. }
  720. }
  721. var addImportedFilesToZip = function (zip, index, importedFiles, folder, then) {
  722. if (index === importedFiles.length) {
  723. then();
  724. return;
  725. }
  726. if (!folder) {
  727. folder = zip.folder("scenes");
  728. }
  729. var url = importedFiles[index];
  730. var name = url.substr(url.lastIndexOf("/") + 1);
  731. addContentToZip(folder,
  732. name,
  733. url,
  734. null,
  735. true,
  736. function () {
  737. addImportedFilesToZip(zip, index + 1, importedFiles, folder, then);
  738. });
  739. }
  740. var getZip = function () {
  741. if (engine.scenes.length === 0) {
  742. return;
  743. }
  744. var zip = new JSZip();
  745. var scene = engine.scenes[0];
  746. var textures = scene.textures;
  747. var importedFiles = scene.importedMeshesFiles;
  748. document.getElementById("statusBar").innerHTML = "Creating archive...Please wait";
  749. if (zipCode.indexOf("textures/worldHeightMap.jpg") !== -1) {
  750. textures.push({ name: "textures/worldHeightMap.jpg" });
  751. }
  752. addContentToZip(zip,
  753. "index.html",
  754. "zipContent/index.html",
  755. zipCode,
  756. false,
  757. function () {
  758. addTexturesToZip(zip,
  759. 0,
  760. textures,
  761. null,
  762. function () {
  763. addImportedFilesToZip(zip,
  764. 0,
  765. importedFiles,
  766. null,
  767. function () {
  768. var blob = zip.generate({ type: "blob" });
  769. saveAs(blob, "sample.zip");
  770. document.getElementById("statusBar").innerHTML = "";
  771. });
  772. });
  773. });
  774. }
  775. // Versions
  776. setVersion = function (version) {
  777. switch (version) {
  778. case "stable":
  779. location.href = "indexStable.html" + location.hash;
  780. break;
  781. default:
  782. location.href = "index.html" + location.hash;
  783. break;
  784. }
  785. }
  786. // Fonts
  787. setFontSize = function (size) {
  788. fontSize = size;
  789. jsEditor.updateOptions({ fontSize: size });
  790. var array = document.getElementsByClassName("displayFontSize");
  791. for (var i = 0; i < array.length; i++) {
  792. var subArray = array[i].children;
  793. for (var j = 0; j < subArray.length; j++) {
  794. subArray[j].classList.remove("selected");
  795. if (subArray[j].innerText == size) subArray[j].classList.add("selected");
  796. }
  797. }
  798. };
  799. showQRCode = function () {
  800. $("#qrCodeImage").empty();
  801. var playgroundCode = window.location.href.split("#");
  802. playgroundCode.shift();
  803. $("#qrCodeImage").qrcode({ text: "https://playground.babylonjs.com/frame.html#" + (playgroundCode.join("#")) });
  804. };
  805. // Fullscreen
  806. document.getElementById("renderCanvas").addEventListener("webkitfullscreenchange", function () {
  807. if (document.webkitIsFullScreen) goFullPage();
  808. else exitFullPage();
  809. }, false);
  810. var goFullPage = function () {
  811. var canvasElement = document.getElementById("renderCanvas");
  812. canvasElement.style.position = "absolute";
  813. canvasElement.style.top = 0;
  814. canvasElement.style.left = 0;
  815. canvasElement.style.zIndex = 100;
  816. }
  817. var exitFullPage = function () {
  818. document.getElementById("renderCanvas").style.position = "relative";
  819. document.getElementById("renderCanvas").style.zIndex = 0;
  820. }
  821. var goFullscreen = function () {
  822. if (engine) {
  823. engine.switchFullscreen(true);
  824. }
  825. }
  826. var editorGoFullscreen = function () {
  827. var editorDiv = document.getElementById("jsEditor");
  828. if (editorDiv.requestFullscreen) {
  829. editorDiv.requestFullscreen();
  830. } else if (editorDiv.mozRequestFullScreen) {
  831. editorDiv.mozRequestFullScreen();
  832. } else if (editorDiv.webkitRequestFullscreen) {
  833. editorDiv.webkitRequestFullscreen();
  834. }
  835. }
  836. var toggleEditor = function () {
  837. var editorButton = document.getElementById("editorButton1280");
  838. var scene = engine.scenes[0];
  839. // If the editor is present
  840. if (editorButton.classList.contains('checked')) {
  841. setToMultipleID("editorButton", "removeClass", 'checked');
  842. splitInstance.collapse(0);
  843. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square" aria-hidden="true"></i>');
  844. } else {
  845. setToMultipleID("editorButton", "addClass", 'checked');
  846. splitInstance.setSizes([50, 50]); // Reset
  847. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  848. }
  849. engine.resize();
  850. if (scene.debugLayer.isVisible()) {
  851. scene.debugLayer.show({ embedMode: true });
  852. }
  853. }
  854. /**
  855. * Set the theme (dark / light)
  856. */
  857. var toggleTheme = function (theme) {
  858. setToMultipleID("darkTheme", "removeClass", "selected");
  859. setToMultipleID("lightTheme", "removeClass", "selected");
  860. // Monaco
  861. var vsTheme;
  862. if (theme == 'dark') {
  863. vsTheme = 'vs-dark'
  864. setToMultipleID("darkTheme", "addClass", "selected");
  865. } else {
  866. vsTheme = 'vs'
  867. setToMultipleID("lightTheme", "addClass", "selected");
  868. }
  869. var oldCode = jsEditor.getValue();
  870. jsEditor.dispose();
  871. editorOptions = {
  872. value: "",
  873. language: monacoMode,
  874. lineNumbers: true,
  875. tabSize: "auto",
  876. insertSpaces: "auto",
  877. roundedSelection: true,
  878. automaticLayout: true,
  879. scrollBeyondLastLine: false,
  880. readOnly: false,
  881. theme: vsTheme,
  882. contextmenu: false,
  883. folding: true,
  884. showFoldingControls: "always",
  885. renderIndentGuides: true,
  886. minimap: {
  887. enabled: true
  888. }
  889. };
  890. editorOptions.minimap.enabled = document.getElementById("minimapToggle1280").classList.contains('checked');
  891. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  892. jsEditor.setValue(oldCode);
  893. setFontSize(fontSize);
  894. jsEditor.onKeyUp(function (evt) {
  895. markDirty();
  896. });
  897. for (var index = 0; index < elementToTheme.length; index++) {
  898. var obj = elementToTheme[index];
  899. var domObjArr = document.querySelectorAll(obj);
  900. for (var domObjIndex = 0; domObjIndex < domObjArr.length; domObjIndex++) {
  901. var domObj = domObjArr[domObjIndex];
  902. domObj.classList.remove('light');
  903. domObj.classList.remove('dark');
  904. domObj.classList.add(theme);
  905. }
  906. }
  907. localStorage.setItem("bjs-playground-theme", theme);
  908. }
  909. /**
  910. * Toggle Typescript / Javascript language
  911. */
  912. var togglescriptLanguage = function (scriptLanguage) {
  913. for (var index = 0; index < elementForscriptLanguage.length; index++) {
  914. var obj = elementForscriptLanguage[index];
  915. var domObjArr = document.querySelectorAll(obj);
  916. for (var domObjIndex = 0; domObjIndex < domObjArr.length; domObjIndex++) {
  917. var domObj = domObjArr[domObjIndex];
  918. domObj.classList.remove('languageJS');
  919. domObj.classList.remove('languageTS');
  920. domObj.classList.add("language" + scriptLanguage);
  921. }
  922. }
  923. if (scriptLanguage == "JS") {
  924. setToMultipleID("toJSbutton", "removeClass", "floatLeft");
  925. }
  926. else if (scriptLanguage == "TS") {
  927. setToMultipleID("toJSbutton", "addClass", "floatLeft");
  928. }
  929. localStorage.setItem("bjs-playground-scriptLanguage", scriptLanguage);
  930. }
  931. var toggleDebug = function () {
  932. // Always showing the debug layer, because you can close it by itself
  933. var scene = engine.scenes[0];
  934. if (scene.debugLayer.isVisible()) {
  935. scene.debugLayer.hide();
  936. }
  937. else {
  938. scene.debugLayer.show({ embedMode: true });
  939. }
  940. }
  941. var toggleMetadata = function () {
  942. var scene = engine.scenes[0];
  943. document.getElementById("saveLayer").style.display = "block";
  944. }
  945. var formatCode = function () {
  946. jsEditor.getAction('editor.action.formatDocument').run();
  947. }
  948. var toggleMinimap = function () {
  949. var minimapToggle = document.getElementById("minimapToggle1280");
  950. if (minimapToggle.classList.contains('checked')) {
  951. jsEditor.updateOptions({ minimap: { enabled: false } });
  952. setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-square" aria-hidden="true"></i>');
  953. } else {
  954. jsEditor.updateOptions({ minimap: { enabled: true } });
  955. setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-check-square" aria-hidden="true"></i>');
  956. }
  957. minimapToggle.classList.toggle('checked');
  958. }
  959. //Navigation Overwrites
  960. var exitPrompt = function (e) {
  961. var safeToggle = document.getElementById("safemodeToggle1280");
  962. if (safeToggle.classList.contains('checked')) {
  963. e = e || window.event;
  964. var message =
  965. 'This page is asking you to confirm that you want to leave - data you have entered may not be saved.';
  966. if (e) {
  967. e.returnValue = message;
  968. }
  969. return message;
  970. }
  971. };
  972. window.onbeforeunload = exitPrompt;
  973. // Snippet
  974. var save = function () {
  975. // Retrieve title if necessary
  976. if (document.getElementById("saveLayer")) {
  977. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  978. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  979. currentSnippetTags = document.getElementById("saveFormTags").value;
  980. }
  981. var xmlHttp = new XMLHttpRequest();
  982. xmlHttp.onreadystatechange = function () {
  983. if (xmlHttp.readyState === 4) {
  984. if (xmlHttp.status === 200) {
  985. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  986. var snippet = JSON.parse(xmlHttp.responseText);
  987. var newUrl = baseUrl + "#" + snippet.id;
  988. currentSnippetToken = snippet.id;
  989. if (snippet.version && snippet.version !== "0") {
  990. newUrl += "#" + snippet.version;
  991. }
  992. location.href = newUrl;
  993. // Hide the complete title & co message
  994. hideNoMetadata();
  995. compileAndRun();
  996. } else {
  997. showError("Unable to save your code. It may be too long.", null);
  998. }
  999. }
  1000. }
  1001. xmlHttp.open("POST", snippetV3Url + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  1002. xmlHttp.setRequestHeader("Content-Type", "application/json");
  1003. var dataToSend = {
  1004. payload: JSON.stringify({
  1005. code: jsEditor.getValue()
  1006. }),
  1007. name: currentSnippetTitle,
  1008. description: currentSnippetDescription,
  1009. tags: currentSnippetTags
  1010. };
  1011. xmlHttp.send(JSON.stringify(dataToSend));
  1012. }
  1013. var askForSave = function () {
  1014. if (currentSnippetTitle == null
  1015. || currentSnippetDescription == null
  1016. || currentSnippetTags == null) {
  1017. document.getElementById("saveLayer").style.display = "block";
  1018. }
  1019. else {
  1020. save();
  1021. }
  1022. };
  1023. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  1024. document.getElementById("saveLayer").style.display = "none";
  1025. save();
  1026. });
  1027. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  1028. document.getElementById("saveLayer").style.display = "none";
  1029. });
  1030. setToMultipleID("mainTitle", "innerHTML", "v" + BABYLON.Engine.Version);
  1031. var previousHash = "";
  1032. var cleanHash = function () {
  1033. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  1034. if (splits.length > 2) {
  1035. splits.splice(2, splits.length - 2);
  1036. }
  1037. location.hash = splits.join("#");
  1038. }
  1039. var checkHash = function (firstTime) {
  1040. if (location.hash) {
  1041. if (previousHash !== location.hash) {
  1042. cleanHash();
  1043. previousHash = location.hash;
  1044. try {
  1045. var xmlHttp = new XMLHttpRequest();
  1046. xmlHttp.onreadystatechange = function () {
  1047. if (xmlHttp.readyState === 4) {
  1048. if (xmlHttp.status === 200) {
  1049. if (!checkTypescriptSupport(xmlHttp)) {
  1050. return;
  1051. }
  1052. var snippet = JSON.parse(xmlHttp.responseText);
  1053. blockEditorChange = true;
  1054. jsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  1055. // Check if title / descr / tags are already set
  1056. if (snippet.name != null && snippet.name != "") {
  1057. currentSnippetTitle = snippet.name;
  1058. }
  1059. else currentSnippetTitle = null;
  1060. if (snippet.description != null && snippet.description != "") {
  1061. currentSnippetDescription = snippet.description;
  1062. }
  1063. else currentSnippetDescription = null;
  1064. if (snippet.tags != null && snippet.tags != "") {
  1065. currentSnippetTags = snippet.tags;
  1066. }
  1067. else currentSnippetTags = null;
  1068. if (currentSnippetTitle != null && currentSnippetTags != null && currentSnippetDescription) {
  1069. if (document.getElementById("saveLayer")) {
  1070. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  1071. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  1072. document.getElementById("saveFormTags").value = currentSnippetTags;
  1073. hideNoMetadata();
  1074. }
  1075. }
  1076. else {
  1077. showNoMetadata();
  1078. }
  1079. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  1080. blockEditorChange = false;
  1081. compileAndRun();
  1082. // setToMultipleID("currentScript", "innerHTML", "Custom");
  1083. }
  1084. }
  1085. };
  1086. var hash = location.hash.substr(1);
  1087. currentSnippetToken = hash.split("#")[0];
  1088. if (!hash.split("#")[1]) hash += "#0";
  1089. xmlHttp.open("GET", snippetV3Url + "/" + hash.replace("#", "/"));
  1090. xmlHttp.send();
  1091. } catch (e) {
  1092. }
  1093. }
  1094. }
  1095. setTimeout(checkHash, 200);
  1096. }
  1097. checkHash(true);
  1098. // ---------- UI
  1099. // Run
  1100. setToMultipleID("runButton", "click", compileAndRun);
  1101. // New
  1102. setToMultipleID("newButton", "click", createNewScript);
  1103. // Clear
  1104. setToMultipleID("clearButton", "click", clear);
  1105. // Save
  1106. setToMultipleID("saveButton", "click", askForSave);
  1107. // Zip
  1108. setToMultipleID("zipButton", "click", getZip);
  1109. // // Themes
  1110. setToMultipleID("darkTheme", "click", [toggleTheme.bind(this, 'dark'), clickOptionSub]);
  1111. setToMultipleID("lightTheme", "click", [toggleTheme.bind(this, 'light'), clickOptionSub]);
  1112. // Size
  1113. var displayFontSize = document.getElementsByClassName('displayFontSize');
  1114. for (var i = 0; i < displayFontSize.length; i++) {
  1115. var options = displayFontSize[i].querySelectorAll('.option');
  1116. for (var j = 0; j < options.length; j++) {
  1117. options[j].addEventListener('click', clickOptionSub);
  1118. }
  1119. }
  1120. // Footer links
  1121. var displayFontSize = document.getElementsByClassName('displayFooterLinks');
  1122. for (var i = 0; i < displayFontSize.length; i++) {
  1123. var options = displayFontSize[i].querySelectorAll('.option');
  1124. for (var j = 0; j < options.length; j++) {
  1125. options[j].addEventListener('click', clickOptionSub);
  1126. }
  1127. }
  1128. // Language (JS / TS)
  1129. setToMultipleID("toTSbutton", "click", function () {
  1130. localStorage.setItem("bjs-playground-scriptLanguage", "TS");
  1131. if (confirm("You need to reload the page to switch to Typescript. Do you want to reload now ?"))
  1132. location.reload();
  1133. });
  1134. setToMultipleID("toJSbutton", "click", function () {
  1135. localStorage.setItem("bjs-playground-scriptLanguage", "JS");
  1136. if (confirm("You need to reload the page to switch to Javascript. Do you want to reload now ?"))
  1137. location.reload();
  1138. });
  1139. // Safe mode
  1140. setToMultipleID("safemodeToggle", 'click', function () {
  1141. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  1142. if (document.getElementById("safemodeToggle1280").classList.contains('checked')) {
  1143. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  1144. } else {
  1145. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square" aria-hidden="true"></i>');
  1146. }
  1147. });
  1148. // Editor
  1149. setToMultipleID("editorButton", "click", toggleEditor);
  1150. // FullScreen
  1151. setToMultipleID("fullscreenButton", "click", goFullscreen);
  1152. // Editor fullScreen
  1153. setToMultipleID("editorFullscreenButton", "click", editorGoFullscreen);
  1154. // Format
  1155. setToMultipleID("formatButton", "click", formatCode);
  1156. // Format
  1157. setToMultipleID("minimapToggle", "click", toggleMinimap);
  1158. // Debug
  1159. setToMultipleID("debugButton", "click", toggleDebug);
  1160. // Metadata
  1161. setToMultipleID("metadataButton", "click", toggleMetadata);
  1162. // Restore theme
  1163. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  1164. toggleTheme(theme);
  1165. toggleMinimap();
  1166. // Restore language
  1167. scriptLanguage = localStorage.getItem("bjs-playground-scriptLanguage") || 'JS';
  1168. togglescriptLanguage(scriptLanguage);
  1169. }
  1170. // Monaco
  1171. var xhr = new XMLHttpRequest();
  1172. xhr.open('GET', "babylon.d.txt", true);
  1173. xhr.onreadystatechange = function () {
  1174. if (xhr.readyState === 4) {
  1175. if (xhr.status === 200) {
  1176. require.config({ paths: { 'vs': 'node_modules/monaco-editor/min/vs' } });
  1177. require(['vs/editor/editor.main'], function () {
  1178. if (monacoMode === "javascript") {
  1179. monaco.languages.typescript.javascriptDefaults.addExtraLib(xhr.responseText, 'babylon.d.ts');
  1180. } else {
  1181. monaco.languages.typescript.typescriptDefaults.addExtraLib(xhr.responseText, 'babylon.d.ts');
  1182. }
  1183. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  1184. run();
  1185. });
  1186. }
  1187. }
  1188. };
  1189. xhr.send(null);
  1190. })();