index.js 22 KB

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