index.js 26 KB

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