index.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. var jsEditor;
  2. (function () {
  3. var multipleSize = [1600, 1475, 1030, 750];
  4. var setToMultipleID = function (id, thingToDo, param) {
  5. multipleSize.forEach(function (size) {
  6. if (thingToDo == "innerHTML") {
  7. document.getElementById(id + size).innerHTML = param
  8. }
  9. else if (thingToDo == "click") {
  10. document.getElementById(id + size).addEventListener("click", param);
  11. }
  12. else if (thingToDo == "addClass") {
  13. document.getElementById(id + size).classList.add(param);
  14. }
  15. else if (thingToDo == "removeClass") {
  16. document.getElementById(id + size).classList.remove(param);
  17. }
  18. else if (thingToDo == "display") {
  19. document.getElementById(id + size).style.display = param;
  20. }
  21. });
  22. };
  23. var editorOptions = {
  24. value: "",
  25. language: "javascript",
  26. lineNumbers: true,
  27. tabSize: "auto",
  28. insertSpaces: "auto",
  29. roundedSelection: true,
  30. automaticLayout: true,
  31. scrollBeyondLastLine: false,
  32. readOnly: false,
  33. theme: "vs",
  34. contextmenu: false,
  35. folding: true,
  36. showFoldingControls: "always",
  37. renderIndentGuides: true
  38. };
  39. var fontSize = 14;
  40. var splitInstance = Split(['#jsEditor', '#canvasZone']);
  41. var elementToTheme = [
  42. '.wrapper .gutter',
  43. '.wrapper #jsEditor',
  44. '.navbar',
  45. '.navbar .select .toDisplay .option',
  46. '.navbar .select .toDisplayBig',
  47. '.navbar .select .toDisplayBig a',
  48. '.navbar .select .toDisplayBig ul li',
  49. '.navbarBottom',
  50. '.navbarBottom .links .link'];
  51. var run = function () {
  52. // #region - Examples playgrounds
  53. var examplesButton = document.getElementsByClassName("examplesButton");
  54. var isExamplesDisplayed = false;
  55. for(var i = 0; i < examplesButton.length; i++) {
  56. examplesButton[i].onclick = function () {
  57. isExamplesDisplayed = !isExamplesDisplayed;
  58. if (isExamplesDisplayed) {
  59. document.getElementById("exampleList").style.display = "block";
  60. document.getElementsByClassName("wrapper")[0].style.width = "calc(100% - 400px)";
  61. }
  62. else {
  63. document.getElementById("exampleList").style.display = "none";
  64. document.getElementsByClassName("wrapper")[0].style.width = "100%";
  65. }
  66. }
  67. }
  68. var filterBarClear = document.getElementById("filterBarClear");
  69. var filterBar = document.getElementById("filterBar");
  70. var filter = function () {
  71. var filterText = filterBar.value.toLowerCase();
  72. if (filterText == "") filterBarClear.style.display = "none";
  73. else filterBarClear.style.display = "inline-block";
  74. var lines = document.getElementsByClassName("itemLine");
  75. for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) {
  76. var line = lines[lineIndex];
  77. if (line.innerText.toLowerCase().indexOf(filterText) > -1) {
  78. line.style.display = "";
  79. } else {
  80. line.style.display = "none";
  81. }
  82. }
  83. var categories = document.getElementsByClassName("categoryContainer");
  84. var displayCount = categories.length;
  85. for (var categoryIndex = 0; categoryIndex < categories.length; categoryIndex++) {
  86. var category = categories[categoryIndex];
  87. category.style.display = "block";
  88. if (category.clientHeight < 25) {
  89. category.style.display = "none";
  90. displayCount--;
  91. }
  92. }
  93. if (displayCount == 0) document.getElementById("noResultsContainer").style.display = "block";
  94. else document.getElementById("noResultsContainer").style.display = "none";
  95. }
  96. filterBar.oninput = function () {
  97. filter();
  98. }
  99. filterBarClear.onclick = function () {
  100. filterBar.value = "";
  101. filter();
  102. }
  103. // #endregion
  104. var blockEditorChange = false;
  105. var markDirty = function () {
  106. if (blockEditorChange) {
  107. return;
  108. }
  109. // setToMultipleID("currentScript", "innerHTML", "Custom");
  110. setToMultipleID("safemodeToggle", "addClass", "checked");
  111. setToMultipleID("minimapToggle", "addClass", "checked");
  112. setToMultipleID('safemodeToggle', 'innerHTML', 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  113. }
  114. jsEditor.onKeyUp(function (evt) {
  115. markDirty();
  116. });
  117. var snippetUrl = "//babylonjs-api2.azurewebsites.net/snippets";
  118. var currentSnippetToken;
  119. var currentSnippetTitle = null;
  120. var currentSnippetDescription = null;
  121. var currentSnippetTags = null;
  122. var engine;
  123. var fpsLabel = document.getElementById("fpsLabel");
  124. var scripts;
  125. var zipCode;
  126. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  127. if (location.href.indexOf("indexstable") !== -1) {
  128. setToMultipleID("currentVersion", "innerHTML", "Version: Stable");
  129. } else {
  130. setToMultipleID("currentVersion", "innerHTML", "Version: Latest");
  131. }
  132. var loadScript = function (scriptURL, title) {
  133. var xhr = new XMLHttpRequest();
  134. xhr.open('GET', scriptURL, true);
  135. xhr.onreadystatechange = function () {
  136. if (xhr.readyState === 4) {
  137. if (xhr.status === 200) {
  138. xhr.onreadystatechange = null;
  139. blockEditorChange = true;
  140. jsEditor.setValue(xhr.responseText);
  141. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  142. blockEditorChange = false;
  143. compileAndRun();
  144. // setToMultipleID("currentScript", "innerHTML", title);
  145. currentSnippetToken = null;
  146. }
  147. }
  148. };
  149. xhr.send(null);
  150. };
  151. var loadScriptFromIndex = function (index) {
  152. if (index === 0) {
  153. index = 1;
  154. }
  155. var script = scripts[index - 1].trim();
  156. loadScript("scripts/" + script + ".js", script);
  157. }
  158. var onScriptClick = function (evt) {
  159. loadScriptFromIndex(evt.target.scriptLinkIndex);
  160. };
  161. var loadScriptsList = function () {
  162. var xhr = new XMLHttpRequest();
  163. xhr.open('GET', 'examples/list.json', true);
  164. xhr.onreadystatechange = function () {
  165. if (xhr.readyState === 4) {
  166. if (xhr.status === 200) {
  167. scripts = JSON.parse(xhr.response)["examples"];
  168. function sortScriptsList(a, b) {
  169. if (a.title < b.title) return -1;
  170. else return 1;
  171. return 0;
  172. }
  173. scripts.sort(sortScriptsList);
  174. var exampleList = document.getElementById("exampleList");
  175. for (var i = 0; i < scripts.length; i++) {
  176. scripts[i].samples.sort(sortScriptsList);
  177. var exampleCategory = document.createElement("div");
  178. exampleCategory.classList.add("categoryContainer");
  179. var exampleCategoryTitle = document.createElement("p");
  180. exampleCategoryTitle.innerText = scripts[i].title;
  181. exampleCategory.appendChild(exampleCategoryTitle);
  182. for (var ii = 0; ii < scripts[i].samples.length; ii++) {
  183. var example = document.createElement("div");
  184. example.classList.add("itemLine");
  185. example.id = ii;
  186. var exampleImg = document.createElement("img");
  187. exampleImg.src = "examples/" + scripts[i].samples[ii].icon;
  188. var exampleContent = document.createElement("div");
  189. exampleContent.classList.add("itemContent");
  190. var exampleContentLink = document.createElement("div");
  191. exampleContentLink.classList.add("itemContentLink");
  192. var exampleTitle = document.createElement("h3");
  193. exampleTitle.classList.add("exampleCategoryTitle");
  194. exampleTitle.innerText = scripts[i].samples[ii].title;
  195. var exampleDescr = document.createElement("div");
  196. exampleDescr.classList.add("itemLineChild");
  197. exampleDescr.innerText = scripts[i].samples[ii].description;
  198. var exampleDocLink = document.createElement("a");
  199. exampleDocLink.classList.add("itemLineDocLink");
  200. exampleDocLink.innerText = "Documentation";
  201. exampleDocLink.href = scripts[i].samples[ii].doc;
  202. exampleDocLink.target = "_blank";
  203. var examplePGLink = document.createElement("a");
  204. examplePGLink.classList.add("itemLinePGLink");
  205. examplePGLink.innerText = "Display";
  206. examplePGLink.href = scripts[i].samples[ii].PGID;
  207. exampleContentLink.appendChild(exampleTitle);
  208. exampleContentLink.appendChild(exampleDescr);
  209. exampleContent.appendChild(exampleContentLink);
  210. exampleContent.appendChild(exampleDocLink);
  211. exampleContent.appendChild(examplePGLink);
  212. example.appendChild(exampleImg);
  213. example.appendChild(exampleContent);
  214. exampleCategory.appendChild(example);
  215. }
  216. exampleList.appendChild(exampleCategory);
  217. }
  218. var noResultContainer = document.createElement("div");
  219. noResultContainer.id = "noResultsContainer";
  220. noResultContainer.classList.add("categoryContainer");
  221. noResultContainer.style.display = "none";
  222. noResultContainer.innerHTML = "<p id='noResults'>No results found.</p>";
  223. exampleList.appendChild(noResultContainer);
  224. if (!location.hash) {
  225. // Query string
  226. var queryString = window.location.search;
  227. if (queryString) {
  228. var query = queryString.replace("?", "");
  229. index = parseInt(query);
  230. if (!isNaN(index)) {
  231. loadScriptFromIndex(index);
  232. } else if (query.indexOf("=") === -1) {
  233. loadScript("scripts/" + query + ".js", query);
  234. } else {
  235. loadScript("scripts/basic scene.js", "Basic scene");
  236. }
  237. } else {
  238. loadScript("scripts/basic scene.js", "Basic scene");
  239. }
  240. }
  241. // Restore theme
  242. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  243. toggleTheme(theme);
  244. // Remove editor if window size is less than 850px
  245. var removeEditorForSmallScreen = function () {
  246. if (mq.matches) {
  247. splitInstance.collapse(0);
  248. } else {
  249. splitInstance.setSizes([50, 50]);
  250. }
  251. }
  252. var mq = window.matchMedia("(max-width: 850px)");
  253. mq.addListener(removeEditorForSmallScreen);
  254. }
  255. }
  256. };
  257. xhr.send(null);
  258. }
  259. var createNewScript = function () {
  260. // check if checked is on
  261. let iCanClear = checkSafeMode("Are you sure you want to create a new playground?");
  262. if (!iCanClear) return;
  263. location.hash = "";
  264. currentSnippetToken = null;
  265. currentSnippetTitle = null;
  266. currentSnippetDescription = null;
  267. currentSnippetTags = null;
  268. showNoMetadata();
  269. 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", -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};');
  270. jsEditor.setPosition({ lineNumber: 11, column: 0 });
  271. jsEditor.focus();
  272. compileAndRun();
  273. }
  274. var clear = function () {
  275. // check if checked is on
  276. let iCanClear = checkSafeMode("Are you sure you want to clear the playground?");
  277. if (!iCanClear) return;
  278. location.hash = "";
  279. currentSnippetToken = null;
  280. jsEditor.setValue('');
  281. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  282. jsEditor.focus();
  283. }
  284. var checkSafeMode = function (message) {
  285. var safeToggle = document.getElementById("safemodeToggle1600");
  286. if (safeToggle.classList.contains('checked')) {
  287. let confirm = window.confirm(message);
  288. if (!confirm) {
  289. return false;
  290. } else {
  291. document.getElementById("safemodeToggle1600").classList.toggle('checked');
  292. return true;
  293. }
  294. } else {
  295. return true;
  296. }
  297. }
  298. var showError = function (errorMessage, errorEvent) {
  299. var errorContent =
  300. '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button>';
  301. if (errorEvent) {
  302. var regEx = /\(.+:(\d+):(\d+)\)\n/g;
  303. var match = regEx.exec(errorEvent.stack);
  304. if (match) {
  305. errorContent += "Line ";
  306. var lineNumber = match[1];
  307. var columnNumber = match[2];
  308. errorContent += lineNumber + ':' + columnNumber + ' - ';
  309. }
  310. }
  311. errorContent += errorMessage + '</div>';
  312. document.getElementById("errorZone").style.display = 'block';
  313. document.getElementById("errorZone").innerHTML = errorContent;
  314. // Close button error
  315. document.getElementById("errorZone").querySelector('.close').addEventListener('click', function () {
  316. document.getElementById("errorZone").style.display = 'none';
  317. });
  318. }
  319. var showNoMetadata = function () {
  320. if (currentSnippetTitle) {
  321. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  322. document.getElementById("saveFormTitle").readOnly = true;
  323. }
  324. else {
  325. document.getElementById("saveFormTitle").value = '';
  326. document.getElementById("saveFormTitle").readOnly = false;
  327. }
  328. if (currentSnippetDescription) {
  329. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  330. document.getElementById("saveFormDescription").readOnly = true;
  331. }
  332. else {
  333. document.getElementById("saveFormDescription").value = '';
  334. document.getElementById("saveFormDescription").readOnly = false;
  335. }
  336. if (currentSnippetTags) {
  337. document.getElementById("saveFormTags").value = currentSnippetTags;
  338. document.getElementById("saveFormTags").readOnly = true;
  339. }
  340. else {
  341. document.getElementById("saveFormTags").value = '';
  342. document.getElementById("saveFormTags").readOnly = false;
  343. }
  344. document.getElementById("saveFormButtons").style.display = "block";
  345. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  346. };
  347. showNoMetadata();
  348. var hideNoMetadata = function () {
  349. document.getElementById("saveFormTitle").readOnly = true;
  350. document.getElementById("saveFormDescription").readOnly = true;
  351. document.getElementById("saveFormTags").readOnly = true;
  352. document.getElementById("saveFormButtonOk").style.display = "none";
  353. setToMultipleID("metadataButton", "display", "inline-block");
  354. };
  355. compileAndRun = function () {
  356. try {
  357. var waitRing = document.getElementById("waitDiv");
  358. if (waitRing) {
  359. waitRing.style.display = "none";
  360. }
  361. if (!BABYLON.Engine.isSupported()) {
  362. showError("Your browser does not support WebGL", null);
  363. return;
  364. }
  365. var showInspector = false;
  366. var showDebugLayer = false;
  367. var initialTabIndex = 0;
  368. showBJSPGMenu();
  369. jsEditor.updateOptions({ readOnly: false });
  370. if (document.getElementsByClassName('insp-wrapper').length > 0) {
  371. for (var i = 0; i < engine.scenes.length; i++) {
  372. if (engine.scenes[i]._debugLayer) {
  373. //TODO: once inspector is updated on netlify, use getActiveTabIndex instead of the following loop
  374. //initialTabIndex = engine.scenes[i]._debugLayer._inspector.getActiveTabIndex();
  375. var tabs = engine.scenes[i]._debugLayer._inspector._tabbar._tabs;
  376. for (var j = 0; j < tabs.length; j++) {
  377. if (tabs[j].isActive()) {
  378. initialTabIndex = j;
  379. break;
  380. }
  381. }
  382. break;
  383. }
  384. }
  385. showInspector = true;
  386. } else if (document.getElementById('DebugLayer')) {
  387. showDebugLayer = true;
  388. }
  389. if (engine) {
  390. engine.dispose();
  391. engine = null;
  392. }
  393. var canvas = document.getElementById("renderCanvas");
  394. document.getElementById("errorZone").style.display = 'none';
  395. document.getElementById("errorZone").innerHTML = "";
  396. document.getElementById("statusBar").innerHTML = "Loading assets...Please wait";
  397. var checkCamera = true;
  398. var wrappedEval = false;
  399. var createEngineFunction = "createDefaultEngine";
  400. var createSceneFunction;
  401. var code = jsEditor.getValue();
  402. var createDefaultEngine = function () {
  403. return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  404. }
  405. var scene;
  406. if (code.indexOf("createEngine") !== -1) {
  407. createEngineFunction = "createEngine";
  408. }
  409. if (code.indexOf("delayCreateScene") !== -1) { // createScene
  410. createSceneFunction = "delayCreateScene";
  411. checkCamera = false;
  412. } else if (code.indexOf("createScene") !== -1) { // createScene
  413. createSceneFunction = "createScene";
  414. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  415. createSceneFunction = "CreateScene";
  416. } else if (code.indexOf("createscene") !== -1) { // createscene
  417. createSceneFunction = "createscene";
  418. }
  419. if (!createSceneFunction) {
  420. // just pasted code.
  421. engine = createDefaultEngine();
  422. scene = new BABYLON.Scene(engine);
  423. eval("runScript = function(scene, canvas) {" + code + "}");
  424. runScript(scene, canvas);
  425. zipCode = "var scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  426. } else {
  427. //execute the code
  428. eval(code);
  429. //create engine
  430. eval("engine = " + createEngineFunction + "()");
  431. if (!engine) {
  432. showError("createEngine function must return an engine.", null);
  433. return;
  434. }
  435. //create scene
  436. eval("scene = " + createSceneFunction + "()");
  437. if (!scene) {
  438. showError(createSceneFunction + " function must return a scene.", null);
  439. return;
  440. }
  441. // update the scene code for the zip file
  442. zipCode = code + "\r\n\r\nvar scene = " + createSceneFunction + "()";
  443. }
  444. engine.runRenderLoop(function () {
  445. if (engine.scenes.length === 0) {
  446. return;
  447. }
  448. if (canvas.width !== canvas.clientWidth) {
  449. engine.resize();
  450. }
  451. var scene = engine.scenes[0];
  452. if (scene.activeCamera || scene.activeCameras.length > 0) {
  453. scene.render();
  454. }
  455. fpsLabel.style.right = document.body.clientWidth - (jsEditor.domElement.clientWidth + canvas.clientWidth) + "px";
  456. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  457. });
  458. if (engine.scenes.length === 0) {
  459. showError("You must at least create a scene.", null);
  460. return;
  461. }
  462. if (checkCamera && engine.scenes[0].activeCamera == null) {
  463. showError("You must at least create a camera.", null);
  464. return;
  465. }
  466. engine.scenes[0].executeWhenReady(function () {
  467. document.getElementById("statusBar").innerHTML = "";
  468. });
  469. if (scene) {
  470. if (showInspector) {
  471. scene.debugLayer.show({ initialTab: initialTabIndex });
  472. scene.executeWhenReady(function () {
  473. scene.debugLayer._inspector.refresh();
  474. })
  475. } else if (showDebugLayer) {
  476. scene.debugLayer.show();
  477. }
  478. }
  479. } catch (e) {
  480. showError(e.message, e);
  481. // Also log error in console to help debug playgrounds
  482. console.error(e);
  483. }
  484. };
  485. window.addEventListener("resize",
  486. function () {
  487. if (engine) {
  488. engine.resize();
  489. }
  490. });
  491. // Load scripts list
  492. loadScriptsList();
  493. // Zip
  494. var addContentToZip = function (zip, name, url, replace, buffer, then) {
  495. if (url.substring(0, 5) == "http:" || url.substring(0, 5) == "blob:" || url.substring(0, 6) == "https:") {
  496. then();
  497. return;
  498. }
  499. var xhr = new XMLHttpRequest();
  500. xhr.open('GET', url, true);
  501. if (buffer) {
  502. xhr.responseType = "arraybuffer";
  503. }
  504. xhr.onreadystatechange = function () {
  505. if (xhr.readyState === 4) {
  506. if (xhr.status === 200) {
  507. var text;
  508. if (!buffer) {
  509. if (replace) {
  510. var splits = replace.split("\r\n");
  511. for (var index = 0; index < splits.length; index++) {
  512. splits[index] = " " + splits[index];
  513. }
  514. replace = splits.join("\r\n");
  515. text = xhr.responseText.replace("####INJECT####", replace);
  516. } else {
  517. text = xhr.responseText;
  518. }
  519. }
  520. zip.file(name, buffer ? xhr.response : text);
  521. then();
  522. }
  523. }
  524. };
  525. xhr.send(null);
  526. }
  527. var addTexturesToZip = function (zip, index, textures, folder, then) {
  528. if (index === textures.length) {
  529. then();
  530. return;
  531. }
  532. if (textures[index].isRenderTarget || textures[index] instanceof BABYLON.DynamicTexture || textures[index].name.indexOf("data:") !== -1) {
  533. addTexturesToZip(zip, index + 1, textures, folder, then);
  534. return;
  535. }
  536. if (textures[index].isCube) {
  537. if (textures[index]._extensions && textures[index].name.indexOf("dds") === -1) {
  538. for (var i = 0; i < 6; i++) {
  539. textures.push({ name: textures[index].name + textures[index]._extensions[i] });
  540. }
  541. }
  542. else {
  543. textures.push({ name: textures[index].name });
  544. }
  545. addTexturesToZip(zip, index + 1, textures, folder, then);
  546. return;
  547. }
  548. if (folder == null) {
  549. folder = zip.folder("textures");
  550. }
  551. var url;
  552. if (textures[index].video) {
  553. url = textures[index].video.currentSrc;
  554. } else {
  555. // url = textures[index].name;
  556. url = textures[index].url ? textures[index].url : textures[index].name;
  557. }
  558. var name = textures[index].name.replace("textures/", "");
  559. // var name = url.substr(url.lastIndexOf("/") + 1);
  560. if (url != null) {
  561. addContentToZip(folder,
  562. name,
  563. url,
  564. null,
  565. true,
  566. function () {
  567. addTexturesToZip(zip, index + 1, textures, folder, then);
  568. });
  569. }
  570. else {
  571. addTexturesToZip(zip, index + 1, textures, folder, then);
  572. }
  573. }
  574. var addImportedFilesToZip = function (zip, index, importedFiles, folder, then) {
  575. if (index === importedFiles.length) {
  576. then();
  577. return;
  578. }
  579. if (!folder) {
  580. folder = zip.folder("scenes");
  581. }
  582. var url = importedFiles[index];
  583. var name = url.substr(url.lastIndexOf("/") + 1);
  584. addContentToZip(folder,
  585. name,
  586. url,
  587. null,
  588. true,
  589. function () {
  590. addImportedFilesToZip(zip, index + 1, importedFiles, folder, then);
  591. });
  592. }
  593. var getZip = function () {
  594. if (engine.scenes.length === 0) {
  595. return;
  596. }
  597. var zip = new JSZip();
  598. var scene = engine.scenes[0];
  599. var textures = scene.textures;
  600. var importedFiles = scene.importedMeshesFiles;
  601. document.getElementById("statusBar").innerHTML = "Creating archive...Please wait";
  602. if (zipCode.indexOf("textures/worldHeightMap.jpg") !== -1) {
  603. textures.push({ name: "textures/worldHeightMap.jpg" });
  604. }
  605. addContentToZip(zip,
  606. "index.html",
  607. "zipContent/index.html",
  608. zipCode,
  609. false,
  610. function () {
  611. addTexturesToZip(zip,
  612. 0,
  613. textures,
  614. null,
  615. function () {
  616. addImportedFilesToZip(zip,
  617. 0,
  618. importedFiles,
  619. null,
  620. function () {
  621. var blob = zip.generate({ type: "blob" });
  622. saveAs(blob, "sample.zip");
  623. document.getElementById("statusBar").innerHTML = "";
  624. });
  625. });
  626. });
  627. }
  628. // Versions
  629. setVersion = function (version) {
  630. switch (version) {
  631. case "stable":
  632. location.href = "indexStable.html" + location.hash;
  633. break;
  634. default:
  635. location.href = "index.html" + location.hash;
  636. break;
  637. }
  638. }
  639. // Fonts
  640. setFontSize = function (size) {
  641. fontSize = size;
  642. jsEditor.updateOptions({ fontSize: size });
  643. setToMultipleID("currentFontSize", "innerHTML", "Font: " + size);
  644. };
  645. // Fullscreen
  646. document.getElementById("renderCanvas").addEventListener("webkitfullscreenchange", function () {
  647. if (document.webkitIsFullScreen) goFullPage();
  648. else exitFullPage();
  649. }, false);
  650. var goFullPage = function () {
  651. var canvasElement = document.getElementById("renderCanvas");
  652. canvasElement.style.position = "absolute";
  653. canvasElement.style.top = 0;
  654. canvasElement.style.left = 0;
  655. canvasElement.style.zIndex = 100;
  656. }
  657. var exitFullPage = function () {
  658. document.getElementById("renderCanvas").style.position = "relative";
  659. document.getElementById("renderCanvas").style.zIndex = 0;
  660. }
  661. var goFullscreen = function () {
  662. if (engine) {
  663. engine.switchFullscreen(true);
  664. }
  665. }
  666. var editorGoFullscreen = function () {
  667. var editorDiv = document.getElementById("jsEditor");
  668. if (editorDiv.requestFullscreen) {
  669. editorDiv.requestFullscreen();
  670. } else if (editorDiv.mozRequestFullScreen) {
  671. editorDiv.mozRequestFullScreen();
  672. } else if (editorDiv.webkitRequestFullscreen) {
  673. editorDiv.webkitRequestFullscreen();
  674. }
  675. }
  676. var toggleEditor = function () {
  677. var editorButton = document.getElementById("editorButton1600");
  678. var scene = engine.scenes[0];
  679. // If the editor is present
  680. if (editorButton.classList.contains('checked')) {
  681. setToMultipleID("editorButton", "removeClass", 'checked');
  682. splitInstance.collapse(0);
  683. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square-o" aria-hidden="true"></i>');
  684. } else {
  685. setToMultipleID("editorButton", "addClass", 'checked');
  686. splitInstance.setSizes([50, 50]); // Reset
  687. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  688. }
  689. engine.resize();
  690. if (scene.debugLayer.isVisible()) {
  691. scene.debugLayer.hide();
  692. scene.debugLayer.show();
  693. }
  694. }
  695. /**
  696. * Toggle the dark theme
  697. */
  698. var toggleTheme = function (theme) {
  699. // Monaco
  700. var vsTheme;
  701. if (theme == 'dark') {
  702. vsTheme = 'vs-dark'
  703. } else {
  704. vsTheme = 'vs'
  705. }
  706. var oldCode = jsEditor.getValue();
  707. jsEditor.dispose();
  708. editorOptions.theme = vsTheme;
  709. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  710. jsEditor.setValue(oldCode);
  711. setFontSize(fontSize);
  712. jsEditor.onKeyUp(function (evt) {
  713. markDirty();
  714. });
  715. for (var index = 0; index < elementToTheme.length; index++) {
  716. var obj = elementToTheme[index];
  717. var domObjArr = document.querySelectorAll(obj);
  718. for (var domObjIndex = 0; domObjIndex < domObjArr.length; domObjIndex++) {
  719. var domObj = domObjArr[domObjIndex];
  720. domObj.classList.remove('light');
  721. domObj.classList.remove('dark');
  722. domObj.classList.add(theme);
  723. }
  724. }
  725. localStorage.setItem("bjs-playground-theme", theme);
  726. }
  727. var toggleDebug = function () {
  728. var debugButton = document.getElementById("debugButton1600");
  729. var scene = engine.scenes[0];
  730. if (debugButton.classList.contains('uncheck')) {
  731. setToMultipleID("debugButton", "removeClass", 'uncheck');
  732. setToMultipleID("debugButton", "innerHTML", 'Inspector<i class="fa fa-check-square" aria-hidden="true"></i>');
  733. scene.debugLayer.show();
  734. } else {
  735. setToMultipleID("debugButton", "addClass", 'uncheck');
  736. setToMultipleID("debugButton", "innerHTML", 'Inspector<i class="fa fa-square-o" aria-hidden="true"></i>');
  737. scene.debugLayer.hide();
  738. }
  739. }
  740. var toggleMetadata = function () {
  741. var scene = engine.scenes[0];
  742. document.getElementById("saveLayer").style.display = "block";
  743. }
  744. var formatCode = function () {
  745. jsEditor.getAction('editor.action.format').run();
  746. }
  747. var toggleMinimap = function () {
  748. var minimapToggle = document.getElementById("minimapToggle1600");
  749. if (minimapToggle.classList.contains('checked')) {
  750. jsEditor.updateOptions({ minimap: { enabled: false } });
  751. setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-square-o" aria-hidden="true"></i>');
  752. } else {
  753. jsEditor.updateOptions({ minimap: { enabled: true } });
  754. setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-check-square" aria-hidden="true"></i>');
  755. }
  756. minimapToggle.classList.toggle('checked');
  757. }
  758. //Navigation Overwrites
  759. var exitPrompt = function (e) {
  760. var safeToggle = document.getElementById("safemodeToggle1600");
  761. if (safeToggle.classList.contains('checked')) {
  762. e = e || window.event;
  763. var message =
  764. 'This page is asking you to confirm that you want to leave - data you have entered may not be saved.';
  765. if (e) {
  766. e.returnValue = message;
  767. }
  768. return message;
  769. }
  770. };
  771. window.onbeforeunload = exitPrompt;
  772. // Snippet
  773. var save = function () {
  774. // Retrieve title if necessary
  775. if (document.getElementById("saveLayer")) {
  776. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  777. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  778. currentSnippetTags = document.getElementById("saveFormTags").value;
  779. }
  780. var xmlHttp = new XMLHttpRequest();
  781. xmlHttp.onreadystatechange = function () {
  782. if (xmlHttp.readyState === 4) {
  783. if (xmlHttp.status === 201) {
  784. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  785. var snippet = JSON.parse(xmlHttp.responseText);
  786. var newUrl = baseUrl + "#" + snippet.id;
  787. currentSnippetToken = snippet.id;
  788. if (snippet.version && snippet.version !== "0") {
  789. newUrl += "#" + snippet.version;
  790. }
  791. location.href = newUrl;
  792. // Hide the complete title & co message
  793. hideNoMetadata();
  794. compileAndRun();
  795. } else {
  796. showError("Unable to save your code. It may be too long.", null);
  797. }
  798. }
  799. }
  800. xmlHttp.open("POST", snippetUrl + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  801. xmlHttp.setRequestHeader("Content-Type", "application/json");
  802. var dataToSend = {
  803. payload: {
  804. code: jsEditor.getValue()
  805. },
  806. name: currentSnippetTitle,
  807. description: currentSnippetDescription,
  808. tags: currentSnippetTags
  809. };
  810. xmlHttp.send(JSON.stringify(dataToSend));
  811. }
  812. var askForSave = function () {
  813. if (currentSnippetTitle == null
  814. || currentSnippetDescription == null
  815. || currentSnippetTags == null) {
  816. document.getElementById("saveLayer").style.display = "block";
  817. }
  818. else {
  819. save();
  820. }
  821. };
  822. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  823. document.getElementById("saveLayer").style.display = "none";
  824. save();
  825. });
  826. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  827. document.getElementById("saveLayer").style.display = "none";
  828. });
  829. document.getElementById("mainTitle").innerHTML = "v" + BABYLON.Engine.Version;
  830. var previousHash = "";
  831. var cleanHash = function () {
  832. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  833. if (splits.length > 2) {
  834. splits.splice(2, splits.length - 2);
  835. }
  836. location.hash = splits.join("#");
  837. }
  838. var checkHash = function (firstTime) {
  839. if (location.hash) {
  840. if (previousHash !== location.hash) {
  841. cleanHash();
  842. previousHash = location.hash;
  843. try {
  844. var xmlHttp = new XMLHttpRequest();
  845. xmlHttp.onreadystatechange = function () {
  846. if (xmlHttp.readyState === 4) {
  847. if (xmlHttp.status === 200) {
  848. var snippet = JSON.parse(xmlHttp.responseText)[0];
  849. blockEditorChange = true;
  850. jsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  851. // Check if title / descr / tags are already set
  852. if (snippet.name != null && snippet.name != "") {
  853. currentSnippetTitle = snippet.name;
  854. }
  855. else currentSnippetTitle = null;
  856. if (snippet.description != null && snippet.description != "") {
  857. currentSnippetDescription = snippet.description;
  858. }
  859. else currentSnippetDescription = null;
  860. if (snippet.tags != null && snippet.tags != "") {
  861. currentSnippetTags = snippet.tags;
  862. }
  863. else currentSnippetTags = null;
  864. if (currentSnippetTitle != null && currentSnippetTags != null && currentSnippetDescription) {
  865. if (document.getElementById("saveLayer")) {
  866. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  867. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  868. document.getElementById("saveFormTags").value = currentSnippetTags;
  869. hideNoMetadata();
  870. }
  871. }
  872. else {
  873. showNoMetadata();
  874. }
  875. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  876. blockEditorChange = false;
  877. compileAndRun();
  878. // setToMultipleID("currentScript", "innerHTML", "Custom");
  879. } else if (firstTime) {
  880. location.href = location.href.replace(location.hash, "");
  881. if (scripts) {
  882. loadScriptFromIndex(0);
  883. }
  884. }
  885. }
  886. };
  887. var hash = location.hash.substr(1);
  888. currentSnippetToken = hash.split("#")[0];
  889. if (!hash.split("#")[1]) hash += "#0";
  890. xmlHttp.open("GET", snippetUrl + "/" + hash.replace("#", "/"));
  891. xmlHttp.send();
  892. } catch (e) {
  893. }
  894. }
  895. }
  896. setTimeout(checkHash, 200);
  897. }
  898. checkHash(true);
  899. // ---------- UI
  900. // Run
  901. setToMultipleID("runButton", "click", compileAndRun);
  902. // New
  903. setToMultipleID("newButton", "click", createNewScript);
  904. // Clear
  905. setToMultipleID("clearButton", "click", clear);
  906. // Save
  907. setToMultipleID("saveButton", "click", askForSave);
  908. // Zip
  909. setToMultipleID("zipButton", "click", getZip);
  910. // Themes
  911. setToMultipleID("darkTheme", "click", toggleTheme.bind(this, 'dark'));
  912. setToMultipleID("lightTheme", "click", toggleTheme.bind(this, 'light'));
  913. // Safe mode
  914. setToMultipleID("safemodeToggle", 'click', function () {
  915. document.getElementById("safemodeToggle1600").classList.toggle('checked');
  916. if (document.getElementById("safemodeToggle1600").classList.contains('checked')) {
  917. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  918. } else {
  919. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square-o" aria-hidden="true"></i>');
  920. }
  921. });
  922. // Editor
  923. setToMultipleID("editorButton", "click", toggleEditor);
  924. // FullScreen
  925. setToMultipleID("fullscreenButton", "click", goFullscreen);
  926. // Editor fullScreen
  927. setToMultipleID("editorFullscreenButton", "click", editorGoFullscreen);
  928. // Format
  929. setToMultipleID("formatButton", "click", formatCode);
  930. // Format
  931. setToMultipleID("minimapToggle", "click", toggleMinimap);
  932. // Debug
  933. setToMultipleID("debugButton", "click", toggleDebug);
  934. // Metadata
  935. setToMultipleID("metadataButton", "click", toggleMetadata);
  936. // Restore theme
  937. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  938. toggleTheme(theme);
  939. }
  940. // Monaco
  941. var xhr = new XMLHttpRequest();
  942. xhr.open('GET', "babylon.d.txt", true);
  943. xhr.onreadystatechange = function () {
  944. if (xhr.readyState === 4) {
  945. if (xhr.status === 200) {
  946. require.config({ paths: { 'vs': 'node_modules/monaco-editor/min/vs' } });
  947. require(['vs/editor/editor.main'], function () {
  948. monaco.languages.typescript.javascriptDefaults.addExtraLib(xhr.responseText, 'babylon.d.ts');
  949. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  950. run();
  951. });
  952. }
  953. }
  954. };
  955. xhr.send(null);
  956. })();