Sigmally Fixes V2

Easily 10X your FPS on Sigmally.com + many bug fixes + great for multiboxing + supports SigMod

目前为 2025-05-10 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Sigmally Fixes V2
  3. // @version 2.7.7
  4. // @description Easily 10X your FPS on Sigmally.com + many bug fixes + great for multiboxing + supports SigMod
  5. // @author 8y8x
  6. // @match https://*.sigmally.com/*
  7. // @license MIT
  8. // @grant none
  9. // @namespace https://8y8x.dev/sigmally-fixes
  10. // @icon https://raw.githubusercontent.com/8y8x/sigmally-fixes/refs/heads/main/icon.png
  11. // @compatible chrome
  12. // @compatible opera
  13. // @compatible edge
  14. // ==/UserScript==
  15.  
  16. // @ts-check
  17. /* eslint
  18. camelcase: 'error',
  19. comma-dangle: ['error', 'always-multiline'],
  20. indent: ['error', 'tab', { SwitchCase: 1 }],
  21. max-len: ['error', { code: 120 }],
  22. no-console: ['error', { allow: ['warn', 'error'] }],
  23. no-trailing-spaces: 'error',
  24. quotes: ['error', 'single'],
  25. semi: 'error',
  26. */ // a light eslint configuration that doesn't compromise code quality
  27. 'use strict';
  28.  
  29. (async () => {
  30. const sfVersion = '2.7.7';
  31. const { Infinity, undefined } = window; // yes, this actually makes a significant difference
  32.  
  33. ////////////////////////////////
  34. // Define Auxiliary Functions //
  35. ////////////////////////////////
  36. const aux = (() => {
  37. const aux = {};
  38.  
  39. /** @type {Map<string, string>} */
  40. aux.clans = new Map();
  41. function fetchClans() {
  42. fetch('https://sigmally.com/api/clans').then(r => r.json()).then(r => {
  43. if (r.status !== 'success') {
  44. setTimeout(() => fetchClans(), 10_000);
  45. return;
  46. }
  47.  
  48. aux.clans.clear();
  49. r.data.forEach(clan => {
  50. if (typeof clan._id !== 'string' || typeof clan.name !== 'string') return;
  51. aux.clans.set(clan._id, clan.name);
  52. });
  53.  
  54. // does not need to be updated often, but just enough so people who leave their tab open don't miss out
  55. setTimeout(() => fetchClans(), 600_000);
  56. }).catch(err => {
  57. console.warn('Error while fetching clans:', err);
  58. setTimeout(() => fetchClans(), 10_000);
  59. });
  60. }
  61. fetchClans();
  62.  
  63. /**
  64. * @template T
  65. * @param {T} x
  66. * @param {string} err should be readable and easily translatable
  67. * @returns {T extends (null | undefined | false | 0) ? never : T}
  68. */
  69. aux.require = (x, err) => {
  70. if (!x) {
  71. err = '[Sigmally Fixes]: ' + err;
  72. prompt(err, err); // use prompt, so people can paste the error message into google translate
  73. throw err;
  74. }
  75.  
  76. return /** @type {any} */ (x);
  77. };
  78.  
  79. const dominantColorCtx = aux.require(
  80. document.createElement('canvas').getContext('2d', { willReadFrequently: true }),
  81. 'Unable to get 2D context for aux utilities. This is probably your browser being dumb, maybe reload ' +
  82. 'the page?',
  83. );
  84. /**
  85. * @param {HTMLImageElement} img
  86. * @returns {[number, number, number, number]}
  87. */
  88. aux.dominantColor = img => {
  89. dominantColorCtx.canvas.width = dominantColorCtx.canvas.height = 7;
  90. dominantColorCtx.drawImage(img, 0, 0, 7, 7);
  91. const data = dominantColorCtx.getImageData(0, 0, 7, 7);
  92.  
  93. const r = [], g = [], b = [];
  94. let sumA = 0, numA = 0;
  95. for (let x = 0; x < 7; ++x) {
  96. for (let y = 0; y < 7; ++y) {
  97. const d = Math.hypot((3 - x) / 6, (3 - y) / 6);
  98. if (d > 1) continue; // do not consider pixels outside a circle, as they may be blank
  99. const pixel = y * 7 + x;
  100. r.push(data.data[pixel * 4]);
  101. g.push(data.data[pixel * 4 + 1]);
  102. b.push(data.data[pixel * 4 + 2]);
  103. sumA += data.data[pixel * 4 + 3];
  104. ++numA;
  105. }
  106. }
  107.  
  108. r.sort();
  109. g.sort();
  110. b.sort();
  111. /** @type {[number, number, number, number]} */
  112. const color = [
  113. r[Math.ceil(r.length / 2)] / 255, g[Math.ceil(g.length / 2)] / 255,
  114. b[Math.ceil(b.length / 2)] / 255, sumA / numA / 255];
  115.  
  116. const max = Math.max(Math.max(color[0], color[1]), color[2]);
  117. if (max === 0) {
  118. color[0] = color[1] = color[2] = 1;
  119. } else {
  120. color[0] *= 1 / max;
  121. color[1] *= 1 / max;
  122. color[2] *= 1 / max;
  123. }
  124.  
  125. color[3] **= 4; // transparent skins should use the player color
  126.  
  127. return color;
  128. };
  129.  
  130. /**
  131. * consistent exponential easing relative to 60fps. this models "x += (targetX - x) * dt" scenarios.
  132. * for example, with a factor of 2, o=0, n=1:
  133. * - at 60fps, 0.5 is returned.
  134. * - at 30fps (after 2 frames), 0.75 is returned.
  135. * - at 15fps (after 4 frames), 0.875 is returned.
  136. * - at 120fps, 0.292893 is returned. if you called this again with o=0.292893, n=1, you would get 0.5.
  137. *
  138. * @param {number} o
  139. * @param {number} n
  140. * @param {number} factor
  141. * @param {number} dt in seconds
  142. */
  143. aux.exponentialEase = (o, n, factor, dt) => {
  144. return o + (n - o) * (1 - (1 - 1 / factor) ** (60 * dt));
  145. };
  146.  
  147. /** @param {KeyboardEvent | MouseEvent} e */
  148. aux.keybind = e => {
  149. if (!e.isTrusted) return undefined; // custom key events are usually missing properties
  150.  
  151. if (e instanceof KeyboardEvent) {
  152. let keybind = e.key;
  153. keybind = keybind[0].toUpperCase() + keybind.slice(1); // capitalize first letter (e.g. Shift, R, /, ...)
  154. if (keybind === '+') keybind = '='; // ensure + can be used to split up keybinds
  155. if (e.ctrlKey) keybind = 'Ctrl+' + keybind;
  156. if (e.altKey) keybind = 'Alt+' + keybind;
  157. if (e.metaKey) keybind = 'Cmd+' + keybind;
  158. if (e.shiftKey) keybind = 'Shift' + keybind;
  159. return keybind;
  160. } else {
  161. return `Mouse${e.button}`;
  162. }
  163. };
  164.  
  165. /**
  166. * @param {string} hex
  167. * @returns {[number, number, number, number]}
  168. */
  169. aux.hex2rgba = hex => {
  170. switch (hex.length) {
  171. case 4: // #rgb
  172. case 5: // #rgba
  173. return [
  174. (parseInt(hex[1], 16) || 0) / 15,
  175. (parseInt(hex[2], 16) || 0) / 15,
  176. (parseInt(hex[3], 16) || 0) / 15,
  177. hex.length === 5 ? (parseInt(hex[4], 16) || 0) / 15 : 1,
  178. ];
  179. case 7: // #rrggbb
  180. case 9: // #rrggbbaa
  181. return [
  182. (parseInt(hex.slice(1, 3), 16) || 0) / 255,
  183. (parseInt(hex.slice(3, 5), 16) || 0) / 255,
  184. (parseInt(hex.slice(5, 7), 16) || 0) / 255,
  185. hex.length === 9 ? (parseInt(hex.slice(7, 9), 16) || 0) / 255 : 1,
  186. ];
  187. default:
  188. return [1, 1, 1, 1];
  189. }
  190. };
  191.  
  192. /**
  193. * @param {number} r
  194. * @param {number} g
  195. * @param {number} b
  196. * @param {number} a
  197. */
  198. aux.rgba2hex = (r, g, b, a) => {
  199. return [
  200. '#',
  201. Math.floor(r * 255).toString(16).padStart(2, '0'),
  202. Math.floor(g * 255).toString(16).padStart(2, '0'),
  203. Math.floor(b * 255).toString(16).padStart(2, '0'),
  204. Math.floor(a * 255).toString(16).padStart(2, '0'),
  205. ].join('');
  206. };
  207.  
  208. // i don't feel like making an awkward adjustment to aux.rgba2hex
  209. /**
  210. * @param {number} r
  211. * @param {number} g
  212. * @param {number} b
  213. * @param {any} _a
  214. */
  215. aux.rgba2hex6 = (r, g, b, _a) => {
  216. return [
  217. '#',
  218. Math.floor(r * 255).toString(16).padStart(2, '0'),
  219. Math.floor(g * 255).toString(16).padStart(2, '0'),
  220. Math.floor(b * 255).toString(16).padStart(2, '0'),
  221. ].join('');
  222. };
  223.  
  224. /** @param {string} name */
  225. aux.parseName = name => name.match(/^\{.*?\}(.*)$/)?.[1] ?? name;
  226.  
  227. /** @param {string} skin */
  228. aux.parseSkin = skin => {
  229. if (!skin) return skin;
  230. skin = skin.replace('1%', '').replace('2%', '').replace('3%', '');
  231. return '/static/skins/' + skin + '.png';
  232. };
  233.  
  234. /**
  235. * @param {DataView} dat
  236. * @param {number} o
  237. * @returns {[string, number]}
  238. */
  239. aux.readZTString = (dat, o) => {
  240. if (dat.getUint8(o) === 0) return ['', o + 1]; // quick return for empty strings (there are a lot)
  241. const startOff = o;
  242. for (; o < dat.byteLength; ++o) {
  243. if (dat.getUint8(o) === 0) break;
  244. }
  245.  
  246. return [aux.textDecoder.decode(new DataView(dat.buffer, startOff, o - startOff)), o + 1];
  247. };
  248.  
  249. /**
  250. * @param {string} selector
  251. * @param {boolean} value
  252. */
  253. aux.setting = (selector, value) => {
  254. /** @type {HTMLInputElement | null} */
  255. const el = document.querySelector(selector);
  256. return el ? el.checked : value;
  257. };
  258.  
  259. /** @param {boolean} accessSigmod */
  260. const settings = accessSigmod => {
  261. try {
  262. // current skin is saved in localStorage
  263. aux.settings = JSON.parse(localStorage.getItem('settings') ?? '');
  264. } catch (_) {
  265. aux.settings = /** @type {any} */ ({});
  266. }
  267.  
  268. // sigmod doesn't have a checkbox for dark theme, so we infer it from the custom map color
  269. const { mapColor } = accessSigmod ? sigmod.settings : {};
  270. if (mapColor) {
  271. aux.settings.darkTheme
  272. = mapColor ? (mapColor[0] < 0.6 && mapColor[1] < 0.6 && mapColor[2] < 0.6) : true;
  273. } else {
  274. aux.settings.darkTheme = aux.setting('input#darkTheme', true);
  275. }
  276. aux.settings.jellyPhysics = aux.setting('input#jellyPhysics', false);
  277. aux.settings.showBorder = aux.setting('input#showBorder', true);
  278. aux.settings.showClanmates = aux.setting('input#showClanmates', true);
  279. aux.settings.showGrid = aux.setting('input#showGrid', true);
  280. aux.settings.showMass = aux.setting('input#showMass', false);
  281. aux.settings.showMinimap = aux.setting('input#showMinimap', true);
  282. aux.settings.showSkins = aux.setting('input#showSkins', true);
  283. aux.settings.zoomout = aux.setting('input#moreZoom', true);
  284. return aux.settings;
  285. };
  286.  
  287. /** @type {{ darkTheme: boolean, jellyPhysics: boolean, showBorder: boolean, showClanmates: boolean,
  288. showGrid: boolean, showMass: boolean, showMinimap: boolean, showSkins: boolean, zoomout: boolean,
  289. gamemode: any, skin: any }} */
  290. aux.settings = settings(false);
  291. setInterval(() => settings(true), 250);
  292. // apply saved gamemode because sigmally fixes connects before the main game even loads
  293. if (aux.settings?.gamemode) {
  294. /** @type {HTMLSelectElement | null} */
  295. const gamemode = document.querySelector('select#gamemode');
  296. if (gamemode)
  297. gamemode.value = aux.settings.gamemode;
  298. }
  299.  
  300. let caught = false;
  301. const tabScan = new BroadcastChannel('sigfix-tabscan');
  302. tabScan.addEventListener('message', () => {
  303. if (caught || world.score(world.selected) <= 50) return;
  304. caught = true;
  305. const str = 'hi! sigmally fixes v2.5.0 is now truly one-tab, so you don\'t need multiple tabs anymore. ' +
  306. 'set a keybind under the "One-tab multibox key" setting and enjoy!';
  307. prompt(str, str);
  308. });
  309. setInterval(() => {
  310. if (world.score(world.selected) > 50 && !caught) tabScan.postMessage(undefined);
  311. }, 5000);
  312.  
  313. aux.textEncoder = new TextEncoder();
  314. aux.textDecoder = new TextDecoder();
  315.  
  316. const trimCtx = aux.require(
  317. document.createElement('canvas').getContext('2d'),
  318. 'Unable to get 2D context for text utilities. This is probably your browser being dumb, maybe reload ' +
  319. 'the page?',
  320. );
  321. trimCtx.font = '20px Ubuntu';
  322. /**
  323. * trims text to a max of 250px at 20px font, same as vanilla sigmally
  324. * @param {string} text
  325. */
  326. aux.trim = text => {
  327. while (trimCtx.measureText(text).width > 250)
  328. text = text.slice(0, -1);
  329.  
  330. return text;
  331. };
  332.  
  333. // @ts-expect-error
  334. let handler = window.signOut;
  335. Object.defineProperty(window, 'signOut', {
  336. get: () => () => {
  337. aux.userData = undefined;
  338. return handler?.();
  339. },
  340. set: x => handler = x,
  341. });
  342.  
  343. /** @type {object | undefined} */
  344. aux.userData = undefined;
  345. aux.oldFetch = /** @type {typeof fetch} */ (fetch.bind(window));
  346. let lastUserData = -Infinity;
  347. // this is the best method i've found to get the userData object, since game.js uses strict mode
  348. Object.defineProperty(window, 'fetch', {
  349. value: new Proxy(fetch, {
  350. apply: (target, thisArg, args) => {
  351. let url = args[0];
  352. const data = args[1];
  353. if (typeof url === 'string') {
  354. if (url.includes('/server/recaptcha/v3'))
  355. return new Promise(() => {}); // block game.js from attempting to go through captcha flow
  356.  
  357. // game.js doesn't think we're connected to a server, we default to eu0 because that's the
  358. // default everywhere else
  359. if (url.includes('/userdata/')) {
  360. // when holding down the respawn key, you can easily make 30+ requests a second,
  361. // bombing you into ratelimit hell
  362. const now = performance.now();
  363. if (now - lastUserData < 500) return new Promise(() => {});
  364. url = url.replace('///', '//eu0.sigmally.com/server/');
  365. lastUserData = now;
  366. }
  367.  
  368. if (url.includes('/server/auth')) {
  369. // sigmod must be properly initialized (client can't be null), otherwise it will error
  370. // and game.js will never get the account data
  371. sigmod.patch();
  372. }
  373.  
  374. // patch the current token in the url and body of the request
  375. if (aux.userData?.token) {
  376. // 128 hex characters surrounded by non-hex characters (lookahead and lookbehind)
  377. const tokenTest = /(?<![0-9a-fA-F])[0-9a-fA-F]{128}(?![0-9a-fA-F])/g;
  378. url = url.replaceAll(tokenTest, aux.userData.token);
  379. if (typeof data?.body === 'string')
  380. data.body = data.body.replaceAll(tokenTest, aux.userData.token);
  381. }
  382.  
  383. args[0] = url;
  384. args[1] = data;
  385. }
  386.  
  387. return target.apply(thisArg, args).then(res => new Proxy(res, {
  388. get: (target, prop, _receiver) => {
  389. if (prop !== 'json') {
  390. const val = target[prop];
  391. if (typeof val === 'function')
  392. return val.bind(target);
  393. else
  394. return val;
  395. }
  396.  
  397. return () => target.json().then(obj => {
  398. if (obj?.body?.user) {
  399. aux.userData = obj.body.user;
  400. // NaN if invalid / undefined
  401. let updated = Number(new Date(aux.userData.updateTime));
  402. if (Number.isNaN(updated))
  403. updated = Date.now();
  404. }
  405.  
  406. return obj;
  407. });
  408. },
  409. }));
  410. },
  411. }),
  412. });
  413.  
  414. // get the latest game.js version whenever possible
  415. // some players are stuck on an older game.js version which does not allow signing in
  416. fetch('https://one.sigmally.com/assets/js/game.js', { cache: 'reload' });
  417. // clicking "continue" immediately makes a request for user data, so we can get it even if sigfixes runs late
  418. /** @type {HTMLButtonElement | null} */ (document.querySelector('#continue_button'))?.click();
  419.  
  420. return aux;
  421. })();
  422.  
  423.  
  424.  
  425. ////////////////////////
  426. // Destroy Old Client //
  427. ////////////////////////
  428. const destructor = (() => {
  429. const destructor = {};
  430.  
  431. const vanillaStack = () => {
  432. try {
  433. throw new Error();
  434. } catch (err) {
  435. // prevent drawing the game, but do NOT prevent saving settings (which is called on RQA)
  436. return err.stack.includes('/game.js') && !err.stack.includes('HTML');
  437. }
  438. };
  439.  
  440. // #1 : kill the rendering process
  441. const oldRQA = requestAnimationFrame;
  442. window.requestAnimationFrame = function(fn) {
  443. return vanillaStack() ? -1 : oldRQA(fn);
  444. };
  445.  
  446. // #2 : kill access to using a WebSocket
  447. destructor.realWebSocket = WebSocket;
  448. Object.defineProperty(window, 'WebSocket', {
  449. value: new Proxy(WebSocket, {
  450. construct(_target, argArray, _newTarget) {
  451. if (argArray[0].includes('sigmally.com') && vanillaStack()) {
  452. throw new Error('sigfix: Preventing new WebSocket() for unknown Sigmally connection');
  453. }
  454.  
  455. // @ts-expect-error
  456. return new destructor.realWebSocket(...argArray);
  457. },
  458. }),
  459. });
  460.  
  461. const cmdRepresentation = new TextEncoder().encode('/leaveworld').toString();
  462. destructor.realWsSend = WebSocket.prototype.send;
  463. WebSocket.prototype.send = function (x) {
  464. if (vanillaStack() && this.url.includes('sigmally.com')) {
  465. this.onclose = null;
  466. this.close();
  467. throw new Error('sigfix: Preventing .send on unknown Sigmally connection');
  468. }
  469.  
  470. return destructor.realWsSend.apply(this, arguments);
  471. };
  472.  
  473. // #3 : prevent keys from being registered by the game
  474. setInterval(() => onkeydown = onkeyup = null, 200);
  475.  
  476. return destructor;
  477. })();
  478.  
  479.  
  480.  
  481. //////////////////////////////////
  482. // Apply Complex SigMod Patches //
  483. //////////////////////////////////
  484. const sigmod = (() => {
  485. const sigmod = {};
  486.  
  487. /** @type {{
  488. * cellColor?: [number, number, number, number],
  489. * fixedLineKey?: string,
  490. * foodColor?: [number, number, number, number],
  491. * font?: string,
  492. * horizontalLineKey?: string,
  493. * mapColor?: [number, number, number, number],
  494. * nameColor1?: [number, number, number, number],
  495. * nameColor2?: [number, number, number, number],
  496. * outlineColor?: [number, number, number, number],
  497. * rapidFeedKey?: string,
  498. * removeOutlines?: boolean,
  499. * respawnKey?: string,
  500. * showNames?: boolean,
  501. * tripleKey?: string,
  502. * verticalLineKey?: string,
  503. * virusImage?: string,
  504. * }} */
  505. sigmod.settings = {};
  506. /** @type {Set<string>} */
  507. const loadedFonts = new Set();
  508. setInterval(() => {
  509. // @ts-expect-error
  510. const real = window.sigmod?.settings;
  511. if (!real) return;
  512. sigmod.exists = true;
  513.  
  514. /**
  515. * @param {'cellColor' | 'foodColor' | 'mapColor' | 'outlineColor' | 'nameColor1' | 'nameColor2'} prop
  516. * @param {any} initial
  517. * @param {any[]} lookups
  518. */
  519. const applyColor = (prop, initial, lookups) => {
  520. for (const lookup of lookups) {
  521. if (lookup && lookup !== initial) {
  522. sigmod.settings[prop] = aux.hex2rgba(lookup);
  523. return;
  524. }
  525. }
  526. sigmod.settings[prop] = undefined;
  527. };
  528. applyColor('cellColor', null, [real.game?.cellColor]);
  529. applyColor('foodColor', null, [real.game?.foodColor]);
  530. applyColor('mapColor', null, [real.game?.map?.color, real.mapColor]);
  531. // sigmod treats the map border as cell borders for some reason
  532. applyColor('outlineColor', '#0000ff', [real.game?.borderColor]);
  533. // note: singular nameColor takes priority
  534. applyColor('nameColor1', '#ffffff', [
  535. real.game?.name?.color,
  536. real.game?.name?.gradient?.enabled && real.game.name.gradient.left,
  537. ]);
  538. applyColor('nameColor2', '#ffffff', [
  539. real.game?.name?.color,
  540. real.game?.name?.gradient?.enabled && real.game.name.gradient.right,
  541. ]);
  542. sigmod.settings.removeOutlines = real.game?.removeOutlines;
  543. sigmod.settings.virusImage = real.game?.virusImage;
  544. sigmod.settings.rapidFeedKey = real.macros?.keys?.rapidFeed;
  545. // sigmod's showNames setting is always "true" interally (i think??)
  546. sigmod.settings.showNames = aux.setting('input#showNames', true);
  547.  
  548. sigmod.settings.tripleKey = real.macros?.keys?.splits?.triple || undefined;
  549. sigmod.settings.font = real.game?.font;
  550.  
  551. // sigmod does not download the bold variants of fonts, so we have to do that ourselves
  552. if (sigmod.settings.font && !loadedFonts.has(sigmod.settings.font)) {
  553. loadedFonts.add(sigmod.settings.font);
  554. const link = document.createElement('link');
  555. link.href = `https://fonts.googleapis.com/css2?family=${sigmod.settings.font}:wght@700&display=swap`;
  556. link.rel = 'stylesheet';
  557. document.head.appendChild(link);
  558. }
  559. }, 200);
  560.  
  561. // patch sigmod when it's ready; typically sigmod loads first, but i can't guarantee that
  562. sigmod.exists = false;
  563. sigmod.proxy = {};
  564. let patchInterval;
  565. sigmod.patch = () => {
  566. const real = /** @type {any} */ (window).sigmod;
  567. if (!real || patchInterval === undefined) return;
  568. sigmod.exists = true;
  569.  
  570. clearInterval(patchInterval);
  571. patchInterval = undefined;
  572.  
  573. // anchor chat and minimap to the screen, so scrolling to zoom doesn't move them
  574. // it's possible that cursed will change something at any time so i'm being safe here
  575. const minimapContainer = /** @type {HTMLElement | null} */ (document.querySelector('.minimapContainer'));
  576. if (minimapContainer) minimapContainer.style.position = 'fixed';
  577.  
  578. const modChat = /** @type {HTMLElement | null} */ (document.querySelector('.modChat'));
  579. if (modChat) modChat.style.position = 'fixed';
  580.  
  581. // sigmod keeps track of the # of displayed messages with a counter, but it doesn't reset on clear
  582. // therefore, if the chat gets cleared with 200 (the maximum) messages in it, it will stay permanently*
  583. // blank
  584. const modMessages = /** @type {HTMLElement | null} */ (document.querySelector('#mod-messages'));
  585. if (modMessages) {
  586. const old = modMessages.removeChild;
  587. modMessages.removeChild = node => {
  588. if (modMessages.children.length > 200) return old.call(modMessages, node);
  589. else return node;
  590. };
  591. }
  592.  
  593. // disable linesplit keys on sigmod's end and enable them here
  594. const lineKeys = real.settings?.macros?.keys?.line;
  595. if (lineKeys) {
  596. sigmod.settings.horizontalLineKey = lineKeys.horizontal;
  597. sigmod.settings.verticalLineKey = lineKeys.vertical;
  598. sigmod.settings.fixedLineKey = lineKeys.fixed;
  599. /** @param {keyof typeof sigmod.settings} key */
  600. const getset = key => ({
  601. // toJSON and toString are implemented so that the key still displays and saves properly,
  602. // while returning an object that would never match anything in a keydown event
  603. get: () => ({ toJSON: () => sigmod.settings[key], toString: () => sigmod.settings[key] }),
  604. set: x => sigmod.settings[key] = x,
  605. });
  606. Object.defineProperties(lineKeys, {
  607. horizontal: getset('horizontalLineKey'),
  608. vertical: getset('verticalLineKey'),
  609. fixed: getset('fixedLineKey'),
  610. });
  611. }
  612. // also disable sigmod's respawn key and reimplement it here
  613. const keys = real.settings?.macros?.keys;
  614. if (keys) {
  615. sigmod.settings.respawnKey = keys.respawn;
  616. Object.defineProperty(keys, 'respawn', {
  617. get: () => ({
  618. toJSON: () => sigmod.settings.respawnKey,
  619. toString: () => sigmod.settings.respawnKey,
  620. }),
  621. set: x => sigmod.settings.respawnKey = x,
  622. });
  623. }
  624.  
  625. // create a fake sigmally proxy for sigmod, which properly relays some packets (because SigMod does not
  626. // support one-tab technology). it should also fix chat bugs due to disconnects and stuff
  627. // we do this by hooking into the SigWsHandler object
  628. {
  629. /** @type {object | undefined} */
  630. let handler;
  631. const old = Function.prototype.bind;
  632. Function.prototype.bind = function(obj) {
  633. if (obj.constructor?.name === 'SigWsHandler') handler = obj;
  634. return old.call(this, obj);
  635. };
  636. new WebSocket('wss://255.255.255.255/sigmally.com?sigfix');
  637. Function.prototype.bind = old;
  638. // handler is expected to be a "SigWsHandler", but it might be something totally different
  639. if (handler && 'sendPacket' in handler && 'handleMessage' in handler) {
  640. // first, set up the handshake (opcode not-really-a-shuffle)
  641. // handshake is reset to false on close (which may or may not happen immediately)
  642. Object.defineProperty(handler, 'handshake', { get: () => true, set: () => {} });
  643. handler.R = handler.C = new Uint8Array(256); // R and C are linked
  644. for (let i = 0; i < 256; ++i) handler.C[i] = i;
  645.  
  646. // expose some functions here, don't directly access the handler anywhere else
  647. sigmod.proxy = {
  648. /** @param {DataView} dat */
  649. handleMessage: dat => handler.handleMessage({ data: dat.buffer }),
  650. isPlaying: () => /** @type {any} */ (window).gameSettings.isPlaying = true,
  651. };
  652.  
  653. // override sendPacket to properly handle what sigmod expects
  654. /** @param {object} buf */
  655. handler.sendPacket = buf => {
  656. if ('build' in buf) buf = buf.build(); // convert sigmod/sigmally Writer class to a buffer
  657. if ('buffer' in buf) buf = buf.buffer;
  658. const dat = new DataView(/** @type {ArrayBuffer} */ (buf));
  659. switch (dat.getUint8(0)) {
  660. // case 0x00, sendPlay, isn't really used outside of secret tournaments
  661. case 0x10: { // used for linesplits and such
  662. net.move(world.selected, dat.getInt32(1, true), dat.getInt32(5, true));
  663. break;
  664. }
  665. // case 0x63, sendChat, already goes directly to sigfix.net.chat
  666. // case 0xdc, sendFakeCaptcha, is not used outside of secret tournaments
  667. }
  668. };
  669. }
  670. }
  671. };
  672. patchInterval = setInterval(sigmod.patch, 500);
  673. sigmod.patch();
  674.  
  675. return sigmod;
  676. })();
  677.  
  678.  
  679.  
  680. /////////////////////////
  681. // Create Options Menu //
  682. /////////////////////////
  683. const settings = (() => {
  684. const settings = {
  685. autoZoom: true,
  686. background: '',
  687. blockBrowserKeybinds: false,
  688. blockNearbyRespawns: false,
  689. boldUi: false,
  690. /** @type {'natural' | 'default'} */
  691. camera: 'default',
  692. /** @type {'default' | 'instant'} */
  693. cameraMovement: 'default',
  694. cameraSmoothness: 2,
  695. cameraSpawnAnimation: true,
  696. cellGlow: false,
  697. cellOpacity: 1,
  698. cellOutlines: true,
  699. clans: false,
  700. clanScaleFactor: 1,
  701. colorUnderSkin: true,
  702. drawDelay: 120,
  703. jellySkinLag: true,
  704. massBold: false,
  705. massOpacity: 1,
  706. massScaleFactor: 1,
  707. mergeCamera: true,
  708. moveAfterLinesplit: false,
  709. multibox: '',
  710. /** @type {string[]} */
  711. multiNames: [],
  712. nameBold: false,
  713. nameScaleFactor: 1,
  714. nbox: false,
  715. nboxCount: 3,
  716. nboxCyclePair: '',
  717. nboxHoldKeybinds: ['', '', '', '', '', '', '', ''],
  718. nboxSelectKeybinds: ['', '', '', '', '', '', '', ''],
  719. nboxSwitchPair: '',
  720. outlineMulti: 0.2,
  721. // delta's default colors, #ff00aa and #ffffff
  722. outlineMultiColor: /** @type {[number, number, number, number]} */ ([1, 0, 2/3, 1]),
  723. outlineMultiInactiveColor: /** @type {[number, number, number, number]} */ ([1, 1, 1, 1]),
  724. pelletGlow: false,
  725. rainbowBorder: false,
  726. scrollFactor: 1,
  727. selfSkin: '',
  728. selfSkinMulti: '',
  729. selfSkinNbox: ['', '', '', '', '', ''],
  730. slowerJellyPhysics: false,
  731. separateBoost: false,
  732. showStats: true,
  733. spectator: false,
  734. spectatorLatency: false,
  735. /** @type {'' | 'latest' | 'flawless'} */
  736. synchronization: 'flawless',
  737. textOutlinesFactor: 1,
  738. // default is the default chat color
  739. theme: /** @type {[number, number, number, number]} */ ([252 / 255, 114 / 255, 0, 0]),
  740. tracer: false,
  741. unsplittableColor: /** @type {[number, number, number, number]} */ ([1, 1, 1, 1]),
  742. yx: false, // hehe
  743. };
  744.  
  745. const settingsExt = {};
  746. Object.setPrototypeOf(settings, settingsExt);
  747.  
  748. try {
  749. Object.assign(settings, JSON.parse(localStorage.getItem('sigfix') ?? ''));
  750. } catch (_) { }
  751.  
  752. // convert old settings
  753. {
  754. if (/** @type {any} */ (settings.multibox) === true) settings.multibox = 'Tab';
  755. else if (/** @type {any} */ (settings.multibox) === false) settings.multibox = '';
  756.  
  757. if (/** @type {any} */ (settings).unsplittableOpacity !== undefined) {
  758. settings.unsplittableColor = [1, 1, 1, /** @type {any} */ (settings).unsplittableOpacity];
  759. delete settings.unsplittableOpacity;
  760. }
  761.  
  762. const { autoZoom, multiCamera, synchronization } = /** @type {any} */ (settings);
  763. if (multiCamera !== undefined) {
  764. if (multiCamera === 'natural' || multiCamera === 'delta' || multiCamera === 'weighted') {
  765. settings.camera = 'natural';
  766. } else if (multiCamera === 'none') settings.camera = 'default';
  767.  
  768. settings.mergeCamera = multiCamera !== 'weighted' && multiCamera !== 'none'; // the two-tab settings
  769. delete settings.multiCamera;
  770. }
  771.  
  772. if (autoZoom === 'auto') settings.autoZoom = true;
  773. else if (autoZoom === 'never') settings.autoZoom = false;
  774.  
  775. // accidentally set the default to 'none' which sucks
  776. if (synchronization === 'none') settings.synchronization = 'flawless';
  777. }
  778.  
  779. /** @type {(() => void)[]} */
  780. const onSyncs = [];
  781. /** @type {(() => void)[]} */
  782. const onUpdates = [];
  783.  
  784. settingsExt.refresh = () => {
  785. onSyncs.forEach(fn => fn());
  786. onUpdates.forEach(fn => fn());
  787. };
  788.  
  789. // allow syncing sigfixes settings in case you leave an extra sig tab open for a long time and would lose your
  790. // changed settings
  791. const channel = new BroadcastChannel('sigfix-settings');
  792. channel.addEventListener('message', msg => {
  793. Object.assign(settings, msg.data);
  794. settingsExt.refresh();
  795. });
  796.  
  797. /** @type {IDBDatabase | undefined} */
  798. settingsExt.database = undefined;
  799. const dbReq = indexedDB.open('sigfix', 1);
  800. dbReq.addEventListener('success', () => void (settingsExt.database = dbReq.result));
  801. dbReq.addEventListener('upgradeneeded', () => {
  802. settingsExt.database = dbReq.result;
  803. settingsExt.database.createObjectStore('images');
  804. });
  805.  
  806. // #1 : define helper functions
  807. /**
  808. * @param {string} html
  809. * @returns {HTMLElement}
  810. */
  811. function fromHTML(html) {
  812. const div = document.createElement('div');
  813. div.innerHTML = html;
  814. return /** @type {HTMLElement} */ (div.firstElementChild);
  815. }
  816.  
  817. settingsExt.save = () => {
  818. localStorage.setItem('sigfix', JSON.stringify(settings));
  819. channel.postMessage(settings);
  820. onUpdates.forEach(fn => fn());
  821. }
  822.  
  823. /**
  824. * @template O, T
  825. * @typedef {{ [K in keyof O]: O[K] extends T ? K : never }[keyof O]} PropertyOfType
  826. */
  827.  
  828. /** @type {HTMLElement | null} */
  829. const vanillaModal = document.querySelector('#cm_modal__settings .ctrl-modal__modal');
  830. if (vanillaModal) vanillaModal.style.width = '440px'; // make modal wider to fit everything properly
  831.  
  832. const vanillaMenu = document.querySelector('#cm_modal__settings .ctrl-modal__content');
  833. vanillaMenu?.appendChild(fromHTML(`
  834. <div class="menu__item">
  835. <div style="width: 100%; height: 1px; background: #bfbfbf;"></div>
  836. </div>
  837. `));
  838.  
  839. /**
  840. * @template T
  841. * @param {T | null} el
  842. * @returns {T}
  843. */
  844. const require = el => /** @type {T} */ (el); // aux.require is unnecessary for requiring our own elements
  845.  
  846. const vanillaContainer = document.createElement('div');
  847. vanillaContainer.className = 'menu__item';
  848. vanillaMenu?.appendChild(vanillaContainer);
  849.  
  850. const sigmodContainer = document.createElement('div');
  851. sigmodContainer.className = 'mod_tab scroll';
  852. sigmodContainer.style.display = 'none';
  853.  
  854. /** @type {{ container: HTMLElement, help: HTMLElement, helpbox: HTMLElement }[]} */
  855. const containers = [];
  856.  
  857. /**
  858. * @param {string} title
  859. * @param {{ sigmod: HTMLElement, vanilla: HTMLElement }[]} components
  860. * @param {() => boolean} show
  861. * @param {string} help
  862. */
  863. const setting = (title, components, show, help) => {
  864. const vanilla = fromHTML(`
  865. <div style="height: 25px; position: relative;">
  866. <div style="height: 25px; line-height: 25px; position: absolute; top: 0; left: 0;">
  867. <a id="sf-help" style="color: #0009; cursor: help; user-select: none;">(?)</a> ${title}
  868. </div>
  869. <div id="sf-components" style="height: 25px; margin-left: 5px; position: absolute; right: 0;
  870. bottom: 0;"></div>
  871. <div id="sf-helpbox" style="display: none; position: absolute; top: calc(100% + 5px); left: 20px;
  872. width: calc(100% - 30px); height: fit-content; padding: 10px; color: #000; background: #fff;
  873. border: 1px solid #999; border-radius: 4px; z-index: 2;">
  874. ${help}
  875. </div>
  876. </div>
  877. `);
  878. const sigmod = fromHTML(`
  879. <div class="modRowItems justify-sb" style="padding: 5px 10px; position: relative;">
  880. <span><a id="sfsm-help" style="color: #fff9; cursor: help; user-select: none;">(?)</a> ${title}\
  881. </span>
  882. <span class="justify-sb" id="sfsm-components"></span>
  883. <div id="sfsm-helpbox" style="display: none; position: absolute; top: calc(100% + 5px); left: 30px;
  884. width: calc(100% - 40px); height: fit-content; padding: 10px; color: #fffe; background: #000;
  885. border: 1px solid #6871f1; border-radius: 4px; z-index: 2;">${help}</div>
  886. </div>
  887. `);
  888.  
  889. const vanillaComponents = require(vanilla.querySelector('#sf-components'));
  890. const sigmodComponents = require(sigmod.querySelector('#sfsm-components'));
  891. for (const pair of components) {
  892. vanillaComponents.appendChild(pair.vanilla);
  893. sigmodComponents.appendChild(pair.sigmod);
  894. }
  895.  
  896. const reshow = () => void (vanilla.style.display = sigmod.style.display = show() ? '' : 'none');
  897. reshow();
  898. onUpdates.push(reshow);
  899.  
  900. vanillaContainer.appendChild(vanilla);
  901. sigmodContainer.appendChild(sigmod);
  902. containers.push({
  903. container: vanilla,
  904. help: require(vanilla.querySelector('#sf-help')),
  905. helpbox: require(vanilla.querySelector('#sf-helpbox')),
  906. }, {
  907. container: sigmod,
  908. help: require(sigmod.querySelector('#sfsm-help')),
  909. helpbox: require(sigmod.querySelector('#sfsm-helpbox')),
  910. });
  911. };
  912.  
  913. /**
  914. * @param {PropertyOfType<typeof settings, number>} property
  915. * @param {number} initial
  916. * @param {number} min
  917. * @param {number} max
  918. * @param {number} step
  919. * @param {number} decimals
  920. */
  921. const slider = (property, initial, min, max, step, decimals) => {
  922. /**
  923. * @param {HTMLInputElement} slider
  924. * @param {HTMLInputElement} display
  925. */
  926. const listen = (slider, display) => {
  927. const change = () => slider.value = display.value = settings[property].toFixed(decimals);
  928. onSyncs.push(change);
  929. change();
  930.  
  931. /** @param {HTMLInputElement} input */
  932. const onInput = input => {
  933. const value = Number(input.value);
  934. if (Number.isNaN(value)) return;
  935.  
  936. settings[property] = value;
  937. change();
  938. settingsExt.save();
  939. };
  940. slider.addEventListener('input', () => onInput(slider));
  941. display.addEventListener('change', () => onInput(display));
  942. };
  943.  
  944. const datalist = `<datalist id="sf-${property}-markers"> <option value="${initial}"></option> </datalist>`;
  945. const vanilla = fromHTML(`
  946. <div>
  947. <input id="sf-${property}" style="display: block; float: left; height: 25px; line-height: 25px;
  948. margin-left: 5px;" min="${min}" max="${max}" step="${step}" value="${initial}"
  949. list="sf-${property}-markers" type="range" />
  950. ${initial !== undefined ? datalist : ''}
  951. <input id="sf-${property}-display" style="display: block; float: left; height: 25px;
  952. line-height: 25px; width: 50px; text-align: center; margin-left: 5px;" />
  953. </div>
  954. `);
  955. const sigmod = fromHTML(`
  956. <span class="justify-sb">
  957. <input id="sfsm-${property}" style="width: 200px;" type="range" min="${min}" max="${max}"
  958. step="${step}" value="${initial}" list="sf-${property}-markers" />
  959. ${initial !== undefined ? datalist : ''}
  960. <input id="sfsm-${property}-display" class="text-center form-control" style="border: none;
  961. width: 50px; margin: 0 15px;" />
  962. </span>
  963. `);
  964.  
  965. listen(require(vanilla.querySelector(`#sf-${property}`)),
  966. require(vanilla.querySelector(`#sf-${property}-display`)));
  967. listen(aux.require(sigmod.querySelector(`#sfsm-${property}`), 'no selector match'),
  968. aux.require(sigmod.querySelector(`#sfsm-${property}-display`), 'no selector match'));
  969. return { sigmod, vanilla };
  970. };
  971.  
  972. /** @param {PropertyOfType<typeof settings, boolean>} property */
  973. const checkbox = property => {
  974. /** @param {HTMLInputElement} input */
  975. const listen = input => {
  976. onSyncs.push(() => input.checked = settings[property]);
  977. input.checked = settings[property];
  978.  
  979. input.addEventListener('input', () => {
  980. settings[property] = input.checked;
  981. settingsExt.save();
  982. });
  983. };
  984.  
  985. const vanilla = fromHTML(`<input id="sf-${property}" type="checkbox" />`);
  986. const sigmod = fromHTML(`
  987. <div style="margin-right: 25px;">
  988. <div class="modCheckbox" style="display: inline-block;">
  989. <input id="sfsm-${property}" type="checkbox" />
  990. <label class="cbx" for="sfsm-${property}"></label>
  991. </div>
  992. </div>
  993. `);
  994. listen(/** @type {HTMLInputElement} */ (vanilla));
  995. listen(require(sigmod.querySelector(`#sfsm-${property}`)));
  996. return { sigmod, vanilla };
  997. };
  998.  
  999. /**
  1000. * @param {any} property
  1001. * @param {any} parent
  1002. * @param {string} key
  1003. */
  1004. const image = (property, parent = settings, key = property) => {
  1005. /**
  1006. * @param {HTMLInputElement} input
  1007. * @param {boolean} isSigmod
  1008. */
  1009. const listen = (input, isSigmod) => {
  1010. onSyncs.push(() => input.value = parent[property]);
  1011. input.value = parent[property];
  1012.  
  1013. input.addEventListener('input', e => {
  1014. if (input.value.startsWith('🖼️')) {
  1015. input.value = parent[property];
  1016. e.preventDefault();
  1017. return;
  1018. }
  1019.  
  1020. /** @type {string} */ (parent[property]) = input.value;
  1021. settingsExt.save();
  1022. });
  1023. input.addEventListener('dragenter', () => void (input.style.borderColor = '#00ccff'));
  1024. input.addEventListener('dragleave',
  1025. () => void (input.style.borderColor = isSigmod ? 'transparent' : ''));
  1026. input.addEventListener('drop', e => {
  1027. input.style.borderColor = isSigmod ? 'transparent' : '';
  1028. e.preventDefault();
  1029.  
  1030. const file = e.dataTransfer?.files[0];
  1031. if (!file) return;
  1032.  
  1033. const { database } = settingsExt;
  1034. if (!database) return;
  1035.  
  1036. input.value = '(importing)';
  1037.  
  1038. const transaction = database.transaction('images', 'readwrite');
  1039. transaction.objectStore('images').put(file, key);
  1040.  
  1041. transaction.addEventListener('complete', () => {
  1042. /** @type {string} */ (parent[property]) = input.value = `🖼️ ${file.name}`;
  1043. settingsExt.save();
  1044. render.resetDatabaseCache();
  1045. });
  1046. transaction.addEventListener('error', err => {
  1047. input.value = '(failed to load image)';
  1048. console.warn('sigfix database error:', err);
  1049. });
  1050. });
  1051. };
  1052.  
  1053. const placeholder = 'https://i.imgur.com/... or drag here';
  1054. const vanilla = fromHTML(`<input id="sf-${property}" placeholder="${placeholder}" type="text" />`);
  1055. const sigmod = fromHTML(`<input class="modInput" id="sfsm-${property}" placeholder="${placeholder}"
  1056. style="border: 1px solid transparent; width: 250px;" type="text" />`);
  1057. listen(/** @type {HTMLInputElement} */ (vanilla), false);
  1058. listen(/** @type {HTMLInputElement} */ (sigmod), true);
  1059. return { sigmod, vanilla };
  1060. };
  1061.  
  1062. /** @param {PropertyOfType<typeof settings, [number, number, number, number]>} property */
  1063. const color = (property, toggle = false) => {
  1064. /**
  1065. * @param {HTMLInputElement} input
  1066. * @param {HTMLInputElement} alpha
  1067. */
  1068. const listen = (input, alpha) => {
  1069. const update = () => {
  1070. input.value = aux.rgba2hex6(...settings[property]);
  1071. if (toggle) alpha.checked = settings[property][3] > 0;
  1072. else alpha.value = String(settings[property][3]);
  1073. };
  1074. onSyncs.push(update);
  1075. update();
  1076.  
  1077. const changed = () => {
  1078. settings[property] = aux.hex2rgba(input.value);
  1079. if (toggle) settings[property][3] = alpha.checked ? 1 : 0;
  1080. else settings[property][3] = Number(alpha.value);
  1081. settingsExt.save();
  1082. };
  1083. input.addEventListener('input', changed);
  1084. alpha.addEventListener('input', changed);
  1085. };
  1086.  
  1087. const vanilla = fromHTML(`
  1088. <div>
  1089. <input id="sf-${property}-alpha" type="${toggle ? 'checkbox' : 'range'}" min="0" max="1" \
  1090. step="0.01" ${toggle ? '' : 'style="width: 100px;"'} />
  1091. <input id="sf-${property}" type="color" />
  1092. </div>
  1093. `);
  1094. const sigmod = fromHTML(`
  1095. <div style="margin-right: 25px;">
  1096. ${toggle ? `<div class="modCheckbox" style="display: inline-block;">
  1097. <input id="sfsm-${property}-alpha" type="checkbox" />
  1098. <label class="cbx" for="sfsm-${property}-alpha"></label>
  1099. </div>` : `<input id="sfsm-${property}-alpha" type="range" min="0" max="1" step="0.01" \
  1100. style="width: 100px" />`}
  1101. <input id="sfsm-${property}" type="color" />
  1102. </div>
  1103. `);
  1104. listen(require(vanilla.querySelector(`#sf-${property}`)),
  1105. require(vanilla.querySelector(`#sf-${property}-alpha`)));
  1106. listen(require(sigmod.querySelector(`#sfsm-${property}`)),
  1107. require(sigmod.querySelector(`#sfsm-${property}-alpha`)));
  1108. return { sigmod, vanilla };
  1109. };
  1110.  
  1111. /**
  1112. * @param {PropertyOfType<typeof settings, string>} property
  1113. * @param {[string, string][]} options
  1114. */
  1115. const dropdown = (property, options) => {
  1116. /** @param {HTMLSelectElement} input */
  1117. const listen = input => {
  1118. onSyncs.push(() => input.value = settings[property]);
  1119. input.value = settings[property];
  1120.  
  1121. input.addEventListener('input', () => {
  1122. /** @type {string} */ (settings[property]) = input.value;
  1123. settingsExt.save();
  1124. });
  1125. };
  1126.  
  1127. const vanilla = fromHTML(`
  1128. <select id="sf-${property}">
  1129. ${options.map(([value, name]) => `<option value="${value}">${name}</option>`).join('\n')}
  1130. </select>
  1131. `);
  1132. const sigmod = fromHTML(`
  1133. <select class="form-control" id="sfsm-${property}" style="width: 250px;">
  1134. ${options.map(([value, name]) => `<option value="${value}">${name}</option>`).join('\n')}
  1135. </select>
  1136. `);
  1137. listen(/** @type {HTMLSelectElement} */ (vanilla));
  1138. listen(/** @type {HTMLSelectElement} */ (sigmod));
  1139. return { sigmod, vanilla };
  1140. };
  1141.  
  1142. /**
  1143. * @param {any} property
  1144. * @param {any} parent
  1145. */
  1146. const keybind = (property, parent = settings) => {
  1147. /** @param {HTMLInputElement} input */
  1148. const listen = input => {
  1149. onSyncs.push(() => input.value = parent[property]);
  1150. input.value = parent[property];
  1151.  
  1152. input.addEventListener('keydown', e => {
  1153. if (e.key === 'Control' || e.key === 'Alt' || e.key === 'Meta') return;
  1154. if (e.code === 'Escape' || e.code === 'Backspace') {
  1155. parent[property] = input.value = '';
  1156. } else {
  1157. parent[property] = input.value = aux.keybind(e) ?? '';
  1158. }
  1159. settingsExt.save();
  1160. e.preventDefault(); // prevent the key being typed in
  1161. });
  1162. input.addEventListener('mousedown', e => {
  1163. if (e.button === 0 && document.activeElement !== input) return; // do default action
  1164. parent[property] = input.value = aux.keybind(e) ?? '';
  1165. settingsExt.save();
  1166. e.preventDefault();
  1167. });
  1168. input.addEventListener('contextmenu', e => void e.preventDefault());
  1169. };
  1170.  
  1171. const vanilla = fromHTML(`<input id="sf-${property}" placeholder="..." type="text" style="
  1172. text-align: center; width: 80px;" />`);
  1173. const sigmod = fromHTML(`<input class="keybinding" id="sfsm-${property}" placeholder="..."
  1174. style="max-width: 100px; width: 100px;" type="text" />`);
  1175. listen(/** @type {HTMLInputElement} */ (vanilla));
  1176. listen(/** @type {HTMLInputElement} */ (sigmod));
  1177. return { sigmod, vanilla };
  1178. };
  1179.  
  1180. addEventListener('mousedown', ev => {
  1181. for (const { container, help, helpbox } of containers) {
  1182. if (container.contains(/** @type {Node | null} */ (ev.target))) {
  1183. if (ev.target === help) helpbox.style.display = '';
  1184. } else {
  1185. if (helpbox.style.display === '') helpbox.style.display = 'none';
  1186. }
  1187. }
  1188. });
  1189.  
  1190. const separator = (text = '•') => {
  1191. vanillaContainer.appendChild(fromHTML(`<div style="text-align: center; width: 100%;">${text}</div>`));
  1192. sigmodContainer.appendChild(fromHTML(`<span class="text-center">${text}</span>`));
  1193. };
  1194.  
  1195. const newTag = `<span style="padding: 2px 5px; border-radius: 10px; background: #76f; color: #fff;
  1196. font-weight: bold; font-size: 0.95rem; user-select: none;">NEW</span>`;
  1197.  
  1198. // #2 : generate ui for settings
  1199. setting('Draw delay', [slider('drawDelay', 120, 40, 300, 1, 0)], () => true,
  1200. 'How long (in milliseconds) cells will lag behind for. Lower values mean cells will very quickly catch ' +
  1201. 'up to where they actually are.');
  1202. setting('Cell outlines', [checkbox('cellOutlines')], () => true,
  1203. 'Whether the subtle dark outlines around cells (including skins) should draw.');
  1204. setting('Cell opacity', [slider('cellOpacity', 1, 0, 1, 0.005, 3)], () => true,
  1205. 'How opaque cells should be. 1 = fully visible, 0 = invisible. It can be helpful to see the size of a ' +
  1206. 'smaller cell under a big cell.');
  1207. setting('Self skin URL', [image('selfSkin')], () => true,
  1208. 'A custom skin for yourself. You can drag+drop a skin here, or use a direct URL. Not visible to others.');
  1209. setting('Secondary skin URL', [image('selfSkinMulti')], () => !!settings.multibox || settings.nbox,
  1210. 'A custom skin for your secondary multibox tab. You can drag+drop a skin here, or use a direct URL. Not ' +
  1211. 'visible to others.');
  1212. setting('Map background', [image('background')], () => true,
  1213. 'A square background image to use within the entire map border. Images 512x512 and under will be treated ' +
  1214. 'as a repeating pattern, where 50 pixels = 1 grid square.');
  1215. setting('Lines between cell and mouse', [checkbox('tracer')], () => true,
  1216. 'If enabled, draws tracers between all of the cells you ' +
  1217. 'control and your mouse. Useful as a hint to your subconscious about which tab you\'re currently on.');
  1218.  
  1219. separator('• camera •');
  1220. setting('Camera style', [dropdown('camera', [['natural', 'Natural (weighted)'], ['default', 'Default']])],
  1221. () => true,
  1222. 'How the camera focuses on your cells. <br>' +
  1223. '- A "natural" camera follows your center of mass. If you have a lot of small back pieces, they would ' +
  1224. 'barely affect your camera position. <br>' +
  1225. '- The "default" camera focuses on every cell equally. If you have a lot of small back pieces, your ' +
  1226. 'camera would focus on those instead. <br>' +
  1227. 'When one-tab multiboxing, you <b>must</b> use the Natural (weighted) camera style.');
  1228. setting('Camera movement',
  1229. [dropdown('cameraMovement', [['default', 'Default'], ['instant', 'Instant']])], () => true,
  1230. 'How the camera moves. <br>' +
  1231. '- "Default" camera movement follows your cell positions, but when a cell dies or splits, it immediately ' +
  1232. 'stops or starts focusing on it. Artificial smoothness is added - you can control that with the ' +
  1233. '"Camera smoothness" setting. <br>' +
  1234. '- "Instant" camera movement exactly follows your cells without lagging behind, gradually focusing more ' +
  1235. 'or less on cells while they split or die. There is no artificial smoothness, but you should use a ' +
  1236. 'higher draw delay (at least 100). You might find this significantly smoother than the default camera.');
  1237. setting('Camera smoothness', [slider('cameraSmoothness', 2, 1, 10, 0.1, 1)],
  1238. () => settings.cameraMovement === 'default',
  1239. 'How slowly the camera lags behind. The default is 2; using 4 moves the camera about twice as slowly, ' +
  1240. 'for example. Setting to 1 removes all camera smoothness.');
  1241. setting('Zoom speed', [slider('scrollFactor', 1, 0.05, 1, 0.05, 2)], () => true,
  1242. 'A smaller zoom speed lets you fine-tune your zoom.');
  1243. setting('Auto-zoom', [checkbox('autoZoom')], () => true,
  1244. 'When enabled, automatically zooms in/out for you based on how big you are.');
  1245. setting('Move camera while spawning', [checkbox('cameraSpawnAnimation')], () => true,
  1246. 'When spawning, normally the camera will take a bit of time to move to where your cell spawned. This ' +
  1247. 'can be disabled.');
  1248.  
  1249. separator('• multibox •');
  1250. setting('Multibox keybind', [keybind('multibox')], () => true,
  1251. 'The key to press for switching multibox tabs. "Tab" is recommended, but you can also use "Ctrl+Tab" and ' +
  1252. 'most other keybinds.');
  1253. setting(`Vision merging ${newTag}`,
  1254. [dropdown('synchronization', [['flawless', 'Flawless (recommended)'], ['latest', 'Latest'], ['', 'None']])],
  1255. () => !!settings.multibox || settings.nbox || settings.spectator,
  1256. 'How multiple connections synchronize the cells they can see. <br>' +
  1257. '- "Flawless" ensures all connections are synchronized to be on the same ping. If one connection gets a ' +
  1258. 'lag spike, all connections will get that lag spike too. <br>' +
  1259. '- "Latest" uses the most recent data across all connections. Lag spikes will be much less noticeable, ' +
  1260. 'however cells that are farther away might warp around and appear buggy. <br>' +
  1261. '- "None" only shows what your current tab can see. <br>' +
  1262. '"Flawless" is recommended for all users, however if you find it laggy you should try "Latest".');
  1263. setting('One-tab mode', [checkbox('mergeCamera')], () => !!settings.multibox || settings.nbox,
  1264. 'When enabled, your camera will focus on both multibox tabs at once. Disable this if you prefer two-tab-' +
  1265. 'style multiboxing. <br>' +
  1266. 'When one-tab multiboxing, you <b>must</b> use the Natural (weighted) camera style.');
  1267. setting('Multibox outline thickness', [slider('outlineMulti', 0.2, 0, 1, 0.01, 2)],
  1268. () => !!settings.multibox || settings.nbox,
  1269. 'When multiboxing, rings appear on your cells, the thickness being a % of your cell radius. This only ' +
  1270. 'shows when you\'re near one of your tabs.');
  1271. setting('Current tab outline color', [color('outlineMultiColor')], () => !!settings.multibox || settings.nbox,
  1272. 'The color of the rings around your current multibox tab. Only shown when near another tab. The slider ' +
  1273. 'is the outline opacity.');
  1274. setting('Other tab outline color', [color('outlineMultiInactiveColor')], () => !!settings.multibox || settings.nbox,
  1275. 'The color of the rings around your other inactive multibox tabs. Only shown when near another tab. The ' +
  1276. 'slider is the outline opacity.');
  1277. setting('Block respawns near other tabs', [checkbox('blockNearbyRespawns')], () => !!settings.multibox || settings.nbox,
  1278. 'When enabled, the respawn key (using SigMod) will be disabled if your multibox tabs are close. ' +
  1279. 'This means you can spam the respawn key until your multibox tab spawns nearby.');
  1280.  
  1281. // don't allow turning on without multiboxing enabled first
  1282. setting('N-boxing', [checkbox('nbox')], () => !!settings.multibox || settings.nbox,
  1283. '<h1>ADVANCED USERS ONLY.</h1>' +
  1284. 'Enables multiboxing with 3 or more tabs (known as triboxing or quadboxing). <br>' +
  1285. 'Official Sigmally servers limit how many connections can be made from an IP address (usually 3). If you ' +
  1286. 'can\'t connect some of your tabs: <br>' +
  1287. '- Try disabling the spectator tab for a third connection. <br>' +
  1288. '- Try using proxies to connect via multiple IP addresses. <br>' +
  1289. '- Try playing on a private server instead. <br>' +
  1290. 'When enabled, the multibox keybind above will cycle between all tabs.');
  1291. setting('N-box tab count', [slider('nboxCount', 3, 3, 8, 1, 0)], () => settings.nbox,
  1292. 'The number of tabs to make available for selection.');
  1293. setting('N-box change pair', [keybind('nboxCyclePair')],
  1294. () => settings.nbox,
  1295. 'Pressing this key will cycle between selecting pairs #1/#2, #3/#4, #5/#6, and #7/#8. The last used tab ' +
  1296. 'in this pair will be selected. (Think of this as switching between multiple multibox game windows.)');
  1297. setting('N-box switch within pair', [keybind('nboxSwitchPair')],
  1298. () => settings.nbox,
  1299. 'Pressing this key will switch between tabs within your current pair (from #1/#2, #3/#4, #5/#6, or #7/#8).');
  1300. for (let i = 0; i < 8; ++i) {
  1301. setting(`N-box select tab #${i + 1}`, [keybind(i, settings.nboxSelectKeybinds)],
  1302. () => settings.nbox && settings.nboxCount >= i + 1,
  1303. `Pressing this key will switch to tab #${i + 1}.`);
  1304. }
  1305. for (let i = 0; i < 8; ++i) {
  1306. setting(`N-box hold tab #${i + 1}`, [keybind(i, settings.nboxHoldKeybinds)],
  1307. () => settings.nbox && settings.nboxCount >= i + 1,
  1308. `Holding this key will temporarily switch to tab #${i + 1}. Releasing all n-box keys will return you ` +
  1309. 'to the last selected tab.');
  1310. }
  1311. for (let i = 2; i < 8; ++i) {
  1312. setting(`N-box skin #${i + 1}`, [image(i, settings.selfSkinNbox, `selfSkinNbox.${i}`)],
  1313. () => settings.nbox && settings.nboxCount >= i + 1,
  1314. `A custom skin for tab #${i + 1}. You can drag+drop a skin here, or use a direct URL. Not ` +
  1315. 'visible to others.');
  1316. }
  1317.  
  1318. separator('• text •');
  1319. setting('Name scale factor', [slider('nameScaleFactor', 1, 0.5, 2, 0.01, 2)], () => true,
  1320. 'The size multiplier of names.');
  1321. setting('Mass scale factor', [slider('massScaleFactor', 1, 0.5, 4, 0.01, 2)], () => true,
  1322. 'The size multiplier of mass (which is half the size of names).');
  1323. setting('Mass opacity', [slider('massOpacity', 1, 0, 1, 0.01, 2)], () => true,
  1324. 'The opacity of the mass text. You might find it visually appealing to have mass be a little dimmer than ' +
  1325. 'names.');
  1326. setting('Bold name / mass text', [checkbox('nameBold'), checkbox('massBold')], () => true,
  1327. 'Uses the bold Ubuntu font (like Agar.io) for names (left checkbox) or mass (right checkbox).');
  1328. setting('Show clans', [checkbox('clans')], () => true,
  1329. 'When enabled, shows the name of the clan a player is in above their name. ' +
  1330. 'If you turn off names (using SigMod), then player names will be replaced with their clan\'s.');
  1331. setting('Clan scale factor', [slider('clanScaleFactor', 1, 0.5, 4, 0.01, 2)], () => settings.clans,
  1332. 'The size multiplier of a player\'s clan displayed above their name. When names are off, names will be ' +
  1333. 'replaced with clans and use the name scale factor instead.');
  1334. setting('Text outline thickness', [slider('textOutlinesFactor', 1, 0, 2, 0.01, 2)], () => true,
  1335. 'The multiplier of the thickness of the black stroke around names, mass, and clans on cells. You can set ' +
  1336. 'this to 0 to disable outlines AND text shadows.');
  1337.  
  1338. separator('• other •');
  1339. setting('Theme color', [color('theme', true)], () => true,
  1340. 'If enabled, uses this color for the minimap (and chat, if not using SigMod). It\'s a small detail that ' +
  1341. 'can make the game feel more immersive.');
  1342. setting('Block all browser keybinds', [checkbox('blockBrowserKeybinds')], () => true,
  1343. 'When enabled, only F11 is allowed to be pressed when in fullscreen. Most other browser and system ' +
  1344. 'keybinds will be disabled.');
  1345. setting('Unsplittable cell outline', [color('unsplittableColor')], () => true,
  1346. 'The color of the ring around cells that cannot split. The slider ');
  1347. setting('Jelly physics skin size lag', [checkbox('jellySkinLag')], () => true,
  1348. 'Jelly physics causes cells to grow and shrink slower than text and skins, making the game more ' +
  1349. 'satisfying. If you have a skin that looks weird only with jelly physics, try turning this off.');
  1350. setting('Slower jelly physics', [checkbox('slowerJellyPhysics')], () => true,
  1351. 'Sigmally Fixes normally speeds up the jelly physics animation for it to be tolerable when splitrunning. ' +
  1352. 'If you prefer how it was in the vanilla client (really slow but satisfying), enable this setting.');
  1353. setting('Cell / pellet glow', [checkbox('cellGlow'), checkbox('pelletGlow')], () => true,
  1354. 'When enabled, gives cells or pellets a slight glow. Basically, shaders for Sigmally. This is very ' +
  1355. 'optimized and should not impact performance.');
  1356. setting('Rainbow border', [checkbox('rainbowBorder')], () => true,
  1357. 'Gives the map a rainbow border. So shiny!!!');
  1358. setting('Top UI uses bold text', [checkbox('boldUi')], () => true,
  1359. 'When enabled, the top-left score and stats UI and the leaderboard will use the bold Ubuntu font.');
  1360. setting('Show server stats', [checkbox('showStats')], () => true,
  1361. 'When disabled, hides the top-left server stats including the player count and server uptime.');
  1362. setting('Connect spectating tab', [checkbox('spectator')], () => true,
  1363. 'Automatically connects an extra tab and sets it to spectate #1.');
  1364. setting('Show spectator tab ping', [checkbox('spectatorLatency')], () => settings.spectator,
  1365. 'When enabled, shows another ping measurement for your spectator tab.');
  1366. setting('Separate XP boost from score', [checkbox('separateBoost')], () => true,
  1367. 'If you have an XP boost, your score will be doubled. If you don\'t want that, you can separate the XP ' +
  1368. 'boost from your score.');
  1369. setting('Color under skin', [checkbox('colorUnderSkin')], () => true,
  1370. 'When disabled, transparent skins will be see-through and not show your cell color. Turn this off ' +
  1371. 'if using a bubble skin, for example.');
  1372. setting('Move after linesplit', [checkbox('moveAfterLinesplit')], () => true,
  1373. 'When doing a horizontal or vertical linesplit, your position is frozen. With this setting enabled, you ' +
  1374. 'will begin moving forwards in that axis once you split, letting you go farther than normal.');
  1375.  
  1376. setting(`<span style="padding: 2px 5px; border-radius: 10px; background: #76f; color: #fff;
  1377. font-weight: bold; font-size: 0.95rem; user-select: none;">yx's secret setting</span>`,
  1378. [checkbox('yx')], () => settings.yx, 'yx\'s top secret settings');
  1379.  
  1380. // #3 : create options for sigmod
  1381. let sigmodInjection;
  1382. sigmodInjection = setInterval(() => {
  1383. const nav = document.querySelector('.mod_menu_navbar');
  1384. const content = document.querySelector('.mod_menu_content');
  1385. if (!nav || !content) return;
  1386.  
  1387. clearInterval(sigmodInjection);
  1388.  
  1389. content.appendChild(sigmodContainer);
  1390.  
  1391. const navButton = fromHTML('<button class="mod_nav_btn">🔥 Sig Fixes</button>');
  1392. nav.appendChild(navButton);
  1393. navButton.addEventListener('click', () => {
  1394. // basically openModTab() from sigmod
  1395. (/** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll('.mod_tab'))).forEach(tab => {
  1396. tab.style.opacity = '0';
  1397. setTimeout(() => tab.style.display = 'none', 200);
  1398. });
  1399.  
  1400. (/** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll('.mod_nav_btn'))).forEach(tab => {
  1401. tab.classList.remove('mod_selected');
  1402. });
  1403.  
  1404. navButton.classList.add('mod_selected');
  1405. setTimeout(() => {
  1406. sigmodContainer.style.display = 'flex';
  1407. setTimeout(() => sigmodContainer.style.opacity = '1', 10);
  1408. }, 200);
  1409. });
  1410. }, 100);
  1411.  
  1412. return settings;
  1413. })();
  1414.  
  1415.  
  1416.  
  1417. /////////////////////
  1418. // Prepare Game UI //
  1419. /////////////////////
  1420. const ui = (() => {
  1421. const ui = {};
  1422.  
  1423. (() => {
  1424. const title = document.querySelector('#title');
  1425. if (!title) return;
  1426.  
  1427. const watermark = document.createElement('span');
  1428. watermark.innerHTML = `<a href="https://greasyfork.org/scripts/483587/versions" \
  1429. target="_blank">Sigmally Fixes ${sfVersion}</a> by yx`;
  1430. if (sfVersion.includes('BETA')) {
  1431. watermark.innerHTML += ' <br><a \
  1432. href="https://raw.githubusercontent.com/8y8x/sigmally-fixes/refs/heads/main/sigmally-fixes.user.js"\
  1433. target="_blank">[Update beta here]</a>';
  1434. }
  1435. title.insertAdjacentElement('afterend', watermark);
  1436.  
  1437. // check if this version is problematic, don't do anything if this version is too new to be in versions.json
  1438. // take care to ensure users can't be logged
  1439. fetch('https://raw.githubusercontent.com/8y8x/sigmally-fixes/main/versions.json')
  1440. .then(res => res.json())
  1441. .then(res => {
  1442. if (sfVersion in res && !res[sfVersion].ok && res[sfVersion].alert) {
  1443. const color = res[sfVersion].color || '#f00';
  1444. const box = document.createElement('div');
  1445. box.style.cssText = `background: ${color}3; border: 1px solid ${color}; width: 100%; \
  1446. height: fit-content; font-size: 1em; padding: 5px; margin: 5px 0; border-radius: 3px; \
  1447. color: ${color}`;
  1448. box.innerHTML = String(res[sfVersion].alert)
  1449. .replace(/\<|\>/g, '') // never allow html tag injection
  1450. .replace(/\{link\}/g, '<a href="https://greasyfork.org/scripts/483587">[click here]</a>')
  1451. .replace(/\{autolink\}/g, '<a href="\
  1452. https://update.greasyfork.org/scripts/483587/Sigmally%20Fixes%20V2.user.js">\
  1453. [click here]</a>');
  1454.  
  1455. watermark.insertAdjacentElement('afterend', box);
  1456. }
  1457. })
  1458. .catch(err => console.warn('Failed to check Sigmally Fixes version:', err));
  1459. })();
  1460.  
  1461. ui.game = (() => {
  1462. const game = {};
  1463.  
  1464. /** @type {HTMLCanvasElement | null} */
  1465. const oldCanvas = document.querySelector('canvas#canvas');
  1466. if (!oldCanvas) {
  1467. throw 'exiting script - no canvas found';
  1468. }
  1469.  
  1470. const newCanvas = document.createElement('canvas');
  1471. newCanvas.id = 'sf-canvas';
  1472. newCanvas.style.cssText = `background: #003; width: 100vw; height: 100vh; position: fixed; top: 0; left: 0;
  1473. z-index: 1;`;
  1474. game.canvas = newCanvas;
  1475. (document.querySelector('body div') ?? document.body).appendChild(newCanvas);
  1476.  
  1477. // leave the old canvas so the old client can actually run
  1478. oldCanvas.style.display = 'none';
  1479.  
  1480. // forward macro inputs from the canvas to the old one - this is for sigmod mouse button controls
  1481. newCanvas.addEventListener('mousedown', e => oldCanvas.dispatchEvent(new MouseEvent('mousedown', e)));
  1482. newCanvas.addEventListener('mouseup', e => oldCanvas.dispatchEvent(new MouseEvent('mouseup', e)));
  1483. // forward mouse movements from the old canvas to the window - this is for sigmod keybinds that move
  1484. // the mouse
  1485. oldCanvas.addEventListener('mousemove', e => dispatchEvent(new MouseEvent('mousemove', e)));
  1486.  
  1487. const gl = aux.require(
  1488. newCanvas.getContext('webgl2', { alpha: false, antialias: false, depth: false }),
  1489. 'Couldn\'t get WebGL2 context. Possible causes:\r\n' +
  1490. '- Maybe GPU/Hardware acceleration needs to be enabled in your browser settings; \r\n' +
  1491. '- Maybe your browser is just acting weird and it might fix itself after a restart; \r\n' +
  1492. '- Maybe your GPU drivers are exceptionally old.',
  1493. );
  1494.  
  1495. game.gl = gl;
  1496.  
  1497. // indicate that we will restore the context
  1498. newCanvas.addEventListener('webglcontextlost', e => {
  1499. e.preventDefault(); // signal that we want to restore the context
  1500. });
  1501. newCanvas.addEventListener('webglcontextrestored', () => {
  1502. glconf.init();
  1503. // cleanup old caches (after render), as we can't do this within glconf.init()
  1504. render.resetDatabaseCache();
  1505. render.resetTextCache();
  1506. render.resetTextureCache();
  1507. });
  1508.  
  1509. function resize() {
  1510. // devicePixelRatio does not have very high precision; it could be 0.800000011920929 for example
  1511. newCanvas.width = Math.ceil(innerWidth * (devicePixelRatio - 0.0001));
  1512. newCanvas.height = Math.ceil(innerHeight * (devicePixelRatio - 0.0001));
  1513. game.gl.viewport(0, 0, newCanvas.width, newCanvas.height);
  1514. }
  1515.  
  1516. addEventListener('resize', resize);
  1517. resize();
  1518.  
  1519. return game;
  1520. })();
  1521.  
  1522. ui.stats = (() => {
  1523. const container = document.createElement('div');
  1524. container.style.cssText = 'position: fixed; top: 10px; left: 10px; width: 400px; height: fit-content; \
  1525. user-select: none; z-index: 2; transform-origin: top left; font-family: Ubuntu;';
  1526. document.body.appendChild(container);
  1527.  
  1528. const score = document.createElement('div');
  1529. score.style.cssText = 'font-size: 30px; color: #fff; line-height: 1.0;';
  1530. container.appendChild(score);
  1531.  
  1532. const measures = document.createElement('div');
  1533. measures.style.cssText = 'font-size: 20px; color: #fff; line-height: 1.1;';
  1534. container.appendChild(measures);
  1535.  
  1536. const misc = document.createElement('div');
  1537. // white-space: pre; allows using \r\n to insert line breaks
  1538. misc.style.cssText = 'font-size: 14px; color: #fff; white-space: pre; line-height: 1.1; opacity: 0.5;';
  1539. container.appendChild(misc);
  1540.  
  1541. /** @param {symbol} view */
  1542. const update = view => {
  1543. const fontFamily = `"${sigmod.settings.font || 'Ubuntu'}", Ubuntu`;
  1544. if (container.style.fontFamily !== fontFamily) container.style.fontFamily = fontFamily;
  1545.  
  1546. const color = aux.settings.darkTheme ? '#fff' : '#000';
  1547. score.style.color = color;
  1548. measures.style.color = color;
  1549. misc.style.color = color;
  1550.  
  1551. score.style.fontWeight = measures.style.fontWeight = settings.boldUi ? 'bold' : 'normal';
  1552. measures.style.opacity = settings.showStats ? '1' : '0.5';
  1553. misc.style.opacity = settings.showStats ? '0.5' : '0';
  1554.  
  1555. const scoreVal = world.score(world.selected);
  1556. const multiplier = (typeof aux.userData?.boost === 'number' && aux.userData.boost > Date.now()) ? 2 : 1;
  1557. if (scoreVal > world.stats.highestScore) world.stats.highestScore = scoreVal;
  1558. let scoreHtml;
  1559. if (scoreVal <= 0) scoreHtml = '';
  1560. else if (settings.separateBoost) {
  1561. scoreHtml = `Score: ${Math.floor(scoreVal)}`;
  1562. if (multiplier > 1) scoreHtml += ` <span style="color: #fc6;">(X${multiplier})</span>`;
  1563. } else {
  1564. scoreHtml = 'Score: ' + Math.floor(scoreVal * multiplier);
  1565. }
  1566. score.innerHTML = scoreHtml;
  1567.  
  1568. const con = net.connections.get(view);
  1569. let measuresText = `${Math.floor(render.fps)} FPS`;
  1570. if (con?.latency !== undefined) {
  1571. measuresText += ` ${con.latency === -1 ? '????' : Math.floor(con.latency)}ms`;
  1572. const spectateCon = net.connections.get(world.viewId.spectate);
  1573. if (settings.spectatorLatency && spectateCon?.latency !== undefined) {
  1574. measuresText
  1575. += ` (${spectateCon.latency === -1 ? '????' : Math.floor(spectateCon.latency)}ms)`;
  1576. }
  1577. measuresText += ' ping';
  1578. }
  1579. measures.textContent = measuresText;
  1580. };
  1581.  
  1582. /** @param {object | undefined} stats */
  1583. const updateStats = (stats) => {
  1584. if (!stats) {
  1585. misc.textContent = '';
  1586. return;
  1587. }
  1588.  
  1589. let uptime;
  1590. if (stats.uptime < 60) {
  1591. uptime = Math.floor(stats.uptime) + 's';
  1592. } else {
  1593. uptime = Math.floor(stats.uptime / 60 % 60) + 'min';
  1594. if (stats.uptime >= 60 * 60)
  1595. uptime = Math.floor(stats.uptime / 60 / 60 % 24) + 'hr ' + uptime;
  1596. if (stats.uptime >= 24 * 60 * 60)
  1597. uptime = Math.floor(stats.uptime / 24 / 60 / 60 % 60) + 'd ' + uptime;
  1598. }
  1599.  
  1600. misc.textContent = [
  1601. `${stats.name} (${stats.gamemode})`,
  1602. `${stats.external} / ${stats.limit} players`,
  1603. // bots do not count towards .playing
  1604. `${stats.playing} playing` + (stats.internal > 0 ? ` + ${stats.internal} bots` : ''),
  1605. `${stats.spectating} spectating`,
  1606. `${(stats.loadTime / 40 * 100).toFixed(1)}% load @ ${uptime}`,
  1607. ].join('\r\n');
  1608. };
  1609.  
  1610. /** @type {object | undefined} */
  1611. let lastStats;
  1612. setInterval(() => { // update as frequently as possible
  1613. const currentStats = world.views.get(world.selected)?.stats;
  1614. if (currentStats !== lastStats) updateStats(lastStats = currentStats);
  1615. });
  1616.  
  1617. return { update };
  1618. })();
  1619.  
  1620. ui.leaderboard = (() => {
  1621. const container = document.createElement('div');
  1622. container.style.cssText = 'position: fixed; top: 10px; right: 10px; width: 200px; height: fit-content; \
  1623. user-select: none; z-index: 2; background: #0006; padding: 15px 5px; transform-origin: top right; \
  1624. display: none;';
  1625. document.body.appendChild(container);
  1626.  
  1627. const title = document.createElement('div');
  1628. title.style.cssText = 'font-family: Ubuntu; font-size: 30px; color: #fff; text-align: center; width: 100%;';
  1629. title.textContent = 'Leaderboard';
  1630. container.appendChild(title);
  1631.  
  1632. const linesContainer = document.createElement('div');
  1633. linesContainer.style.cssText = `font-family: Ubuntu; font-size: 20px; line-height: 1.2; width: 100%;
  1634. height: fit-content; text-align: ${settings.yx ? 'right' : 'center'}; white-space: pre; overflow: hidden;`;
  1635. container.appendChild(linesContainer);
  1636.  
  1637. /** @type {HTMLDivElement[]} */
  1638. const lines = [];
  1639. /** @param {{ me: boolean, name: string, sub: boolean, place: number | undefined }[]} lb */
  1640. function update(lb) {
  1641. const fontFamily = `"${sigmod.settings.font || 'Ubuntu'}", Ubuntu`;
  1642. if (linesContainer.style.fontFamily !== fontFamily)
  1643. linesContainer.style.fontFamily = title.style.fontFamily = fontFamily;
  1644.  
  1645. const friends = /** @type {any} */ (window).sigmod?.friend_names;
  1646. const friendSettings = /** @type {any} */ (window).sigmod?.friends_settings;
  1647. lb.forEach((entry, i) => {
  1648. let line = lines[i];
  1649. if (!line) {
  1650. line = document.createElement('div');
  1651. line.style.display = 'none';
  1652. linesContainer.appendChild(line);
  1653. lines.push(line);
  1654. }
  1655.  
  1656. line.style.display = 'block';
  1657. line.textContent = `${entry.place ?? i + 1}. ${entry.name || 'An unnamed cell'}`;
  1658. if (entry.me) line.style.color = '#faa';
  1659. else if (friends instanceof Set && friends.has(entry.name) && friendSettings?.highlight_friends)
  1660. line.style.color = friendSettings.highlight_color;
  1661. else if (entry.sub) line.style.color = '#ffc826';
  1662. else line.style.color = '#fff';
  1663. });
  1664.  
  1665. for (let i = lb.length; i < lines.length; ++i)
  1666. lines[i].style.display = 'none';
  1667.  
  1668. container.style.display = lb.length > 0 ? '' : 'none';
  1669. container.style.fontWeight = settings.boldUi ? 'bold' : 'normal';
  1670. }
  1671.  
  1672. /** @type {object | undefined} */
  1673. let lastLb;
  1674. setInterval(() => { // update leaderboard frequently
  1675. const currentLb = world.views.get(world.selected)?.leaderboard;
  1676. if (currentLb !== lastLb) update((lastLb = currentLb) ?? []);
  1677. });
  1678. })();
  1679.  
  1680. /** @type {HTMLElement} */
  1681. const mainMenu = aux.require(
  1682. document.querySelector('#__line1')?.parentElement,
  1683. 'Can\'t find the main menu UI. Try reloading the page?',
  1684. );
  1685.  
  1686. /** @type {HTMLElement} */
  1687. const statsContainer = aux.require(
  1688. document.querySelector('#__line2'),
  1689. 'Can\'t find the death screen UI. Try reloading the page?',
  1690. );
  1691.  
  1692. /** @type {HTMLElement} */
  1693. const continueButton = aux.require(
  1694. document.querySelector('#continue_button'),
  1695. 'Can\'t find the continue button (on death). Try reloading the page?',
  1696. );
  1697.  
  1698. /** @type {HTMLElement | null} */
  1699. const menuLinks = document.querySelector('#menu-links');
  1700. /** @type {HTMLElement | null} */
  1701. const overlay = document.querySelector('#overlays');
  1702.  
  1703. // sigmod uses this to detect if the menu is closed or not, otherwise this is unnecessary
  1704. /** @type {HTMLElement | null} */
  1705. const menuWrapper = document.querySelector('#menu-wrapper');
  1706.  
  1707. let escOverlayVisible = true;
  1708. /**
  1709. * @param {boolean} [show]
  1710. */
  1711. ui.toggleEscOverlay = show => {
  1712. escOverlayVisible = show ?? !escOverlayVisible;
  1713. if (escOverlayVisible) {
  1714. mainMenu.style.display = '';
  1715. if (overlay) overlay.style.display = '';
  1716. if (menuLinks) menuLinks.style.display = '';
  1717. if (menuWrapper) menuWrapper.style.display = '';
  1718.  
  1719. ui.deathScreen.hide();
  1720. } else {
  1721. mainMenu.style.display = 'none';
  1722. if (overlay) overlay.style.display = 'none';
  1723. if (menuLinks) menuLinks.style.display = 'none';
  1724. if (menuWrapper) menuWrapper.style.display = 'none';
  1725. }
  1726.  
  1727. ui.captcha.reposition();
  1728. };
  1729.  
  1730. ui.escOverlayVisible = () => escOverlayVisible;
  1731.  
  1732. ui.deathScreen = (() => {
  1733. const deathScreen = {};
  1734. let visible = false;
  1735.  
  1736. continueButton.addEventListener('click', () => {
  1737. ui.toggleEscOverlay(true);
  1738. visible = false;
  1739. });
  1740.  
  1741. /** @type {HTMLElement | null} */
  1742. const bonus = document.querySelector('#menu__bonus');
  1743.  
  1744. deathScreen.check = () => {
  1745. if (world.stats.spawnedAt !== undefined && !world.alive()) deathScreen.show();
  1746. };
  1747.  
  1748. deathScreen.show = () => {
  1749. const boost = typeof aux.userData?.boost === 'number' && aux.userData.boost > Date.now();
  1750. if (bonus) {
  1751. if (boost) {
  1752. bonus.style.display = '';
  1753. bonus.textContent = `Bonus score: ${Math.round(world.stats.highestScore)}`;
  1754. } else {
  1755. bonus.style.display = 'none';
  1756. }
  1757. }
  1758.  
  1759. const foodEatenElement = document.querySelector('#food_eaten');
  1760. if (foodEatenElement)
  1761. foodEatenElement.textContent = world.stats.foodEaten.toString();
  1762.  
  1763. const highestMassElement = document.querySelector('#highest_mass');
  1764. if (highestMassElement)
  1765. highestMassElement.textContent = (Math.round(world.stats.highestScore) * (boost ? 2 : 1)).toString();
  1766.  
  1767. const highestPositionElement = document.querySelector('#top_leaderboard_position');
  1768. if (highestPositionElement)
  1769. highestPositionElement.textContent = world.stats.highestPosition.toString();
  1770.  
  1771. const timeAliveElement = document.querySelector('#time_alive');
  1772. if (timeAliveElement) {
  1773. const time = (performance.now() - (world.stats.spawnedAt ?? 0)) / 1000;
  1774. const hours = Math.floor(time / 60 / 60);
  1775. const mins = Math.floor(time / 60 % 60);
  1776. const seconds = Math.floor(time % 60);
  1777.  
  1778. timeAliveElement.textContent = `${hours ? hours + ' h' : ''} ${mins ? mins + ' m' : ''} `
  1779. + `${seconds ? seconds + ' s' : ''}`;
  1780. }
  1781.  
  1782. statsContainer.classList.remove('line--hidden');
  1783. visible = true;
  1784. ui.toggleEscOverlay(false);
  1785. if (overlay) overlay.style.display = '';
  1786. world.stats = { foodEaten: 0, highestPosition: 200, highestScore: 0, spawnedAt: undefined };
  1787.  
  1788. ui.captcha.reposition();
  1789. };
  1790.  
  1791. deathScreen.hide = () => {
  1792. statsContainer?.classList.add('line--hidden');
  1793. visible = false;
  1794. // no need for ui.captcha.reposition() because the esc overlay will always be shown on deathScreen.hide
  1795. // ads are managed by the game client
  1796. };
  1797.  
  1798. deathScreen.visible = () => visible;
  1799.  
  1800. return deathScreen;
  1801. })();
  1802.  
  1803. ui.minimap = (() => {
  1804. const canvas = document.createElement('canvas');
  1805. canvas.style.cssText = 'position: fixed; bottom: 0; right: 0; background: #0006; width: 200px; \
  1806. height: 200px; z-index: 2; user-select: none;';
  1807. canvas.width = canvas.height = 200;
  1808. document.body.appendChild(canvas);
  1809.  
  1810. const ctx = aux.require(
  1811. canvas.getContext('2d', { willReadFrequently: false }),
  1812. 'Unable to get 2D context for the minimap. This is probably your browser being dumb, maybe reload ' +
  1813. 'the page?',
  1814. );
  1815.  
  1816. return { canvas, ctx };
  1817. })();
  1818.  
  1819. ui.chat = (() => {
  1820. const chat = {};
  1821.  
  1822. const block = aux.require(
  1823. document.querySelector('#chat_block'),
  1824. 'Can\'t find the chat UI. Try reloading the page?',
  1825. );
  1826.  
  1827. /**
  1828. * @param {ParentNode} root
  1829. * @param {string} selector
  1830. */
  1831. function clone(root, selector) {
  1832. /** @type {HTMLElement} */
  1833. const old = aux.require(
  1834. root.querySelector(selector),
  1835. `Can't find this chat element: ${selector}. Try reloading the page?`,
  1836. );
  1837.  
  1838. const el = /** @type {HTMLElement} */ (old.cloneNode(true));
  1839. el.id = '';
  1840. old.style.display = 'none';
  1841. old.insertAdjacentElement('afterend', el);
  1842.  
  1843. return el;
  1844. }
  1845.  
  1846. // can't just replace the chat box - otherwise sigmod can't hide it - so we make its children invisible
  1847. // elements grabbed with clone() are only styled by their class, not id
  1848. const toggle = clone(document, '#chat_vsbltyBtn');
  1849. const scrollbar = clone(document, '#chat_scrollbar');
  1850. const thumb = clone(scrollbar, '#chat_thumb');
  1851.  
  1852. const input = chat.input = /** @type {HTMLInputElement} */ (aux.require(
  1853. document.querySelector('#chat_textbox'),
  1854. 'Can\'t find the chat textbox. Try reloading the page?',
  1855. ));
  1856.  
  1857. // allow zooming in/out on trackpad without moving the UI
  1858. input.style.position = 'fixed';
  1859. toggle.style.position = 'fixed';
  1860. scrollbar.style.position = 'fixed';
  1861.  
  1862. const list = document.createElement('div');
  1863. list.style.cssText = 'width: 400px; height: 182px; position: fixed; bottom: 54px; left: 46px; \
  1864. overflow: hidden; user-select: none; z-index: 301;';
  1865. block.appendChild(list);
  1866.  
  1867. let toggled = true;
  1868. toggle.style.borderBottomLeftRadius = '10px'; // a bug fix :p
  1869. toggle.addEventListener('click', () => {
  1870. toggled = !toggled;
  1871. input.style.display = toggled ? '' : 'none';
  1872. scrollbar.style.display = toggled ? 'block' : 'none';
  1873. list.style.display = toggled ? '' : 'none';
  1874.  
  1875. if (toggled) {
  1876. toggle.style.borderTopRightRadius = toggle.style.borderBottomRightRadius = '';
  1877. toggle.style.opacity = '';
  1878. } else {
  1879. toggle.style.borderTopRightRadius = toggle.style.borderBottomRightRadius = '10px';
  1880. toggle.style.opacity = '0.25';
  1881. }
  1882. });
  1883.  
  1884. scrollbar.style.display = 'block';
  1885. let scrollTop = 0; // keep a float here, because list.scrollTop is always casted to an int
  1886. let thumbHeight = 1;
  1887. let lastY;
  1888. thumb.style.height = '182px';
  1889.  
  1890. function updateThumb() {
  1891. thumb.style.bottom = (1 - list.scrollTop / (list.scrollHeight - 182)) * (182 - thumbHeight) + 'px';
  1892. }
  1893.  
  1894. function scroll() {
  1895. if (scrollTop >= list.scrollHeight - 182 - 40) {
  1896. // close to bottom, snap downwards
  1897. list.scrollTop = scrollTop = list.scrollHeight - 182;
  1898. }
  1899.  
  1900. thumbHeight = Math.min(Math.max(182 / list.scrollHeight, 0.1), 1) * 182;
  1901. thumb.style.height = thumbHeight + 'px';
  1902. updateThumb();
  1903. }
  1904.  
  1905. let scrolling = false;
  1906. thumb.addEventListener('mousedown', () => void (scrolling = true));
  1907. addEventListener('mouseup', () => void (scrolling = false));
  1908. addEventListener('mousemove', e => {
  1909. const deltaY = e.clientY - lastY;
  1910. lastY = e.clientY;
  1911.  
  1912. if (!scrolling) return;
  1913. e.preventDefault();
  1914.  
  1915. if (lastY === undefined) {
  1916. lastY = e.clientY;
  1917. return;
  1918. }
  1919.  
  1920. list.scrollTop = scrollTop = Math.min(Math.max(
  1921. scrollTop + deltaY * list.scrollHeight / 182, 0), list.scrollHeight - 182);
  1922. updateThumb();
  1923. });
  1924.  
  1925. let lastWasBarrier = true; // init to true, so we don't print a barrier as the first ever message (ugly)
  1926. /**
  1927. * @param {string} authorName
  1928. * @param {[number, number, number, number]} rgb
  1929. * @param {string} text
  1930. * @param {boolean} server
  1931. */
  1932. chat.add = (authorName, rgb, text, server) => {
  1933. lastWasBarrier = false;
  1934.  
  1935. const container = document.createElement('div');
  1936. const author = document.createElement('span');
  1937. author.style.cssText = `color: ${aux.rgba2hex(...rgb)}; padding-right: 0.75em;`;
  1938. author.textContent = aux.trim(authorName);
  1939. container.appendChild(author);
  1940.  
  1941. const msg = document.createElement('span');
  1942. if (server) msg.style.cssText = `color: ${aux.rgba2hex(...rgb)}`;
  1943. msg.textContent = server ? text : aux.trim(text); // /help text can get cut off
  1944. container.appendChild(msg);
  1945.  
  1946. while (list.children.length > 100)
  1947. list.firstChild?.remove();
  1948.  
  1949. list.appendChild(container);
  1950.  
  1951. scroll();
  1952. };
  1953.  
  1954. chat.barrier = () => {
  1955. if (lastWasBarrier) return;
  1956. lastWasBarrier = true;
  1957.  
  1958. const barrier = document.createElement('div');
  1959. barrier.style.cssText = 'width: calc(100% - 20px); height: 1px; background: #8888; margin: 10px;';
  1960. list.appendChild(barrier);
  1961.  
  1962. scroll();
  1963. };
  1964.  
  1965. chat.matchTheme = () => {
  1966. list.style.color = aux.settings.darkTheme ? '#fffc' : '#000c';
  1967. // make author names darker in light theme
  1968. list.style.filter = aux.settings.darkTheme ? '' : 'brightness(75%)';
  1969.  
  1970. toggle.style.backgroundColor = settings.theme[3] ? aux.rgba2hex6(...settings.theme) : '#e37955';
  1971. thumb.style.backgroundColor = settings.theme[3] ? aux.rgba2hex6(...settings.theme) : '#fc7200';
  1972. };
  1973.  
  1974. setInterval(() => chat.matchTheme(), 500);
  1975.  
  1976. return chat;
  1977. })();
  1978.  
  1979. /** @param {string} msg */
  1980. ui.error = msg => {
  1981. const modal = /** @type {HTMLElement | null} */ (document.querySelector('#errormodal'));
  1982. if (modal) modal.style.display = 'block';
  1983. const desc = document.querySelector('#errormodal p');
  1984. if (desc) desc.innerHTML = msg;
  1985. };
  1986.  
  1987. ui.captcha = (() => {
  1988. const captcha = {};
  1989.  
  1990. const modeBtns = /** @type {HTMLElement | null} */ (document.querySelector('.mode-btns'));
  1991. /** @type {HTMLButtonElement} */
  1992. const play = aux.require(document.querySelector('button#play-btn'),
  1993. 'Can\'t find the play button. Try reloading the page?');
  1994. /** @type {HTMLButtonElement} */
  1995. const spectate = aux.require(document.querySelector('button#spectate-btn'),
  1996. 'Can\'t find the spectate button. Try reloading the page?');
  1997.  
  1998. /** @type {((grecaptcha: any) => void) | undefined} */
  1999. let grecaptchaResolve;
  2000. /** @type {Promise<any>} */
  2001. const grecaptcha = new Promise(r => grecaptchaResolve = r);
  2002. /** @type {((turnstile: any) => void) | undefined} */
  2003. let turnstileResolve;
  2004. /** @type {Promise<any>} */
  2005. const turnstile = new Promise(r => turnstileResolve = r);
  2006. let CAPTCHA2, CAPTCHA3, TURNSTILE;
  2007.  
  2008. let readyCheck;
  2009. readyCheck = setInterval(() => {
  2010. // it's possible that recaptcha or turnstile may be removed in the future, so we be redundant to stay
  2011. // safe
  2012. if (grecaptchaResolve) {
  2013. let grecaptchaReal;
  2014. ({ grecaptcha: grecaptchaReal, CAPTCHA2, CAPTCHA3 } = /** @type {any} */ (window));
  2015. if (grecaptchaReal?.ready && CAPTCHA2 && CAPTCHA3) {
  2016. const resolve = grecaptchaResolve;
  2017. grecaptchaResolve = undefined;
  2018.  
  2019. grecaptchaReal.ready(() => {
  2020. // prevent game.js from using grecaptcha and messing things up
  2021. let { grecaptcha: grecaptchaNew } = /** @type {any} */ (window);
  2022. /** @type {any} */ (window).grecaptcha = {
  2023. execute: () => {},
  2024. ready: () => {},
  2025. render: () => {},
  2026. reset: () => {},
  2027. };
  2028. resolve(grecaptchaNew);
  2029. });
  2030. }
  2031. }
  2032.  
  2033. if (turnstileResolve) {
  2034. let turnstileReal;
  2035. ({ turnstile: turnstileReal, TURNSTILE } = /** @type {any} */ (window));
  2036. if (turnstileReal?.ready && TURNSTILE) {
  2037. const resolve = turnstileResolve;
  2038. turnstileResolve = undefined;
  2039.  
  2040. // turnstile.ready not needed
  2041. // prevent game.js from using turnstile and messing things up
  2042. /** @type {any} */ (window).turnstile = {
  2043. execute: () => {},
  2044. ready: () => {},
  2045. render: () => {},
  2046. reset: () => {},
  2047. };
  2048. resolve(turnstileReal);
  2049. }
  2050. }
  2051.  
  2052. if (!grecaptchaResolve && !turnstileResolve)
  2053. clearInterval(readyCheck);
  2054. }, 50);
  2055.  
  2056. /**
  2057. * @typedef {{
  2058. * cb: ((token: string) => void) | undefined,
  2059. * handle: any,
  2060. * mount: HTMLElement,
  2061. * reposition: () => boolean,
  2062. * type: string,
  2063. * }} CaptchaInstance
  2064. * @type {Map<symbol, CaptchaInstance>}
  2065. */
  2066. const captchas = new Map();
  2067.  
  2068. /** @param {symbol} view */
  2069. captcha.remove = view => {
  2070. const inst = captchas.get(view);
  2071. if (!inst) return;
  2072.  
  2073. if (inst.type === 'v2') grecaptcha.then(g => g.reset(inst.handle));
  2074. // don't do anything for v3
  2075. else if (inst.type === 'turnstile') turnstile.then(t => t.remove(inst.handle));
  2076.  
  2077. inst.cb = () => {}; // ensure the token gets voided if solved
  2078. inst.mount.remove();
  2079. captchas.delete(view);
  2080. captcha.reposition(); // ensure play/spectate buttons reappear
  2081. };
  2082.  
  2083. /**
  2084. * @param {symbol} view
  2085. * @param {string} type
  2086. * @param {(token: string) => void} cb
  2087. */
  2088. captcha.request = (view, type, cb) => {
  2089. const oldInst = captchas.get(view);
  2090. if (oldInst?.type === type && oldInst.cb) {
  2091. oldInst.cb = cb;
  2092. return;
  2093. }
  2094.  
  2095. captcha.remove(view);
  2096.  
  2097. const mount = document.createElement('div');
  2098. document.body.appendChild(mount);
  2099. const reposition = () => {
  2100. let replacesModeButtons = false;
  2101. if (view === world.viewId.spectate) {
  2102. mount.style.cssText = 'position: fixed; bottom: 10px; left: 50vw; transform: translateX(-50%); \
  2103. z-index: 1000;';
  2104. } else if (view !== world.selected || ui.deathScreen.visible()) {
  2105. mount.style.cssText = 'opacity: 0;'; // don't use display: none;
  2106. } else if (escOverlayVisible && modeBtns) {
  2107. const place = modeBtns?.getBoundingClientRect();
  2108. mount.style.cssText = `position: fixed; top: ${place ? place.top + 'px' : '50vh'};
  2109. left: ${place ? (place.left + place.width / 2) + 'px' : '50vw'};
  2110. transform: translate(-50%, ${place ? '0%' : '-50%'}); z-index: 1000;`;
  2111. replacesModeButtons = type !== 'v3'; // v3 is invisible, so it shouldn't hide the play buttons
  2112. } else {
  2113. mount.style.cssText = `position: fixed; top: 50vh; left: 50vw; transform: translate(-50%, -50%);
  2114. z-index: 1000;`;
  2115. }
  2116.  
  2117. return replacesModeButtons;
  2118. };
  2119.  
  2120. /** @type {CaptchaInstance} */
  2121. const inst = { cb, handle: undefined, mount, reposition, type };
  2122. captchas.set(view, inst);
  2123. captcha.reposition();
  2124.  
  2125. if (type === 'v2') {
  2126. grecaptcha.then(g => {
  2127. inst.handle = g.render(mount, {
  2128. callback: token => {
  2129. inst.cb?.(token);
  2130. inst.cb = undefined;
  2131. },
  2132. 'error-callback': () => setTimeout(() => g.reset(inst.handle), 1000),
  2133. 'expired-callback': () => setTimeout(() => g.reset(inst.handle), 1000),
  2134. sitekey: CAPTCHA2,
  2135. theme: sigmod.exists ? 'dark' : 'light',
  2136. });
  2137. });
  2138. } else if (type === 'v3') {
  2139. grecaptcha.then(g => {
  2140. g.execute(CAPTCHA3).then(token => {
  2141. inst.cb?.(token);
  2142. inst.cb = undefined;
  2143. });
  2144. });
  2145. } else if (type === 'turnstile') {
  2146. turnstile.then(t => {
  2147. inst.handle = t.render(mount, {
  2148. callback: token => {
  2149. inst.cb?.(token);
  2150. inst.cb = undefined;
  2151. },
  2152. 'error-callback': () => setTimeout(() => t.reset(inst.handle), 1000),
  2153. 'expired-callback': () => setTimeout(() => t.reset(inst.handle), 1000),
  2154. sitekey: TURNSTILE,
  2155. theme: sigmod.exists ? 'dark' : 'light',
  2156. });
  2157. });
  2158. }
  2159. };
  2160.  
  2161. captcha.reposition = () => {
  2162. let replacingModeButtons = false;
  2163. for (const inst of captchas.values()) replacingModeButtons = inst.reposition() || replacingModeButtons;
  2164.  
  2165. play.style.display = spectate.style.display = replacingModeButtons ? 'none' : '';
  2166. };
  2167.  
  2168. addEventListener('resize', () => captcha.reposition());
  2169.  
  2170. return captcha;
  2171. })();
  2172.  
  2173. ui.linesplit = (() => {
  2174. const linesplit = {};
  2175.  
  2176. const overlay = document.createElement('div');
  2177. overlay.style.cssText = `position: fixed; bottom: 10px; left: 50vw; transform: translateX(-50%);
  2178. font: bold 24px Ubuntu; color: #fffc; z-index: 999;`;
  2179. document.body.appendChild(overlay);
  2180.  
  2181. linesplit.update = () => {
  2182. const inputs = input.views.get(world.selected);
  2183. if (!inputs?.lock) {
  2184. overlay.style.display = 'none';
  2185. return;
  2186. }
  2187.  
  2188. if (inputs.lock.type === 'horizontal') {
  2189. // left-right arrow svg
  2190. overlay.innerHTML = `
  2191. <svg viewBox="-6 0 36 24" style="width: 36px; height: 24px; vertical-align: bottom;">
  2192. <path stroke="currentColor" stroke-width="3" fill="none"
  2193. d="M22,12 L2,12 M6,8 L2,12 L6,16 M18,8 L22,12 L18,16"></path>
  2194. </svg>(${sigmod.settings?.horizontalLineKey?.toUpperCase()})`;
  2195. overlay.style.display = '';
  2196. } else if (inputs.lock.type === 'vertical') {
  2197. // up-down arrow svg
  2198. overlay.innerHTML = `
  2199. <svg viewBox="0 0 24 24" style="width: 24px; height: 24px; vertical-align: bottom;">
  2200. <path stroke="currentColor" stroke-width="3" fill="none"
  2201. d="M12,22 L12,2 M8,6 L12,2 L16,6 M8,18 L12,22 L16,18"></path>
  2202. </svg>(${sigmod.settings?.verticalLineKey?.toUpperCase()})`;
  2203. overlay.style.display = '';
  2204. } else if (inputs.lock.type === 'fixed') {
  2205. // left-right + up-down arrow svg
  2206. overlay.innerHTML = `
  2207. <svg viewBox="-6 0 36 24" style="width: 36px; height: 24px; vertical-align: bottom;">
  2208. <path stroke="currentColor" stroke-width="3" fill="none"
  2209. d="M22,12 L2,12 M6,8 L2,12 L6,16 M18,8 L22,12 L18,16
  2210. M12,22 L12,2 M8,6 L12,2 L16,6 M8,18 L12,22 L16,18"></path>
  2211. </svg>(${sigmod.settings?.fixedLineKey?.toUpperCase()})`;
  2212. overlay.style.display = '';
  2213. }
  2214. };
  2215.  
  2216. return linesplit;
  2217. })();
  2218.  
  2219. const style = document.createElement('style');
  2220. style.innerHTML = `
  2221. /* make sure nothing gets cut off on the center menu panel */
  2222. #menu-wrapper > .menu-center { height: fit-content !important; }
  2223. /* hide the outline that sigmod puts on the minimap (i don't like it) */
  2224. .minimap { border: none !important; box-shadow: none !important; }
  2225. `;
  2226. document.head.appendChild(style);
  2227.  
  2228. return ui;
  2229. })();
  2230.  
  2231.  
  2232.  
  2233. ///////////////////////////
  2234. // Setup World Variables //
  2235. ///////////////////////////
  2236. /**
  2237. * @typedef {{
  2238. * nx: number, ny: number, nr: number,
  2239. * born: number, deadAt: number | undefined, deadTo: number,
  2240. * }} CellFrameWritable
  2241. * @typedef {Readonly<CellFrameWritable>} CellFrame
  2242. * @typedef {{
  2243. * ox: number, oy: number, or: number,
  2244. * jr: number, a: number, updated: number,
  2245. * }} CellInterpolation
  2246. * @typedef {{
  2247. * name: string, skin: string, sub: boolean, clan: string,
  2248. * rgb: [number, number, number],
  2249. * jagged: boolean, eject: boolean,
  2250. * }} CellDescription
  2251. * @typedef {CellInterpolation & CellDescription & { frames: CellFrame[] }} CellRecord
  2252. * @typedef {{
  2253. * id: number,
  2254. * merged: (CellFrameWritable & CellInterpolation) | undefined,
  2255. * model: CellFrame | undefined,
  2256. * views: Map<symbol, CellRecord>,
  2257. * }} Cell
  2258. * @typedef {{
  2259. * border: { l: number, r: number, t: number, b: number } | undefined,
  2260. * camera: {
  2261. * x: number, tx: number,
  2262. * y: number, ty: number,
  2263. * scale: number, tscale: number,
  2264. * merged: boolean,
  2265. * updated: number,
  2266. * },
  2267. * leaderboard: { name: string, me: boolean, sub: boolean, place: number | undefined }[],
  2268. * owned: number[],
  2269. * spawned: number,
  2270. * stats: object | undefined,
  2271. * used: number,
  2272. * }} Vision
  2273. */
  2274. const world = (() => {
  2275. const world = {};
  2276.  
  2277. // #1 : define cell variables and functions
  2278. /** @type {Map<number, Cell>} */
  2279. world.cells = new Map();
  2280. /** @type {Map<number, Cell>} */
  2281. world.pellets = new Map();
  2282. world.multis = [Symbol(), Symbol(), Symbol(), Symbol(), Symbol(), Symbol(), Symbol(), Symbol()];
  2283. world.viewId = {
  2284. primary: world.multis[0],
  2285. secondary: world.multis[1],
  2286. spectate: Symbol(),
  2287. };
  2288. world.selected = world.viewId.primary;
  2289. /** @type {Map<symbol, Vision>} */
  2290. world.views = new Map();
  2291.  
  2292. world.alive = () => {
  2293. for (const [view, vision] of world.views) {
  2294. for (const id of vision.owned) {
  2295. const cell = world.cells.get(id);
  2296. // if a cell does not exist yet, we treat it as alive
  2297. if (!cell) return true;
  2298.  
  2299. const frame = cell.views.get(view)?.frames[0];
  2300. if (frame?.deadAt === undefined) return true;
  2301. }
  2302. }
  2303. return false;
  2304. };
  2305.  
  2306. /**
  2307. * @typedef {{ mass: number, scale: number, sumX: number, sumY: number, weight: number }} SingleCamera
  2308. * @param {symbol} view
  2309. * @param {Vision | undefined} vision
  2310. * @param {number} weightExponent
  2311. * @param {number} now
  2312. * @returns {SingleCamera}
  2313. */
  2314. world.singleCamera = (view, vision, weightExponent, now) => {
  2315. vision ??= world.views.get(view);
  2316. if (!vision) return { mass: 0, scale: 1, sumX: 0, sumY: 0, weight: 0 };
  2317.  
  2318. let mass = 0;
  2319. let r = 0;
  2320. let sumX = 0;
  2321. let sumY = 0;
  2322. let weight = 0;
  2323. for (const id of (world.views.get(view)?.owned ?? [])) {
  2324. const cell = world.cells.get(id);
  2325. /** @type {CellFrame | undefined} */
  2326. const frame = world.synchronized ? cell?.merged : cell?.views.get(view)?.frames[0];
  2327. /** @type {CellInterpolation | undefined} */
  2328. const interp = world.synchronized ? cell?.merged : cell?.views.get(view);
  2329. if (!frame || !interp) continue;
  2330. // don't include cells owned before respawning
  2331. if (frame.born < vision.spawned) continue;
  2332.  
  2333. if (settings.cameraMovement === 'instant') {
  2334. const xyr = world.xyr(frame, interp, undefined, undefined, false, now);
  2335. r += xyr.r * xyr.a;
  2336. mass += (xyr.r * xyr.r / 100) * xyr.a;
  2337. const cellWeight = xyr.a * (xyr.r ** weightExponent);
  2338. sumX += xyr.x * cellWeight;
  2339. sumY += xyr.y * cellWeight;
  2340. weight += cellWeight;
  2341. } else { // settings.cameraMovement === 'default'
  2342. if (frame.deadAt !== undefined) continue;
  2343. const xyr = world.xyr(frame, interp, undefined, undefined, false, now);
  2344. r += frame.nr;
  2345. mass += frame.nr * frame.nr / 100;
  2346. const cellWeight = frame.nr ** weightExponent;
  2347. sumX += xyr.x * cellWeight;
  2348. sumY += xyr.y * cellWeight;
  2349. weight += cellWeight;
  2350. }
  2351. }
  2352.  
  2353. const scale = Math.min(64 / r, 1) ** 0.4;
  2354. return { mass, scale, sumX, sumY, weight };
  2355. };
  2356.  
  2357. /**
  2358. * @param {number} now
  2359. */
  2360. world.cameras = now => {
  2361. const weightExponent = settings.camera !== 'default' ? 2 : 0;
  2362.  
  2363. // #1 : create disjoint sets of all cameras that are close together
  2364. /** @type {Map<symbol, SingleCamera>}>} */
  2365. const cameras = new Map();
  2366. /** @type {Map<symbol, Set<symbol>>} */
  2367. const sets = new Map();
  2368. for (const [view, vision] of world.views) {
  2369. cameras.set(view, world.singleCamera(view, vision, weightExponent, now));
  2370. sets.set(view, new Set([view]));
  2371. }
  2372.  
  2373. // compute even if tabs won't actually be merged, because the multi outlines must still show
  2374. if (settings.multibox || settings.nbox) {
  2375. for (const [view, vision] of world.views) {
  2376. const set = /** @type {Set<symbol>} */ (sets.get(view));
  2377.  
  2378. const camera = /** @type {SingleCamera} */ (cameras.get(view));
  2379. if (camera.weight <= 0 || now - vision.used > 20_000) continue; // don't merge with inactive tabs
  2380. const x = camera.sumX / camera.weight;
  2381. const y = camera.sumY / camera.weight;
  2382. const width = 1920 / 2 / camera.scale;
  2383. const height = 1080 / 2 / camera.scale;
  2384.  
  2385. for (const [otherView, otherVision] of world.views) {
  2386. const otherSet = /** @type {Set<symbol>} */ (sets.get(otherView));
  2387. if (set === otherSet || now - otherVision.used > 20_000) continue;
  2388.  
  2389. const otherCamera = /** @type {SingleCamera} */ (cameras.get(otherView));
  2390. if (otherCamera.weight <= 0) continue;
  2391. const otherX = otherCamera.sumX / otherCamera.weight;
  2392. const otherY = otherCamera.sumY / otherCamera.weight;
  2393. const otherWidth = 1920 / 2 / otherCamera.scale;
  2394. const otherHeight = 1080 / 2 / otherCamera.scale;
  2395.  
  2396. // only merge with tabs if their vision regions are close. expand threshold depending on
  2397. // how much mass each tab has (if both tabs are large, allow them to go pretty far)
  2398. const threshold = 1000 + Math.min(camera.weight / 100 / 25, otherCamera.weight / 100 / 25);
  2399. if (Math.abs(x - otherX) <= width + otherWidth + threshold
  2400. && Math.abs(y - otherY) <= height + otherHeight + threshold) {
  2401. // merge disjoint sets
  2402. for (const connectedView of otherSet) {
  2403. set.add(connectedView);
  2404. sets.set(connectedView, set);
  2405. }
  2406. }
  2407. }
  2408. }
  2409. }
  2410.  
  2411. // #2 : calculate and update merged camera positions
  2412. /** @type {Set<Set<symbol>>} */
  2413. const computed = new Set();
  2414. for (const set of sets.values()) {
  2415. if (computed.has(set)) continue;
  2416. let mass = 0;
  2417. let sumX = 0;
  2418. let sumY = 0;
  2419. let weight = 0;
  2420. if (settings.mergeCamera) {
  2421. for (const view of set) {
  2422. const camera = /** @type {SingleCamera} */ (cameras.get(view));
  2423. mass += camera.mass;
  2424. sumX += camera.sumX;
  2425. sumY += camera.sumY;
  2426. weight += camera.weight;
  2427. }
  2428. }
  2429.  
  2430. for (const view of set) {
  2431. const vision = /** @type {Vision} */ (world.views.get(view));
  2432.  
  2433. if (!settings.mergeCamera) {
  2434. ({ mass, sumX, sumY, weight } = /** @type {SingleCamera} */ (cameras.get(view)));
  2435. }
  2436.  
  2437. let xyFactor;
  2438. if (weight <= 0) {
  2439. xyFactor = 20;
  2440. } else if (settings.cameraMovement === 'instant') {
  2441. xyFactor = 1;
  2442. } else {
  2443. // when spawning, move camera quickly (like vanilla), then make it smoother after a bit
  2444. const aliveFor = (performance.now() - vision.spawned) / 1000;
  2445. const a = Math.min(Math.max((aliveFor - 0.3) / 0.3, 0), 1);
  2446. const base = settings.cameraSpawnAnimation ? 2 : 1;
  2447. xyFactor = Math.min(settings.cameraSmoothness, base * (1-a) + settings.cameraSmoothness * a);
  2448. }
  2449.  
  2450. if (weight > 0) {
  2451. vision.camera.tx = sumX / weight;
  2452. vision.camera.ty = sumY / weight;
  2453. let scale;
  2454. if (settings.camera === 'default') scale = /** @type {SingleCamera} */ (cameras.get(view)).scale;
  2455. else scale = Math.min(64 / Math.sqrt(100 * mass), 1) ** 0.4;
  2456. vision.camera.tscale = settings.autoZoom ? scale : 0.25;
  2457. }
  2458.  
  2459. const dt = (now - vision.camera.updated) / 1000;
  2460. vision.camera.x = aux.exponentialEase(vision.camera.x, vision.camera.tx, xyFactor, dt);
  2461. vision.camera.y = aux.exponentialEase(vision.camera.y, vision.camera.ty, xyFactor, dt);
  2462. vision.camera.scale
  2463. = aux.exponentialEase(vision.camera.scale, input.zoom * vision.camera.tscale, 9, dt);
  2464.  
  2465. vision.camera.merged = set.size > 1;
  2466. vision.camera.updated = now;
  2467. }
  2468.  
  2469. computed.add(set);
  2470. }
  2471. };
  2472.  
  2473. /** @param {symbol} view */
  2474. world.create = view => {
  2475. const old = world.views.get(view);
  2476. if (old) return old;
  2477.  
  2478. const vision = {
  2479. border: undefined,
  2480. camera: { x: 0, tx: 0, y: 0, ty: 0, scale: 0, tscale: 0, merged: false, updated: performance.now() - 1 },
  2481. leaderboard: [],
  2482. owned: [],
  2483. spawned: -Infinity,
  2484. stats: undefined,
  2485. used: -Infinity,
  2486. };
  2487. world.views.set(view, vision);
  2488. return vision;
  2489. };
  2490.  
  2491. /** @type {number | undefined} */
  2492. let disagreementAt, disagreementStart;
  2493. world.synchronized = false;
  2494. world.merge = () => {
  2495. if (!settings.synchronization || world.views.size <= 1) {
  2496. disagreementStart = disagreementAt = undefined;
  2497. world.synchronized = false;
  2498. return;
  2499. }
  2500.  
  2501. // the obvious solution to merging tabs is to prefer the primary tab's cells, then tack on the secondary
  2502. // tab's cells. this is fast and easy, but causes very noticeable flickering and warping when a cell enters
  2503. // or leaves the primary tab's vision. this is what delta suffers from.
  2504. //
  2505. // we could instead check cells visible on both tabs to see if they share the same target x, y, and r.
  2506. // if they all do, then the connections are synchronized and both visions can be merged.
  2507. // this works well, however latency can fluctuate and results in connections being completely unable to
  2508. // synchronize between themselves if they are off by at least 40ms. this happens often, and significantly
  2509. // more to players who usually have higher ping.
  2510. //
  2511. // in the below approach, we keep a record of how every cell is updated (where a lower index => more recent)
  2512. // and try to figure out the lowest possible index for all views such that they see the same frames across
  2513. // all cells.
  2514. // however, doing this is complicated. consider the following scenarios:
  2515. //
  2516. // > Scenario #1
  2517. // > a cell is standing still and visible across multiple views. then every frame will have a perfect match
  2518. // > between views, regardless of each connection's latency, and no frames will be ruled out.
  2519. // > therefore, finding a perfect match across multiple indices of 0 MUST NOT imply a perfect match could
  2520. // > be found on all other cells.
  2521. //
  2522. // > Scenario #2
  2523. // > view A has been alone observing a cell for a while, and view A has abnormally high ping.
  2524. // > that cell now comes into view B's vision, but view B has much better ping.
  2525. // > therefore, the frame(s) view B sees of that cell will be completely disjoint from view A's.
  2526. // > therefore, a match not existing MUST NOT imply the visions cannot be synchronized.
  2527. //
  2528. // > Scenario #3
  2529. // > view A and view B have been observing a cell for a while. view A has abnormally high ping.
  2530. // > the cell momentarily exits view B's vision, then after a few ticks re-enters its vision.
  2531. // > once view A catches up to a frame that was missed by view B (because the cell was out of B's vision),
  2532. // > it will not be able to find a match.
  2533. // > therefore, this MUST NOT imply that view A's latest frames cannot be used.
  2534. //
  2535. // the solution involves undirected bipartite graphs representing two different views and which indices are
  2536. // compatible with each other. for example:
  2537. // > (view A) (view B)
  2538. // > 0 (x=12, y=34, r=56) ┌─── 0 (x=44, y=55, r=66)
  2539. // > 1 (x=34, y=56, r=61) │ 1 (x=55, y=66, r=77)
  2540. // > 2 (x=44, y=55, r=66) ────┘
  2541. // > there is a compatible connection between 2A - 0B (illustrated)
  2542. // > there are incompatible connections between 0A - 0B, 0A - 1B, 1A - 0B, 1A - 1B, 2A - 1B
  2543. // > there are no connections between 0A - 2B, 1A - 2B, 2A - 2B, 0A - 3B, ...etc
  2544. //
  2545. // > (view A) (view B)
  2546. // > 0 (x=1, y=1, r=100) ┌────── 0 (x=2, y=2, r=100)
  2547. // > 1 (x=2, y=2, r=100) ──┘ ┌──── 1 (x=3, y=3, r=100)
  2548. // > 2 (x=3, y=3, r=100) ────┘ ┌── 2 (x=4, y=4, r=100)
  2549. // > 3 (x=4, y=4, r=100) ──────┘ 3 (x=5, y=5, r=101)
  2550. // > there are compatible connections between 1A - 0B, 2A - 1B, 3A - 2B
  2551. // > there are incompatible connections between 0A - 0B, 0A - 1B, ..., 1A - 1B, 1A - 1C, ...
  2552. // > there are no connections between 0A - 4B, 1A - 4B, ..., 0A - 5B, ...
  2553. //
  2554. // then, we connect all bipartite graphs together and find the smallest indices across all views.
  2555. // but how does this actually scale?
  2556. //
  2557. // if there are two views, then we start at the first view on the first index. then:
  2558. // - if there is a compatible connection to the second view, use it, and we're done.
  2559. // - if not, and if there is an incompatible connection, then increment index by 1. repeat.
  2560. // - if there are no connections, then we're done.
  2561. //
  2562. // now if there are more views, start at the first view[1] (meaning 1st index). then:
  2563. // - check for a compatible connection to the second view[1], [2], ..., [12].
  2564. // - if there is a compatible connection on index i:
  2565. // - check for a compatible connection from second view[i] to the third view[1], [2], ..., [12].
  2566. // - if there is a compatible connection on index j:
  2567. // - first, ensure it is also compatible with the first view[1] (backwards compatibility)
  2568. // - if it isn't, then treat this as an incompatible connection
  2569. // - otherwise, if all views agree, then try checking the fourth view
  2570. // - if there isn't, but there is an incompatible connection, then flag a disagreement
  2571. // - if there isn't, but there is an incompatible connection, then flag a disagreement
  2572. // - otherwise, a "cluster" has been completely found (a collection of nearby views). go to the next view
  2573. // that isn't part of any cluster, and repeat
  2574. //
  2575. // note that if one tab sees a cell as "dead", the connection is also deemed compatible. this is to ensure
  2576. // there are no long lag spikes while one tab leaves from another tab (for example, when the spectator tab
  2577. // teleports away).
  2578.  
  2579. const now = performance.now();
  2580. /** @type {{ [x: number | symbol]: number }} indexed by viewInt or symbol view */
  2581. const indices = {};
  2582.  
  2583. if (settings.synchronization === 'flawless') {
  2584. // #1 : set up bipartite graphs between every pair of views
  2585. /** @type {Map<symbol, number>} */
  2586. const viewToInt = new Map();
  2587. /** @type {Map<number, symbol>} */
  2588. const intToView = new Map();
  2589. for (const view of world.views.keys()) {
  2590. intToView.set(viewToInt.size, view);
  2591. viewToInt.set(view, viewToInt.size);
  2592. }
  2593. const viewDim = viewToInt.size;
  2594.  
  2595. // each pair of views (view1, view2, where view1Int < view2Int) has a 12x12 graph, where
  2596. // graph[i * viewDim + j] describes the existence of an undirected connection between index i on view1
  2597. // and index j on view2.
  2598. const COMPATIBLE = 1 << 0;
  2599. const INCOMPATIBLE = 1 << 1;
  2600. const graphDim = 12; // same as maximum history size
  2601. /** @type {Map<number, Uint8Array>} */
  2602. const graphs = new Map();
  2603. for (let i = 0; i < viewToInt.size; ++i) {
  2604. for (let j = i + 1; j < viewToInt.size; ++j) {
  2605. graphs.set(i * viewDim + j, new Uint8Array(graphDim * graphDim));
  2606. }
  2607. }
  2608.  
  2609. // #2 : establish relationships in every graph
  2610. // pellets never change, so it would be useless to try and compare them
  2611. for (const cell of world.cells.values()) {
  2612. for (const view1 of cell.views.keys()) {
  2613. const record1 = /** @type {CellRecord} */ (cell.views.get(view1));
  2614. for (const view2 of cell.views.keys()) {
  2615. if (view1 === view2) continue;
  2616. const record2 = /** @type {CellRecord} */ (cell.views.get(view2));
  2617.  
  2618. const view1Int = /** @type {number} */ (viewToInt.get(view1));
  2619. const view2Int = /** @type {number} */ (viewToInt.get(view2));
  2620. if (view1Int > view2Int) continue; // only access graphs where view1 < view2
  2621. const graph = /** @type {Uint8Array} */ (graphs.get(view1Int * viewDim + view2Int));
  2622.  
  2623. for (let i = 0; i < record1.frames.length; ++i) {
  2624. const frame1 = record1.frames[i];
  2625. for (let j = 0; j < record2.frames.length; ++j) {
  2626. const frame2 = record2.frames[j];
  2627.  
  2628. if (frame1.deadAt !== undefined || frame2.deadAt !== undefined || (frame1.nx === frame2.nx && frame1.ny === frame2.ny && frame1.nr === frame2.nr)) {
  2629. graph[i * graphDim + j] |= COMPATIBLE;
  2630. } else {
  2631. graph[i * graphDim + j] |= INCOMPATIBLE;
  2632. }
  2633. }
  2634. }
  2635. }
  2636. }
  2637. }
  2638.  
  2639. // #3 : find the lowest indices across all views that are compatible with each other
  2640. /**
  2641. * @param {{ viewInt: number, i: number }[]} previous
  2642. * @param {number} viewInt
  2643. * @param {number} i
  2644. * @returns {boolean}
  2645. */
  2646. const explore = (previous, viewInt, i) => {
  2647. // try and find the next view that is compatible
  2648. for (let next = viewInt + 1; next < viewDim; ++next) {
  2649. if (indices[next] !== undefined) continue;
  2650.  
  2651. const graph = /** @type {Uint8Array} */ (graphs.get(viewInt * viewDim + next));
  2652. let incompatible = false;
  2653. for (let j = 0; j < graphDim; ++j) {
  2654. const con = graph[i * graphDim + j];
  2655. if (con & INCOMPATIBLE) {
  2656. incompatible = true;
  2657. } else if (con & COMPATIBLE) {
  2658. // we found a connection
  2659. // TODO: checking for backwards compatibility seems to break things
  2660. previous.push({ viewInt, i });
  2661. const ok = explore(previous, next, j);
  2662. previous.pop();
  2663. if (ok) {
  2664. indices[next] = indices[/** @type {symbol} */ (intToView.get(next))] = j;
  2665. return true;
  2666. }
  2667.  
  2668. incompatible = false;
  2669. } else; // don't do anything if the connection is undefined
  2670. }
  2671.  
  2672. // if an incompatible connection was found with no other good choices, then there is a conflict
  2673. // and don't allow it
  2674. if (incompatible) return false;
  2675. }
  2676.  
  2677. return true;
  2678. };
  2679.  
  2680. startCluster: for (let viewInt = 0; viewInt < viewDim; ++viewInt) {
  2681. if (indices[viewInt] !== undefined) continue; // don't re-process a cluster
  2682.  
  2683. // try and start a cluster with some index
  2684. for (let i = 0; i < graphDim; ++i) {
  2685. if (explore([], viewInt, i)) {
  2686. indices[viewInt] = indices[/** @type {symbol} */ (intToView.get(viewInt))] = i;
  2687. continue startCluster;
  2688. }
  2689. }
  2690.  
  2691. // if everything is incompatible, then there is a disagreement somewhere
  2692. // (shouldn't really happen unless a huge lag spike hits)
  2693. disagreementStart ??= now;
  2694. disagreementAt = now;
  2695. if (now - disagreementStart > 1000) world.synchronized = false;
  2696. return;
  2697. }
  2698. } else { // settings.synchronization === 'latest'
  2699. let i = 0;
  2700. for (const view of world.views.keys()) {
  2701. indices[i++] = indices[view] = 0;
  2702. }
  2703. }
  2704.  
  2705. // #4 : find a model frame for all cells and pellets
  2706. for (const key of /** @type {const} */ (['cells', 'pellets'])) {
  2707. for (const cell of world[key].values()) {
  2708. /** @type {[symbol, CellRecord] | undefined} */
  2709. let modelPair;
  2710. modelViewLoop: for (const pair of cell.views) {
  2711. if (!modelPair) {
  2712. modelPair = pair;
  2713. continue;
  2714. }
  2715.  
  2716. const [modelView, model] = modelPair;
  2717. const [view, record] = pair;
  2718.  
  2719. const modelFrame = model.frames[indices[modelView]];
  2720. const frame = record.frames[indices[view]];
  2721.  
  2722. const modelDisappeared = !modelFrame || (modelFrame.deadAt !== undefined && modelFrame.deadTo === -1);
  2723. const thisDisappeared = !frame || (frame.deadAt !== undefined && frame.deadTo === -1);
  2724.  
  2725. if (modelDisappeared && thisDisappeared) {
  2726. // both have currently disappeared; prefer the one that "disappeared" later
  2727. for (let off = 1; off < 12; ++off) {
  2728. const modelFrameOffset = model.frames[indices[modelView] + off];
  2729. const frameOffset = record.frames[indices[view] + off];
  2730.  
  2731. const modelOffsetAlive = modelFrameOffset && modelFrameOffset.deadAt === undefined;
  2732. const frameOffsetAlive = frameOffset && frameOffset.deadAt === undefined;
  2733. if (modelOffsetAlive && frameOffsetAlive) {
  2734. // both disappeared at the same time, doesn't matter
  2735. continue modelViewLoop;
  2736. } else if (modelOffsetAlive && !frameOffsetAlive) {
  2737. // model disappeared last, so prefer it
  2738. continue modelViewLoop;
  2739. } else if (!modelOffsetAlive && frameOffsetAlive) {
  2740. // current disappeared last, so prefer it
  2741. modelPair = pair;
  2742. continue modelViewLoop;
  2743. } else; // we haven't found when either one disappeared
  2744. }
  2745. } else if (modelDisappeared && !thisDisappeared) {
  2746. // current is the only one visible, so prefer it
  2747. modelPair = pair;
  2748. } else if (!modelDisappeared && thisDisappeared) {
  2749. // model is the only one visible, so prefer it (don't change anything)
  2750. } else; // both are visible and synchronized, so it doesn't matter
  2751. }
  2752.  
  2753. // in very rare circumstances, this ends up being undefined, for some reason
  2754. if (modelPair) cell.model = modelPair[1].frames[indices[modelPair[0]]] ?? cell.model;
  2755. }
  2756. }
  2757.  
  2758. // #5 : create or update the merged frame for all cells and pellets
  2759. for (const key of /** @type {const} */ (['cells', 'pellets'])) {
  2760. for (const cell of world[key].values()) {
  2761. const { model, merged } = cell;
  2762. if (!model) { // could happen
  2763. cell.merged = undefined;
  2764. continue;
  2765. }
  2766.  
  2767. if (!merged || (merged.deadAt !== undefined && model.deadAt === undefined)) {
  2768. cell.merged = {
  2769. nx: model.nx, ny: model.ny, nr: model.nr,
  2770. born: now, deadAt: model.deadAt !== undefined ? now : undefined, deadTo: model.deadTo,
  2771. ox: model.nx, oy: model.ny, or: model.nr,
  2772. jr: model.nr, a: 0, updated: now,
  2773. };
  2774. } else {
  2775. if (merged.deadAt === undefined && (model.deadAt !== undefined || model.nx !== merged.nx || model.ny !== merged.ny || model.nr !== merged.nr)) {
  2776. const xyr = world.xyr(merged, merged, undefined, undefined, key === 'pellets', now);
  2777.  
  2778. merged.ox = xyr.x;
  2779. merged.oy = xyr.y;
  2780. merged.or = xyr.r;
  2781. merged.jr = xyr.jr;
  2782. merged.a = xyr.a;
  2783. merged.updated = now;
  2784. }
  2785.  
  2786. merged.nx = model.nx;
  2787. merged.ny = model.ny;
  2788. merged.nr = model.nr;
  2789. merged.deadAt = model.deadAt !== undefined ? (merged.deadAt ?? now) : undefined;
  2790. merged.deadTo = model.deadTo;
  2791. }
  2792. }
  2793. }
  2794.  
  2795. // #6 : clean up history for all cells, because we don't want to ever go back in time
  2796. for (const key of /** @type {const} */ (['cells', 'pellets'])) {
  2797. for (const cell of world[key].values()) {
  2798. for (const [view, record] of cell.views) {
  2799. // leave the current frame, because .frames must have at least one element
  2800. record.frames.splice(indices[view] + 1, Infinity);
  2801. }
  2802. }
  2803. }
  2804.  
  2805. disagreementStart = undefined;
  2806. // if there ever a disagreement that caused synchronization to be disabled, wait a bit after things
  2807. // resolve to make sure they stay resolved
  2808. if (disagreementAt === undefined || now - disagreementAt > 1000) world.synchronized = true;
  2809. };
  2810.  
  2811. /** @param {symbol} view */
  2812. world.score = view => {
  2813. let score = 0;
  2814. for (const id of (world.views.get(view)?.owned ?? [])) {
  2815. const cell = world.cells.get(id);
  2816. if (!cell) continue;
  2817.  
  2818. /** @type {CellFrame | undefined} */
  2819. const frame = world.synchronized ? cell.merged : cell.views.get(view)?.frames[0];
  2820. if (!frame || frame.deadAt !== undefined) continue;
  2821. score += frame.nr * frame.nr / 100; // use exact score as given by the server, no interpolation
  2822. }
  2823.  
  2824. return score;
  2825. };
  2826.  
  2827. /**
  2828. * @param {CellFrame} frame
  2829. * @param {CellInterpolation} interp
  2830. * @param {CellFrame | undefined} killerFrame
  2831. * @param {CellInterpolation | undefined} killerInterp
  2832. * @param {boolean} pellet
  2833. * @param {number} now
  2834. * @returns {{ x: number, y: number, r: number, jr: number, a: number }}
  2835. */
  2836. world.xyr = (frame, interp, killerFrame, killerInterp, pellet, now) => {
  2837. let nx = frame.nx;
  2838. let ny = frame.ny;
  2839. if (killerFrame && killerInterp) {
  2840. // animate towards the killer's interpolated position (not the target position) for extra smoothness
  2841. // we also assume the killer has not died (if it has, then weird stuff is OK to occur)
  2842. const killerXyr = world.xyr(killerFrame, killerInterp, undefined, undefined, false, now);
  2843. nx = killerXyr.x;
  2844. ny = killerXyr.y;
  2845. }
  2846.  
  2847. let x, y, r, a;
  2848. if (pellet && frame.deadAt === undefined) {
  2849. x = nx;
  2850. y = ny;
  2851. r = frame.nr;
  2852. a = 1;
  2853. } else {
  2854. let alpha = (now - interp.updated) / settings.drawDelay;
  2855. alpha = alpha < 0 ? 0 : alpha > 1 ? 1 : alpha;
  2856.  
  2857. x = interp.ox + (nx - interp.ox) * alpha;
  2858. y = interp.oy + (ny - interp.oy) * alpha;
  2859. r = interp.or + (frame.nr - interp.or) * alpha;
  2860.  
  2861. const targetA = frame.deadAt !== undefined ? 0 : 1;
  2862. a = interp.a + (targetA - interp.a) * alpha;
  2863. }
  2864.  
  2865. const dt = (now - interp.updated) / 1000;
  2866.  
  2867. return {
  2868. x, y, r,
  2869. jr: aux.exponentialEase(interp.jr, r, settings.slowerJellyPhysics ? 10 : 5, dt),
  2870. a,
  2871. };
  2872. };
  2873.  
  2874. // clean up dead, invisible cells ONLY before uploading pellets
  2875. let lastClean = performance.now();
  2876. world.clean = () => {
  2877. const now = performance.now();
  2878. if (now - lastClean < 200) return;
  2879. lastClean = now;
  2880.  
  2881. for (const key of /** @type {const} */ (['cells', 'pellets'])) {
  2882. for (const [id, cell] of world[key]) {
  2883. for (const [view, record] of cell.views) {
  2884. const firstFrame = record.frames[0];
  2885. const lastFrame = record.frames[record.frames.length - 1];
  2886. if (firstFrame.deadAt !== lastFrame.deadAt) continue;
  2887. if (lastFrame.deadAt !== undefined && now - lastFrame.deadAt >= settings.drawDelay + 200)
  2888. cell.views.delete(view);
  2889. }
  2890.  
  2891. if (cell.views.size === 0) world[key].delete(id);
  2892. }
  2893. }
  2894. };
  2895.  
  2896.  
  2897.  
  2898. // #2 : define stats
  2899. world.stats = {
  2900. foodEaten: 0,
  2901. highestPosition: 200,
  2902. highestScore: 0,
  2903. /** @type {number | undefined} */
  2904. spawnedAt: undefined,
  2905. };
  2906.  
  2907.  
  2908.  
  2909. return world;
  2910. })();
  2911.  
  2912.  
  2913.  
  2914. //////////////////////////
  2915. // Setup All Networking //
  2916. //////////////////////////
  2917. const net = (() => {
  2918. const net = {};
  2919.  
  2920. // #1 : define state
  2921. /** @type {Map<symbol, {
  2922. * captchaType: string | undefined,
  2923. * handshake: { shuffle: Uint8Array, unshuffle: Uint8Array } | undefined,
  2924. * latency: number | undefined,
  2925. * pinged: number | undefined,
  2926. * playBlock: { state: 'leaving' | 'joining', started: number } | undefined,
  2927. * rejections: number,
  2928. * retries: number,
  2929. * ws: WebSocket | undefined,
  2930. * }>} */
  2931. net.connections = new Map();
  2932.  
  2933. /** @param {symbol} view */
  2934. net.create = view => {
  2935. if (net.connections.has(view)) return;
  2936.  
  2937. net.connections.set(view, {
  2938. captchaType: undefined,
  2939. handshake: undefined,
  2940. latency: undefined,
  2941. pinged: undefined,
  2942. playBlock: undefined,
  2943. rejections: 0,
  2944. retries: 0,
  2945. ws: connect(view),
  2946. });
  2947. };
  2948.  
  2949. let captchaPostQueue = Promise.resolve();
  2950.  
  2951. /**
  2952. * @param {symbol} view
  2953. * @param {(() => void)=} establishedCallback
  2954. * @returns {WebSocket | undefined}
  2955. */
  2956. const connect = (view, establishedCallback) => {
  2957. if (net.connections.get(view)?.ws) return; // already being handled by another process
  2958.  
  2959. // do not allow sigmod's args[0].includes('sigmally.com') check to pass
  2960. const realUrl = net.url();
  2961. const fakeUrl = /** @type {any} */ ({ includes: () => false, toString: () => realUrl });
  2962. let ws;
  2963. try {
  2964. ws = new WebSocket(fakeUrl);
  2965. } catch (err) {
  2966. console.error('can\'t make WebSocket:', err);
  2967. aux.require(null, 'The server address is invalid. It probably has a typo.\n' +
  2968. '- If using an insecure address (starting with "ws://" and not "wss://") that isn\'t localhost, ' +
  2969. 'enable Insecure Content in this site\'s browser settings.\n' +
  2970. '- If using a local server, make sure to use localhost and not any other local IP.');
  2971. return; // ts-check is dumb
  2972. }
  2973.  
  2974. {
  2975. const con = net.connections.get(view);
  2976. if (con) con.ws = ws;
  2977. }
  2978.  
  2979. ws.binaryType = 'arraybuffer';
  2980. ws.addEventListener('close', e => {
  2981. console.error('WebSocket closed:', e);
  2982. establishedCallback?.();
  2983. establishedCallback = undefined;
  2984.  
  2985. const connection = net.connections.get(view);
  2986. const vision = world.views.get(view);
  2987. if (!connection || !vision) return; // if the entry no longer exists, don't reconnect
  2988.  
  2989. connection.handshake = undefined;
  2990. connection.latency = undefined;
  2991. connection.pinged = undefined;
  2992. connection.playBlock = undefined;
  2993. ++connection.rejections;
  2994. if (connection.retries > 0) --connection.retries;
  2995.  
  2996. vision.border = undefined;
  2997. // don't reset vision.camera
  2998. vision.owned = [];
  2999. vision.leaderboard = [];
  3000. vision.spawned = -Infinity;
  3001. vision.stats = undefined;
  3002.  
  3003. for (const key of /** @type {const} */ (['cells', 'pellets'])) {
  3004. for (const [id, resolution] of world[key]) {
  3005. resolution.views.delete(view);
  3006. if (resolution.views.size === 0) world[key].delete(id);
  3007. }
  3008. }
  3009.  
  3010. connection.ws = undefined;
  3011. world.merge();
  3012. render.upload(true);
  3013.  
  3014. const thisUrl = net.url();
  3015. const url = new URL(thisUrl); // use the current url, not realUrl
  3016. const captchaEndpoint = `http${url.protocol === 'ws:' ? '' : 's'}://${url.host}/server/recaptcha/v3`;
  3017.  
  3018. /** @param {string} type */
  3019. const requestCaptcha = type => {
  3020. ui.captcha.request(view, type, token => {
  3021. captchaPostQueue = captchaPostQueue.then(() => new Promise(resolve => {
  3022. aux.oldFetch(captchaEndpoint, {
  3023. method: 'POST',
  3024. headers: { 'content-type': 'application/json' },
  3025. body: JSON.stringify({ token }),
  3026. }).then(res => res.json()).then(res => res.status).catch(() => 'rejected')
  3027. .then(status => {
  3028. if (status === 'complete') connect(view, resolve);
  3029. else setTimeout(() => connect(view, resolve), 1000);
  3030. });
  3031. }));
  3032. });
  3033. };
  3034.  
  3035. if (connection.retries > 0) {
  3036. setTimeout(() => connect(view), 500);
  3037. } else {
  3038. aux.oldFetch(captchaEndpoint).then(res => res.json()).then(res => res.version).catch(() => 'none')
  3039. .then(type => {
  3040. connection.retries = 3;
  3041. if (type === 'v2' || type === 'v3' || type === 'turnstile') requestCaptcha(type);
  3042. else setTimeout(() => connect(view), connection.rejections >= 5 ? 5000 : 500);
  3043. });
  3044. }
  3045. });
  3046. ws.addEventListener('error', () => {});
  3047. ws.addEventListener('message', e => {
  3048. const connection = net.connections.get(view);
  3049. const vision = world.views.get(view);
  3050. if (!connection || !vision) return ws.close();
  3051. const dat = new DataView(e.data);
  3052.  
  3053. if (!connection.handshake) {
  3054. // skip version "SIG 0.0.1\0"
  3055. let o = 10;
  3056.  
  3057. const shuffle = new Uint8Array(256);
  3058. const unshuffle = new Uint8Array(256);
  3059. for (let i = 0; i < 256; ++i) {
  3060. const shuffled = dat.getUint8(o + i);
  3061. shuffle[i] = shuffled;
  3062. unshuffle[shuffled] = i;
  3063. }
  3064.  
  3065. connection.handshake = { shuffle, unshuffle };
  3066.  
  3067. if (world.alive()) net.play(world.selected, input.playData(input.name(view), false));
  3068. return;
  3069. }
  3070.  
  3071. // do this so the packet can easily be sent to sigmod afterwards
  3072. dat.setUint8(0, connection.handshake.unshuffle[dat.getUint8(0)]);
  3073.  
  3074. const now = performance.now();
  3075. let o = 1;
  3076. switch (dat.getUint8(0)) {
  3077. case 0x10: { // world update
  3078. // carry forward record frames
  3079. for (const key of /** @type {const} */ (['cells', 'pellets'])) {
  3080. for (const cell of world[key].values()) {
  3081. const record = cell.views.get(view);
  3082. if (!record) continue;
  3083.  
  3084. record.frames.unshift(record.frames[0]);
  3085. record.frames.splice(12, Infinity);
  3086. }
  3087. }
  3088.  
  3089. // (a) : eat
  3090. const killCount = dat.getUint16(o, true);
  3091. o += 2;
  3092. for (let i = 0; i < killCount; ++i) {
  3093. const killerId = dat.getUint32(o, true);
  3094. const killedId = dat.getUint32(o + 4, true);
  3095. o += 8;
  3096.  
  3097. let pellet = true;
  3098. let killed = world.pellets.get(killedId) ?? (pellet = false, world.cells.get(killedId));
  3099. if (!killed) continue;
  3100.  
  3101. const record = killed.views.get(view);
  3102. if (!record) continue;
  3103.  
  3104. const frame = record.frames[0];
  3105. // update interpolation using old targets
  3106. const xyr = world.xyr(record.frames[0], record, undefined, undefined, pellet, now);
  3107. record.ox = xyr.x;
  3108. record.oy = xyr.y;
  3109. record.or = xyr.r;
  3110. record.jr = xyr.jr;
  3111. record.a = xyr.a;
  3112. record.updated = now;
  3113.  
  3114. // update new targets (and dead-ness)
  3115. record.frames[0] = {
  3116. nx: frame.nx, ny: frame.ny, nr: frame.nr,
  3117. born: frame.born, deadAt: now, deadTo: killerId,
  3118. };
  3119.  
  3120. if (pellet && vision.owned.includes(killerId)) {
  3121. ++world.stats.foodEaten;
  3122. net.food(view); // dumbass quest code go brrr
  3123. }
  3124. }
  3125.  
  3126. // (b) : add, upd
  3127. do {
  3128. const id = dat.getUint32(o, true);
  3129. o += 4;
  3130. if (id === 0) break;
  3131.  
  3132. const x = dat.getInt16(o, true);
  3133. const y = dat.getInt16(o + 2, true);
  3134. const r = dat.getUint16(o + 4, true);
  3135. const flags = dat.getUint8(o + 6);
  3136. // (void 1 byte, "isUpdate")
  3137. // (void 1 byte, "isPlayer")
  3138. const sub = !!dat.getUint8(o + 9);
  3139. o += 10;
  3140.  
  3141. let clan; [clan, o] = aux.readZTString(dat, o);
  3142.  
  3143. /** @type {[number, number, number] | undefined} */
  3144. let rgb;
  3145. if (flags & 0x02) { // update color
  3146. rgb = [dat.getUint8(o++) / 255, dat.getUint8(o++) / 255, dat.getUint8(o++) / 255];
  3147. }
  3148.  
  3149. /** @type {string | undefined} */
  3150. let skin;
  3151. if (flags & 0x04) { // update skin
  3152. [skin, o] = aux.readZTString(dat, o);
  3153. skin = aux.parseSkin(skin);
  3154. }
  3155.  
  3156. /** @type {string | undefined} */
  3157. let name;
  3158. if (flags & 0x08) { // update name
  3159. [name, o] = aux.readZTString(dat, o);
  3160. name = aux.parseName(name);
  3161. if (name) render.textFromCache(name, sub); // make sure the texture is ready on render
  3162. }
  3163.  
  3164. const jagged = !!(flags & 0x11); // spiked or agitated
  3165. const eject = !!(flags & 0x20);
  3166. const pellet = r <= 40 && !eject; // tourney servers have bigger pellets (r=40)
  3167. const cell = (pellet ? world.pellets : world.cells).get(id);
  3168. const record = cell?.views.get(view);
  3169. if (record) {
  3170. const frame = record.frames[0];
  3171. if (frame.deadAt === undefined) {
  3172. // update interpolation using old targets
  3173. const xyr = world.xyr(record.frames[0], record, undefined, undefined, pellet, now);
  3174. record.ox = xyr.x;
  3175. record.oy = xyr.y;
  3176. record.or = xyr.r;
  3177. record.jr = xyr.jr;
  3178. record.a = xyr.a;
  3179. } else {
  3180. // cell just reappeared, discard all old data
  3181. record.ox = x;
  3182. record.oy = y;
  3183. record.or = r;
  3184. record.jr = r;
  3185. record.a = 0;
  3186. }
  3187.  
  3188. record.updated = now;
  3189.  
  3190. // update target frame
  3191. record.frames[0] = {
  3192. nx: x, ny: y, nr: r,
  3193. born: frame.born, deadAt: undefined, deadTo: -1
  3194. };
  3195.  
  3196. // update desc
  3197. if (name !== undefined) record.name = name;
  3198. if (skin !== undefined) record.skin = skin;
  3199. if (rgb !== undefined) record.rgb = rgb;
  3200. record.clan = clan;
  3201. record.jagged = jagged;
  3202. record.eject = eject;
  3203. } else {
  3204. /** @type {CellRecord} */
  3205. const record = {
  3206. ox: x, oy: y, or: r,
  3207. jr: r, a: 0, updated: now,
  3208. frames: [{
  3209. nx: x, ny: y, nr: r,
  3210. born: now, deadAt: undefined, deadTo: -1,
  3211. }],
  3212. name: name ?? '', skin: skin ?? '', sub, clan,
  3213. rgb: rgb ?? [0.5, 0.5, 0.5],
  3214. jagged, eject,
  3215. };
  3216. if (cell) {
  3217. cell.views.set(view, record);
  3218. } else {
  3219. (pellet ? world.pellets : world.cells).set(id, {
  3220. id,
  3221. merged: undefined,
  3222. model: undefined,
  3223. views: new Map([[ view, record ]]),
  3224. });
  3225. }
  3226. }
  3227. } while (true);
  3228.  
  3229. // (c) : del
  3230. const deleteCount = dat.getUint16(o, true);
  3231. o += 2;
  3232. for (let i = 0; i < deleteCount; ++i) {
  3233. const deletedId = dat.getUint32(o, true);
  3234. o += 4;
  3235.  
  3236. const record
  3237. = (world.pellets.get(deletedId) ?? world.cells.get(deletedId))?.views.get(view);
  3238. if (!record) continue;
  3239.  
  3240. const frame = record.frames[0];
  3241. if (frame.deadAt !== undefined) continue;
  3242. record.frames[0] = {
  3243. nx: frame.nx, ny: frame.ny, nr: frame.nr,
  3244. born: frame.born, deadAt: now, deadTo: -1,
  3245. };
  3246. // no interpolation stuff is updated because the target positions won't be changed,
  3247. // unlike on eat where nx and ny are set to the killer's
  3248. }
  3249.  
  3250. // (d) : finalize, upload data
  3251. world.merge();
  3252. world.clean();
  3253. render.upload(true);
  3254.  
  3255. // (e) : clear own cells that don't exist anymore (NOT on world.clean!)
  3256. for (let i = 0; i < vision.owned.length; ++i) {
  3257. const cell = world.cells.get(vision.owned[i]);
  3258. if (!cell) {
  3259. vision.owned.splice(i--, 1);
  3260. continue;
  3261. }
  3262. const record = cell?.views.get(view);
  3263.  
  3264. if (record && record.frames[0].deadAt === undefined && connection.playBlock?.state === 'joining') {
  3265. connection.playBlock = undefined;
  3266. }
  3267. }
  3268.  
  3269. ui.deathScreen.check();
  3270. break;
  3271. }
  3272.  
  3273. case 0x11: { // update camera pos
  3274. vision.camera.tx = dat.getFloat32(o, true);
  3275. vision.camera.ty = dat.getFloat32(o + 4, true);
  3276. vision.camera.tscale = dat.getFloat32(o + 8, true);
  3277. break;
  3278. }
  3279.  
  3280. case 0x12: { // delete all cells
  3281. // happens every time you respawn
  3282. if (connection.playBlock?.state === 'leaving') connection.playBlock.state = 'joining';
  3283. // the server won't respond to pings if you aren't in a world, and we don't want to show '????'
  3284. // unless there's actually a problem
  3285. connection.pinged = undefined;
  3286.  
  3287. // DO NOT just clear the maps! when respawning, OgarII will not resend cell data if we spawn
  3288. // nearby.
  3289. for (const key of /** @type {const} */ (['cells', 'pellets'])) {
  3290. for (const cell of world[key].values()) {
  3291. const record = cell.views.get(view);
  3292. if (!record) continue;
  3293.  
  3294. const frame = record.frames[0];
  3295. record.frames.unshift({
  3296. nx: frame.nx, ny: frame.ny, nr: frame.nr,
  3297. born: frame.born, deadAt: frame.deadAt ?? now, deadTo: frame.deadTo || -1,
  3298. });
  3299. }
  3300. }
  3301. world.merge();
  3302. render.upload(true);
  3303. // passthrough
  3304. }
  3305. case 0x14: { // delete my cells
  3306. // only reset spawn time if no other tab is alive.
  3307. // this could be cheated (if you alternate respawning your tabs, for example) but i don't think
  3308. // multiboxers ever see the stats menu anyway
  3309. if (!world.alive()) world.stats.spawnedAt = undefined;
  3310. ui.deathScreen.hide(); // don't trigger death screen on respawn
  3311. break;
  3312. }
  3313.  
  3314. case 0x20: { // new owned cell
  3315. // check if this is the first owned cell
  3316. let first = true;
  3317. let firstThis = true;
  3318. for (const [otherView, otherVision] of world.views) {
  3319. for (const id of otherVision.owned) {
  3320. const record = world.cells.get(id)?.views.get(otherView);
  3321. if (!record) continue;
  3322. const frame = record.frames[0];
  3323. if (frame.deadAt !== undefined) continue;
  3324.  
  3325. first = false;
  3326. if (otherVision === vision) {
  3327. firstThis = false;
  3328. break;
  3329. }
  3330. }
  3331. }
  3332. if (first) world.stats.spawnedAt = now;
  3333. if (firstThis) vision.spawned = now;
  3334.  
  3335. vision.owned.push(dat.getUint32(o, true));
  3336. break;
  3337. }
  3338.  
  3339. case 0x31: { // ffa leaderboard list
  3340. const lb = [];
  3341. const count = dat.getUint32(o, true);
  3342. o += 4;
  3343.  
  3344. /** @type {number | undefined} */
  3345. let myPosition;
  3346. for (let i = 0; i < count; ++i) {
  3347. const me = !!dat.getUint32(o, true);
  3348. o += 4;
  3349.  
  3350. let name; [name, o] = aux.readZTString(dat, o);
  3351. name = aux.parseName(name);
  3352.  
  3353. // why this is copied into every leaderboard entry is beyond my understanding
  3354. myPosition = dat.getUint32(o, true);
  3355. const sub = !!dat.getUint32(o + 4, true);
  3356. o += 8;
  3357.  
  3358. lb.push({ name, sub, me, place: undefined });
  3359. }
  3360.  
  3361. if (myPosition) { // myPosition could be zero
  3362. if (myPosition - 1 >= lb.length) {
  3363. const nick = input.nick[world.multis.indexOf(view) || 0].value;
  3364. lb.push({
  3365. me: true,
  3366. name: aux.parseName(nick),
  3367. place: myPosition,
  3368. sub: false, // doesn't matter
  3369. });
  3370. }
  3371.  
  3372. world.stats.highestPosition = Math.min(world.stats.highestPosition, myPosition);
  3373. }
  3374.  
  3375. vision.leaderboard = lb;
  3376. break;
  3377. }
  3378.  
  3379. case 0x40: { // border update
  3380. vision.border = {
  3381. l: dat.getFloat64(o, true),
  3382. t: dat.getFloat64(o + 8, true),
  3383. r: dat.getFloat64(o + 16, true),
  3384. b: dat.getFloat64(o + 24, true),
  3385. };
  3386. break;
  3387. }
  3388.  
  3389. case 0x63: { // chat message
  3390. // only handle non-server chat messages on the primary tab, to prevent duplicate messages
  3391. const flags = dat.getUint8(o++);
  3392. const server = flags & 0x80;
  3393. if (view !== world.viewId.primary && !server) return; // skip sigmod processing too
  3394. const rgb = /** @type {[number, number, number, number]} */
  3395. ([dat.getUint8(o++) / 255, dat.getUint8(o++) / 255, dat.getUint8(o++) / 255, 1]);
  3396.  
  3397. let name; [name, o] = aux.readZTString(dat, o);
  3398. let msg; [msg, o] = aux.readZTString(dat, o);
  3399. ui.chat.add(name, rgb, msg, !!(flags & 0x80));
  3400. break;
  3401. }
  3402.  
  3403. case 0xb4: { // incorrect password alert
  3404. ui.error('Password is incorrect');
  3405. break;
  3406. }
  3407.  
  3408. case 0xfe: { // server stats (in response to a ping)
  3409. let statString; [statString, o] = aux.readZTString(dat, o);
  3410. vision.stats = JSON.parse(statString);
  3411. if (connection.pinged !== undefined) connection.latency = now - connection.pinged;
  3412. connection.pinged = undefined;
  3413. break;
  3414. }
  3415. }
  3416.  
  3417. sigmod.proxy.handleMessage?.(dat);
  3418. });
  3419. ws.addEventListener('open', () => {
  3420. establishedCallback?.();
  3421. establishedCallback = undefined;
  3422.  
  3423. const connection = net.connections.get(view);
  3424. const vision = world.views.get(view);
  3425. if (!connection || !vision) return ws.close();
  3426.  
  3427. ui.captcha.remove(view);
  3428.  
  3429. connection.rejections = 0;
  3430. connection.retries = 0;
  3431.  
  3432. vision.camera.x = vision.camera.tx = 0;
  3433. vision.camera.y = vision.camera.ty = 0;
  3434. vision.camera.scale = input.zoom;
  3435. vision.camera.tscale = 1;
  3436. ws.send(aux.textEncoder.encode('SIG 0.0.1\x00'));
  3437. });
  3438.  
  3439. return ws;
  3440. };
  3441.  
  3442. // ping loop
  3443. setInterval(() => {
  3444. for (const connection of net.connections.values()) {
  3445. if (!connection.handshake || connection.ws?.readyState !== WebSocket.OPEN) continue;
  3446. if (connection.pinged !== undefined) connection.latency = -1; // display '????ms'
  3447. connection.pinged = performance.now();
  3448. connection.ws.send(connection.handshake.shuffle.slice(0xfe, 0xfe + 1));
  3449. }
  3450. }, 2000);
  3451.  
  3452. // #2 : define helper functions
  3453. /** @type {HTMLSelectElement | null} */
  3454. const gamemode = document.querySelector('#gamemode');
  3455. /** @type {HTMLOptionElement | null} */
  3456. const firstGamemode = document.querySelector('#gamemode option');
  3457. net.url = () => {
  3458. if (location.search.startsWith('?ip=')) return location.search.slice('?ip='.length);
  3459. else return 'wss://' + (gamemode?.value || firstGamemode?.value || 'ca0.sigmally.com/ws/');
  3460. };
  3461.  
  3462. /** @param {symbol} view */
  3463. net.respawnable = view => {
  3464. const vision = world.views.get(view);
  3465. const con = net.connections.get(view);
  3466. if (!vision || !con?.ws) return false;
  3467.  
  3468. // only allow respawns on localhost (players on personal private servers can simply append `localhost`)
  3469. return world.score(view) < 5500 || con.ws.url.includes('localhost');
  3470. };
  3471.  
  3472. // disconnect if a different gamemode is selected
  3473. // an interval is preferred because the game can apply its gamemode setting *after* connecting without
  3474. // triggering any events
  3475. setInterval(() => {
  3476. for (const connection of net.connections.values()) {
  3477. if (!connection.ws) continue;
  3478. if (connection.ws.readyState !== WebSocket.CONNECTING && connection.ws.readyState !== WebSocket.OPEN)
  3479. continue;
  3480. if (connection.ws.url === net.url()) continue;
  3481. connection.ws.close();
  3482. }
  3483. }, 200);
  3484.  
  3485. /**
  3486. * @param {symbol} view
  3487. * @param {number} opcode
  3488. * @param {object} data
  3489. */
  3490. const sendJson = (view, opcode, data) => {
  3491. // must check readyState as a weboscket might be in the 'CLOSING' state (so annoying!)
  3492. const connection = net.connections.get(view);
  3493. if (!connection?.handshake || connection.ws?.readyState !== WebSocket.OPEN) return;
  3494. const dataBuf = aux.textEncoder.encode(JSON.stringify(data));
  3495. const dat = new DataView(new ArrayBuffer(dataBuf.byteLength + 2));
  3496.  
  3497. dat.setUint8(0, connection.handshake.shuffle[opcode]);
  3498. for (let i = 0; i < dataBuf.byteLength; ++i) {
  3499. dat.setUint8(1 + i, dataBuf[i]);
  3500. }
  3501. connection.ws.send(dat);
  3502. };
  3503.  
  3504. // #5 : export input functions
  3505. /**
  3506. * @param {symbol} view
  3507. * @param {number} x
  3508. * @param {number} y
  3509. */
  3510. net.move = (view, x, y) => {
  3511. const connection = net.connections.get(view);
  3512. if (!connection?.handshake || connection.ws?.readyState !== WebSocket.OPEN) return;
  3513. const dat = new DataView(new ArrayBuffer(13));
  3514.  
  3515. dat.setUint8(0, connection.handshake.shuffle[0x10]);
  3516. dat.setInt32(1, x, true);
  3517. dat.setInt32(5, y, true);
  3518. connection.ws.send(dat);
  3519.  
  3520. sigmod.proxy.isPlaying?.(); // without this, the respawn key will build up timeouts and make the game laggy
  3521. };
  3522.  
  3523. /** @param {number} opcode */
  3524. const bindOpcode = opcode => /** @param {symbol} view */ view => {
  3525. const connection = net.connections.get(view);
  3526. if (!connection?.handshake || connection.ws?.readyState !== WebSocket.OPEN) return;
  3527. connection.ws.send(connection.handshake.shuffle.slice(opcode, opcode + 1));
  3528. };
  3529. net.w = bindOpcode(21);
  3530. net.qdown = bindOpcode(18);
  3531. net.qup = bindOpcode(19);
  3532. net.split = bindOpcode(17);
  3533. // quests
  3534. net.food = bindOpcode(0xc0);
  3535. net.time = bindOpcode(0xbf);
  3536.  
  3537. // reversed argument order for sigmod compatibility
  3538. /**
  3539. * @param {string} msg
  3540. * @param {symbol=} view
  3541. */
  3542. net.chat = (msg, view = world.selected) => {
  3543. const connection = net.connections.get(view);
  3544. if (!connection?.handshake || connection.ws?.readyState !== WebSocket.OPEN) return;
  3545.  
  3546. if (msg.toLowerCase().startsWith('/leaveworld') && !net.respawnable(view)) return; // prevent abuse
  3547.  
  3548. const msgBuf = aux.textEncoder.encode(msg);
  3549. const dat = new DataView(new ArrayBuffer(msgBuf.byteLength + 3));
  3550.  
  3551. dat.setUint8(0, connection.handshake.shuffle[0x63]);
  3552. // skip flags
  3553. for (let i = 0; i < msgBuf.byteLength; ++i) {
  3554. dat.setUint8(2 + i, msgBuf[i]);
  3555. }
  3556. connection.ws.send(dat);
  3557. };
  3558.  
  3559. /**
  3560. * @param {symbol} view
  3561. * @param {{ name: string, skin: string, [x: string]: any }} data
  3562. */
  3563. net.play = (view, data) => {
  3564. const connection = net.connections.get(view);
  3565. const now = performance.now();
  3566. if (!data.state) {
  3567. if (!connection || (connection.playBlock !== undefined && now - connection.playBlock.started < 750) || world.score(view) > 0) return;
  3568. connection.playBlock = { state: 'joining', started: now };
  3569. ui.deathScreen.hide();
  3570. }
  3571. sendJson(view, 0x00, data);
  3572. };
  3573.  
  3574. /**
  3575. * @param {symbol} view
  3576. * @param {{ name: string, skin: string, [x: string]: any }} data
  3577. */
  3578. net.respawn = (view, data) => {
  3579. const connection = net.connections.get(view);
  3580. if (!connection?.handshake || connection.ws?.readyState !== WebSocket.OPEN) return;
  3581.  
  3582. const now = performance.now();
  3583. if (connection.playBlock !== undefined && now - connection.playBlock.started < 750) return;
  3584.  
  3585. const score = world.score(view);
  3586. if (score <= 0) { // if dead, no need to leave+rejoin the world
  3587. net.play(view, data);
  3588. return;
  3589. } else if (!net.respawnable(view)) return;
  3590.  
  3591. if (settings.blockNearbyRespawns) {
  3592. const vision = world.views.get(view);
  3593. if (!vision?.border) return;
  3594.  
  3595. world.cameras(now);
  3596. const { l, r, t, b } = vision.border;
  3597.  
  3598. for (const [otherView, otherVision] of world.views) {
  3599. if (otherView === view || world.score(otherView) <= 0) continue;
  3600.  
  3601. // block respawns if both views are close enough (minimap squares give too large of a threshold)
  3602. const d = Math.hypot(vision.camera.tx - otherVision.camera.tx, vision.camera.ty - otherVision.camera.ty);
  3603. if (d <= Math.min(r - l, b - t) / 4) return;
  3604. }
  3605. }
  3606.  
  3607. connection.playBlock = { state: 'leaving', started: now };
  3608. net.chat('/leaveworld', view); // immediately remove from world, which removes all player cells
  3609. sendJson(view, 0x00, data); // enqueue into matchmaker (/joinworld is not available if dead)
  3610. setTimeout(() => { // wait until Matchmaker.update() puts us into a world
  3611. sendJson(view, 0x00, data); // spawn
  3612. }, 60); // = 40ms (1 tick) + 20ms (margin of error)
  3613. };
  3614.  
  3615. // create initial connection
  3616. world.create(world.viewId.primary);
  3617. net.create(world.viewId.primary);
  3618. let lastChangedSpectate = -Infinity;
  3619. setInterval(() => {
  3620. if (!settings.multibox && !settings.nbox) {
  3621. world.selected = world.viewId.primary;
  3622. ui.captcha.reposition();
  3623. ui.linesplit.update();
  3624. }
  3625.  
  3626. if (settings.spectator) {
  3627. const vision = world.create(world.viewId.spectate);
  3628. net.create(world.viewId.spectate);
  3629. net.play(world.viewId.spectate, { name: '', skin: '', clan: aux.userData?.clan, state: 2 });
  3630.  
  3631. // only press Q to toggle once in a while, in case ping is above 200
  3632. const now = performance.now();
  3633. if (now - lastChangedSpectate > 1000) {
  3634. if (vision.camera.tscale > 0.39) { // when roaming, the spectate scale is set to ~0.4
  3635. net.qdown(world.viewId.spectate);
  3636. lastChangedSpectate = now;
  3637. }
  3638. } else {
  3639. net.qup(world.viewId.spectate); // doubly serves as anti-afk
  3640. }
  3641. } else {
  3642. const con = net.connections.get(world.viewId.spectate);
  3643. if (con?.ws && con?.ws.readyState !== WebSocket.CLOSED && con?.ws.readyState !== WebSocket.CLOSING) {
  3644. con?.ws.close();
  3645. }
  3646. net.connections.delete(world.viewId.spectate);
  3647. world.views.delete(world.viewId.spectate);
  3648. input.views.delete(world.viewId.spectate);
  3649.  
  3650. for (const key of /** @type {const} */ (['cells', 'pellets'])) {
  3651. for (const [id, resolution] of world[key]) {
  3652. resolution.views.delete(world.viewId.spectate);
  3653. if (resolution.views.size === 0) world[key].delete(id);
  3654. }
  3655. }
  3656. }
  3657. }, 200);
  3658.  
  3659. // dumbass quest code go brrr
  3660. setInterval(() => {
  3661. for (const view of net.connections.keys()) net.time(view);
  3662. }, 1000);
  3663.  
  3664. return net;
  3665. })();
  3666.  
  3667.  
  3668.  
  3669. //////////////////////////
  3670. // Setup Input Handlers //
  3671. //////////////////////////
  3672. const input = (() => {
  3673. const input = {};
  3674.  
  3675. // #1 : general inputs
  3676. // between -1 and 1
  3677. /** @type {[number, number]} */
  3678. input.current = [0, 0];
  3679. /** @type {Map<symbol, {
  3680. * forceW: boolean,
  3681. * lock: { type: 'point', mouse: [number, number], world: [number, number], until: number }
  3682. * | { type: 'horizontal', world: [number, number], lastSplit: number }
  3683. * | { type: 'vertical', world: [number, number], lastSplit: number }
  3684. * | { type: 'fixed' }
  3685. * | undefined,
  3686. * mouse: [number, number], // between -1 and 1
  3687. * w: boolean,
  3688. * world: [number, number], // world position; only updates when tab is selected
  3689. * }>} */
  3690. input.views = new Map();
  3691. input.zoom = 1;
  3692.  
  3693. input.nboxSelectedPairs = [world.multis[0], world.multis[2], world.multis[4], world.multis[6]];
  3694. input.nboxSelectedReal = world.viewId.primary;
  3695. /** @type {Set<symbol>} */
  3696. input.nboxSelectedTemporary = new Set();
  3697.  
  3698. /** @param {symbol} view */
  3699. const create = view => {
  3700. const old = input.views.get(view);
  3701. if (old) return old;
  3702.  
  3703. /** @type {typeof input.views extends Map<symbol, infer T> ? T : never} */
  3704. const inputs = { forceW: false, lock: undefined, mouse: [0, 0], w: false, world: [0, 0] };
  3705. input.views.set(view, inputs);
  3706. return inputs;
  3707. };
  3708.  
  3709. /**
  3710. * @param {symbol} view
  3711. * @param {[number, number]} x, y
  3712. * @returns {[number, number]}
  3713. */
  3714. input.toWorld = (view, [x, y]) => {
  3715. const camera = world.views.get(view)?.camera;
  3716. if (!camera) return [0, 0];
  3717. return [
  3718. camera.x + x * (innerWidth / innerHeight) * 540 / camera.scale,
  3719. camera.y + y * 540 / camera.scale,
  3720. ];
  3721. };
  3722.  
  3723. // sigmod freezes the player by overlaying an invisible div, so we just listen for canvas movements instead
  3724. addEventListener('mousemove', e => {
  3725. if (ui.escOverlayVisible()) return;
  3726. // sigmod freezes the player by overlaying an invisible div, so we respect it
  3727. if (e.target instanceof HTMLDivElement
  3728. && /** @type {CSSUnitValue | undefined} */ (e.target.attributeStyleMap.get('z-index'))?.value === 99)
  3729. return;
  3730. input.current = [(e.clientX / innerWidth * 2) - 1, (e.clientY / innerHeight * 2) - 1];
  3731. });
  3732.  
  3733. const unfocused = () => ui.escOverlayVisible() || document.activeElement?.tagName === 'INPUT';
  3734.  
  3735. /** @param {symbol} view */
  3736. input.name = view => {
  3737. const i = world.multis.indexOf(view);
  3738. if (i <= 0) return input.nick[0]?.value || '';
  3739. else return settings.multiNames[i - 1] || '';
  3740. };
  3741.  
  3742. /**
  3743. * @param {symbol} view
  3744. * @param {boolean} forceUpdate
  3745. */
  3746. input.move = (view, forceUpdate) => {
  3747. const now = performance.now();
  3748. const inputs = input.views.get(view) ?? create(view);
  3749. if (view === world.selected) inputs.mouse = input.current;
  3750.  
  3751. const worldMouse = input.toWorld(view, inputs.mouse);
  3752.  
  3753. switch (inputs.lock?.type) {
  3754. case 'point':
  3755. if (now > inputs.lock.until) break;
  3756. const d = Math.hypot(inputs.mouse[0] - inputs.lock.mouse[0], inputs.mouse[1] - inputs.lock.mouse[1]);
  3757. // only lock the mouse as long as the mouse has not moved further than 25% (of 2) of the screen away
  3758. if (d < 0.5 || Number.isNaN(d)) {
  3759. net.move(view, ...inputs.lock.world);
  3760. return;
  3761. }
  3762. break;
  3763. case 'horizontal':
  3764. if (settings.moveAfterLinesplit && inputs.lock.lastSplit !== -Infinity) {
  3765. // move horizontally only after splitting to maximize distance travelled
  3766. if (Math.abs(inputs.mouse[0]) <= 0.2) {
  3767. net.move(view, worldMouse[0], inputs.lock.world[1]);
  3768. } else {
  3769. net.move(view, (2 ** 31 - 1) * (inputs.mouse[0] >= 0 ? 1 : -1), inputs.lock.world[1]);
  3770. }
  3771. } else {
  3772. net.move(view, ...inputs.lock.world);
  3773. }
  3774. return;
  3775.  
  3776. case 'vertical':
  3777. if (settings.moveAfterLinesplit ? inputs.lock.lastSplit !== -Infinity : now - inputs.lock.lastSplit <= 150) {
  3778. // vertical linesplits require a bit of upwards movement to split upwards
  3779. if (Math.abs(inputs.mouse[1]) <= 0.2) {
  3780. net.move(view, inputs.lock.world[0], worldMouse[1]);
  3781. } else {
  3782. net.move(view, inputs.lock.world[0], (2 ** 31 - 1) * (inputs.mouse[1] >= 0 ? 1 : -1));
  3783. }
  3784. } else {
  3785. net.move(view, ...inputs.lock.world);
  3786. }
  3787. return;
  3788.  
  3789. case 'fixed':
  3790. // rotate around the tab's camera center (otherwise, spinning around on a tab feels unnatural)
  3791. const worldCenter = world.singleCamera(view, undefined, settings.camera !== 'default' ? 2 : 0, now);
  3792. const x = worldMouse[0] - worldCenter.sumX / worldCenter.weight;
  3793. const y = worldMouse[1] - worldCenter.sumY / worldCenter.weight;
  3794. // create two points along the 2^31 integer boundary (OgarII uses ~~x and ~~y to truncate positions
  3795. // to 32-bit integers), choose which one is closer to zero (the one actually within the boundary)
  3796. const max = 2 ** 31 - 1;
  3797. const xClamp = /** @type {const} */ ([max * Math.sign(x), y / x * max * Math.sign(x)]);
  3798. const yClamp = /** @type {const} */ ([x / y * max * Math.sign(y), max * Math.sign(y)]);
  3799. if (Math.hypot(...xClamp) < Math.hypot(...yClamp)) net.move(view, ...xClamp);
  3800. else net.move(view, ...yClamp);
  3801. return;
  3802. }
  3803.  
  3804. inputs.lock = undefined;
  3805. if (world.selected === view || forceUpdate) inputs.world = worldMouse;
  3806. net.move(view, ...inputs.world);
  3807. };
  3808.  
  3809. /** @param {symbol} view */
  3810. input.split = view => {
  3811. const inputs = create(view);
  3812. if (inputs?.lock?.type === 'vertical' || inputs?.lock?.type === 'horizontal') {
  3813. inputs.lock.lastSplit = performance.now();
  3814. }
  3815. input.move(view, true);
  3816. net.split(view);
  3817. };
  3818.  
  3819. /** @param {symbol} view */
  3820. input.autoRespawn = view => {
  3821. if (!world.alive()) return;
  3822. net.play(world.selected, input.playData(input.name(view), false));
  3823. };
  3824.  
  3825. /**
  3826. * @param {symbol} view
  3827. */
  3828. input.tab = view => {
  3829. if (view === world.selected) return;
  3830. const oldView = world.selected;
  3831. const inputs = create(oldView);
  3832. const newInputs = create(view);
  3833.  
  3834. newInputs.w = inputs.w;
  3835. inputs.w = false; // stop current tab from feeding; don't change forceW
  3836. // update mouse immediately (after setTimeout, when mouse events happen)
  3837. setTimeout(() => inputs.world = input.toWorld(oldView, inputs.mouse = input.current));
  3838.  
  3839. world.selected = view;
  3840. world.create(world.selected);
  3841. net.create(world.selected);
  3842.  
  3843. ui.captcha.reposition();
  3844. ui.linesplit.update();
  3845. };
  3846.  
  3847. setInterval(() => {
  3848. create(world.selected);
  3849. for (const [view, inputs] of input.views) {
  3850. input.move(view, false);
  3851. // if tapping W very fast, make sure at least one W is ejected
  3852. if (inputs.forceW || inputs.w) net.w(view);
  3853. inputs.forceW = false;
  3854. }
  3855. }, 40);
  3856.  
  3857. /** @type {Node | null} */
  3858. let sigmodChat;
  3859. setInterval(() => sigmodChat ||= document.querySelector('.modChat'), 500);
  3860. addEventListener('wheel', e => {
  3861. if (unfocused()) return;
  3862. // when scrolling through sigmod chat, don't allow zooming.
  3863. // for consistency, use the container .modChat and not #mod-messages as #mod-messages can have zero height
  3864. if (sigmodChat && sigmodChat.contains(/** @type {Node} */ (e.target))) return;
  3865. // support for the very obscure "scroll by page" setting in windows
  3866. // i don't think browsers support DOM_DELTA_LINE, so assume DOM_DELTA_PIXEL otherwise
  3867. const deltaY = e.deltaMode === e.DOM_DELTA_PAGE ? e.deltaY : e.deltaY / 100;
  3868. input.zoom *= 0.8 ** (deltaY * settings.scrollFactor);
  3869. const minZoom = (!settings.multibox && !settings.nbox && !aux.settings.zoomout) ? 1 : 0.8 ** 15;
  3870. input.zoom = Math.min(Math.max(input.zoom, minZoom), 0.8 ** -21);
  3871. });
  3872.  
  3873. /**
  3874. * @param {KeyboardEvent | MouseEvent} e
  3875. * @returns {boolean}
  3876. */
  3877. const handleKeybind = e => {
  3878. const keybind = aux.keybind(e)?.toLowerCase();
  3879. if (!keybind) return false;
  3880.  
  3881. const release = e.type === 'keyup' || e.type === 'mouseup';
  3882. if (!release && settings.multibox && keybind === settings.multibox.toLowerCase()) {
  3883. e.preventDefault(); // prevent selecting anything on the page
  3884.  
  3885. // cycle to the next tab
  3886. const tabs = settings.nbox ? settings.nboxCount : 2;
  3887. const i = world.multis.indexOf(world.selected);
  3888. const newI = Math.min((i + 1) % tabs, world.multis.length);
  3889. input.nboxSelectedNonTemporary = world.multis[newI];
  3890.  
  3891. input.nboxSelectedTemporary.clear();
  3892. input.nboxSelectedNonTemporary = world.multis[newI];
  3893. input.nboxSelectedPairs[Math.floor(newI / 2)] = world.multis[newI];
  3894.  
  3895. input.tab(world.multis[newI]);
  3896. input.autoRespawn(world.multis[newI]);
  3897. return true;
  3898. }
  3899.  
  3900. if (settings.nbox) {
  3901. if (!release && keybind === settings.nboxSwitchPair.toLowerCase()) {
  3902. const i = world.multis.indexOf(input.nboxSelectedReal);
  3903. const pair = Math.floor(i / 2);
  3904. // don't allow switching in a pair that doesn't exist
  3905. const partner = pair * 2 === i ? (i + 1 < settings.nboxCount ? i + 1 : i) : i - 1;
  3906. input.nboxSelectedReal = input.nboxSelectedPairs[pair] = world.multis[partner];
  3907. input.nboxSelectedTemporary.clear(); // but still clear the temporary holds regardless
  3908. input.tab(world.multis[partner]);
  3909. input.autoRespawn(world.selected);
  3910. return true;
  3911. }
  3912.  
  3913. if (!release && keybind === settings.nboxCyclePair.toLowerCase()) {
  3914. const i = world.multis.indexOf(input.nboxSelectedReal);
  3915. const pair = Math.floor(i / 2);
  3916. const newPair = (pair + 1) % Math.ceil(settings.nboxCount / 2);
  3917. input.nboxSelectedReal = input.nboxSelectedPairs[newPair];
  3918. input.nboxSelectedTemporary.clear();
  3919. input.tab(input.nboxSelectedReal);
  3920. input.autoRespawn(world.selected);
  3921. return true;
  3922. }
  3923.  
  3924. for (let i = 0; i < settings.nboxCount; ++i) {
  3925. if (!release && keybind === settings.nboxSelectKeybinds[i].toLowerCase()) {
  3926. input.nboxSelectedReal = input.nboxSelectedPairs[Math.floor(i / 2)] = world.multis[i];
  3927. input.nboxSelectedTemporary.clear();
  3928. input.tab(world.multis[i]);
  3929. input.autoRespawn(world.selected);
  3930. return true;
  3931. }
  3932.  
  3933. const hold = settings.nboxHoldKeybinds[i].toLowerCase();
  3934. if (keybind === hold || (release && hold.endsWith('+' + keybind))) {
  3935. if (release) {
  3936. input.nboxSelectedTemporary.delete(world.multis[i]);
  3937. if (input.nboxSelectedTemporary.size === 0) input.tab(input.nboxSelectedReal);
  3938. } else {
  3939. input.nboxSelectedTemporary.add(world.multis[i]);
  3940. input.tab(world.multis[i]);
  3941. }
  3942. input.autoRespawn(world.selected);
  3943. return true;
  3944. }
  3945. }
  3946. }
  3947.  
  3948. return false;
  3949. };
  3950.  
  3951. addEventListener('keydown', e => {
  3952. const view = world.selected;
  3953. const inputs = input.views.get(view) ?? create(view);
  3954.  
  3955. // never allow pressing Tab by itself
  3956. if (e.code === 'Tab' && !e.ctrlKey && !e.altKey && !e.metaKey) e.preventDefault();
  3957.  
  3958. if (e.code === 'Escape') {
  3959. if (document.activeElement === ui.chat.input) ui.chat.input.blur();
  3960. else ui.toggleEscOverlay();
  3961. return;
  3962. }
  3963.  
  3964. if (unfocused()) {
  3965. if (e.code === 'Enter' && document.activeElement === ui.chat.input && ui.chat.input.value.length > 0) {
  3966. net.chat(ui.chat.input.value.slice(0, 15), world.selected);
  3967. ui.chat.input.value = '';
  3968. ui.chat.input.blur();
  3969. }
  3970.  
  3971. return;
  3972. }
  3973.  
  3974. if (handleKeybind(e)) return;
  3975.  
  3976. if (settings.blockBrowserKeybinds) {
  3977. if (e.code === 'F11') {
  3978. // force true fullscreen to make sure Ctrl+W and other binds are caught.
  3979. // not well supported on safari
  3980. if (!document.fullscreenElement) {
  3981. document.body.requestFullscreen?.()?.catch(() => {});
  3982. /** @type {any} */ (navigator).keyboard?.lock()?.catch(() => {});
  3983. } else {
  3984. document.exitFullscreen?.()?.catch(() => {});
  3985. /** @type {any} */ (navigator).keyboard?.unlock()?.catch(() => {});
  3986. }
  3987. }
  3988.  
  3989. if (e.code !== 'Tab') e.preventDefault(); // allow ctrl+tab and alt+tab
  3990. } else if (e.ctrlKey && e.code === 'KeyW') {
  3991. e.preventDefault(); // doesn't seem to work for me, but works for others
  3992. }
  3993.  
  3994. // if fast feed is rebound, only allow the spoofed W's from sigmod
  3995. let fastFeeding = e.code === 'KeyW';
  3996. if (sigmod.settings.rapidFeedKey && sigmod.settings.rapidFeedKey !== 'w') {
  3997. fastFeeding &&= !e.isTrusted;
  3998. }
  3999. if (fastFeeding) inputs.forceW = inputs.w = true;
  4000.  
  4001. switch (e.code) {
  4002. case 'KeyQ':
  4003. if (!e.repeat) net.qdown(world.selected);
  4004. break;
  4005. case 'Space': {
  4006. if (!e.repeat) {
  4007. // send mouse position immediately, so the split will go in the correct direction.
  4008. // setTimeout is used to ensure that our mouse position is actually updated (it comes after
  4009. // keydown events)
  4010. setTimeout(() => input.split(view));
  4011. }
  4012. break;
  4013. }
  4014. case 'Enter': {
  4015. ui.chat.input.focus();
  4016. break;
  4017. }
  4018. }
  4019.  
  4020. // use e.isTrusted in case the key was bound to W
  4021. if (e.isTrusted && e.key.toLowerCase() === sigmod.settings.tripleKey?.toLowerCase()) {
  4022. // don't override any locks, and don't update 'until'
  4023. inputs.lock ||= {
  4024. type: 'point',
  4025. mouse: inputs.mouse,
  4026. world: input.toWorld(world.selected, inputs.mouse),
  4027. until: performance.now() + 650,
  4028. };
  4029. }
  4030.  
  4031. const vision = world.views.get(view);
  4032. if (!vision) return;
  4033. const camera = world.singleCamera(view, vision, 0, Infinity); // use latest data (.nx, .ny), uninterpolated
  4034.  
  4035. if (e.isTrusted && e.key.toLowerCase() === sigmod.settings.horizontalLineKey?.toLowerCase()) {
  4036. if (inputs.lock?.type === 'horizontal') {
  4037. inputs.lock = undefined;
  4038. ui.linesplit.update();
  4039. return;
  4040. }
  4041.  
  4042. inputs.lock = {
  4043. type: 'horizontal',
  4044. world: [camera.sumX / camera.weight, camera.sumY / camera.weight],
  4045. lastSplit: -Infinity,
  4046. };
  4047. ui.linesplit.update();
  4048. return;
  4049. }
  4050.  
  4051. if (e.isTrusted && e.key.toLowerCase() === sigmod.settings.verticalLineKey?.toLowerCase()) {
  4052. if (inputs.lock?.type === 'vertical') {
  4053. inputs.lock = undefined;
  4054. ui.linesplit.update();
  4055. return;
  4056. }
  4057.  
  4058. inputs.lock = {
  4059. type: 'vertical',
  4060. world: [camera.sumX / camera.weight, camera.sumY / camera.weight],
  4061. lastSplit: -Infinity,
  4062. };
  4063. ui.linesplit.update();
  4064. return;
  4065. }
  4066.  
  4067. if (e.isTrusted && e.key.toLowerCase() === sigmod.settings.fixedLineKey?.toLowerCase()) {
  4068. if (inputs.lock?.type === 'fixed') inputs.lock = undefined;
  4069. else inputs.lock = { type: 'fixed' };
  4070. ui.linesplit.update();
  4071. return;
  4072. }
  4073.  
  4074. if (e.isTrusted && e.key.toLowerCase() === sigmod.settings.respawnKey?.toLowerCase()) {
  4075. net.respawn(view, input.playData(input.name(view), false));
  4076. return;
  4077. }
  4078. });
  4079.  
  4080. addEventListener('keyup', e => {
  4081. // allow inputs if unfocused
  4082. if (e.code === 'KeyQ') net.qup(world.selected);
  4083. else if (e.code === 'KeyW') {
  4084. const inputs = input.views.get(world.selected) ?? create(world.selected);
  4085. inputs.w = false; // don't change forceW
  4086. }
  4087.  
  4088. if (handleKeybind(e)) return;
  4089. });
  4090.  
  4091. addEventListener('mousedown', e => {
  4092. if (unfocused()) return;
  4093. handleKeybind(e);
  4094. });
  4095. addEventListener('mouseup', e => {
  4096. if (unfocused()) return;
  4097. handleKeybind(e);
  4098. });
  4099.  
  4100. // prompt before closing window
  4101. addEventListener('beforeunload', e => e.preventDefault());
  4102.  
  4103. // prevent right clicking on the game
  4104. ui.game.canvas.addEventListener('contextmenu', e => e.preventDefault());
  4105.  
  4106. // prevent dragging when some things are selected - i have a habit of unconsciously clicking all the time,
  4107. // making me regularly drag text, disabling my mouse inputs for a bit
  4108. addEventListener('dragstart', e => e.preventDefault());
  4109.  
  4110.  
  4111.  
  4112. // #2 : play and spectate buttons, and captcha
  4113. /**
  4114. * @param {string} name
  4115. * @param {boolean} spectating
  4116. */
  4117. input.playData = (name, spectating) => {
  4118. /** @type {HTMLInputElement | null} */
  4119. const password = document.querySelector('input#password');
  4120.  
  4121. return {
  4122. state: spectating ? 2 : undefined,
  4123. name,
  4124. skin: aux.userData ? aux.settings.skin : '',
  4125. token: aux.userData?.token,
  4126. sub: (aux.userData?.subscription ?? 0) > Date.now(),
  4127. clan: aux.userData?.clan,
  4128. showClanmates: aux.settings.showClanmates,
  4129. password: password?.value,
  4130. email: aux.userData?.email,
  4131. };
  4132. };
  4133.  
  4134. /** @type {HTMLInputElement[]} */
  4135. input.nick = [aux.require(document.querySelector('input#nick'),
  4136. 'Can\'t find the nickname element. Try reloading the page?')];
  4137.  
  4138. const nickList = () => {
  4139. const target = settings.nbox ? settings.nboxCount : settings.multibox ? 2 : 1;
  4140. for (let i = input.nick.length; i < target; ++i) {
  4141. const el = /** @type {HTMLInputElement} */ (input.nick[0].cloneNode(true));
  4142. el.maxLength = 50;
  4143. el.placeholder = `Nickname #${i + 1}`;
  4144. el.value = settings.multiNames[i - 1] || '';
  4145.  
  4146. el.addEventListener('change', () => {
  4147. settings.multiNames[i - 1] = el.value;
  4148. settings.save();
  4149. });
  4150.  
  4151. const row = /** @type {Element} */ (input.nick[0].parentElement?.cloneNode());
  4152. row.appendChild(el);
  4153. input.nick[input.nick.length - 1].parentElement?.insertAdjacentElement('afterend', row);
  4154. input.nick.push(el);
  4155. }
  4156.  
  4157. for (let i = input.nick.length; i > target; --i) {
  4158. input.nick.pop()?.parentElement?.remove();
  4159. }
  4160. };
  4161. nickList();
  4162. setInterval(nickList, 500);
  4163.  
  4164. /** @type {HTMLButtonElement} */
  4165. const play = aux.require(document.querySelector('button#play-btn'),
  4166. 'Can\'t find the play button. Try reloading the page?');
  4167. /** @type {HTMLButtonElement} */
  4168. const spectate = aux.require(document.querySelector('button#spectate-btn'),
  4169. 'Can\'t find the spectate button. Try reloading the page?');
  4170.  
  4171. play.addEventListener('click', () => {
  4172. const con = net.connections.get(world.selected);
  4173. if (!con?.handshake) return;
  4174. ui.toggleEscOverlay(false);
  4175. net.play(world.selected, input.playData(input.name(world.selected), false));
  4176. });
  4177. spectate.addEventListener('click', () => {
  4178. const con = net.connections.get(world.selected);
  4179. if (!con?.handshake) return;
  4180. ui.toggleEscOverlay(false);
  4181. net.play(world.selected, input.playData(input.name(world.selected), true));
  4182. });
  4183.  
  4184. play.disabled = spectate.disabled = true;
  4185. setInterval(() => {
  4186. play.disabled = spectate.disabled = !net.connections.get(world.selected)?.handshake;
  4187. }, 100);
  4188.  
  4189. return input;
  4190. })();
  4191.  
  4192.  
  4193.  
  4194. //////////////////////////
  4195. // Configure WebGL Data //
  4196. //////////////////////////
  4197. const glconf = (() => {
  4198. // note: WebGL functions only really return null if the context is lost - in which case, data will be replaced
  4199. // anyway after it's restored. so, we cast everything to a non-null type.
  4200. const glconf = {};
  4201. const programs = glconf.programs = {};
  4202. const uniforms = glconf.uniforms = {};
  4203. /** @type {WebGLBuffer} */
  4204. glconf.pelletAlphaBuffer = /** @type {never} */ (undefined);
  4205. /** @type {WebGLBuffer} */
  4206. glconf.pelletBuffer = /** @type {never} */ (undefined);
  4207. glconf.vao = {};
  4208.  
  4209. const gl = ui.game.gl;
  4210. /** @type {Map<string, number>} */
  4211. const uboBindings = new Map();
  4212.  
  4213. /**
  4214. * @param {string} name
  4215. * @param {number} type
  4216. * @param {string} source
  4217. */
  4218. function shader(name, type, source) {
  4219. const s = /** @type {WebGLShader} */ (gl.createShader(type));
  4220. gl.shaderSource(s, source);
  4221. gl.compileShader(s);
  4222.  
  4223. // note: compilation errors should not happen in production
  4224. aux.require(
  4225. gl.getShaderParameter(s, gl.COMPILE_STATUS) || gl.isContextLost(),
  4226. `Can\'t compile WebGL2 shader "${name}". You might be on a weird browser.\n\nFull error log:\n` +
  4227. gl.getShaderInfoLog(s),
  4228. );
  4229.  
  4230. return s;
  4231. }
  4232.  
  4233. /**
  4234. * @param {string} name
  4235. * @param {string} vSource
  4236. * @param {string} fSource
  4237. * @param {string[]} ubos
  4238. * @param {string[]} textures
  4239. */
  4240. function program(name, vSource, fSource, ubos, textures) {
  4241. const vShader = shader(`${name}.vShader`, gl.VERTEX_SHADER, vSource.trim());
  4242. const fShader = shader(`${name}.fShader`, gl.FRAGMENT_SHADER, fSource.trim());
  4243. const p = /** @type {WebGLProgram} */ (gl.createProgram());
  4244.  
  4245. gl.attachShader(p, vShader);
  4246. gl.attachShader(p, fShader);
  4247. gl.linkProgram(p);
  4248.  
  4249. // note: linking errors should not happen in production
  4250. aux.require(
  4251. gl.getProgramParameter(p, gl.LINK_STATUS) || gl.isContextLost(),
  4252. `Can\'t link WebGL2 program "${name}". You might be on a weird browser.\n\nFull error log:\n` +
  4253. gl.getProgramInfoLog(p),
  4254. );
  4255.  
  4256. for (const tag of ubos) {
  4257. const index = gl.getUniformBlockIndex(p, tag); // returns 4294967295 if invalid... just don't make typos
  4258. let binding = uboBindings.get(tag);
  4259. if (binding === undefined)
  4260. uboBindings.set(tag, binding = uboBindings.size);
  4261. gl.uniformBlockBinding(p, index, binding);
  4262.  
  4263. const size = gl.getActiveUniformBlockParameter(p, index, gl.UNIFORM_BLOCK_DATA_SIZE);
  4264. const ubo = uniforms[tag] = gl.createBuffer();
  4265. gl.bindBuffer(gl.UNIFORM_BUFFER, ubo);
  4266. gl.bufferData(gl.UNIFORM_BUFFER, size, gl.DYNAMIC_DRAW);
  4267. gl.bindBufferBase(gl.UNIFORM_BUFFER, binding, ubo);
  4268. }
  4269.  
  4270. // bind texture uniforms to TEXTURE0, TEXTURE1, etc.
  4271. gl.useProgram(p);
  4272. for (let i = 0; i < textures.length; ++i) {
  4273. const loc = gl.getUniformLocation(p, textures[i]);
  4274. gl.uniform1i(loc, i);
  4275. }
  4276. gl.useProgram(null);
  4277.  
  4278. return p;
  4279. }
  4280.  
  4281. const parts = {
  4282. boilerplate: '#version 300 es\nprecision highp float; precision highp int;',
  4283. borderUbo: `layout(std140) uniform Border { // size = 0x28
  4284. vec4 u_border_color; // @ 0x00, i = 0
  4285. vec4 u_border_xyzw_lrtb; // @ 0x10, i = 4
  4286. int u_border_flags; // @ 0x20, i = 8
  4287. float u_background_width; // @ 0x24, i = 9
  4288. float u_background_height; // @ 0x28, i = 10
  4289. float u_border_time; // @ 0x2c, i = 11
  4290. };`,
  4291. cameraUbo: `layout(std140) uniform Camera { // size = 0x10
  4292. float u_camera_ratio; // @ 0x00
  4293. float u_camera_scale; // @ 0x04
  4294. vec2 u_camera_pos; // @ 0x08
  4295. };`,
  4296. cellUbo: `layout(std140) uniform Cell { // size = 0x28
  4297. float u_cell_radius; // @ 0x00, i = 0
  4298. float u_cell_radius_skin; // @ 0x04, i = 1
  4299. vec2 u_cell_pos; // @ 0x08, i = 2
  4300. vec4 u_cell_color; // @ 0x10, i = 4
  4301. float u_cell_alpha; // @ 0x20, i = 8
  4302. int u_cell_flags; // @ 0x24, i = 9
  4303. };`,
  4304. cellSettingsUbo: `layout(std140) uniform CellSettings { // size = 0x40
  4305. vec4 u_cell_active_outline; // @ 0x00
  4306. vec4 u_cell_inactive_outline; // @ 0x10
  4307. vec4 u_cell_unsplittable_outline; // @ 0x20
  4308. vec4 u_cell_subtle_outline_override; // @ 0x30
  4309. float u_cell_active_outline_thickness; // @ 0x40
  4310. };`,
  4311. circleUbo: `layout(std140) uniform Circle { // size = 0x08
  4312. float u_circle_alpha; // @ 0x00
  4313. float u_circle_scale; // @ 0x04
  4314. };`,
  4315. textUbo: `layout(std140) uniform Text { // size = 0x38
  4316. vec4 u_text_color1; // @ 0x00, i = 0
  4317. vec4 u_text_color2; // @ 0x10, i = 4
  4318. float u_text_alpha; // @ 0x20, i = 8
  4319. float u_text_aspect_ratio; // @ 0x24, i = 9
  4320. float u_text_scale; // @ 0x28, i = 10
  4321. int u_text_silhouette_enabled; // @ 0x2c, i = 11
  4322. vec2 u_text_offset; // @ 0x30, i = 12
  4323. };`,
  4324. tracerUbo: `layout(std140) uniform Tracer { // size = 0x10
  4325. vec4 u_tracer_color; // @ 0x00, i = 0
  4326. float u_tracer_thickness; // @ 0x10, i = 4
  4327. };`,
  4328. };
  4329.  
  4330.  
  4331.  
  4332. glconf.init = () => {
  4333. gl.enable(gl.BLEND);
  4334. gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  4335.  
  4336. // create programs and uniforms
  4337. programs.bg = program('bg', `
  4338. ${parts.boilerplate}
  4339. layout(location = 0) in vec2 a_vertex;
  4340. ${parts.borderUbo}
  4341. ${parts.cameraUbo}
  4342. flat out float f_blur;
  4343. flat out float f_thickness;
  4344. out vec2 v_uv;
  4345. out vec2 v_world_pos;
  4346.  
  4347. void main() {
  4348. f_blur = 1.0 * (540.0 * u_camera_scale);
  4349. f_thickness = max(3.0 / f_blur, 25.0); // force border to always be visible, otherwise it flickers
  4350.  
  4351. v_world_pos = a_vertex * vec2(u_camera_ratio, 1.0) / u_camera_scale;
  4352. v_world_pos += u_camera_pos * vec2(1.0, -1.0);
  4353.  
  4354. if ((u_border_flags & 0x04) != 0) { // background repeating
  4355. v_uv = v_world_pos * 0.02 * (50.0 / u_background_width);
  4356. v_uv /= vec2(1.0, u_background_height / u_background_width);
  4357. } else {
  4358. v_uv = (v_world_pos - vec2(u_border_xyzw_lrtb.x, u_border_xyzw_lrtb.z))
  4359. / vec2(u_border_xyzw_lrtb.y - u_border_xyzw_lrtb.x,
  4360. u_border_xyzw_lrtb.w - u_border_xyzw_lrtb.z);
  4361. v_uv = vec2(v_uv.x, 1.0 - v_uv.y); // flip vertically
  4362. }
  4363.  
  4364. gl_Position = vec4(a_vertex, 0, 1); // span the whole screen
  4365. }
  4366. `, `
  4367. ${parts.boilerplate}
  4368. flat in float f_blur;
  4369. flat in float f_thickness;
  4370. in vec2 v_uv;
  4371. in vec2 v_world_pos;
  4372. ${parts.borderUbo}
  4373. ${parts.cameraUbo}
  4374. uniform sampler2D u_texture;
  4375. out vec4 out_color;
  4376.  
  4377. void main() {
  4378. if ((u_border_flags & 0x01) != 0) { // background enabled
  4379. if ((u_border_flags & 0x04) != 0 // repeating
  4380. || (0.0 <= min(v_uv.x, v_uv.y) && max(v_uv.x, v_uv.y) <= 1.0)) { // within border
  4381. out_color = texture(u_texture, v_uv);
  4382. }
  4383. }
  4384.  
  4385. // make a larger inner rectangle and a normal inverted outer rectangle
  4386. float inner_alpha = min(
  4387. min((v_world_pos.x + f_thickness) - u_border_xyzw_lrtb.x,
  4388. u_border_xyzw_lrtb.y - (v_world_pos.x - f_thickness)),
  4389. min((v_world_pos.y + f_thickness) - u_border_xyzw_lrtb.z,
  4390. u_border_xyzw_lrtb.w - (v_world_pos.y - f_thickness))
  4391. );
  4392. float outer_alpha = max(
  4393. max(u_border_xyzw_lrtb.x - v_world_pos.x, v_world_pos.x - u_border_xyzw_lrtb.y),
  4394. max(u_border_xyzw_lrtb.z - v_world_pos.y, v_world_pos.y - u_border_xyzw_lrtb.w)
  4395. );
  4396. float alpha = clamp(f_blur * min(inner_alpha, outer_alpha), 0.0, 1.0);
  4397. if (u_border_color.a == 0.0) alpha = 0.0;
  4398.  
  4399. vec4 border_color;
  4400. if ((u_border_flags & 0x08) != 0) { // rainbow border
  4401. float angle = atan(v_world_pos.y, v_world_pos.x) + u_border_time;
  4402. float red = (2.0/3.0) * cos(6.0 * angle) + 1.0/3.0;
  4403. float green = (2.0/3.0) * cos(6.0 * angle - 2.0 * 3.1415926535 / 3.0) + 1.0/3.0;
  4404. float blue = (2.0/3.0) * cos(6.0 * angle - 4.0 * 3.1415926535 / 3.0) + 1.0/3.0;
  4405. border_color = vec4(red, green, blue, 1.0);
  4406. } else {
  4407. border_color = u_border_color;
  4408. }
  4409.  
  4410. out_color = out_color * (1.0 - alpha) + border_color * alpha;
  4411. }
  4412. `, ['Border', 'Camera'], ['u_texture']);
  4413.  
  4414.  
  4415.  
  4416. programs.cell = program('cell', `
  4417. ${parts.boilerplate}
  4418. layout(location = 0) in vec2 a_vertex;
  4419. ${parts.cameraUbo}
  4420. ${parts.cellUbo}
  4421. ${parts.cellSettingsUbo}
  4422. flat out vec4 f_active_outline;
  4423. flat out float f_active_radius;
  4424. flat out float f_blur;
  4425. flat out int f_color_under_skin;
  4426. flat out int f_show_skin;
  4427. flat out vec4 f_subtle_outline;
  4428. flat out float f_subtle_radius;
  4429. flat out vec4 f_unsplittable_outline;
  4430. flat out float f_unsplittable_radius;
  4431. out vec2 v_vertex;
  4432. out vec2 v_uv;
  4433.  
  4434. void main() {
  4435. f_blur = 0.5 * u_cell_radius * (540.0 * u_camera_scale);
  4436. f_color_under_skin = u_cell_flags & 0x20;
  4437. f_show_skin = u_cell_flags & 0x01;
  4438.  
  4439. // subtle outlines (at least 1px wide)
  4440. float subtle_thickness = max(max(u_cell_radius * 0.02, 2.0 / (540.0 * u_camera_scale)), 10.0);
  4441. f_subtle_radius = 1.0 - (subtle_thickness / u_cell_radius);
  4442. if ((u_cell_flags & 0x02) != 0) {
  4443. f_subtle_outline = u_cell_color * 0.9; // darker outline by default
  4444. f_subtle_outline.rgb += (u_cell_subtle_outline_override.rgb - f_subtle_outline.rgb)
  4445. * u_cell_subtle_outline_override.a;
  4446. } else {
  4447. f_subtle_outline = vec4(0, 0, 0, 0);
  4448. }
  4449.  
  4450. // unsplittable cell outline, 2x the subtle thickness
  4451. // (except at small sizes, it shouldn't look overly thick)
  4452. float unsplittable_thickness = max(max(u_cell_radius * 0.04, 4.0 / (540.0 * u_camera_scale)), 10.0);
  4453. f_unsplittable_radius = 1.0 - (unsplittable_thickness / u_cell_radius);
  4454. if ((u_cell_flags & 0x10) != 0) {
  4455. f_unsplittable_outline = u_cell_unsplittable_outline;
  4456. } else {
  4457. f_unsplittable_outline = vec4(0, 0, 0, 0);
  4458. }
  4459.  
  4460. // active multibox outlines (thick, a % of the visible cell radius)
  4461. // or at minimum, 3x the subtle thickness
  4462. float active_thickness = max(max(u_cell_radius * 0.06, 6.0 / (540.0 * u_camera_scale)), 10.0);
  4463. f_active_radius = 1.0 - max(active_thickness / u_cell_radius, u_cell_active_outline_thickness);
  4464. if ((u_cell_flags & 0x0c) != 0) {
  4465. f_active_outline = (u_cell_flags & 0x04) != 0 ? u_cell_active_outline : u_cell_inactive_outline;
  4466. } else {
  4467. f_active_outline = vec4(0, 0, 0, 0);
  4468. }
  4469.  
  4470. v_vertex = a_vertex;
  4471. v_uv = a_vertex * min(u_cell_radius / u_cell_radius_skin, 1.0) * 0.5 + 0.5;
  4472.  
  4473. vec2 clip_pos = -u_camera_pos + u_cell_pos + v_vertex * u_cell_radius;
  4474. clip_pos *= u_camera_scale * vec2(1.0 / u_camera_ratio, -1.0);
  4475. gl_Position = vec4(clip_pos, 0, 1);
  4476. }
  4477. `, `
  4478. ${parts.boilerplate}
  4479. flat in vec4 f_active_outline;
  4480. flat in float f_active_radius;
  4481. flat in float f_blur;
  4482. flat in int f_color_under_skin;
  4483. flat in int f_show_skin;
  4484. flat in vec4 f_subtle_outline;
  4485. flat in float f_subtle_radius;
  4486. flat in vec4 f_unsplittable_outline;
  4487. flat in float f_unsplittable_radius;
  4488. in vec2 v_vertex;
  4489. in vec2 v_uv;
  4490. ${parts.cameraUbo}
  4491. ${parts.cellUbo}
  4492. ${parts.cellSettingsUbo}
  4493. uniform sampler2D u_skin;
  4494. out vec4 out_color;
  4495.  
  4496. void main() {
  4497. float d = length(v_vertex.xy);
  4498. if (f_show_skin == 0 || f_color_under_skin != 0) {
  4499. out_color = u_cell_color;
  4500. }
  4501.  
  4502. // skin
  4503. if (f_show_skin != 0) {
  4504. vec4 tex = texture(u_skin, v_uv);
  4505. out_color = out_color * (1.0 - tex.a) + tex;
  4506. }
  4507.  
  4508. // subtle outline
  4509. float a = clamp(f_blur * (d - f_subtle_radius), 0.0, 1.0) * f_subtle_outline.a;
  4510. out_color.rgb += (f_subtle_outline.rgb - out_color.rgb) * a;
  4511.  
  4512. // active multibox outline
  4513. a = clamp(f_blur * (d - f_active_radius), 0.0, 1.0) * f_active_outline.a;
  4514. out_color.rgb += (f_active_outline.rgb - out_color.rgb) * a;
  4515.  
  4516. // unsplittable cell outline
  4517. a = clamp(f_blur * (d - f_unsplittable_radius), 0.0, 1.0) * f_unsplittable_outline.a;
  4518. out_color.rgb += (f_unsplittable_outline.rgb - out_color.rgb) * a;
  4519.  
  4520. // final circle mask
  4521. a = clamp(-f_blur * (d - 1.0), 0.0, 1.0);
  4522. out_color.a *= a * u_cell_alpha;
  4523. }
  4524. `, ['Camera', 'Cell', 'CellSettings'], ['u_skin']);
  4525.  
  4526.  
  4527.  
  4528. // also used to draw glow
  4529. programs.circle = program('circle', `
  4530. ${parts.boilerplate}
  4531. layout(location = 0) in vec2 a_vertex;
  4532. layout(location = 1) in vec2 a_cell_pos;
  4533. layout(location = 2) in float a_cell_radius;
  4534. layout(location = 3) in vec4 a_cell_color;
  4535. layout(location = 4) in float a_cell_alpha;
  4536. ${parts.cameraUbo}
  4537. ${parts.circleUbo}
  4538. out vec2 v_vertex;
  4539. flat out float f_blur;
  4540. flat out vec4 f_cell_color;
  4541.  
  4542. void main() {
  4543. float radius = a_cell_radius;
  4544. f_cell_color = a_cell_color * vec4(1, 1, 1, a_cell_alpha * u_circle_alpha);
  4545. if (u_circle_scale > 0.0) {
  4546. f_blur = 1.0;
  4547. radius *= u_circle_scale;
  4548. } else {
  4549. f_blur = 0.5 * a_cell_radius * (540.0 * u_camera_scale);
  4550. }
  4551. v_vertex = a_vertex;
  4552.  
  4553. vec2 clip_pos = -u_camera_pos + a_cell_pos + v_vertex * radius;
  4554. clip_pos *= u_camera_scale * vec2(1.0 / u_camera_ratio, -1.0);
  4555. gl_Position = vec4(clip_pos, 0, 1);
  4556. }
  4557. `, `
  4558. ${parts.boilerplate}
  4559. in vec2 v_vertex;
  4560. flat in float f_blur;
  4561. flat in vec4 f_cell_color;
  4562. out vec4 out_color;
  4563.  
  4564. void main() {
  4565. // use squared distance for more natural glow; shouldn't matter for pellets
  4566. float d = length(v_vertex.xy);
  4567. out_color = f_cell_color;
  4568. out_color.a *= clamp(f_blur * (1.0 - d), 0.0, 1.0);
  4569. }
  4570. `, ['Camera', 'Circle'], []);
  4571.  
  4572.  
  4573.  
  4574. programs.text = program('text', `
  4575. ${parts.boilerplate}
  4576. layout(location = 0) in vec2 a_vertex;
  4577. ${parts.cameraUbo}
  4578. ${parts.cellUbo}
  4579. ${parts.textUbo}
  4580. out vec4 v_color;
  4581. out vec2 v_uv;
  4582. out vec2 v_vertex;
  4583.  
  4584. void main() {
  4585. v_uv = a_vertex * 0.5 + 0.5;
  4586. float c2_alpha = (v_uv.x + v_uv.y) / 2.0;
  4587. v_color = u_text_color1 * (1.0 - c2_alpha) + u_text_color2 * c2_alpha;
  4588. v_vertex = a_vertex;
  4589.  
  4590. vec2 clip_space = v_vertex * u_text_scale + u_text_offset;
  4591. clip_space *= u_cell_radius_skin * 0.45 * vec2(u_text_aspect_ratio, 1.0);
  4592. clip_space += -u_camera_pos + u_cell_pos;
  4593. clip_space *= u_camera_scale * vec2(1.0 / u_camera_ratio, -1.0);
  4594. gl_Position = vec4(clip_space, 0, 1);
  4595. }
  4596. `, `
  4597. ${parts.boilerplate}
  4598. in vec4 v_color;
  4599. in vec2 v_uv;
  4600. in vec2 v_vertex;
  4601. ${parts.cameraUbo}
  4602. ${parts.cellUbo}
  4603. ${parts.textUbo}
  4604. uniform sampler2D u_texture;
  4605. uniform sampler2D u_silhouette;
  4606. out vec4 out_color;
  4607.  
  4608. float f(float x) {
  4609. // a cubic function with turning points at (0,0) and (1,0)
  4610. // meant to sharpen out blurry linear interpolation
  4611. return x * x * (3.0 - 2.0*x);
  4612. }
  4613.  
  4614. vec4 fv(vec4 v) {
  4615. return vec4(f(v.x), f(v.y), f(v.z), f(v.w));
  4616. }
  4617.  
  4618. void main() {
  4619. vec4 normal = texture(u_texture, v_uv);
  4620.  
  4621. if (u_text_silhouette_enabled != 0) {
  4622. vec4 silhouette = texture(u_silhouette, v_uv);
  4623.  
  4624. // #fff - #000 => color (text)
  4625. // #fff - #fff => #fff (respect emoji)
  4626. // #888 - #888 => #888 (respect emoji)
  4627. // #fff - #888 => #888 + color/2 (blur/antialias)
  4628. out_color = silhouette + fv(normal - silhouette) * v_color;
  4629. } else {
  4630. out_color = fv(normal) * v_color;
  4631. }
  4632.  
  4633. out_color.a *= u_text_alpha;
  4634. }
  4635. `, ['Camera', 'Cell', 'Text'], ['u_texture', 'u_silhouette']);
  4636.  
  4637. programs.tracer = program('tracer', `
  4638. ${parts.boilerplate}
  4639. layout(location = 0) in vec2 a_vertex;
  4640. layout(location = 1) in vec2 a_pos1;
  4641. layout(location = 2) in vec2 a_pos2;
  4642. ${parts.cameraUbo}
  4643. ${parts.tracerUbo}
  4644. out vec2 v_vertex;
  4645.  
  4646. void main() {
  4647. v_vertex = a_vertex;
  4648. float alpha = (a_vertex.x + 1.0) / 2.0;
  4649. float d = length(a_pos2 - a_pos1);
  4650. float thickness = 0.001 / u_camera_scale * u_tracer_thickness;
  4651. // black magic
  4652. vec2 world_pos = a_pos1 + (a_pos2 - a_pos1)
  4653. * mat2(alpha, a_vertex.y / d * thickness, a_vertex.y / d * -thickness, alpha);
  4654.  
  4655. vec2 clip_pos = -u_camera_pos + world_pos;
  4656. clip_pos *= u_camera_scale * vec2(1.0 / u_camera_ratio, -1.0);
  4657. gl_Position = vec4(clip_pos, 0, 1);
  4658. }
  4659. `, `
  4660. ${parts.boilerplate}
  4661. in vec2 v_pos;
  4662. ${parts.tracerUbo}
  4663. out vec4 out_color;
  4664.  
  4665. void main() {
  4666. out_color = u_tracer_color;
  4667. }
  4668. `, ['Camera', 'Tracer'], []);
  4669.  
  4670. // initialize two VAOs; one for pellets and all other objects (0), one for cell glow only (1)
  4671. glconf.vao = {};
  4672. const squareVAA = () => {
  4673. // square (location = 0), used for all instances
  4674. gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
  4675. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ -1, -1, 1, -1, -1, 1, 1, 1 ]), gl.STATIC_DRAW);
  4676. gl.enableVertexAttribArray(0);
  4677. gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
  4678. };
  4679. const circleVAA = () => {
  4680. // circle buffer (each instance is 6 floats or 24 bytes)
  4681. const circleBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer());
  4682. gl.bindBuffer(gl.ARRAY_BUFFER, circleBuffer);
  4683. // a_cell_pos, vec2 (location = 1)
  4684. gl.enableVertexAttribArray(1);
  4685. gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 4 * 7, 0);
  4686. gl.vertexAttribDivisor(1, 1);
  4687. // a_cell_radius, float (location = 2)
  4688. gl.enableVertexAttribArray(2);
  4689. gl.vertexAttribPointer(2, 1, gl.FLOAT, false, 4 * 7, 4 * 2);
  4690. gl.vertexAttribDivisor(2, 1);
  4691. // a_cell_color, vec3 (location = 3)
  4692. gl.enableVertexAttribArray(3);
  4693. gl.vertexAttribPointer(3, 4, gl.FLOAT, false, 4 * 7, 4 * 3);
  4694. gl.vertexAttribDivisor(3, 1);
  4695.  
  4696. return circleBuffer;
  4697. };
  4698. const alphaVAA = () => {
  4699. // circle alpha buffer, updated every frame
  4700. const alphaBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer());
  4701. gl.bindBuffer(gl.ARRAY_BUFFER, alphaBuffer);
  4702. // a_cell_alpha, float (location = 4)
  4703. gl.enableVertexAttribArray(4);
  4704. gl.vertexAttribPointer(4, 1, gl.FLOAT, false, 0, 0);
  4705. gl.vertexAttribDivisor(4, 1);
  4706.  
  4707. return alphaBuffer;
  4708. };
  4709. const lineVAA = () => {
  4710. // circle alpha buffer, updated every frame
  4711. const lineBuffer = /** @type {WebGLBuffer} */ (gl.createBuffer());
  4712. gl.bindBuffer(gl.ARRAY_BUFFER, lineBuffer);
  4713. // a_pos1, vec2 (location = 1)
  4714. gl.enableVertexAttribArray(1);
  4715. gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 4 * 4, 0);
  4716. gl.vertexAttribDivisor(1, 1);
  4717. // a_pos2, vec2 (location = 2)
  4718. gl.enableVertexAttribArray(2);
  4719. gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 4 * 4, 4 * 2);
  4720. gl.vertexAttribDivisor(2, 1);
  4721.  
  4722. return lineBuffer;
  4723. };
  4724.  
  4725. // main vao
  4726. {
  4727. const vao = /** @type {WebGLVertexArrayObject} */ (gl.createVertexArray());
  4728. gl.bindVertexArray(vao);
  4729. squareVAA();
  4730. glconf.vao.main = { vao };
  4731. }
  4732. // cell glow vao
  4733. {
  4734. const vao = /** @type {WebGLVertexArrayObject} */ (gl.createVertexArray());
  4735. gl.bindVertexArray(vao);
  4736. squareVAA();
  4737. glconf.vao.cell = { vao, circle: circleVAA(), alpha: alphaVAA() };
  4738. }
  4739. // pellet + pellet glow vao
  4740. {
  4741. const vao = /** @type {WebGLVertexArrayObject} */ (gl.createVertexArray());
  4742. gl.bindVertexArray(vao);
  4743. squareVAA();
  4744. glconf.vao.pellet = { vao, circle: circleVAA(), alpha: alphaVAA() };
  4745. }
  4746. // tracer vao
  4747. {
  4748. const vao = /** @type {WebGLVertexArrayObject} */ (gl.createVertexArray());
  4749. gl.bindVertexArray(vao);
  4750. squareVAA();
  4751. glconf.vao.tracer = { vao, line: lineVAA() };
  4752. }
  4753. };
  4754.  
  4755. glconf.init();
  4756. return glconf;
  4757. })();
  4758.  
  4759.  
  4760.  
  4761. ///////////////////////////////
  4762. // Define Rendering Routines //
  4763. ///////////////////////////////
  4764. const render = (() => {
  4765. const render = {};
  4766. const { gl } = ui.game;
  4767.  
  4768. // #1 : define small misc objects
  4769. // no point in breaking this across multiple lines
  4770. // eslint-disable-next-line max-len
  4771. const darkGridSrc = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAGBJREFUaIHtz4EJwCAAwDA39oT/H+qeEAzSXNA+a61xgfmeLtilEU0jmkY0jWga0TSiaUTTiKYRTSOaRjSNaBrRNKJpRNOIphFNI5pGNI1oGtE0omlEc83IN8aYpyN2+AH6nwOVa0odrQAAAABJRU5ErkJggg==';
  4772. // eslint-disable-next-line max-len
  4773. const lightGridSrc = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAGFJREFUaIHtzwENgDAQwMA9LvAvdJgg2UF6CtrZe6+vm5n7Oh3xlkY0jWga0TSiaUTTiKYRTSOaRjSNaBrRNKJpRNOIphFNI5pGNI1oGtE0omlE04imEc1vRmatdZ+OeMMDa8cDlf3ZAHkAAAAASUVORK5CYII=';
  4774.  
  4775. let lastMinimapDraw = performance.now();
  4776. /** @type {{ bg: ImageData, darkTheme: boolean } | undefined} */
  4777. let minimapCache;
  4778. document.fonts.addEventListener('loadingdone', () => void (minimapCache = undefined));
  4779.  
  4780.  
  4781. // #2 : define caching functions
  4782. const { resetDatabaseCache, resetTextureCache, textureFromCache, textureFromDatabase } = (() => {
  4783. /** @type {Map<string, {
  4784. * color: [number, number, number, number], texture: WebGLTexture, width: number, height: number
  4785. * } | null>} */
  4786. const cache = new Map();
  4787. render.textureCache = cache;
  4788.  
  4789. /** @type {Map<string, {
  4790. * color: [number, number, number, number], texture: WebGLTexture, width: number, height: number
  4791. * } | null>} */
  4792. const dbCache = new Map();
  4793. render.dbCache = dbCache;
  4794.  
  4795. return {
  4796. resetTextureCache: () => cache.clear(),
  4797. /**
  4798. * @param {string} src
  4799. * @returns {{
  4800. * color: [number, number, number, number], texture: WebGLTexture, width: number, height: number
  4801. * } | undefined}
  4802. */
  4803. textureFromCache: src => {
  4804. const cached = cache.get(src);
  4805. if (cached !== undefined)
  4806. return cached ?? undefined;
  4807.  
  4808. cache.set(src, null);
  4809.  
  4810. const image = new Image();
  4811. image.crossOrigin = '';
  4812. image.addEventListener('load', () => {
  4813. const texture = /** @type {WebGLTexture} */ (gl.createTexture());
  4814. if (!texture) return;
  4815.  
  4816. gl.bindTexture(gl.TEXTURE_2D, texture);
  4817. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4818. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
  4819. gl.generateMipmap(gl.TEXTURE_2D);
  4820.  
  4821. const color = aux.dominantColor(image);
  4822. cache.set(src, { color, texture, width: image.width, height: image.height });
  4823. });
  4824. image.src = src;
  4825.  
  4826. return undefined;
  4827. },
  4828. resetDatabaseCache: () => dbCache.clear(),
  4829. /**
  4830. * @param {string} key
  4831. * @returns {{
  4832. * color: [number, number, number, number], texture: WebGLTexture, width: number, height: number
  4833. * } | undefined}
  4834. */
  4835. textureFromDatabase: key => {
  4836. const cached = dbCache.get(key);
  4837. if (cached !== undefined)
  4838. return cached ?? undefined;
  4839.  
  4840. /** @type {IDBDatabase | undefined} */
  4841. const database = settings.database;
  4842. if (!database) return undefined;
  4843.  
  4844. dbCache.set(key, null);
  4845. const req = database.transaction('images').objectStore('images').get(key);
  4846. req.addEventListener('success', () => {
  4847. if (!req.result) return;
  4848.  
  4849. const reader = new FileReader();
  4850. reader.addEventListener('load', () => {
  4851. const image = new Image();
  4852. // this can cause a lot of lag (~500ms) when loading a large image for the first time
  4853. image.addEventListener('load', () => {
  4854. const texture = gl.createTexture();
  4855. if (!texture) return;
  4856.  
  4857. gl.bindTexture(gl.TEXTURE_2D, texture);
  4858. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4859. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
  4860. gl.generateMipmap(gl.TEXTURE_2D);
  4861.  
  4862. const color = aux.dominantColor(image);
  4863. dbCache.set(key, { color, texture, width: image.width, height: image.height });
  4864. });
  4865. image.src = /** @type {string} */ (reader.result);
  4866. });
  4867. reader.readAsDataURL(req.result);
  4868. });
  4869. req.addEventListener('error', err => {
  4870. console.warn(`sigfix database failed to get ${key}:`, err);
  4871. });
  4872. },
  4873. };
  4874. })();
  4875. render.resetDatabaseCache = resetDatabaseCache;
  4876. render.resetTextureCache = resetTextureCache;
  4877.  
  4878. const { maxMassWidth, refreshTextCache, massTextFromCache, resetTextCache, textFromCache } = (() => {
  4879. /**
  4880. * @template {boolean} T
  4881. * @typedef {{
  4882. * aspectRatio: number,
  4883. * text: WebGLTexture | null,
  4884. * silhouette: WebGLTexture | null | undefined,
  4885. * accessed: number
  4886. * }} CacheEntry
  4887. */
  4888. /** @type {Map<string, CacheEntry<boolean>>} */
  4889. const cache = new Map();
  4890. render.textCache = cache;
  4891.  
  4892. setInterval(() => {
  4893. // remove text after not being used for 1 minute
  4894. const now = performance.now();
  4895. cache.forEach((entry, text) => {
  4896. if (now - entry.accessed > 60_000) {
  4897. // immediately delete text instead of waiting for GC
  4898. if (entry.text !== undefined)
  4899. gl.deleteTexture(entry.text);
  4900. if (entry.silhouette !== undefined)
  4901. gl.deleteTexture(entry.silhouette);
  4902. cache.delete(text);
  4903. }
  4904. });
  4905. }, 60_000);
  4906.  
  4907. const canvas = document.createElement('canvas');
  4908. const ctx = aux.require(
  4909. canvas.getContext('2d', { willReadFrequently: true }),
  4910. 'Unable to get 2D context for text drawing. This is probably your browser being weird, maybe reload ' +
  4911. 'the page?',
  4912. );
  4913.  
  4914. // sigmod forces a *really* ugly shadow on ctx.fillText so we have to lock the property beforehand
  4915. const realProps = Object.getOwnPropertyDescriptors(Object.getPrototypeOf(ctx));
  4916. const realShadowBlurSet
  4917. = aux.require(realProps.shadowBlur.set, 'did CanvasRenderingContext2D spec change?').bind(ctx);
  4918. const realShadowColorSet
  4919. = aux.require(realProps.shadowColor.set, 'did CanvasRenderingContext2D spec change?').bind(ctx);
  4920. Object.defineProperties(ctx, {
  4921. shadowBlur: {
  4922. get: () => 0,
  4923. set: x => {
  4924. if (x === 0) realShadowBlurSet(0);
  4925. else realShadowBlurSet(8);
  4926. },
  4927. },
  4928. shadowColor: {
  4929. get: () => 'transparent',
  4930. set: x => {
  4931. if (x === 'transparent') realShadowColorSet('transparent');
  4932. else realShadowColorSet('#0003');
  4933. },
  4934. },
  4935. });
  4936.  
  4937. /**
  4938. * @param {string} text
  4939. * @param {boolean} silhouette
  4940. * @param {boolean} mass
  4941. * @returns {WebGLTexture | null}
  4942. */
  4943. const texture = (text, silhouette, mass) => {
  4944. const texture = gl.createTexture();
  4945. if (!texture) return texture;
  4946.  
  4947. const baseTextSize = 96;
  4948. const textSize = baseTextSize * (mass ? 0.5 * settings.massScaleFactor : settings.nameScaleFactor);
  4949. const lineWidth = Math.ceil(textSize / 10) * settings.textOutlinesFactor;
  4950.  
  4951. let font = '';
  4952. if (mass ? settings.massBold : settings.nameBold)
  4953. font = 'bold';
  4954. font += ` ${textSize}px "${sigmod.settings.font || 'Ubuntu'}", Ubuntu`;
  4955.  
  4956. ctx.font = font;
  4957. // if rendering an empty string (somehow) then width can be 0 with no outlines
  4958. canvas.width = (ctx.measureText(text).width + lineWidth * 4) || 1;
  4959. canvas.height = textSize * 3;
  4960. ctx.clearRect(0, 0, canvas.width, canvas.height);
  4961.  
  4962. // setting canvas.width resets the canvas state
  4963. ctx.font = font;
  4964. ctx.lineJoin = 'round';
  4965. ctx.lineWidth = lineWidth;
  4966. ctx.fillStyle = silhouette ? '#000' : '#fff';
  4967. ctx.strokeStyle = '#000';
  4968. ctx.textBaseline = 'middle';
  4969.  
  4970. ctx.shadowBlur = lineWidth;
  4971. ctx.shadowColor = lineWidth > 0 ? '#0002' : 'transparent';
  4972.  
  4973. // add a space, which is to prevent sigmod from detecting the name
  4974. if (lineWidth > 0) ctx.strokeText(text + ' ', lineWidth * 2, textSize * 1.5);
  4975. ctx.shadowColor = 'transparent';
  4976. ctx.fillText(text + ' ', lineWidth * 2, textSize * 1.5);
  4977.  
  4978. const data = ctx.getImageData(0, 0, canvas.width, canvas.height);
  4979.  
  4980. gl.bindTexture(gl.TEXTURE_2D, texture);
  4981. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, data);
  4982. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
  4983. gl.generateMipmap(gl.TEXTURE_2D);
  4984. return texture;
  4985. };
  4986.  
  4987. let maxMassWidth = 0;
  4988. /** @type {({ height: number, width: number, texture: WebGLTexture | null } | undefined)[]} */
  4989. const massTextCache = [];
  4990.  
  4991. /**
  4992. * @param {string} digit
  4993. * @returns {{ height: number, width: number, texture: WebGLTexture | null }}
  4994. */
  4995. const massTextFromCache = digit => {
  4996. let cached = massTextCache[/** @type {any} */ (digit)];
  4997. if (!cached) {
  4998. cached = massTextCache[digit] = {
  4999. texture: texture(digit, false, true),
  5000. height: canvas.height, // mind the execution order
  5001. width: canvas.width,
  5002. };
  5003. if (cached.width > maxMassWidth) maxMassWidth = cached.width;
  5004. }
  5005.  
  5006. return cached;
  5007. };
  5008.  
  5009. const resetTextCache = () => {
  5010. cache.clear();
  5011. maxMassWidth = 0;
  5012. while (massTextCache.length > 0) massTextCache.pop();
  5013. };
  5014.  
  5015. /** @type {{
  5016. * massBold: boolean, massScaleFactor: number, nameBold: boolean, nameScaleFactor: number,
  5017. * outlinesFactor: number, font: string | undefined,
  5018. * } | undefined} */
  5019. let drawn;
  5020.  
  5021. const refreshTextCache = () => {
  5022. if (!drawn ||
  5023. (drawn.massBold !== settings.massBold || drawn.massScaleFactor !== settings.massScaleFactor
  5024. || drawn.nameBold !== settings.nameBold || drawn.nameScaleFactor !== settings.nameScaleFactor
  5025. || drawn.outlinesFactor !== settings.textOutlinesFactor || drawn.font !== sigmod.settings.font)
  5026. ) {
  5027. resetTextCache();
  5028. drawn = {
  5029. massBold: settings.massBold, massScaleFactor: settings.massScaleFactor,
  5030. nameBold: settings.nameBold, nameScaleFactor: settings.nameScaleFactor,
  5031. outlinesFactor: settings.textOutlinesFactor, font: sigmod.settings.font,
  5032. };
  5033. }
  5034. };
  5035.  
  5036. /**
  5037. * @template {boolean} T
  5038. * @param {string} text
  5039. * @param {T} silhouette
  5040. * @returns {CacheEntry<T>}
  5041. */
  5042. const textFromCache = (text, silhouette) => {
  5043. let entry = cache.get(text);
  5044. if (!entry) {
  5045. const shortened = aux.trim(text);
  5046. /** @type {CacheEntry<T>} */
  5047. entry = {
  5048. text: texture(shortened, false, false),
  5049. aspectRatio: canvas.width / canvas.height, // mind the execution order
  5050. silhouette: silhouette ? texture(shortened, true, false) : undefined,
  5051. accessed: performance.now(),
  5052. };
  5053. cache.set(text, entry);
  5054. } else {
  5055. entry.accessed = performance.now();
  5056. }
  5057.  
  5058. if (silhouette && entry.silhouette === undefined) {
  5059. setTimeout(() => {
  5060. entry.silhouette = texture(aux.trim(text), true, false);
  5061. });
  5062. }
  5063.  
  5064. return entry;
  5065. };
  5066.  
  5067. // reload text once Ubuntu has loaded, prevents some serif fonts from being locked in
  5068. // also support loading in new fonts at any time via sigmod
  5069. document.fonts.addEventListener('loadingdone', () => resetTextCache());
  5070.  
  5071. return {
  5072. maxMassWidth: () => maxMassWidth,
  5073. massTextFromCache,
  5074. refreshTextCache,
  5075. resetTextCache,
  5076. textFromCache,
  5077. };
  5078. })();
  5079. render.resetTextCache = resetTextCache;
  5080. render.textFromCache = textFromCache;
  5081.  
  5082. // #3 : define other render functions
  5083. /**
  5084. * @param {CellFrame} frame
  5085. * @param {number} now
  5086. */
  5087. render.alpha = (frame, now) => {
  5088. // TODO: lots of opportunity here to make the game look nice (like delta)
  5089. // note that 0 drawDelay is supported here
  5090. let alpha = (now - frame.born) / settings.drawDelay;
  5091. if (frame.deadAt !== undefined) {
  5092. alpha = Math.min(alpha, 1 - (now - frame.deadAt) / settings.drawDelay);
  5093. }
  5094.  
  5095. return Math.min(Math.max(alpha, 0), 1);
  5096. };
  5097.  
  5098. /**
  5099. * @param {Cell} cell
  5100. */
  5101. render.skin = cell => {
  5102. /** @type {CellDescription} */
  5103. const desc = world.synchronized ? cell.views.values().next().value : cell.views.get(world.selected);
  5104. if (!desc) return undefined;
  5105.  
  5106. let ownerView;
  5107. for (const [view, vision] of world.views) {
  5108. if (vision.owned.includes(cell.id)) {
  5109. ownerView = view;
  5110. break;
  5111. }
  5112. }
  5113.  
  5114. // 🖼️
  5115. let texture;
  5116. if (ownerView) {
  5117. const index = world.multis.indexOf(ownerView);
  5118. if (index >= 2) {
  5119. if (settings.selfSkinNbox[index]) {
  5120. if (settings.selfSkinNbox[index].startsWith('🖼️')) texture = textureFromDatabase(`selfSkinNbox.${index}`);
  5121. else texture = textureFromCache(settings.selfSkinNbox[index]);
  5122. }
  5123. } else {
  5124. const prop = ownerView === world.viewId.secondary ? 'selfSkinMulti' : 'selfSkin';
  5125. if (settings[prop]) {
  5126. if (settings[prop].startsWith('🖼️')) texture = textureFromDatabase(prop);
  5127. else texture = textureFromCache(settings[prop]);
  5128. }
  5129. }
  5130. }
  5131.  
  5132. // allow turning off sigmally skins while still using custom skins
  5133. if (!texture && aux.settings.showSkins && desc.skin) {
  5134. texture = textureFromCache(desc.skin);
  5135. }
  5136.  
  5137. return texture;
  5138. };
  5139.  
  5140. const circleBuffers = {
  5141. cell: new Float32Array(0),
  5142. cellAlpha: new Float32Array(0),
  5143. /** @type {object | undefined} */
  5144. lastCellVao: undefined,
  5145. pellet: new Float32Array(0),
  5146. pelletAlpha: new Float32Array(0),
  5147. pelletsUploaded: 0,
  5148. /** @type {object | undefined} */
  5149. lastPelletVao: undefined,
  5150. };
  5151. /** @param {boolean} pellets */
  5152. render.upload = pellets => {
  5153. const now = performance.now();
  5154. if (now - render.lastFrame > 1000) {
  5155. // do not render pellets on inactive windows (very laggy!)
  5156. circleBuffers.pelletsUploaded = 0;
  5157. return;
  5158. }
  5159.  
  5160. let uploading = 0;
  5161. for (const cell of world[pellets ? 'pellets' : 'cells'].values()) {
  5162. const frame = world.synchronized ? cell.merged : cell.views.get(world.selected)?.frames[0];
  5163. if (!frame) continue;
  5164. if (pellets) {
  5165. if (frame.deadTo === -1) ++uploading;
  5166. } else {
  5167. /** @type {CellDescription} */
  5168. const desc = world.synchronized ? cell.views.values().next().value : cell.views.get(world.selected);
  5169. if (!desc) continue; // shouldn't happen
  5170. if (!desc.jagged) ++uploading; // don't make viruses glow
  5171. }
  5172. }
  5173.  
  5174. let alpha = circleBuffers[pellets ? 'pelletAlpha' : 'cellAlpha'];
  5175. let instances = circleBuffers[pellets ? 'pellet' : 'cell'];
  5176. const vao = glconf.vao[pellets ? 'pellet' : 'cell'];
  5177.  
  5178. // resize buffers as necessary
  5179. let capacity = alpha.length || 1;
  5180. let resizing = circleBuffers[pellets ? 'lastPelletVao' : 'lastCellVao'] !== vao;
  5181. while (capacity < uploading) {
  5182. capacity *= 2;
  5183. resizing = true;
  5184. }
  5185. if (resizing) {
  5186. alpha = circleBuffers[pellets ? 'pelletAlpha' : 'cellAlpha'] = new Float32Array(capacity);
  5187. instances = circleBuffers[pellets ? 'pellet' : 'cell'] = new Float32Array(capacity * 7);
  5188. }
  5189.  
  5190. const override = pellets ? sigmod.settings.foodColor : sigmod.settings.cellColor;
  5191. let i = 0;
  5192. for (const cell of world[pellets ? 'pellets' : 'cells'].values()) {
  5193. const frame = world.synchronized ? cell.merged : cell.views.get(world.selected)?.frames[0];
  5194. if (!frame || (pellets && frame.deadTo !== -1)) continue;
  5195.  
  5196. let x, y, r;
  5197. if (pellets) {
  5198. ({ nx: x, ny: y, nr: r } = frame);
  5199. } else {
  5200. const interp = world.synchronized ? cell.merged : cell.views.get(world.selected);
  5201. if (!interp) continue; // should never happen (ts-check)
  5202.  
  5203. /** @type {CellFrame | undefined} */
  5204. let killerFrame;
  5205. /** @type {CellInterpolation | undefined} */
  5206. let killerInterp;
  5207. let killer = frame.deadTo !== -1 && world.cells.get(frame.deadTo);
  5208. if (killer) {
  5209. killerFrame = world.synchronized ? killer.merged : killer.views.get(world.selected)?.frames[0];
  5210. killerInterp = world.synchronized ? killer.merged : killer.views.get(world.selected);
  5211. }
  5212.  
  5213. ({ x, y, r } = world.xyr(frame, interp, killerFrame, killerInterp, false, now));
  5214. }
  5215. instances[i * 7] = x;
  5216. instances[i * 7 + 1] = y;
  5217. instances[i * 7 + 2] = r;
  5218.  
  5219. /** @type {CellDescription} */
  5220. const desc = world.synchronized ? cell.views.values().next().value : cell.views.get(world.selected);
  5221. if (!desc || desc.jagged) continue;
  5222.  
  5223. /** @type {[number, number, number] | [number, number, number, number]} */
  5224. let color = desc.rgb;
  5225. if (pellets) {
  5226. if (override?.[0] === 0 && override?.[1] === 0 && override?.[2] === 0) {
  5227. color = [color[0], color[1], color[2], override[3]];
  5228. } else if (override) {
  5229. color = override;
  5230. }
  5231. } else {
  5232. if (override) color = override;
  5233. const skin = render.skin(cell);
  5234. if (skin) {
  5235. // blend with player color
  5236. if (settings.colorUnderSkin) {
  5237. color = [
  5238. color[0] + (skin.color[0] - color[0]) * skin.color[3],
  5239. color[1] + (skin.color[1] - color[1]) * skin.color[3],
  5240. color[2] + (skin.color[2] - color[2]) * skin.color[3],
  5241. 1
  5242. ];
  5243. } else {
  5244. color = [skin.color[0], skin.color[1], skin.color[2], 1];
  5245. }
  5246. }
  5247. }
  5248. instances[i * 7 + 3] = color[0];
  5249. instances[i * 7 + 4] = color[1];
  5250. instances[i * 7 + 5] = color[2];
  5251. instances[i * 7 + 6] = color[3] ?? 1;
  5252.  
  5253. ++i;
  5254. }
  5255.  
  5256. // now, upload data
  5257. if (resizing) {
  5258. gl.bindBuffer(gl.ARRAY_BUFFER, vao.alpha);
  5259. gl.bufferData(gl.ARRAY_BUFFER, alpha.byteLength, gl.STATIC_DRAW);
  5260. gl.bindBuffer(gl.ARRAY_BUFFER, vao.circle);
  5261. gl.bufferData(gl.ARRAY_BUFFER, instances, gl.STATIC_DRAW);
  5262. } else {
  5263. gl.bindBuffer(gl.ARRAY_BUFFER, vao.circle);
  5264. gl.bufferSubData(gl.ARRAY_BUFFER, 0, instances);
  5265. }
  5266. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  5267.  
  5268. if (pellets) circleBuffers.pelletsUploaded = uploading;
  5269. circleBuffers[pellets ? 'lastPelletVao' : 'lastCellVao'] = vao;
  5270. };
  5271.  
  5272. let tracerFloats = new Float32Array(0);
  5273.  
  5274. // #4 : define ubo views
  5275. // firefox (and certain devices) adds some padding to uniform buffer sizes, so best to check its size
  5276. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Border);
  5277. const borderUboBuffer = new ArrayBuffer(gl.getBufferParameter(gl.UNIFORM_BUFFER, gl.BUFFER_SIZE));
  5278. // must reference an arraybuffer for the memory to be shared between these views
  5279. const borderUboFloats = new Float32Array(borderUboBuffer);
  5280. const borderUboInts = new Int32Array(borderUboBuffer);
  5281.  
  5282. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Cell);
  5283. const cellUboBuffer = new ArrayBuffer(gl.getBufferParameter(gl.UNIFORM_BUFFER, gl.BUFFER_SIZE));
  5284. const cellUboFloats = new Float32Array(cellUboBuffer);
  5285. const cellUboInts = new Int32Array(cellUboBuffer);
  5286.  
  5287. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Circle);
  5288. const circleUboFloats = new Float32Array(gl.getBufferParameter(gl.UNIFORM_BUFFER, gl.BUFFER_SIZE) / 4);
  5289.  
  5290. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Text);
  5291. const textUboBuffer = new ArrayBuffer(gl.getBufferParameter(gl.UNIFORM_BUFFER, gl.BUFFER_SIZE));
  5292. const textUboFloats = new Float32Array(textUboBuffer);
  5293. const textUboInts = new Int32Array(textUboBuffer);
  5294.  
  5295. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Tracer);
  5296. const tracerUboFloats = new Float32Array(gl.getBufferParameter(gl.UNIFORM_BUFFER, gl.BUFFER_SIZE) / 4);
  5297.  
  5298. gl.bindBuffer(gl.UNIFORM_BUFFER, null); // leaving uniform buffer bound = scary!
  5299.  
  5300.  
  5301. // #5 : define the render function
  5302. const start = performance.now();
  5303. render.fps = 0;
  5304. render.lastFrame = performance.now();
  5305. const renderGame = () => {
  5306. const now = performance.now();
  5307. const dt = Math.max(now - render.lastFrame, 0.1) / 1000; // there's a chance (now - lastFrame) can be 0
  5308. render.fps += (1 / dt - render.fps) / 10;
  5309. render.lastFrame = now;
  5310.  
  5311. if (gl.isContextLost()) {
  5312. requestAnimationFrame(renderGame);
  5313. return;
  5314. }
  5315.  
  5316. // get settings
  5317. const defaultVirusSrc = '/assets/images/viruses/2.png';
  5318. const virusSrc = sigmod.settings.virusImage || defaultVirusSrc;
  5319. const { cellColor, foodColor, outlineColor, showNames } = sigmod.settings;
  5320.  
  5321. refreshTextCache();
  5322.  
  5323. const vision = aux.require(world.views.get(world.selected), 'no selected vision (BAD BUG)');
  5324. vision.used = performance.now();
  5325. world.cameras(now);
  5326.  
  5327. // note: most routines are named, for benchmarking purposes
  5328. (function setGlobalUniforms() {
  5329. // note that binding the same buffer to gl.UNIFORM_BUFFER twice in a row causes it to not update.
  5330. // why that happens is completely beyond me but oh well.
  5331. // for consistency, we always bind gl.UNIFORM_BUFFER to null directly after updating it.
  5332. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Camera);
  5333. gl.bufferSubData(gl.UNIFORM_BUFFER, 0, new Float32Array([
  5334. ui.game.canvas.width / ui.game.canvas.height, vision.camera.scale / 540,
  5335. vision.camera.x, vision.camera.y,
  5336. ]));
  5337. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5338.  
  5339. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.CellSettings);
  5340. gl.bufferSubData(gl.UNIFORM_BUFFER, 0, new Float32Array([
  5341. ...settings.outlineMultiColor, // cell_active_outline
  5342. ...settings.outlineMultiInactiveColor, // cell_inactive_outline
  5343. ...settings.unsplittableColor, // cell_unsplittable_outline
  5344. ...(outlineColor ?? [0, 0, 0, 0]), // cell_subtle_outline_override
  5345. settings.outlineMulti,
  5346. ]));
  5347. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5348. })();
  5349.  
  5350. (function background() {
  5351. if (sigmod.settings.mapColor) {
  5352. gl.clearColor(...sigmod.settings.mapColor);
  5353. } else if (aux.settings.darkTheme) {
  5354. gl.clearColor(0x11 / 255, 0x11 / 255, 0x11 / 255, 1); // #111
  5355. } else {
  5356. gl.clearColor(0xf2 / 255, 0xfb / 255, 0xff / 255, 1); // #f2fbff
  5357. }
  5358. gl.clear(gl.COLOR_BUFFER_BIT);
  5359.  
  5360. gl.useProgram(glconf.programs.bg);
  5361. gl.bindVertexArray(glconf.vao.main.vao);
  5362.  
  5363. let texture;
  5364. if (settings.background) {
  5365. if (settings.background.startsWith('🖼️'))
  5366. texture = textureFromDatabase('background');
  5367. else
  5368. texture = textureFromCache(settings.background);
  5369. } else if (aux.settings.showGrid) {
  5370. texture = textureFromCache(aux.settings.darkTheme ? darkGridSrc : lightGridSrc);
  5371. }
  5372. gl.bindTexture(gl.TEXTURE_2D, texture?.texture ?? null);
  5373. const repeating = texture && texture.width <= 512 && texture.height <= 512;
  5374.  
  5375. let borderColor;
  5376. let borderLrtb;
  5377. borderColor = (aux.settings.showBorder && vision.border) ? [0, 0, 1, 1] /* #00ff */
  5378. : [0, 0, 0, 0] /* transparent */;
  5379. borderLrtb = vision.border || { l: 0, r: 0, t: 0, b: 0 };
  5380.  
  5381. // u_border_color
  5382. borderUboFloats[0] = borderColor[0]; borderUboFloats[1] = borderColor[1];
  5383. borderUboFloats[2] = borderColor[2]; borderUboFloats[3] = borderColor[3];
  5384. // u_border_xyzw_lrtb
  5385. borderUboFloats[4] = borderLrtb.l;
  5386. borderUboFloats[5] = borderLrtb.r;
  5387. borderUboFloats[6] = borderLrtb.t;
  5388. borderUboFloats[7] = borderLrtb.b;
  5389.  
  5390. // flags
  5391. borderUboInts[8] = (texture ? 0x01 : 0) | (aux.settings.darkTheme ? 0x02 : 0) | (repeating ? 0x04 : 0)
  5392. | (settings.rainbowBorder ? 0x08 : 0);
  5393.  
  5394. // u_background_width and u_background_height
  5395. borderUboFloats[9] = texture?.width ?? 1;
  5396. borderUboFloats[10] = texture?.height ?? 1;
  5397. borderUboFloats[11] = (now - start) / 1000 * 0.2 % (Math.PI * 2);
  5398.  
  5399. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Border);
  5400. gl.bufferSubData(gl.UNIFORM_BUFFER, 0, borderUboFloats);
  5401. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5402. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  5403. })();
  5404.  
  5405. (function cells() {
  5406. // don't render anything if the current tab is not connected
  5407. const con = net.connections.get(world.selected);
  5408. if (!con?.handshake) return;
  5409.  
  5410. // for white cell outlines
  5411. let nextCellIdx = 0;
  5412. /** @type {(CellFrame | undefined)[]} */
  5413. const ownedToFrame = vision.owned.map(id => {
  5414. const cell = world.cells.get(id);
  5415. return world.synchronized ? cell?.merged : cell?.views.get(world.selected)?.frames[0];
  5416. });
  5417. for (const cell of ownedToFrame) {
  5418. if (cell && cell.deadAt === undefined) ++nextCellIdx;
  5419. }
  5420. const canSplit = ownedToFrame.map(cell => {
  5421. if (!cell || cell.nr < 128) return false;
  5422. return nextCellIdx++ < 16;
  5423. });
  5424.  
  5425. /**
  5426. * @param {Cell} cell
  5427. * @param {boolean} pellet
  5428. */
  5429. const draw = (cell, pellet) => {
  5430. // #1 : draw cell
  5431. /** @type {CellFrame | undefined} */
  5432. const frame = world.synchronized ? cell.merged : cell.views.get(world.selected)?.frames[0];
  5433. /** @type {CellInterpolation | undefined} */
  5434. const interp = world.synchronized ? cell.merged : cell.views.get(world.selected);
  5435. if (!frame || !interp) return;
  5436.  
  5437. /** @type {CellDescription | undefined} */
  5438. const desc = world.synchronized ? cell.views.values().next().value : cell.views.get(world.selected);
  5439. if (!desc) return;
  5440.  
  5441. /** @type {CellFrame | undefined} */
  5442. let killerFrame;
  5443. /** @type {CellInterpolation | undefined} */
  5444. let killerInterp;
  5445. let killer = frame.deadTo !== -1 && world.cells.get(frame.deadTo);
  5446. if (killer) {
  5447. killerFrame = world.synchronized ? killer.merged : killer.views.get(world.selected)?.frames[0];
  5448. killerInterp = world.synchronized ? killer.merged : killer.views.get(world.selected);
  5449. }
  5450.  
  5451. gl.useProgram(glconf.programs.cell);
  5452.  
  5453. const alpha = render.alpha(frame, now);
  5454. cellUboFloats[8] = alpha * settings.cellOpacity;
  5455.  
  5456. const { x, y, r, jr } = world.xyr(frame, interp, killerFrame, killerInterp, pellet, now);
  5457. // without jelly physics, the radius of cells is adjusted such that its subtle outline doesn't go
  5458. // past its original radius.
  5459. // jelly physics does not do this, so colliding cells need to look kinda 'joined' together,
  5460. // so we multiply the radius by 1.02 (approximately the size increase from the stroke thickness)
  5461. cellUboFloats[2] = x;
  5462. cellUboFloats[3] = y;
  5463. if (aux.settings.jellyPhysics && !desc.jagged && !pellet) {
  5464. const strokeThickness = Math.max(jr * 0.01, 10);
  5465. cellUboFloats[0] = jr + strokeThickness;
  5466. cellUboFloats[1] = (settings.jellySkinLag ? r : jr) + strokeThickness;
  5467. } else {
  5468. cellUboFloats[0] = cellUboFloats[1] = r + 2;
  5469. }
  5470.  
  5471. if (desc.jagged) {
  5472. const virusTexture = textureFromCache(virusSrc);
  5473. if (virusTexture) {
  5474. gl.bindTexture(gl.TEXTURE_2D, virusTexture.texture);
  5475. cellUboInts[9] = 0x01; // skin and nothing else
  5476. // draw a fully transparent cell
  5477. cellUboFloats[4] = cellUboFloats[5] = cellUboFloats[6] = cellUboFloats[7] = 0;
  5478. } else {
  5479. cellUboInts[9] = 0;
  5480. // #ff000080 if the virus texture doesn't load
  5481. cellUboFloats[4] = 1;
  5482. cellUboFloats[5] = 0;
  5483. cellUboFloats[6] = 0;
  5484. cellUboFloats[7] = 0.5;
  5485. }
  5486.  
  5487. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Cell);
  5488. gl.bufferSubData(gl.UNIFORM_BUFFER, 0, cellUboBuffer);
  5489. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5490. if (!aux.settings.darkTheme && virusSrc === defaultVirusSrc) {
  5491. // draw default viruses twice as strong for better contrast against light theme
  5492. cellUboFloats[8] = alpha * settings.cellOpacity;
  5493. }
  5494. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  5495. return;
  5496. }
  5497.  
  5498. cellUboInts[9] = 0;
  5499.  
  5500. /** @type {[number, number, number, number] | [number, number, number] | undefined} */
  5501. let color = pellet ? foodColor : cellColor;
  5502. if (pellet && foodColor && foodColor[0] === 0 && foodColor[1] === 0 && foodColor[2] === 0) {
  5503. color = [desc.rgb[0], desc.rgb[1], desc.rgb[2], foodColor[3]];
  5504. } else {
  5505. color ??= desc.rgb;
  5506. }
  5507.  
  5508. cellUboFloats[4] = color[0]; cellUboFloats[5] = color[1];
  5509. cellUboFloats[6] = color[2]; cellUboFloats[7] = color[3] ?? 1;
  5510.  
  5511. cellUboInts[9] |= settings.cellOutlines ? 0x02 : 0;
  5512. cellUboInts[9] |= settings.colorUnderSkin ? 0x20 : 0;
  5513.  
  5514. if (!pellet) {
  5515. /** @type {symbol | undefined} */
  5516. let ownerView;
  5517. let ownerVision;
  5518. for (const [otherView, otherVision] of world.views) {
  5519. if (!otherVision.owned.includes(cell.id)) continue;
  5520. ownerView = otherView;
  5521. ownerVision = otherVision;
  5522. break;
  5523. }
  5524.  
  5525. if (ownerView === world.selected) {
  5526. const myIndex = vision.owned.indexOf(cell.id);
  5527. if (!canSplit[myIndex]) cellUboInts[9] |= 0x10;
  5528.  
  5529. if (vision.camera.merged) cellUboInts[9] |= 0x04;
  5530. } else if (ownerVision) {
  5531. if (ownerVision.camera.merged) cellUboInts[9] |= 0x08;
  5532. }
  5533.  
  5534. const texture = render.skin(cell);
  5535. if (texture) {
  5536. cellUboInts[9] |= 0x01; // skin
  5537. gl.bindTexture(gl.TEXTURE_2D, texture.texture);
  5538. }
  5539. }
  5540.  
  5541. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Cell);
  5542. gl.bufferSubData(gl.UNIFORM_BUFFER, 0, cellUboBuffer);
  5543. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5544. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  5545.  
  5546. // #2 : draw text
  5547. if (pellet) return;
  5548. const name = desc.name || 'An unnamed cell';
  5549. const showThisName = (showNames ?? true) && frame.nr >= 64;
  5550. const showThisMass = aux.settings.showMass && frame.nr >= 64;
  5551. const clan = (settings.clans && aux.clans.get(desc.clan)) || '';
  5552. if (!showThisName && !showThisMass && !clan) return;
  5553.  
  5554. gl.useProgram(glconf.programs.text);
  5555. textUboFloats[8] = alpha; // text_alpha
  5556.  
  5557. let useSilhouette = false;
  5558. if (desc.sub) {
  5559. // text_color1 = #eb9500 * 1.2
  5560. textUboFloats[0] = 0xeb / 255 * 1.2; textUboFloats[1] = 0x95 / 255 * 1.2;
  5561. textUboFloats[2] = 0x00 / 255 * 1.2; textUboFloats[3] = 1;
  5562. // text_color2 = #f9bf0d * 1.2
  5563. textUboFloats[4] = 0xf9 / 255 * 1.2; textUboFloats[5] = 0xbf / 255 * 1.2;
  5564. textUboFloats[6] = 0x0d / 255 * 1.2; textUboFloats[7] = 1;
  5565. useSilhouette = true;
  5566. } else {
  5567. // text_color1 = text_color2 = #fff
  5568. textUboFloats[0] = textUboFloats[1] = textUboFloats[2] = textUboFloats[3] = 1;
  5569. textUboFloats[4] = textUboFloats[5] = textUboFloats[6] = textUboFloats[7] = 1;
  5570. }
  5571.  
  5572. if (input.nick.find(el => el.value === name)) {
  5573. const { nameColor1, nameColor2 } = sigmod.settings;
  5574. if (nameColor1) {
  5575. textUboFloats[0] = nameColor1[0]; textUboFloats[1] = nameColor1[1];
  5576. textUboFloats[2] = nameColor1[2]; textUboFloats[3] = nameColor1[3];
  5577. useSilhouette = true;
  5578. }
  5579.  
  5580. if (nameColor2) {
  5581. textUboFloats[4] = nameColor2[0]; textUboFloats[5] = nameColor2[1];
  5582. textUboFloats[6] = nameColor2[2]; textUboFloats[7] = nameColor2[3];
  5583. useSilhouette = true;
  5584. }
  5585. }
  5586.  
  5587. if (clan) {
  5588. const { aspectRatio, text, silhouette } = textFromCache(clan, useSilhouette);
  5589. if (text) {
  5590. textUboFloats[9] = aspectRatio; // text_aspect_ratio
  5591. textUboFloats[10]
  5592. = showThisName ? settings.clanScaleFactor * 0.5 : settings.nameScaleFactor;
  5593. textUboInts[11] = Number(useSilhouette); // text_silhouette_enabled
  5594. textUboFloats[12] = 0; // text_offset.x
  5595. textUboFloats[13] = showThisName
  5596. ? -settings.nameScaleFactor/3 - settings.clanScaleFactor/6 : 0; // text_offset.y
  5597.  
  5598. gl.bindTexture(gl.TEXTURE_2D, text);
  5599. if (silhouette) {
  5600. gl.activeTexture(gl.TEXTURE1);
  5601. gl.bindTexture(gl.TEXTURE_2D, silhouette);
  5602. gl.activeTexture(gl.TEXTURE0);
  5603. }
  5604.  
  5605. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Text);
  5606. gl.bufferSubData(gl.UNIFORM_BUFFER, 0, textUboBuffer);
  5607. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5608. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  5609. }
  5610. }
  5611.  
  5612. if (showThisName) {
  5613. const { aspectRatio, text, silhouette } = textFromCache(name, useSilhouette);
  5614. if (text) {
  5615. textUboFloats[9] = aspectRatio; // text_aspect_ratio
  5616. textUboFloats[10] = settings.nameScaleFactor; // text_scale
  5617. textUboInts[11] = Number(useSilhouette); // text_silhouette_enabled
  5618. textUboFloats[12] = textUboFloats[13] = 0; // text_offset = (0, 0)
  5619.  
  5620. gl.bindTexture(gl.TEXTURE_2D, text);
  5621. if (silhouette) {
  5622. gl.activeTexture(gl.TEXTURE1);
  5623. gl.bindTexture(gl.TEXTURE_2D, silhouette);
  5624. gl.activeTexture(gl.TEXTURE0);
  5625. }
  5626.  
  5627. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Text);
  5628. gl.bufferSubData(gl.UNIFORM_BUFFER, 0, textUboBuffer);
  5629. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5630. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  5631. }
  5632. }
  5633.  
  5634. if (showThisMass) {
  5635. textUboFloats[8] = alpha * settings.massOpacity; // text_alpha
  5636. textUboFloats[10] = 0.5 * settings.massScaleFactor; // text_scale
  5637. textUboInts[11] = 0; // text_silhouette_enabled
  5638.  
  5639. let yOffset;
  5640. if (showThisName)
  5641. yOffset = (settings.nameScaleFactor + 0.5 * settings.massScaleFactor) / 3;
  5642. else if (clan)
  5643. yOffset = (1 + 0.5 * settings.massScaleFactor) / 3;
  5644. else
  5645. yOffset = 0;
  5646. // draw each digit separately, as Ubuntu makes them all the same width.
  5647. // significantly reduces the size of the text cache
  5648. const mass = Math.floor(frame.nr * frame.nr / 100).toString();
  5649. const maxWidth = maxMassWidth();
  5650. for (let i = 0; i < mass.length; ++i) {
  5651. const { height, width, texture } = massTextFromCache(mass[i]);
  5652. textUboFloats[9] = width / height; // text_aspect_ratio
  5653. // text_offset.x; kerning is fixed by subtracting most of the padding from lineWidth
  5654. textUboFloats[12] = (i - (mass.length - 1) / 2) * settings.massScaleFactor
  5655. * (maxWidth / width)
  5656. * (maxWidth - 20 * settings.textOutlinesFactor * settings.massScaleFactor) / maxWidth;
  5657. textUboFloats[13] = yOffset;
  5658. gl.bindTexture(gl.TEXTURE_2D, texture);
  5659.  
  5660. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Text);
  5661. gl.bufferSubData(gl.UNIFORM_BUFFER, 0, textUboBuffer);
  5662. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5663. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  5664. }
  5665. }
  5666. }
  5667.  
  5668. // draw pellets
  5669. {
  5670. // blend function for all pellets
  5671. if (settings.pelletGlow && aux.settings.darkTheme) gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  5672.  
  5673. // draw unanimated pellets using instanced drawing
  5674. gl.useProgram(glconf.programs.circle);
  5675. gl.bindVertexArray(glconf.vao.pellet.vao);
  5676. let i = 0;
  5677. for (const cell of world.pellets.values()) {
  5678. const frame = world.synchronized ? cell.merged : cell.views.get(world.selected)?.frames[0];
  5679. if (frame?.deadTo !== -1) continue;
  5680. circleBuffers.pelletAlpha[i++] = render.alpha(frame, now);
  5681. }
  5682. gl.bindBuffer(gl.ARRAY_BUFFER, glconf.vao.pellet.alpha);
  5683. gl.bufferSubData(gl.ARRAY_BUFFER, 0, circleBuffers.pelletAlpha);
  5684. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  5685.  
  5686. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Circle);
  5687. circleUboFloats[0] = 1; // alpha
  5688. circleUboFloats[1] = 0; // scale (0 means no blur)
  5689. gl.bufferSubData(gl.UNIFORM_BUFFER, 0, circleUboFloats);
  5690. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5691. // pellet data is not uploaded if tab is closed for a while, so pelletsUploaded would be 0
  5692. gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, circleBuffers.pelletsUploaded);
  5693.  
  5694. if (settings.pelletGlow) {
  5695. // draw unanimated pellet glow
  5696. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  5697. circleUboFloats[0] = 0.25; // alpha
  5698. circleUboFloats[1] = 2; // scale
  5699. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Circle);
  5700. gl.bufferData(gl.UNIFORM_BUFFER, circleUboFloats, gl.STATIC_DRAW);
  5701. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5702. gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, i);
  5703.  
  5704. // reset blend func
  5705. gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  5706. }
  5707.  
  5708. // draw animated pellets without instanced drawing
  5709. gl.bindVertexArray(glconf.vao.main.vao);
  5710. for (const cell of world.pellets.values()) {
  5711. const frame = world.synchronized ? cell.merged : cell.views.get(world.selected)?.frames[0];
  5712. if (frame && frame.deadTo !== -1) draw(cell, true);
  5713. // do not make eaten pellets glow
  5714. }
  5715. }
  5716.  
  5717. // draw cells
  5718. {
  5719. /** @type {[Cell, number][]} */
  5720. const sorted = [];
  5721. for (const cell of world.cells.values()) {
  5722. const frame = world.synchronized ? cell.merged : cell.views.get(world.selected)?.frames[0];
  5723. const interp = world.synchronized ? cell.merged : cell.views.get(world.selected);
  5724. if (!frame || !interp) continue;
  5725.  
  5726. const a = Math.min(Math.max((now - interp.updated) / settings.drawDelay, 0), 1);
  5727. const computedR = interp.or + (frame.nr - interp.or) * a;
  5728. sorted.push([cell, computedR]);
  5729. }
  5730.  
  5731. gl.bindVertexArray(glconf.vao.main.vao);
  5732. sorted.sort(([_a, ar], [_b, br]) => ar - br);
  5733. for (const [cell] of sorted) draw(cell, false);
  5734.  
  5735. // draw glow *after* all cells (so the glow goes above the text)
  5736. if (settings.cellGlow) {
  5737. render.upload(false);
  5738. let i = 0;
  5739. for (const cell of world.cells.values()) {
  5740. const frame = world.synchronized ? cell.merged : cell.views.get(world.selected)?.frames[0];
  5741. /** @type {CellDescription} */
  5742. const desc = world.synchronized ? cell.views.values().next().value : cell.views.get(world.selected);
  5743. if (!frame || !desc || desc.jagged) continue;
  5744.  
  5745. let alpha = render.alpha(frame, now);
  5746. // it looks kinda weird when cells get sucked in when being eaten
  5747. if (frame.deadTo !== -1) alpha *= 0.25;
  5748. circleBuffers.cellAlpha[i++] = alpha;
  5749. }
  5750.  
  5751. gl.useProgram(glconf.programs.circle);
  5752. gl.bindVertexArray(glconf.vao.cell.vao);
  5753. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  5754.  
  5755. gl.bindBuffer(gl.ARRAY_BUFFER, glconf.vao.cell.alpha);
  5756. gl.bufferSubData(gl.ARRAY_BUFFER, 0, circleBuffers.cellAlpha);
  5757. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  5758.  
  5759. circleUboFloats[0] = 0.25; // alpha
  5760. // scale (can't be too big, otherwise it looks weird when cells come into view)
  5761. circleUboFloats[1] = 1.5;
  5762. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Circle);
  5763. gl.bufferData(gl.UNIFORM_BUFFER, circleUboFloats, gl.STATIC_DRAW);
  5764. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5765. gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, i);
  5766.  
  5767. gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  5768. }
  5769. }
  5770.  
  5771. // draw tracers
  5772. if (settings.tracer) {
  5773. gl.useProgram(glconf.programs.tracer);
  5774. gl.bindVertexArray(glconf.vao.tracer.vao);
  5775.  
  5776. tracerUboFloats[0] = 0.5; // #7f7f7f color
  5777. tracerUboFloats[1] = 0.5;
  5778. tracerUboFloats[2] = 0.5;
  5779. tracerUboFloats[3] = 0.5;
  5780. tracerUboFloats[4] = 2; // line thickness
  5781. gl.bindBuffer(gl.UNIFORM_BUFFER, glconf.uniforms.Tracer);
  5782. gl.bufferSubData(gl.UNIFORM_BUFFER, 0, tracerUboFloats);
  5783. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  5784.  
  5785. const mouse = input.toWorld(world.selected, input.current);
  5786. const inputs = input.views.get(world.selected);
  5787. if (!inputs) return; // tracers are the last step in cells(), so a return is OK
  5788.  
  5789. // resize by powers of 2
  5790. let capacity = tracerFloats.length || 1;
  5791. while (vision.owned.length * 4 > capacity) capacity *= 2;
  5792. const resizing = capacity !== tracerFloats.length;
  5793. if (resizing) tracerFloats = new Float32Array(capacity);
  5794.  
  5795. const camera
  5796. = world.singleCamera(world.selected, vision, settings.camera !== 'default' ? 2 : 0, now);
  5797.  
  5798. let i = 0;
  5799. for (const id of vision.owned) {
  5800. const cell = world.cells.get(id);
  5801. const frame = world.synchronized ? cell?.merged : cell?.views.get(world.selected)?.frames[0];
  5802. const interp = world.synchronized ? cell?.merged : cell?.views.get(world.selected);
  5803. if (!frame || !interp || frame.deadAt !== undefined) continue;
  5804.  
  5805. const { x, y } = world.xyr(frame, interp, undefined, undefined, false, now);
  5806. tracerFloats[i * 4] = x;
  5807. tracerFloats[i * 4 + 1] = y;
  5808. tracerFloats[i * 4 + 2] = mouse[0];
  5809. tracerFloats[i * 4 + 3] = mouse[1];
  5810.  
  5811. switch (inputs.lock?.type) {
  5812. case 'point':
  5813. if (now > inputs.lock.until) break;
  5814. tracerFloats[i * 4 + 2] = inputs.lock.world[0];
  5815. tracerFloats[i * 4 + 3] = inputs.lock.world[1];
  5816. break;
  5817. case 'horizontal':
  5818. tracerFloats[i * 4 + 3] = inputs.lock.world[1];
  5819. break;
  5820. case 'vertical':
  5821. tracerFloats[i * 4 + 2] = inputs.lock.world[0];
  5822. break;
  5823. case 'fixed':
  5824. const dx = mouse[0] - camera.sumX / camera.weight;
  5825. const dy = mouse[1] - camera.sumY / camera.weight;
  5826. const d = Math.hypot(dx, dy);
  5827. tracerFloats[i * 4 + 2] = x + dx * 1e6 / d;
  5828. tracerFloats[i * 4 + 3] = y + dy * 1e6 / d;
  5829. }
  5830. ++i;
  5831. }
  5832.  
  5833. gl.bindBuffer(gl.ARRAY_BUFFER, glconf.vao.tracer.line);
  5834. if (resizing) gl.bufferData(gl.ARRAY_BUFFER, tracerFloats, gl.STATIC_DRAW);
  5835. else gl.bufferSubData(gl.ARRAY_BUFFER, 0, tracerFloats);
  5836. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  5837. gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, i);
  5838. }
  5839. })();
  5840.  
  5841. ui.stats.update(world.selected);
  5842.  
  5843. (function minimap() {
  5844. if (now - lastMinimapDraw < 40) return; // should be good enough when multiboxing, may change later
  5845. lastMinimapDraw = now;
  5846.  
  5847. if (!aux.settings.showMinimap) {
  5848. ui.minimap.canvas.style.display = 'none';
  5849. return;
  5850. } else {
  5851. ui.minimap.canvas.style.display = '';
  5852. }
  5853.  
  5854. const { canvas, ctx } = ui.minimap;
  5855. // clears the canvas
  5856. const canvasLength = canvas.width = canvas.height = Math.ceil(200 * (devicePixelRatio - 0.0001));
  5857. const sectorSize = canvas.width / 5;
  5858.  
  5859. // always use this style for drawing section and minimap names
  5860. ctx.font = `${Math.floor(sectorSize / 3)}px "${sigmod.settings.font || 'Ubuntu'}", Ubuntu`;
  5861. ctx.textAlign = 'center';
  5862. ctx.textBaseline = 'middle';
  5863.  
  5864. // cache the background if necessary (25 texts = bad)
  5865. if (minimapCache && minimapCache.bg.width === canvasLength
  5866. && minimapCache.darkTheme === aux.settings.darkTheme) {
  5867. ctx.putImageData(minimapCache.bg, 0, 0);
  5868. } else {
  5869. // draw section names
  5870. ctx.fillStyle = '#fff';
  5871. ctx.globalAlpha = aux.settings.darkTheme ? 0.3 : 0.7;
  5872.  
  5873. const cols = ['1', '2', '3', '4', '5'];
  5874. const rows = ['A', 'B', 'C', 'D', 'E'];
  5875. cols.forEach((col, y) => {
  5876. rows.forEach((row, x) => {
  5877. ctx.fillText(row + col, (x + 0.5) * sectorSize, (y + 0.5) * sectorSize);
  5878. });
  5879. });
  5880.  
  5881. minimapCache = {
  5882. bg: ctx.getImageData(0, 0, canvas.width, canvas.height),
  5883. darkTheme: aux.settings.darkTheme,
  5884. };
  5885. }
  5886.  
  5887. const { border } = vision;
  5888. if (!border) return;
  5889.  
  5890. // sigmod overlay resizes itself differently, so we correct it whenever we need to
  5891. /** @type {HTMLCanvasElement | null} */
  5892. const sigmodMinimap = document.querySelector('canvas.minimap');
  5893. if (sigmodMinimap) {
  5894. // we need to check before updating the canvas, otherwise we will clear it
  5895. if (sigmodMinimap.style.width !== '200px' || sigmodMinimap.style.height !== '200px')
  5896. sigmodMinimap.style.width = sigmodMinimap.style.height = '200px';
  5897.  
  5898. if (sigmodMinimap.width !== canvas.width || sigmodMinimap.height !== canvas.height)
  5899. sigmodMinimap.width = sigmodMinimap.height = canvas.width;
  5900. }
  5901.  
  5902. const gameWidth = (border.r - border.l);
  5903. const gameHeight = (border.b - border.t);
  5904.  
  5905. // highlight current section
  5906. ctx.fillStyle = settings.theme[3] ? aux.rgba2hex6(...settings.theme) : '#ff0';
  5907. ctx.globalAlpha = 0.3;
  5908.  
  5909. const sectionX = Math.floor((vision.camera.x - border.l) / gameWidth * 5);
  5910. const sectionY = Math.floor((vision.camera.y - border.t) / gameHeight * 5);
  5911. ctx.fillRect(sectionX * sectorSize, sectionY * sectorSize, sectorSize, sectorSize);
  5912.  
  5913. ctx.globalAlpha = 1;
  5914.  
  5915. // draw cells
  5916. /**
  5917. * @param {{ nx: number, ny: number, nr: number }} frame
  5918. * @param {{ rgb: [number, number, number] | [number, number, number, number] }} desc
  5919. */
  5920. const drawCell = (frame, desc) => {
  5921. const x = (frame.nx - border.l) / gameWidth * canvas.width;
  5922. const y = (frame.ny - border.t) / gameHeight * canvas.height;
  5923. const r = Math.max(frame.nr / gameWidth * canvas.width, 2);
  5924.  
  5925. ctx.scale(0.01, 0.01); // prevent sigmod from treating minimap cells as pellets
  5926. ctx.fillStyle = aux.rgba2hex6(desc.rgb[0], desc.rgb[1], desc.rgb[2], 1);
  5927. ctx.beginPath();
  5928. ctx.moveTo((x + r) * 100, y * 100);
  5929. ctx.arc(x * 100, y * 100, r * 100, 0, 2 * Math.PI);
  5930. ctx.fill();
  5931. ctx.resetTransform();
  5932. };
  5933.  
  5934. /**
  5935. * @param {number} x
  5936. * @param {number} y
  5937. * @param {string} name
  5938. */
  5939. const drawName = function drawName(x, y, name) {
  5940. x = (x - border.l) / gameWidth * canvas.width;
  5941. y = (y - border.t) / gameHeight * canvas.height;
  5942.  
  5943. ctx.fillStyle = '#fff';
  5944. // add a space to prevent sigmod from detecting names
  5945. ctx.fillText(name + ' ', x, y - 7 * devicePixelRatio - sectorSize / 6);
  5946. };
  5947.  
  5948. // draw clanmates (and other tabs) first, below yourself
  5949. // clanmates are grouped by name AND color, ensuring they stay separate
  5950. /** @type {Map<string, { name: string, n: number, x: number, y: number }>} */
  5951. const avgPos = new Map();
  5952. for (const cell of world.cells.values()) {
  5953. const frame = world.synchronized ? cell.merged : cell.views.get(world.selected)?.frames[0];
  5954. /** @type {CellDescription} */
  5955. const desc = world.synchronized ? cell.views.values().next().value : cell.views.get(world.selected);
  5956. if (!frame || !desc || frame.deadAt !== undefined) continue;
  5957.  
  5958. let ownedByOther = false;
  5959. for (const [view, vision] of world.views) {
  5960. if (view === world.selected) continue;
  5961. ownedByOther = vision.owned.includes(cell.id) && frame.born >= vision.spawned;
  5962. if (ownedByOther) break;
  5963. }
  5964. if ((!desc.clan || desc.clan !== aux.userData?.clan) && !ownedByOther) continue;
  5965.  
  5966. drawCell(frame, desc);
  5967.  
  5968. const name = desc.name || 'An unnamed cell';
  5969. const hash = desc.name + (desc.rgb[0] * 65536 + desc.rgb[1] * 256 + desc.rgb[2]);
  5970. const entry = avgPos.get(hash);
  5971. if (entry) {
  5972. ++entry.n;
  5973. entry.x += frame.nx;
  5974. entry.y += frame.ny;
  5975. } else {
  5976. avgPos.set(hash, { name, n: 1, x: frame.nx, y: frame.ny });
  5977. }
  5978. }
  5979.  
  5980. avgPos.forEach(entry => {
  5981. drawName(entry.x / entry.n, entry.y / entry.n, entry.name);
  5982. });
  5983.  
  5984. // draw my cells above everyone else
  5985. let myName = '';
  5986. let ownN = 0;
  5987. let ownX = 0;
  5988. let ownY = 0;
  5989. for (const id of vision.owned) {
  5990. const cell = world.cells.get(id);
  5991. const frame = world.synchronized ? cell?.merged : cell?.views.get(world.selected)?.frames[0];
  5992. const desc = world.synchronized ? cell?.views.values().next().value : cell?.views.get(world.selected);
  5993. if (!frame || !desc || frame.deadAt !== undefined) continue;
  5994.  
  5995. drawCell(frame, desc);
  5996. myName = desc.name || 'An unnamed cell';
  5997. ++ownN;
  5998. ownX += frame.nx;
  5999. ownY += frame.ny;
  6000. }
  6001.  
  6002. if (ownN <= 0) {
  6003. // if no cells were drawn, draw our spectate pos instead
  6004. drawCell({ nx: vision.camera.x, ny: vision.camera.y, nr: gameWidth / canvas.width * 5, },
  6005. { rgb: settings.theme[3] ? settings.theme : [1, 0.6, 0.6] });
  6006. } else {
  6007. ownX /= ownN;
  6008. ownY /= ownN;
  6009. // draw name above player's cells
  6010. drawName(ownX, ownY, myName);
  6011.  
  6012. // send a hint to sigmod
  6013. ctx.globalAlpha = 0;
  6014. ctx.fillText(`X: ${ownX}, Y: ${ownY}`, 0, -1000);
  6015. }
  6016. })();
  6017.  
  6018. requestAnimationFrame(renderGame);
  6019. }
  6020.  
  6021. requestAnimationFrame(renderGame);
  6022. return render;
  6023. })();
  6024.  
  6025.  
  6026.  
  6027. // @ts-expect-error for debugging purposes and other scripts. dm me on discord @ 8y8x to guarantee stability
  6028. window.sigfix = {
  6029. destructor, aux, sigmod, ui, settings, world, net, input, glconf, render,
  6030. };
  6031. })();