index.js 23 KB

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