index.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. (function () {
  2. var jsEditor;
  3. var run = function () {
  4. var blockEditorChange = false;
  5. jsEditor.onKeyDown(function (evt) {
  6. });
  7. jsEditor.onKeyUp(function (evt) {
  8. if (blockEditorChange) {
  9. return;
  10. }
  11. document.getElementById("currentScript").innerHTML = "Custom";
  12. document.getElementById('safemodeToggle').checked = true;
  13. });
  14. var snippetUrl = "https://babylonjs-api2.azurewebsites.net/snippets";
  15. var currentSnippetToken;
  16. var currentSnippetTitle = null;
  17. var currentSnippetDescription = null;
  18. var currentSnippetTags = null;
  19. var engine;
  20. var fpsLabel = document.getElementById("fpsLabel");
  21. var scripts;
  22. var zipCode;
  23. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  24. var currentVersionElement = document.getElementById("currentVersion");
  25. if (currentVersionElement) {
  26. switch (BABYLON.Engine.Version) {
  27. case "2.5":
  28. currentVersionElement.innerHTML = "Version: " + BABYLON.Engine.Version;
  29. break;
  30. default:
  31. currentVersionElement.innerHTML = "Version: Latest";
  32. break;
  33. }
  34. }
  35. var loadScript = function (scriptURL, title) {
  36. var xhr = new XMLHttpRequest();
  37. xhr.open('GET', scriptURL, true);
  38. xhr.onreadystatechange = function () {
  39. if (xhr.readyState === 4) {
  40. if (xhr.status === 200) {
  41. blockEditorChange = true;
  42. jsEditor.setValue(xhr.responseText);
  43. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  44. blockEditorChange = false;
  45. compileAndRun();
  46. document.getElementById("currentScript").innerHTML = title;
  47. currentSnippetToken = null;
  48. }
  49. }
  50. };
  51. xhr.send(null);
  52. };
  53. var loadScriptFromIndex = function (index) {
  54. if (index === 0) {
  55. index = 1;
  56. }
  57. var script = scripts[index - 1].trim();
  58. loadScript("scripts/" + script + ".js", script);
  59. }
  60. var onScriptClick = function (evt) {
  61. loadScriptFromIndex(evt.target.scriptLinkIndex);
  62. }
  63. var loadScriptsList = function () {
  64. var xhr = new XMLHttpRequest();
  65. xhr.open('GET', 'scripts/scripts.txt', true);
  66. xhr.onreadystatechange = function () {
  67. if (xhr.readyState === 4) {
  68. if (xhr.status === 200) {
  69. scripts = xhr.responseText.split("\n");
  70. var ul = document.getElementById("scriptsList");
  71. var index;
  72. for (index = 0; index < scripts.length; index++) {
  73. var li = document.createElement("li");
  74. var a = document.createElement("a");
  75. li.class = "scriptsListEntry";
  76. a.href = "#";
  77. a.innerHTML = (index + 1) + " - " + scripts[index];
  78. a.scriptLinkIndex = index + 1;
  79. a.onclick = onScriptClick;
  80. li.appendChild(a);
  81. ul.appendChild(li);
  82. }
  83. if (!location.hash) {
  84. // Query string
  85. var queryString = window.location.search;
  86. if (queryString) {
  87. var query = queryString.replace("?", "");
  88. index = parseInt(query);
  89. if (!isNaN(index)) {
  90. loadScriptFromIndex(index);
  91. } else {
  92. loadScript("scripts/" + query + ".js", query);
  93. }
  94. } else {
  95. loadScript("scripts/basic scene.js", "Basic scene");
  96. }
  97. }
  98. }
  99. }
  100. };
  101. xhr.send(null);
  102. }
  103. var createNewScript = function () {
  104. location.hash = "";
  105. currentSnippetToken = null;
  106. currentSnippetTitle = null;
  107. currentSnippetDescription = null;
  108. currentSnippetTags = null;
  109. document.getElementById("saveMessage").style.display = "block";
  110. 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// More info here: https://doc.babylonjs.com/generals/The_Playground_Tutorial\r\n\r\nvar createScene = function() {\r\n\tvar scene = new BABYLON.Scene(engine);\r\n\tvar camera = new BABYLON.ArcRotateCamera("Camera", 0, 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};');
  111. jsEditor.setPosition({ lineNumber: 11, column: 0 });
  112. jsEditor.focus();
  113. compileAndRun();
  114. }
  115. var clear = function () {
  116. location.hash = "";
  117. currentSnippetToken = null;
  118. jsEditor.setValue('');
  119. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  120. jsEditor.focus();
  121. }
  122. var showError = function (errorMessage, errorEvent) {
  123. var errorContent =
  124. '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button><h4>Compilation error</h4>'
  125. if (errorEvent) {
  126. var regEx = /\(.+:(\d+):(\d+)\)\n/g;
  127. var match = regEx.exec(errorEvent.stack);
  128. if (match) {
  129. errorContent += "Line ";
  130. var lineNumber = match[1];
  131. var columnNumber = match[2];
  132. errorContent += lineNumber + ':' + columnNumber + ' - ';
  133. }
  134. }
  135. errorContent += errorMessage + '</div>';
  136. document.getElementById("errorZone").innerHTML = errorContent;
  137. }
  138. compileAndRun = function () {
  139. try {
  140. if (!BABYLON.Engine.isSupported()) {
  141. showError("Your browser does not support WebGL", null);
  142. return;
  143. }
  144. if (engine) {
  145. engine.dispose();
  146. engine = null;
  147. }
  148. var canvas = document.getElementById("renderCanvas");
  149. engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  150. document.getElementById("errorZone").innerHTML = "";
  151. document.getElementById("statusBar").innerHTML = "Loading assets...Please wait";
  152. engine.runRenderLoop(function () {
  153. if (engine.scenes.length === 0) {
  154. return;
  155. }
  156. if (canvas.width !== canvas.clientWidth) {
  157. engine.resize();
  158. }
  159. var scene = engine.scenes[0];
  160. if (scene.activeCamera || scene.activeCameras.length > 0) {
  161. scene.render();
  162. }
  163. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  164. });
  165. var code = jsEditor.getValue();
  166. var scene;
  167. if (code.indexOf("createScene") !== -1) { // createScene
  168. eval(code);
  169. scene = createScene();
  170. if (!scene) {
  171. showError("createScene function must return a scene.", null);
  172. return;
  173. }
  174. zipCode = code + "\r\n\r\nvar scene = createScene();";
  175. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  176. eval(code);
  177. scene = CreateScene();
  178. if (!scene) {
  179. showError("CreateScene function must return a scene.", null);
  180. return;
  181. }
  182. zipCode = code + "\r\n\r\nvar scene = CreateScene();";
  183. } else if (code.indexOf("createscene") !== -1) { // createscene
  184. eval(code);
  185. scene = createscene();
  186. if (!scene) {
  187. showError("createscene function must return a scene.", null);
  188. return;
  189. }
  190. zipCode = code + "\r\n\r\nvar scene = createscene();";
  191. } else { // Direct code
  192. scene = new BABYLON.Scene(engine);
  193. eval("runScript = function(scene, canvas) {" + code + "}");
  194. runScript(scene, canvas);
  195. zipCode = "var scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  196. }
  197. if (engine.scenes.length === 0) {
  198. showError("You must at least create a scene.", null);
  199. return;
  200. }
  201. if (engine.scenes[0].activeCamera == null) {
  202. showError("You must at least create a camera.", null);
  203. return;
  204. }
  205. engine.scenes[0].executeWhenReady(function () {
  206. document.getElementById("statusBar").innerHTML = "";
  207. });
  208. } catch (e) {
  209. showError(e.message, e);
  210. }
  211. };
  212. window.addEventListener("resize",
  213. function () {
  214. if (engine) {
  215. engine.resize();
  216. }
  217. });
  218. // Load scripts list
  219. loadScriptsList();
  220. // Zip
  221. var addContentToZip = function (zip, name, url, replace, buffer, then) {
  222. var xhr = new XMLHttpRequest();
  223. xhr.open('GET', url, true);
  224. if (buffer) {
  225. xhr.responseType = "arraybuffer";
  226. }
  227. xhr.onreadystatechange = function () {
  228. if (xhr.readyState === 4) {
  229. if (xhr.status === 200) {
  230. var text;
  231. if (!buffer) {
  232. if (replace) {
  233. var splits = replace.split("\r\n");
  234. for (var index = 0; index < splits.length; index++) {
  235. splits[index] = " " + splits[index];
  236. }
  237. replace = splits.join("\r\n");
  238. text = xhr.responseText.replace("####INJECT####", replace);
  239. } else {
  240. text = xhr.responseText;
  241. }
  242. }
  243. zip.file(name, buffer ? xhr.response : text);
  244. then();
  245. }
  246. }
  247. };
  248. xhr.send(null);
  249. }
  250. var addTexturesToZip = function (zip, index, textures, folder, then) {
  251. if (index === textures.length) {
  252. then();
  253. return;
  254. }
  255. if (textures[index].isRenderTarget || textures[index] instanceof BABYLON.DynamicTexture) {
  256. addTexturesToZip(zip, index + 1, textures, folder, then);
  257. return;
  258. }
  259. if (textures[index].isCube) {
  260. if (textures[index]._extensions) {
  261. for (var i = 0; i < 6; i++) {
  262. textures.push({ name: textures[index].name + textures[index]._extensions[i] });
  263. }
  264. }
  265. else {
  266. textures.push({ name: textures[index].name });
  267. }
  268. addTexturesToZip(zip, index + 1, textures, folder, then);
  269. return;
  270. }
  271. if (folder == null) {
  272. folder = zip.folder("textures");
  273. }
  274. var url;
  275. if (textures[index].video) {
  276. url = textures[index].video.currentSrc;
  277. } else {
  278. url = textures[index].name;
  279. }
  280. var name = url.substr(url.lastIndexOf("/") + 1);
  281. addContentToZip(folder,
  282. name,
  283. url,
  284. null,
  285. true,
  286. function () {
  287. addTexturesToZip(zip, index + 1, textures, folder, then);
  288. });
  289. }
  290. var addImportedFilesToZip = function (zip, index, importedFiles, folder, then) {
  291. if (index === importedFiles.length) {
  292. then();
  293. return;
  294. }
  295. if (!folder) {
  296. folder = zip.folder("scenes");
  297. }
  298. var url = importedFiles[index];
  299. var name = url.substr(url.lastIndexOf("/") + 1);
  300. addContentToZip(folder,
  301. name,
  302. url,
  303. null,
  304. true,
  305. function () {
  306. addImportedFilesToZip(zip, index + 1, importedFiles, folder, then);
  307. });
  308. }
  309. var getZip = function () {
  310. if (engine.scenes.length === 0) {
  311. return;
  312. }
  313. var zip = new JSZip();
  314. var scene = engine.scenes[0];
  315. var textures = scene.textures;
  316. var importedFiles = scene.importedMeshesFiles;
  317. document.getElementById("statusBar").innerHTML = "Creating archive...Please wait";
  318. if (zipCode.indexOf("textures/worldHeightMap.jpg") !== -1) {
  319. textures.push({ name: "textures/worldHeightMap.jpg" });
  320. }
  321. addContentToZip(zip,
  322. "index.html",
  323. "zipContent/index.html",
  324. zipCode,
  325. false,
  326. function () {
  327. addTexturesToZip(zip,
  328. 0,
  329. textures,
  330. null,
  331. function () {
  332. addImportedFilesToZip(zip,
  333. 0,
  334. importedFiles,
  335. null,
  336. function () {
  337. var blob = zip.generate({ type: "blob" });
  338. saveAs(blob, "sample.zip");
  339. document.getElementById("statusBar").innerHTML = "";
  340. });
  341. });
  342. });
  343. }
  344. // Versions
  345. setVersion = function (version) {
  346. switch (version) {
  347. case "2.5":
  348. location.href = "index2_5.html" + location.hash;
  349. break;
  350. default:
  351. location.href = "index.html" + location.hash;
  352. break;
  353. }
  354. }
  355. // Fonts
  356. setFontSize = function (size) {
  357. document.querySelector(".monaco-editor").style.fontSize = size + "px";
  358. document.getElementById("currentFontSize").innerHTML = "Font: " + size;
  359. };
  360. // Fullscreen
  361. var goFullscreen = function () {
  362. if (engine) {
  363. engine.switchFullscreen(true);
  364. }
  365. }
  366. var toggleEditor = function () {
  367. var editorButton = document.getElementById("editorButton");
  368. var scene = engine.scenes[0];
  369. if (editorButton.innerHTML === "-Editor") {
  370. editorButton.innerHTML = "+Editor";
  371. document.getElementById("jsEditor").style.display = "none";
  372. document.getElementById("canvasZone").style.flexBasis = "100%";
  373. } else {
  374. editorButton.innerHTML = "-Editor";
  375. document.getElementById("jsEditor").style.display = "block";
  376. document.getElementById("canvasZone").style.flexBasis = undefined;
  377. }
  378. engine.resize();
  379. if (scene.debugLayer.isVisible()) {
  380. scene.debugLayer.hide();
  381. scene.debugLayer.show();
  382. }
  383. }
  384. var toggleDebug = function () {
  385. var debugButton = document.getElementById("debugButton");
  386. var scene = engine.scenes[0];
  387. if (debugButton.innerHTML === "+Debug layer") {
  388. debugButton.innerHTML = "-Debug layer";
  389. scene.debugLayer.show();
  390. } else {
  391. debugButton.innerHTML = "+Debug layer";
  392. scene.debugLayer.hide();
  393. }
  394. }
  395. // UI
  396. document.getElementById("runButton").addEventListener("click", compileAndRun);
  397. document.getElementById("zipButton").addEventListener("click", getZip);
  398. document.getElementById("fullscreenButton").addEventListener("click", goFullscreen);
  399. document.getElementById("newButton").addEventListener("click", createNewScript);
  400. document.getElementById("clearButton").addEventListener("click", clear);
  401. document.getElementById("editorButton").addEventListener("click", toggleEditor);
  402. document.getElementById("debugButton").addEventListener("click", toggleDebug);
  403. //Navigation Overwrites
  404. var exitPrompt = function (e) {
  405. var safeToggle = document.getElementById("safemodeToggle");
  406. if (safeToggle.checked) {
  407. e = e || window.event;
  408. var message =
  409. 'This page is asking you to confirm that you want to leave - data you have entered may not be saved.';
  410. if (e) {
  411. e.returnValue = message;
  412. }
  413. return message;
  414. }
  415. };
  416. window.onbeforeunload = exitPrompt;
  417. // Snippet
  418. var save = function () {
  419. // Retrieve title if necessary
  420. if (document.getElementById("saveLayer")) {
  421. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  422. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  423. currentSnippetTags = document.getElementById("saveFormTags").value;
  424. }
  425. var xmlHttp = new XMLHttpRequest();
  426. xmlHttp.onreadystatechange = function () {
  427. if (xmlHttp.readyState === 4) {
  428. if (xmlHttp.status === 201) {
  429. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  430. var snippet = JSON.parse(xmlHttp.responseText);
  431. var newUrl = baseUrl + "#" + snippet.id;
  432. currentSnippetToken = snippet.id;
  433. if (snippet.version && snippet.version !== "0") {
  434. newUrl += "#" + snippet.version;
  435. }
  436. location.href = newUrl;
  437. // Hide the complete title & co message
  438. document.getElementById("saveMessage").style.display = "none";
  439. compileAndRun();
  440. } else {
  441. showError("Unable to save your code. It may be too long.", null);
  442. }
  443. }
  444. }
  445. xmlHttp.open("POST", snippetUrl + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  446. xmlHttp.setRequestHeader("Content-Type", "application/json");
  447. var dataToSend = {
  448. payload: {
  449. code: jsEditor.getValue()
  450. },
  451. name: currentSnippetTitle,
  452. description: currentSnippetDescription,
  453. tags: currentSnippetTags
  454. };
  455. xmlHttp.send(JSON.stringify(dataToSend));
  456. }
  457. document.getElementById("saveButton").addEventListener("click", function () {
  458. if (currentSnippetTitle == null
  459. && currentSnippetDescription == null
  460. && currentSnippetTags == null) {
  461. document.getElementById("saveLayer").style.display = "block";
  462. }
  463. else {
  464. save();
  465. }
  466. });
  467. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  468. document.getElementById("saveLayer").style.display = "none";
  469. save();
  470. });
  471. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  472. document.getElementById("saveLayer").style.display = "none";
  473. });
  474. document.getElementById("saveMessage").addEventListener("click", function () {
  475. document.getElementById("saveMessage").style.display = "none";
  476. });
  477. document.getElementById("mainTitle").innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " Playground";
  478. var previousHash = "";
  479. var cleanHash = function () {
  480. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  481. if (splits.length > 2) {
  482. splits.splice(2, splits.length - 2);
  483. }
  484. location.hash = splits.join("#");
  485. }
  486. var checkHash = function (firstTime) {
  487. if (location.hash) {
  488. if (previousHash !== location.hash) {
  489. cleanHash();
  490. previousHash = location.hash;
  491. try {
  492. var xmlHttp = new XMLHttpRequest();
  493. xmlHttp.onreadystatechange = function () {
  494. if (xmlHttp.readyState === 4) {
  495. if (xmlHttp.status === 200) {
  496. var snippet = JSON.parse(xmlHttp.responseText)[0];
  497. blockEditorChange = true;
  498. jsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  499. // Check if title / descr / tags are already set
  500. if ((snippet.name != null && snippet.name != "")
  501. || (snippet.description != null && snippet.description != "")
  502. || (snippet.tags != null && snippet.tags != "")) {
  503. currentSnippetTitle = snippet.name;
  504. currentSnippetDescription = snippet.description;
  505. currentSnippetTags = snippet.tags;
  506. if (document.getElementById("saveLayer")) {
  507. var elem = document.getElementById("saveLayer");
  508. // elem.outerHTML = "";
  509. // delete elem;
  510. document.getElementById("saveFormTitle").value = '';
  511. document.getElementById("saveFormDescription").value = '';
  512. document.getElementById("saveFormTags").value = '';
  513. elem.style.display = 'none';
  514. }
  515. }
  516. else {
  517. currentSnippetTitle = null;
  518. currentSnippetDescription = null;
  519. currentSnippetTags = null;
  520. document.getElementById("saveMessage").style.display = "block";
  521. }
  522. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  523. blockEditorChange = false;
  524. compileAndRun();
  525. document.getElementById("currentScript").innerHTML = "Custom";
  526. } else if (firstTime) {
  527. location.href = location.href.replace(location.hash, "");
  528. if (scripts) {
  529. loadScriptFromIndex(0);
  530. }
  531. }
  532. }
  533. }
  534. var hash = location.hash.substr(1);
  535. currentSnippetToken = hash.split("#")[0];
  536. xmlHttp.open("GET", snippetUrl + "/" + hash.replace("#", "/"));
  537. xmlHttp.send();
  538. } catch (e) {
  539. }
  540. }
  541. }
  542. setTimeout(checkHash, 200);
  543. }
  544. checkHash(true);
  545. }
  546. // Monaco
  547. var xhr = new XMLHttpRequest();
  548. xhr.open('GET', "babylon.d.txt", true);
  549. xhr.onreadystatechange = function () {
  550. if (xhr.readyState === 4) {
  551. if (xhr.status === 200) {
  552. require.config({ paths: { 'vs': 'node_modules/monaco-editor/min/vs' } });
  553. require(['vs/editor/editor.main'], function () {
  554. monaco.languages.typescript.javascriptDefaults.addExtraLib(xhr.responseText, 'babylon.d.ts');
  555. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), {
  556. value: "",
  557. language: "javascript",
  558. lineNumbers: true,
  559. tabSize: "auto",
  560. insertSpaces: "auto",
  561. roundedSelection: true,
  562. scrollBeyondLastLine: false,
  563. automaticLayout: true,
  564. readOnly: false,
  565. theme: "vs",
  566. contextmenu: false
  567. });
  568. run();
  569. });
  570. }
  571. }
  572. };
  573. xhr.send(null);
  574. })();