From 30757767a717422f65cf95e00d2edf581ec08ced Mon Sep 17 00:00:00 2001 From: Jeffrey Alan Scudder Date: Thu, 4 Dec 2025 19:33:05 +0000 Subject: [PATCH] feat(1v1): implement hybrid UDP/WebSocket multiplayer - Add 1v1:move UDP handler in session-server for position broadcasts - Update 1v1.mjs to use UDP for position updates, WebSocket for events - Update geckos.io to 3.0.2 (server + client bundle) - Add udp.mjs 1v1:move listener with handle-based player matching - Create comprehensive UDP multiplayer analysis document - Add CLI test scripts: - udp-multiplayer-test.mjs (WebSocket-based, 95% success) - udp-geckos-test.mjs (true UDP via WebRTC, 95% success) - Install node-datachannel for Node.js WebRTC polyfill This hybrid approach uses: - WebSocket: reliable events (join, leave, combat actions) - UDP/WebRTC: low-latency position updates (~20Hz) --- package-lock.json | 273 ++++++- package.json | 2 + plans/udp-multiplayer-analysis.md | 529 ++++++++++++++ session-server/package-lock.json | 685 +----------------- session-server/package.json | 1 + session-server/session.mjs | 12 + .../dep/geckos.io-client.3.0.2.min.js | 1 + .../public/aesthetic.computer/disks/1v1.mjs | 51 +- system/public/aesthetic.computer/lib/udp.mjs | 7 +- tests/udp-geckos-test.mjs | 209 ++++++ tests/udp-multiplayer-test.mjs | 195 +++++ 11 files changed, 1274 insertions(+), 691 deletions(-) create mode 100644 plans/udp-multiplayer-analysis.md create mode 100644 system/public/aesthetic.computer/dep/geckos.io-client.3.0.2.min.js create mode 100644 tests/udp-geckos-test.mjs create mode 100644 tests/udp-multiplayer-test.mjs diff --git a/package-lock.json b/package-lock.json index c5eed7560e..64eb5e6bb9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "gif-encoder-2": "^1.0.5", "jszip": "^3.10.1", "mongodb": "^6.20.0", + "node-datachannel": "^0.30.0", "node-fetch": "^3.3.2", "ntp-client": "^0.5.3", "obscenity": "^0.4.5", @@ -24,6 +25,7 @@ "ws": "^8.18.3" }, "devDependencies": { + "@geckos.io/client": "^3.0.2", "@swc/core": "^1.15.3", "blessed": "^0.1.81", "chalk": "^5.6.2", @@ -2064,6 +2066,35 @@ "dev": true, "license": "MIT" }, + "node_modules/@geckos.io/client": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@geckos.io/client/-/client-3.0.2.tgz", + "integrity": "sha512-nZnhG8IiDBvKKNonguz2sBv4Y8rVpxz5SK9NIvLF7nIUQ2YUUHWcQ4OYBwLUjzSUWdzAjiTP1rPa5azXJw7MRA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@geckos.io/common": "^3.0.2" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/yandeu" + } + }, + "node_modules/@geckos.io/common": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@geckos.io/common/-/common-3.0.2.tgz", + "integrity": "sha512-2Rf61S+Xya1FwGnIShfdP7GPE73o9zDQRbiFEd/SCTkIApR2MusJholLJ88cmWHXY9bX0nDpyiflgwYYUfXx7g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@yandeu/events": "0.0.7" + }, + "funding": { + "url": "https://github.com/sponsors/yandeu" + } + }, "node_modules/@isaacs/balanced-match": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz", @@ -4481,6 +4512,19 @@ "node": ">=10.0.0" } }, + "node_modules/@yandeu/events": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/@yandeu/events/-/events-0.0.7.tgz", + "integrity": "sha512-l78u4CooPw/WlN3H15bhOpims+gAsAkxbcjDn1GZ5oa+h9wqg+pBBzZos38xDeqKW/UVgPMkurVDPrf7JhhmTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.2" + }, + "funding": { + "url": "https://github.com/sponsors/yandeu" + } + }, "node_modules/7zip-bin": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/7zip-bin/-/7zip-bin-5.2.0.tgz", @@ -5050,7 +5094,6 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "dev": true, "license": "MIT", "dependencies": { "buffer": "^5.5.0", @@ -5062,7 +5105,6 @@ "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "dev": true, "funding": [ { "type": "github", @@ -5087,7 +5129,6 @@ "version": "3.6.2", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dev": true, "license": "MIT", "dependencies": { "inherits": "^2.0.3", @@ -6191,7 +6232,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "dev": true, "license": "MIT", "dependencies": { "mimic-response": "^3.1.0" @@ -6207,7 +6247,6 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=10" @@ -6216,6 +6255,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/defaults": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz", @@ -6316,7 +6364,6 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.1.tgz", "integrity": "sha512-ecqj/sy1jcK1uWrwpR67UhYrIFQ+5WlGxth34WquCbamhFA6hkkwiu37o6J5xCHdo1oixJRfVRw+ywV+Hq/0Aw==", - "dev": true, "license": "Apache-2.0", "engines": { "node": ">=8" @@ -6851,7 +6898,6 @@ "version": "1.4.5", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "dev": true, "license": "MIT", "dependencies": { "once": "^1.4.0" @@ -7082,6 +7128,15 @@ "node": ">=0.8.x" } }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, "node_modules/exponential-backoff": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.2.tgz", @@ -7327,6 +7382,12 @@ "dev": true, "license": "MIT" }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, "node_modules/fs-extra": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", @@ -7529,6 +7590,12 @@ "integrity": "sha512-fsRAKbZuUoZ7FYGjpFElmflTkKwsn/CzAmL/xDl4558aTAgysIDCUF6AXWO8dmai/ApfZACbPVAM+vPezJXlFg==", "license": "UNLICENSE" }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, "node_modules/glob": { "version": "10.4.5", "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", @@ -8083,6 +8150,12 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, "node_modules/intl-messageformat": { "version": "10.7.18", "resolved": "https://registry.npmjs.org/intl-messageformat/-/intl-messageformat-10.7.18.tgz", @@ -8984,7 +9057,6 @@ "version": "1.2.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -9181,6 +9253,12 @@ "node": ">=10" } }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, "node_modules/module-details-from-path": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz", @@ -9257,6 +9335,12 @@ "integrity": "sha512-HoMUjhH9T8DDBNT+6xzkrd9ga/XiBI4xLr58LJACwK6G3HTOPeMz4nB4KJs33L2BelrIJa7P0VuNaVF3hMYfjg==", "license": "(Apache-2.0 AND MIT)" }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, "node_modules/ndarray": { "version": "1.0.19", "resolved": "https://registry.npmjs.org/ndarray/-/ndarray-1.0.19.tgz", @@ -9313,7 +9397,6 @@ "version": "3.77.0", "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.77.0.tgz", "integrity": "sha512-DSmt0OEcLoK4i3NuscSbGjOf3bqiDEutejqENSplMSFA/gmB8mkED9G4pKWnPl7MDU4rSHebKPHeitpDfyH0cQ==", - "dev": true, "license": "MIT", "dependencies": { "semver": "^7.3.5" @@ -9349,6 +9432,19 @@ "node": ">=v0.6.5" } }, + "node_modules/node-datachannel": { + "version": "0.30.0", + "resolved": "https://registry.npmjs.org/node-datachannel/-/node-datachannel-0.30.0.tgz", + "integrity": "sha512-1KDc8eMY5ccFBlV9J6xTxBNRKpqsHITV5sfQMNGxrfjyzFVOzdeRxVVH7kvhiOcZeJpGpncsncCF8/VwAZf+8w==", + "hasInstallScript": true, + "license": "MPL 2.0", + "dependencies": { + "prebuild-install": "^7.1.3" + }, + "engines": { + "node": ">=18.20.0" + } + }, "node_modules/node-domexception": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", @@ -9571,7 +9667,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, "license": "ISC", "dependencies": { "wrappy": "1" @@ -10109,6 +10204,80 @@ "node": "^12.20.0 || >=14" } }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/prebuild-install/node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/prebuild-install/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/prebuild-install/node_modules/tar-fs": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/prebuild-install/node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/prettier": { "version": "3.6.2", "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", @@ -10244,7 +10413,6 @@ "version": "3.0.3", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz", "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==", - "dev": true, "license": "MIT", "dependencies": { "end-of-stream": "^1.1.0", @@ -10353,6 +10521,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, "node_modules/read-binary-file-arch": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz", @@ -10694,7 +10877,6 @@ "version": "7.7.3", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", - "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -10897,6 +11079,51 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, "node_modules/simple-update-notifier": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", @@ -11232,6 +11459,15 @@ "node": ">=8" } }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/strnum": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz", @@ -11714,6 +11950,18 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, "node_modules/type-fest": { "version": "4.41.0", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", @@ -12058,7 +12306,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, "license": "ISC" }, "node_modules/ws": { diff --git a/package.json b/package.json index 34129e0d2a..ea16cbab66 100644 --- a/package.json +++ b/package.json @@ -75,6 +75,7 @@ }, "homepage": "https://github.com/digitpain/aesthetic.computer#readme", "devDependencies": { + "@geckos.io/client": "^3.0.2", "@swc/core": "^1.15.3", "blessed": "^0.1.81", "chalk": "^5.6.2", @@ -105,6 +106,7 @@ "gif-encoder-2": "^1.0.5", "jszip": "^3.10.1", "mongodb": "^6.20.0", + "node-datachannel": "^0.30.0", "node-fetch": "^3.3.2", "ntp-client": "^0.5.3", "obscenity": "^0.4.5", diff --git a/plans/udp-multiplayer-analysis.md b/plans/udp-multiplayer-analysis.md new file mode 100644 index 0000000000..4388db414c --- /dev/null +++ b/plans/udp-multiplayer-analysis.md @@ -0,0 +1,529 @@ +# Aesthetic Computer Realtime Multiplayer Stack Analysis + +## Executive Summary + +Aesthetic Computer has a **dual-protocol networking architecture** using both WebSockets (reliable, ordered) and WebRTC DataChannels via geckos.io (UDP-like, low-latency). Both protocols connect to a single `session.mjs` monolith. The current `1v1.mjs` game piece uses **only WebSocket** for position updates, leaving the UDP infrastructure underutilized for real-time game data. + +--- + +## 1. Session Server (`session.mjs`) + +### Overview +The session server is a **Fastify-based monolith** that handles: +- WebSocket connections for game clients, chat, and status dashboards +- UDP connections via geckos.io (WebRTC DataChannels) +- Redis pub/sub for cross-instance messaging +- Firebase Cloud Messaging for notifications + +### WebSocket Connection Handling + +```javascript +// Connection tracking +let connectionId = 0; // Incremental ID for WebSocket clients +const connections = {}; // Map of WebSocket connections by ID +const clients = {}; // Unified client tracking: { handle, user, location, websocket: true/false, udp: true/false } + +// On WebSocket connection: +connections[connectionId] = ws; +const id = connectionId; +clients[id].websocket = true; + +// Message handler - relays messages to all clients or specific groups +ws.on("message", (data) => { + const msg = JSON.parse(data.toString()); + msg.id = id; // Attach client identifier + + // Handle different message types (1v1:join, 1v1:move, world:*, etc.) + // Then relay to others + everyone(JSON.stringify(msg)); +}); +``` + +### UDP Support (via geckos.io) + +**Yes, UDP support exists!** The server uses [geckos.io](https://github.com/geckosio/geckos.io) for WebRTC DataChannel connections: + +```javascript +import geckos from "@geckos.io/server"; + +const io = geckos(); +io.addServer(server); // Hook up to the HTTP Server + +// Track UDP channels separately +const udpChannels = {}; + +io.onConnection((channel) => { + udpChannels[channel.id] = { + connectedAt: Date.now(), + state: channel.webrtcConnection.state, + user: null, + handle: null + }; + + // Initialize client record + if (!clients[channel.id]) clients[channel.id] = { udp: true }; + + // Handle identity for linking WebSocket and UDP + channel.on("udp:identity", (data) => { + const identity = JSON.parse(data); + clients[channel.id].user = identity.user?.sub; + clients[channel.id].handle = identity.handle; + }); + + // Current UDP channels (hardcoded): + channel.on("tv", (data) => { channel.room.emit("tv", data); }); + channel.on("fairy:point", (data) => { channel.broadcast.emit("fairy:point", data); }); +}); +``` + +### Player/Client Identification + +Clients are tracked in a unified `clients` object with identity from multiple sources: + +| Property | Source | Description | +|----------|--------|-------------| +| `handle` | Login, message content | User's display name (e.g., `@jas`) | +| `user` | Auth token (`sub`) | Unique user identifier | +| `websocket` | Connection type | `true` if connected via WebSocket | +| `udp` | Connection type | `true` if connected via UDP | +| `ip` | Socket address | Client IP for geolocation | +| `geo` | geoip-lite | Country, region, city, timezone | +| `slug` | `client-slug` | Current piece/slug the user is viewing | + +**Key insight:** WebSocket and UDP connections have **separate IDs** (connectionId for WS, channel.id for UDP). They're linked via the `clients` map using the same `user` or `handle`. + +--- + +## 2. UDP Client Library (`lib/udp.mjs`) + +The client-side UDP library wraps geckos.io: + +```javascript +import Geckos from "../dep/geckos.io-client.2.3.2.min.js"; + +function connect(port = 8889, url = undefined, send) { + channel = Geckos({ url, port }); + + channel.onConnect((error) => { + if (error) { reconnect(); return; } + + send({ type: "udp:connected" }); + connected = true; + + // Send identity for server-side linking + if (window.acUSER || window.acHANDLE) { + channel.emit("udp:identity", JSON.stringify({ + user: window.acUSER, + handle: window.acHANDLE + })); + } + + // Listen for incoming messages + channel.on("tv", (content) => respond("tv", content)); + channel.on("fairy:point", (content) => respond("fairy:point", content)); + }); +} + +export const UDP = { + connect, + disconnect, + send: ({ type, content }) => { + if (connected) channel.emit(type, JSON.stringify(content)); + }, +}; +``` + +--- + +## 3. Client-Side Networking in `disk.mjs` + +### Socket API Exposed to Pieces + +Pieces can access networking through `$commonApi`: + +```javascript +$commonApi.net.socket = function (receive) { + receiver = receive; // Store the piece's message handler + if (!socket) { + startSocket(); + clearTimeout(socketStartDelay); + } else { + // Already connected + if (socket?.id) receiver(socket.id, "connected:already"); + } + return socket; +}; +``` + +### UDP API Exposed to Pieces + +```javascript +// In disk.mjs +let udp = { + send: (type, content) => { + send({ type: "udp:send", content: { type, content } }); + }, + receive: (type, content) => { + // Dispatch to piece's receive handler + udpReceive?.(type, content); + }, + connected: false, + kill: (outageSeconds) => { + udp.connected = false; + send({ type: "udp:disconnect", content: { outageSeconds } }); + }, +}; + +// Pieces can access via: +$commonApi.net.udp = (receive) => { + udpReceive = receive; + return udp; +}; +``` + +### Session Establishment Flow + +```javascript +// 1. Client requests session from Netlify function +const sesh = await session(slug, forceProd, monolith); +// Returns: { url: "https://session-server.aesthetic.computer", udp: "https://udp.aesthetic.computer" } + +// 2. Connect to both protocols +// WebSocket: +socket.connect(url.host + url.pathname, receiver, reload, "wss"); + +// UDP (via bios.mjs): +send({ + type: "udp:connect", + content: { + url: `https://${udpUrl.hostname}`, + port: udpUrl.port, + }, +}); +``` + +--- + +## 4. `1v1.mjs` - Current FPS Game Piece + +### Current Networking Implementation + +The game currently uses **WebSocket only** for multiplayer: + +```javascript +// In boot(): +server = socket((id, type, content) => { + if (type === "left") { + delete others[id]; + delete playerBoxes[id]; + } + + if (type.startsWith("connected")) { + self.id = id; + gameState = "lobby"; + server.send("1v1:join", { handle, pos, rot, health }); + } + + if (type === "1v1:join") { + others[id] = { handle, pos, rot, health }; + // Create camera frustum visualization + } + + if (type === "1v1:move") { + if (others[id]) { + others[id].pos = content.pos; + others[id].rot = content.rot; + } + } +}); + +// In sim() - called every frame: +if (server && gameState === "playing" && graphInstance) { + server.send("1v1:move", { + pos: { x: graphInstance.x, y: graphInstance.y, z: graphInstance.z }, + rot: { x: graphInstance.rotX, y: graphInstance.rotY, z: graphInstance.rotZ }, + }); +} +``` + +### Problems with Current Approach + +1. **High latency**: WebSocket messages go through TCP with head-of-line blocking +2. **Bandwidth waste**: Position updates every frame (~60/sec) over reliable transport +3. **No packet loss tolerance**: Old position data is delivered even when stale + +--- + +## 5. Existing UDP Infrastructure + +### Current UDP Channel Names (Hardcoded in session.mjs) + +| Channel | Purpose | +|---------|---------| +| `tv` | Broadcast to all in room | +| `fairy:point` | Broadcast to all except sender | +| `udp:identity` | Client identification | + +### WebRTC Setup + +The session server uses geckos.io which handles WebRTC signaling automatically: +- ICE candidates exchanged over HTTP +- STUN/TURN servers configured (currently default) +- DataChannels with `ordered: false, maxRetransmits: 0` for UDP-like behavior + +--- + +## 6. Recommendations for UDP Position Updates + +### Option A: Add New UDP Channel (Minimal Changes) + +**Server-side (`session.mjs`):** +```javascript +channel.on("1v1:move", (data) => { + if (channel.webrtcConnection.state === "open") { + try { + // Broadcast to all in the same room except sender + channel.broadcast.emit("1v1:move", data); + } catch (err) { + console.warn("UDP broadcast error:", err); + } + } +}); +``` + +**Client-side (`1v1.mjs`):** +```javascript +// In boot(): +const udpChannel = net.udp((type, content) => { + if (type === "1v1:move" && content.id !== self.id) { + if (others[content.id]) { + others[content.id].pos = content.pos; + others[content.id].rot = content.rot; + } + } +}); + +// In sim(): +if (udpChannel.connected && gameState === "playing") { + udpChannel.send("1v1:move", { + id: self.id, // Include sender ID + pos: self.pos, + rot: self.rot, + seq: frameCount++, // For ordering/staleness detection + }); +} +``` + +### Option B: Hybrid Approach (Best Practice) + +Use WebSocket for: +- Connection/join/leave events +- Combat events (hits, deaths, respawns) +- Chat messages +- Game state changes + +Use UDP for: +- Position/rotation updates +- Velocity updates +- Interpolation hints + +**Linking WebSocket and UDP sessions:** +```javascript +// Client sends same handle/user over both protocols +// Server matches them in the unified `clients` map + +// In 1v1.mjs boot(): +server.send("1v1:join", { handle: self.handle, pos, rot }); +udpChannel.send("1v1:hello", { handle: self.handle }); // Link UDP to same identity +``` + +### Option C: Full Room System (More Work) + +Implement geckos.io rooms for piece-based isolation: + +```javascript +// Server-side +channel.on("1v1:join-room", (data) => { + const { room } = JSON.parse(data); + channel.join(room); +}); + +// Client-side +udpChannel.send("1v1:join-room", { room: "1v1-match-123" }); +``` + +--- + +## 7. Changes Required for UDP Position Updates + +### Minimal Implementation Checklist + +1. **Session Server (`session.mjs`)**: + - Add `1v1:move` channel handler + - Optionally add room system for match isolation + +2. **Client UDP Library (`udp.mjs`)**: + - Add dynamic channel subscription or... + - Hardcode `1v1:move` channel (quick fix) + +3. **`1v1.mjs`**: + - Call `net.udp()` to get UDP handle + - Send position via UDP instead of WebSocket + - Keep WebSocket for join/leave/combat events + +4. **Session API (`session.js`)**: + - Already returns both URLs ✓ + +### Code Changes Summary + +| File | Change | +|------|--------| +| `session.mjs` | Add `channel.on("1v1:move", ...)` handler | +| `udp.mjs` | Add `channel.on("1v1:move", ...)` listener | +| `1v1.mjs` | Use `net.udp()` for position, keep `net.socket()` for events | + +--- + +## 8. Architecture Diagram + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ CLIENT (Browser) │ +├─────────────────────────────────────────────────────────────────┤ +│ 1v1.mjs (Game Piece) │ +│ ├── net.socket() → WebSocket (reliable events) │ +│ └── net.udp() → geckos.io DataChannel (fast position) │ +├─────────────────────────────────────────────────────────────────┤ +│ disk.mjs │ +│ ├── Socket class (WebSocket wrapper) │ +│ └── udp object (sends to bios.mjs) │ +├─────────────────────────────────────────────────────────────────┤ +│ bios.mjs │ +│ └── UDP module (geckos.io client) │ +└─────────────────────────────────────────────────────────────────┘ + │ │ + ▼ ▼ + ┌──────────────────┐ ┌──────────────────┐ + │ WebSocket (TCP) │ │ WebRTC DataChan │ + │ wss://session... │ │ https://udp.... │ + └────────┬─────────┘ └────────┬─────────┘ + │ │ + ▼ ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ SESSION SERVER (Monolith) │ +├─────────────────────────────────────────────────────────────────┤ +│ Fastify HTTP Server │ +│ ├── WebSocketServer (ws) │ +│ │ ├── connections[] - active WS connections │ +│ │ └── Message routing (everyone, others, subscribers) │ +│ │ │ +│ └── geckos.io Server (WebRTC) │ +│ ├── udpChannels{} - active UDP connections │ +│ └── Channel events (tv, fairy:point, etc.) │ +├─────────────────────────────────────────────────────────────────┤ +│ Unified Client Tracking │ +│ clients{} = { handle, user, websocket, udp, ip, geo, ... } │ +├─────────────────────────────────────────────────────────────────┤ +│ Redis (pub/sub for multi-instance) │ +└─────────────────────────────────────────────────────────────────┘ +``` + +--- + +## 9. Key Findings + +1. **UDP infrastructure exists** but is underutilized (only `tv` and `fairy:point` channels) +2. **WebSocket and UDP share identity** via `user` and `handle` in the unified `clients` map +3. **1v1.mjs uses WebSocket for position** - easy to switch to UDP +4. **Channel names are hardcoded** - needs server-side change for new channels +5. **No room system** - all UDP messages broadcast to everyone (fine for small player counts) + +--- + +## 10. Quick Start: Adding UDP to 1v1 + +### Step 1: Server (`session.mjs`) +```javascript +// Add after fairy:point handler +channel.on("1v1:move", (data) => { + if (channel.webrtcConnection.state === "open") { + channel.broadcast.emit("1v1:move", data); + } +}); +``` + +### Step 2: Client UDP lib (`udp.mjs`) +```javascript +// Add in onConnect callback +channel.on("1v1:move", (content) => { + respond("1v1:move", content); +}); +``` + +### Step 3: Game piece (`1v1.mjs`) +```javascript +// In boot(): +const { udp } = net; +udp((type, content) => { + if (type === "1v1:move") { + const parsed = typeof content === 'string' ? JSON.parse(content) : content; + if (parsed.id !== self.id && others[parsed.id]) { + others[parsed.id].pos = parsed.pos; + others[parsed.id].rot = parsed.rot; + } + } +}); + +// In sim(): +if (udp.connected && gameState === "playing") { + udp.send("1v1:move", { id: self.id, pos: self.pos, rot: self.rot }); +} +``` + +--- + +## 11. The WebSocket-UDP Linking Problem + +### Current State +- WebSocket connection gets `connectionId` (incremental integer) +- UDP connection gets `channel.id` (geckos.io generated) +- Both send `handle` and `user` for identity linking +- **But:** They're stored with different IDs in `clients{}` + +### Challenge for 1v1 +When a UDP `1v1:move` comes in, the server doesn't know which WebSocket `connectionId` it maps to unless: +1. The client includes their WebSocket ID in UDP messages (requires exposing `socket.id` to pieces) +2. Server looks up by handle/user (requires O(n) search or secondary index) +3. We create a room system where both protocols join the same room + +### Recommended Solution: Include Handle in UDP Messages + +```javascript +// Client side (1v1.mjs) +udp.send("1v1:move", { + handle: self.handle, // Use handle as the universal identifier + pos: self.pos, + rot: self.rot +}); + +// Server side (session.mjs) +channel.on("1v1:move", (data) => { + // Just broadcast - let clients filter by handle + channel.broadcast.emit("1v1:move", data); +}); + +// Receiving client (1v1.mjs) +if (type === "1v1:move" && content.handle !== self.handle) { + // Find player by handle + const playerId = Object.keys(others).find(id => others[id].handle === content.handle); + if (playerId && others[playerId]) { + others[playerId].pos = content.pos; + others[playerId].rot = content.rot; + } +} +``` + +This works because: +- Handle is set during WebSocket `1v1:join` +- Handle is included in UDP position updates +- Clients match by handle, not connection ID diff --git a/session-server/package-lock.json b/session-server/package-lock.json index 043fb68093..c418ccfbd3 100644 --- a/session-server/package-lock.json +++ b/session-server/package-lock.json @@ -23,6 +23,7 @@ "ws": "^8.18.1" }, "devDependencies": { + "@geckos.io/client": "^3.0.2", "kill-port": "^2.0.1", "nodemon": "^3.1.9", "terminal-kit": "^3.1.2", @@ -53,159 +54,6 @@ "pngjs": "^6.0.0" } }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", - "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", - "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", - "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", - "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", - "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", - "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", - "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", - "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", - "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, "node_modules/@esbuild/linux-arm64": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", @@ -223,227 +71,6 @@ "node": ">=12" } }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", - "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", - "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", - "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", - "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", - "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", - "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", - "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", - "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", - "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", - "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", - "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", - "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", - "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, "node_modules/@fastify/ajv-compiler": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.2.tgz", @@ -642,6 +269,22 @@ "node": ">=20.0.0" } }, + "node_modules/@geckos.io/client": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@geckos.io/client/-/client-3.0.2.tgz", + "integrity": "sha512-nZnhG8IiDBvKKNonguz2sBv4Y8rVpxz5SK9NIvLF7nIUQ2YUUHWcQ4OYBwLUjzSUWdzAjiTP1rPa5azXJw7MRA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@geckos.io/common": "^3.0.2" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/yandeu" + } + }, "node_modules/@geckos.io/common": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/@geckos.io/common/-/common-3.0.2.tgz", @@ -1122,118 +765,6 @@ "@redis/client": "^1.0.0" } }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.53.3.tgz", - "integrity": "sha512-mRSi+4cBjrRLoaal2PnqH82Wqyb+d3HsPUN/W+WslCXsZsyHa9ZeQQX/pQsZaVIWDkPcpV6jJ+3KLbTbgnwv8w==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-android-arm64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.53.3.tgz", - "integrity": "sha512-CbDGaMpdE9sh7sCmTrTUyllhrg65t6SwhjlMJsLr+J8YjFuPmCEjbBSx4Z/e4SmDyH3aB5hGaJUP2ltV/vcs4w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.53.3.tgz", - "integrity": "sha512-Nr7SlQeqIBpOV6BHHGZgYBuSdanCXuw09hon14MGOLGmXAFYjx1wNvquVPmpZnl0tLjg25dEdr4IQ6GgyToCUA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.53.3.tgz", - "integrity": "sha512-DZ8N4CSNfl965CmPktJ8oBnfYr3F8dTTNBQkRlffnUarJ2ohudQD17sZBa097J8xhQ26AwhHJ5mvUyQW8ddTsQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.53.3.tgz", - "integrity": "sha512-yMTrCrK92aGyi7GuDNtGn2sNW+Gdb4vErx4t3Gv/Tr+1zRb8ax4z8GWVRfr3Jw8zJWvpGHNpss3vVlbF58DZ4w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.53.3.tgz", - "integrity": "sha512-lMfF8X7QhdQzseM6XaX0vbno2m3hlyZFhwcndRMw8fbAGUGL3WFMBdK0hbUBIUYcEcMhVLr1SIamDeuLBnXS+Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.53.3.tgz", - "integrity": "sha512-k9oD15soC/Ln6d2Wv/JOFPzZXIAIFLp6B+i14KhxAfnq76ajt0EhYc5YPeX6W1xJkAdItcVT+JhKl1QZh44/qw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.53.3.tgz", - "integrity": "sha512-vTNlKq+N6CK/8UktsrFuc+/7NlEYVxgaEgRXVUVK258Z5ymho29skzW1sutgYjqNnquGwVUObAaxae8rZ6YMhg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, "node_modules/@rollup/rollup-linux-arm64-gnu": { "version": "4.53.3", "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.53.3.tgz", @@ -1262,174 +793,6 @@ "linux" ] }, - "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.53.3.tgz", - "integrity": "sha512-JiuKcp2teLJwQ7vkJ95EwESWkNRFJD7TQgYmCnrPtlu50b4XvT5MOmurWNrCj3IFdyjBQ5p9vnrX4JM6I8OE7g==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.53.3.tgz", - "integrity": "sha512-EoGSa8nd6d3T7zLuqdojxC20oBfNT8nexBbB/rkxgKj5T5vhpAQKKnD+h3UkoMuTyXkP5jTjK/ccNRmQrPNDuw==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.53.3.tgz", - "integrity": "sha512-4s+Wped2IHXHPnAEbIB0YWBv7SDohqxobiiPA1FIWZpX+w9o2i4LezzH/NkFUl8LRci/8udci6cLq+jJQlh+0g==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.53.3.tgz", - "integrity": "sha512-68k2g7+0vs2u9CxDt5ktXTngsxOQkSEV/xBbwlqYcUrAVh6P9EgMZvFsnHy4SEiUl46Xf0IObWVbMvPrr2gw8A==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.53.3.tgz", - "integrity": "sha512-VYsFMpULAz87ZW6BVYw3I6sWesGpsP9OPcyKe8ofdg9LHxSbRMd7zrVrr5xi/3kMZtpWL/wC+UIJWJYVX5uTKg==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.3.tgz", - "integrity": "sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.3.tgz", - "integrity": "sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.53.3.tgz", - "integrity": "sha512-OueLAWgrNSPGAdUdIjSWXw+u/02BRTcnfw9PN41D2vq/JSEPnJnVuBgw18VkN8wcd4fjUs+jFHVM4t9+kBSNLw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ] - }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.53.3.tgz", - "integrity": "sha512-GOFuKpsxR/whszbF/bzydebLiXIHSgsEUp6M0JI8dWvi+fFa1TD6YQa4aSZHtpmh2/uAlj/Dy+nmby3TJ3pkTw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.53.3.tgz", - "integrity": "sha512-iah+THLcBJdpfZ1TstDFbKNznlzoxa8fmnFYK4V67HvmuNYkVdAywJSoteUszvBQ9/HqN2+9AZghbajMsFT+oA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.53.3.tgz", - "integrity": "sha512-J9QDiOIZlZLdcot5NXEepDkstocktoVjkaKUtqzgzpt2yWjGlbYiKyp05rWwk4nypbYUNoFAztEgixoLaSETkg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.53.3.tgz", - "integrity": "sha512-UhTd8u31dXadv0MopwGgNOBpUVROFKWVQgAg5N1ESyCz8AuBcMqm4AuTjrwgQKGDfoFuz02EuMRHQIw/frmYKQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, "node_modules/@tootallnate/once": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", @@ -3118,20 +2481,6 @@ "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", "license": "ISC" }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", diff --git a/session-server/package.json b/session-server/package.json index d781cc2789..aed2816400 100644 --- a/session-server/package.json +++ b/session-server/package.json @@ -36,6 +36,7 @@ "ws": "^8.18.1" }, "devDependencies": { + "@geckos.io/client": "^3.0.2", "kill-port": "^2.0.1", "nodemon": "^3.1.9", "terminal-kit": "^3.1.2", diff --git a/session-server/session.mjs b/session-server/session.mjs index d37554b43e..5af489f122 100644 --- a/session-server/session.mjs +++ b/session-server/session.mjs @@ -1642,6 +1642,18 @@ io.onConnection((channel) => { console.log(channel.webrtcConnection.state); } }); + + // 🎮 1v1 FPS game position updates over UDP (low latency) + channel.on("1v1:move", (data) => { + if (channel.webrtcConnection.state === "open") { + try { + // Broadcast position to all other players except sender + channel.broadcast.emit("1v1:move", data); + } catch (err) { + console.warn("1v1:move broadcast error:", err); + } + } + }); }); // #endregion diff --git a/system/public/aesthetic.computer/dep/geckos.io-client.3.0.2.min.js b/system/public/aesthetic.computer/dep/geckos.io-client.3.0.2.min.js new file mode 100644 index 0000000000..373aff478d --- /dev/null +++ b/system/public/aesthetic.computer/dep/geckos.io-client.3.0.2.min.js @@ -0,0 +1 @@ +var geckos;(()=>{"use strict";var e={d:(t,n)=>{for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>y});class n{fn;context;once;constructor(e,t,n=!1){this.fn=e,this.context=t,this.once=n}}const o=(e,t,o,s,r)=>{if("function"!=typeof o)throw new TypeError("The listener must be a function");const i=new n(o,s||e,r);return e._events.has(t)?e._events.get(t).fn?e._events.set(t,[e._events.get(t),i]):e._events.get(t).push(i):(e._events.set(t,i),e._eventsCount++),e},s=(e,t)=>{0==--e._eventsCount?e._events=new Map:e._events.delete(t)};class r{static get VERSION(){return"0.0.7"}_events=new Map;_eventsCount=0;eventNames(){return Array.from(this._events.keys())}listeners(e){const t=this._events.get(e);if(!t)return[];if(t.fn)return[t.fn];for(var n=0,o=t.length,s=new Array(o);n{t(e,n)}))}removeAllListeners(){this.eventEmitter.removeAllListeners()}}new i;const a="disconnected",c="rawMessage",l="BROWSER_NOT_SUPPORTED",h="COULD_NOT_PARSE_MESSAGE",d=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor,u=("function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,e=>"string"==typeof e),f=e=>e instanceof ArrayBuffer||e instanceof d,g=e=>{let{data:t}=e;t||(t=e);const n=f(t),o=(e=>{try{return"string"==typeof e&&!!isNaN(parseInt(e))&&(JSON.parse(e),!0)}catch(e){return!1}})(t),s=u(t);if(o){const e=JSON.parse(t),n=Object.keys(e)[0];return{key:n,data:e[n]}}return n||s?{key:c,data:t}:{key:"error",data:new Error(h)}};class v{emit(e,t=null){((e,t,n,o=null)=>{var s;const r=(n,o)=>{var s;const r=null!==(s=n.byteLength)&&void 0!==s?s:2*n.length;if("number"==typeof t&&r>t)throw new Error(`maxMessageSize of ${t} exceeded`);Promise.resolve().then((()=>{e.send?e.send(n):o?e.sendMessageBinary(Buffer.from(n)):e.sendMessage(n)})).catch((e=>{console.log("error",e)}))};if(e&&("open"===e.readyState||(null===(s=e.isOpen)||void 0===s?void 0:s.call(e))))try{n===c&&null!==o&&(u(o)||f(o))?r(o,f(o)):r(JSON.stringify({[n]:o}),!1)}catch(e){return console.error("Error in sendMessage.ts: ",e.message),e}})(this.dataChannel,this.maxMessageSize,e,t)}constructor(e,t,n,o){this.url=e,this.authorization=t,this.label=n,this.rtcConfiguration=o,this.bridge=new i,this.onDataChannel=e=>{const{channel:t}=e;t.label===this.label&&(this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onmessage=e=>{const{key:t,data:n}=g(e);this.bridge.emit(t,n)})}}async fetchAdditionalCandidates(e,t){var n;if("closed"===(null===(n=this.dataChannel)||void 0===n?void 0:n.readyState))return;const o=await fetch(`${e}/connections/${t}/additional-candidates`,{method:"GET",headers:{"Content-Type":"application/json"}});if(o.ok){(await o.json()).forEach((e=>{this.localPeerConnection.addIceCandidate(e)}))}}async connect(){const e=`${this.url}/.wrtc/v2`;let t={"Content-Type":"application/json"};this.authorization&&(t={...t,Authorization:this.authorization});let n={};try{const o=await fetch(`${e}/connections`,{method:"POST",headers:t});if(o.status>=300)throw{name:"Error",message:`Connection failed with status code ${o.status}.`,status:o.status,statusText:o.statusText};const s=await o.json();n=s.userData,this.remotePeerConnection=s}catch(e){return console.error(e.message),{error:e}}const{id:o,localDescription:s}=this.remotePeerConnection,r={sdpSemantics:"unified-plan",...this.rtcConfiguration},i=RTCPeerConnection||webkitRTCPeerConnection;this.localPeerConnection=new i(r);((e=10,t=50,n=1.8,o=20)=>Array(e).fill(0).map(((e,s)=>parseInt((t*n**s).toString())+parseInt((Math.random()*o).toString()))))().forEach((t=>{setTimeout((()=>{this.fetchAdditionalCandidates(e,o).catch((()=>{}))}),t)}));try{await this.localPeerConnection.setRemoteDescription(s),this.localPeerConnection.addEventListener("datachannel",this.onDataChannel,{once:!0});const t=await this.localPeerConnection.createAnswer(),r=new RTCSessionDescription({type:"answer",sdp:t.sdp});await this.localPeerConnection.setLocalDescription(r);try{await fetch(`${e}/connections/${o}/remote-description`,{method:"POST",body:JSON.stringify(this.localPeerConnection.localDescription),headers:{"Content-Type":"application/json"}})}catch(e){return console.error(e.message),{error:e}}const i=()=>new Promise((e=>{this.localPeerConnection.addEventListener("datachannel",(()=>{e()}),{once:!0})}));return this.dataChannel||await i(),{userData:n,localPeerConnection:this.localPeerConnection,dataChannel:this.dataChannel,id:o}}catch(e){return console.error(e.message),this.localPeerConnection.close(),{error:e}}}}class m{async connect(e){if(RTCPeerConnection||webkitRTCPeerConnection){const{localPeerConnection:t,dataChannel:n,id:o,userData:s,error:r}=await e.connect();return r?{error:r}:t&&n&&o&&s?(this.localPeerConnection=t,this.dataChannel=n,this.id=o,{userData:s}):{error:new Error('Something went wrong in "await connectionsManager.connect()"')}}{const e=new Error(l);return console.error(e.message),{error:e}}}}const p=(e,t)=>{const{interval:n=150,runs:o=10}=e,s=((e=24)=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let n="";for(let o=0;o{let o=0;if("function"!=typeof n)return void console.error("You have to define your callback function!");const s=setInterval((()=>{n(),o++,o===t-1&&clearInterval(s)}),e);n()})(n,o,(()=>{t(s)}))};class C{constructor(e,t,n,o,s){this.userData={},this.receivedReliableMessages=[],this.url=n?`${e}:${n}`:e,this.connectionsManager=new v(this.url,t,o,s),this.bridge=this.connectionsManager.bridge,this.bridge.on(a,(()=>this.bridge.removeAllListeners()))}onconnectionstatechange(){const e=this.peerConnection.localPeerConnection;e.onconnectionstatechange=()=>{"disconnected"!==e.connectionState&&"closed"!==e.connectionState||this.bridge.emit(a)}}get id(){return this.peerConnection.id}close(){this.peerConnection.localPeerConnection.close(),this.bridge.emit(a);try{const e=`${this.url}/.wrtc/v2`;fetch(`${e}/connections/${this.id}/close`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch(e){console.error(e.message)}}emit(e,t=null,n){n&&n.reliable?p(n,(n=>this.connectionsManager.emit(e,{MESSAGE:t,RELIABLE:1,ID:n}))):this.connectionsManager.emit(e,t)}get raw(){return{emit:e=>this.emit(c,e)}}onRaw(e){this.bridge.on(c,(t=>{(t=>{e(t)})(t)}))}async onConnect(e){var t;this.peerConnection=new m;const n=await this.peerConnection.connect(this.connectionsManager);n.error?e(n.error):(n.userData&&(this.userData=n.userData),this.maxMessageSize=this.connectionsManager.maxMessageSize=null===(t=this.peerConnection.localPeerConnection.sctp)||void 0===t?void 0:t.maxMessageSize,this.onconnectionstatechange(),e())}onDisconnect(e){this.bridge.on(a,e)}on(e,t){this.bridge.on(e,(e=>{e&&1===e.RELIABLE&&"undefined"!==e.ID?((()=>{const e=(new Date).getTime();this.receivedReliableMessages.forEach(((t,n,o)=>{t.expire<=e&&o.splice(n,1)}))})(),0===this.receivedReliableMessages.filter((t=>t.id===e.ID)).length&&(this.receivedReliableMessages.push({id:e.ID,timestamp:new Date,expire:(new Date).getTime()+15e3}),t(e.MESSAGE))):t(e)}))}}const y=(e={})=>{const{authorization:t,iceServers:n=[],iceTransportPolicy:o="all",label:s="geckos.io",port:r=9208,url:i=`${location.protocol}//${location.hostname}`}=e;return new C(i,t,r,s,{iceServers:n,iceTransportPolicy:o})};geckos=t.default})(); \ No newline at end of file diff --git a/system/public/aesthetic.computer/disks/1v1.mjs b/system/public/aesthetic.computer/disks/1v1.mjs index c344616e1c..d45d7d8a20 100644 --- a/system/public/aesthetic.computer/disks/1v1.mjs +++ b/system/public/aesthetic.computer/disks/1v1.mjs @@ -51,6 +51,9 @@ let paintingTextureLoaded = false; // Track if we've loaded the painting let globalSign; let globalGlyphs; +// 🩰 UDP channel for low-latency position updates +let udpChannel; + // Combat const SHOOT_COOLDOWN = 200; // ms between shots const DAMAGE_PER_HIT = 20; @@ -154,8 +157,8 @@ function logSceneDebug() { } -function boot({ Form, CUBEL, QUAD, penLock, system, get, net: { socket }, handle, help, sign, glyphs }) { - console.log("🎮 1v1 boot", { hasForm: !!Form, hasSocket: !!socket, hasHandle: !!handle, hasSign: !!sign }); +function boot({ Form, CUBEL, QUAD, penLock, system, get, net: { socket, udp }, handle, help, sign, glyphs }) { + console.log("🎮 1v1 boot", { hasForm: !!Form, hasSocket: !!socket, hasHandle: !!handle, hasSign: !!sign, hasUdp: !!udp }); // Store sign and glyphs for use in networking callbacks globalSign = sign; @@ -170,7 +173,32 @@ function boot({ Form, CUBEL, QUAD, penLock, system, get, net: { socket }, handle // Set player handle self.handle = handle() || help.choose("red", "blue", "green", "yellow") + "_player"; - // Initialize networking + // 🩰 Initialize UDP for low-latency position updates + udpChannel = udp((type, content) => { + if (type === "1v1:move") { + // Parse content if it's a string + const data = typeof content === 'string' ? JSON.parse(content) : content; + + // Find player by handle (UDP doesn't use WebSocket IDs) + if (data.handle && data.handle !== self.handle) { + const playerId = Object.keys(others).find(id => others[id].handle === data.handle); + if (playerId && others[playerId]) { + others[playerId].pos = data.pos; + others[playerId].rot = data.rot; + + // Update player box position + if (playerBoxes[playerId]) { + playerBoxes[playerId].position = [data.pos.x, data.pos.y, data.pos.z]; + } + } + } + } + }); + console.log("🩰 UDP channel initialized for position updates"); + + // Initialize WebSocket networking (for reliable events: join/leave/combat) + + // Initialize WebSocket networking (for reliable events: join/leave/combat) server = socket((id, type, content) => { if (type === "left") { console.log("👋 Player left:", id); @@ -318,6 +346,7 @@ function boot({ Form, CUBEL, QUAD, penLock, system, get, net: { socket }, handle gameState = "playing"; } + // WebSocket fallback for position (UDP is primary, but WS works if UDP fails) if (type === "1v1:move") { if (others[id]) { others[id].pos = content.pos; @@ -518,8 +547,8 @@ function boot({ Form, CUBEL, QUAD, penLock, system, get, net: { socket }, handle } function sim() { - // Network update - send position every frame (throttled on server if needed) - if (server && gameState === "playing" && graphInstance) { + // Network update - send position via UDP for low latency + if (gameState === "playing" && graphInstance) { self.pos = { x: graphInstance.x, y: graphInstance.y, @@ -531,10 +560,14 @@ function sim() { z: graphInstance.rotZ }; - server.send("1v1:move", { - pos: self.pos, - rot: self.rot, - }); + // 🩰 Send position over UDP (low latency, unreliable but fast) + if (udpChannel?.connected) { + udpChannel.send("1v1:move", { + handle: self.handle, // Use handle to identify player (links WS and UDP) + pos: self.pos, + rot: self.rot, + }); + } } // Rotate the cube around its local center diff --git a/system/public/aesthetic.computer/lib/udp.mjs b/system/public/aesthetic.computer/lib/udp.mjs index 2bb27fa73d..eb85ac3518 100644 --- a/system/public/aesthetic.computer/lib/udp.mjs +++ b/system/public/aesthetic.computer/lib/udp.mjs @@ -1,4 +1,4 @@ -import Geckos from "../dep/geckos.io-client.2.3.2.min.js"; +import Geckos from "../dep/geckos.io-client.3.0.2.min.js"; import { logs } from "./logs.mjs"; /* #region 🏁 todo @@ -78,6 +78,11 @@ function connect(port = 8889, url = undefined, send) { channel.on("fairy:point", (content) => { respond("fairy:point", content); }); + + // 🎮 1v1 FPS game position updates + channel.on("1v1:move", (content) => { + respond("1v1:move", content); + }); }); channel.onDisconnect((error) => { diff --git a/tests/udp-geckos-test.mjs b/tests/udp-geckos-test.mjs new file mode 100644 index 0000000000..55c2cc847f --- /dev/null +++ b/tests/udp-geckos-test.mjs @@ -0,0 +1,209 @@ +#!/usr/bin/env node +// UDP Multiplayer Test Script (geckos.io / WebRTC DataChannel) +// Tests the 1v1:move channel via UDP on localhost session server +// +// Usage: +// cd session-server && npm run dev # Start session server first +// node tests/udp-geckos-test.mjs +// +// This script tests the actual UDP path using geckos.io client in Node.js + +// Allow self-signed certificates for local development +if (process.env.SESSION_HOST?.includes("localhost") || !process.env.SESSION_HOST) { + process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; +} + +// Polyfill WebRTC for Node.js (required for geckos.io v3) +import * as nodeDataChannel from "node-datachannel/polyfill"; +// Set globals for geckos.io client +globalThis.RTCPeerConnection = nodeDataChannel.RTCPeerConnection; +globalThis.RTCSessionDescription = nodeDataChannel.RTCSessionDescription; +globalThis.RTCIceCandidate = nodeDataChannel.RTCIceCandidate; + +import geckos from "@geckos.io/client"; + +const SESSION_HOST = process.env.SESSION_HOST || "https://localhost"; +const SESSION_PORT = parseInt(process.env.SESSION_PORT || "8889"); +const NUM_FAKE_PLAYERS = 2; +const UPDATE_INTERVAL_MS = 50; // 20 updates per second +const TEST_DURATION_MS = 5000; + +console.log("🧪 UDP Multiplayer Test (geckos.io / WebRTC)"); +console.log("============================================="); +console.log(`📡 Connecting to: ${SESSION_HOST}:${SESSION_PORT}`); +console.log(`👥 Simulating ${NUM_FAKE_PLAYERS} players\n`); + +const players = []; + +class FakePlayer { + constructor(id) { + this.id = id; + this.handle = `udp_test_${id}`; + this.pos = { x: Math.random() * 10 - 5, y: 1.6, z: Math.random() * 10 - 5 }; + this.rot = { x: 0, y: Math.random() * 360, z: 0 }; + this.channel = null; + this.connected = false; + this.receivedMoves = 0; + this.sentMoves = 0; + } + + async connect() { + return new Promise((resolve, reject) => { + // geckos.io client for Node.js + this.channel = geckos({ + url: SESSION_HOST, + port: SESSION_PORT, + // Empty ICE servers for local testing + iceServers: [] + }); + + const timeout = setTimeout(() => { + reject(new Error(`Player ${this.id} UDP connection timeout`)); + }, 15000); + + this.channel.onConnect((error) => { + clearTimeout(timeout); + + if (error) { + console.error(`❌ Player ${this.id} failed to connect:`, error.message || error); + reject(error); + return; + } + + this.connected = true; + console.log(`✅ Player ${this.id} (${this.handle}) UDP connected via WebRTC`); + + // Send identity + this.channel.emit("udp:identity", JSON.stringify({ + user: { sub: `test-user-${this.id}` }, + handle: this.handle + })); + + // Listen for moves from other players + this.channel.on("1v1:move", (data) => { + this.receivedMoves++; + try { + const parsed = typeof data === "string" ? JSON.parse(data) : data; + if (this.receivedMoves <= 3 || this.receivedMoves % 50 === 0) { + console.log(`📨 Player ${this.id} received UDP move from ${parsed.handle}:`, + `pos(${parsed.pos.x.toFixed(2)}, ${parsed.pos.y.toFixed(2)}, ${parsed.pos.z.toFixed(2)})`); + } + } catch (e) { + // Ignore parse errors + } + }); + + resolve(); + }); + + this.channel.onDisconnect(() => { + this.connected = false; + console.log(`🔌 Player ${this.id} UDP disconnected`); + }); + }); + } + + sendPosition() { + if (!this.connected || !this.channel) return; + + // Simulate movement + this.pos.x += (Math.random() - 0.5) * 0.1; + this.pos.z += (Math.random() - 0.5) * 0.1; + this.rot.y += Math.random() * 2; + + this.channel.emit("1v1:move", JSON.stringify({ + handle: this.handle, + pos: this.pos, + rot: this.rot + })); + this.sentMoves++; + } + + disconnect() { + if (this.channel) { + this.channel.close(); + this.connected = false; + } + } + + getStats() { + return { + id: this.id, + handle: this.handle, + connected: this.connected, + sentMoves: this.sentMoves, + receivedMoves: this.receivedMoves + }; + } +} + +async function runTest() { + // Create fake players + for (let i = 0; i < NUM_FAKE_PLAYERS; i++) { + players.push(new FakePlayer(i)); + } + + // Connect all players + console.log("🔗 Connecting players via UDP...\n"); + try { + await Promise.all(players.map(p => p.connect())); + } catch (err) { + console.error("❌ Failed to connect all players:", err.message); + console.error("\n💡 Make sure the session server is running: cd session-server && npm run dev"); + process.exit(1); + } + + console.log("\n✅ All players connected via UDP!\n"); + console.log("📤 Starting position updates...\n"); + + // Start sending position updates + const updateInterval = setInterval(() => { + players.forEach(p => p.sendPosition()); + }, UPDATE_INTERVAL_MS); + + // Run for test duration then print stats + await new Promise(resolve => setTimeout(resolve, TEST_DURATION_MS)); + + clearInterval(updateInterval); + + console.log("\n📊 UDP Test Results:"); + console.log("===================="); + players.forEach(p => { + const stats = p.getStats(); + console.log(`Player ${stats.id} (${stats.handle}): sent ${stats.sentMoves}, received ${stats.receivedMoves} moves`); + }); + + // Calculate expected moves + const expectedSentPerPlayer = TEST_DURATION_MS / UPDATE_INTERVAL_MS; + const expectedReceivedPerPlayer = expectedSentPerPlayer * (NUM_FAKE_PLAYERS - 1); + + console.log(`\n📈 Expected sent per player: ~${expectedSentPerPlayer}`); + console.log(`📈 Expected received per player: ~${expectedReceivedPerPlayer}`); + + const avgReceived = players.reduce((sum, p) => sum + p.getStats().receivedMoves, 0) / players.length; + const successRate = (avgReceived / expectedReceivedPerPlayer * 100).toFixed(1); + console.log(`📈 Average received: ${avgReceived.toFixed(0)} (${successRate}% success rate)`); + + if (avgReceived > 0) { + console.log("\n✅ UDP communication working!"); + } else { + console.log("\n⚠️ No UDP messages received - check server 1v1:move handler"); + } + + // Cleanup + console.log("\n🧹 Cleaning up..."); + players.forEach(p => p.disconnect()); + + console.log("✅ Test complete!\n"); + + // Give time for cleanup + setTimeout(() => process.exit(0), 500); +} + +// Handle errors +process.on("unhandledRejection", (err) => { + console.error("❌ Unhandled error:", err); + process.exit(1); +}); + +runTest(); diff --git a/tests/udp-multiplayer-test.mjs b/tests/udp-multiplayer-test.mjs new file mode 100644 index 0000000000..320b1f72b9 --- /dev/null +++ b/tests/udp-multiplayer-test.mjs @@ -0,0 +1,195 @@ +#!/usr/bin/env node +// UDP Multiplayer Test Script (WebSocket Version) +// Tests the 1v1:move channel via WebSocket on localhost session server +// +// Note: This tests via WebSocket since geckos.io client requires a browser. +// The actual UDP path is tested by running the game in two browser windows. +// +// Usage: +// cd session-server && npm run dev # Start session server first +// node tests/udp-multiplayer-test.mjs + +import WebSocket from "ws"; + +const SESSION_URL = process.env.SESSION_URL || "wss://localhost:8889"; +const NUM_FAKE_PLAYERS = 2; +const UPDATE_INTERVAL_MS = 50; // 20 updates per second + +console.log("🧪 Multiplayer Position Test (WebSocket)"); +console.log("========================================="); +console.log(`📡 Connecting to: ${SESSION_URL}`); +console.log(`👥 Simulating ${NUM_FAKE_PLAYERS} players\n`); +console.log("ℹ️ Note: This tests WebSocket path. For UDP, test with two browser windows.\n"); + +const players = []; + +class FakePlayer { + constructor(id) { + this.id = id; + this.handle = `test_player_${id}`; + this.pos = { x: Math.random() * 10 - 5, y: 1.6, z: Math.random() * 10 - 5 }; + this.rot = { x: 0, y: Math.random() * 360, z: 0 }; + this.ws = null; + this.connected = false; + this.receivedMoves = 0; + this.wsId = null; + } + + async connect() { + return new Promise((resolve, reject) => { + this.ws = new WebSocket(SESSION_URL); + + const timeout = setTimeout(() => { + reject(new Error(`Player ${this.id} connection timeout`)); + }, 10000); + + this.ws.on("open", () => { + clearTimeout(timeout); + this.connected = true; + console.log(`✅ Player ${this.id} (${this.handle}) WebSocket connected`); + }); + + this.ws.on("message", (data) => { + try { + const msg = JSON.parse(data.toString()); + + // Handle connection acknowledgment + if (msg.type === "connected" || msg.type === "connected:already") { + this.wsId = msg.id; + console.log(`🆔 Player ${this.id} assigned WebSocket ID: ${this.wsId}`); + + // Send join message + this.send("1v1:join", { + handle: this.handle, + pos: this.pos, + rot: this.rot, + health: 100 + }); + resolve(); + } + + // Handle moves from other players + if (msg.type === "1v1:move" && msg.id !== this.wsId) { + this.receivedMoves++; + if (this.receivedMoves <= 3 || this.receivedMoves % 100 === 0) { + console.log(`📨 Player ${this.id} received move from ${msg.id}:`, + `pos(${msg.content.pos.x.toFixed(2)}, ${msg.content.pos.y.toFixed(2)}, ${msg.content.pos.z.toFixed(2)})`); + } + } + + // Handle join from other players + if (msg.type === "1v1:join" && msg.id !== this.wsId) { + console.log(`👋 Player ${this.id} sees ${msg.content.handle} joined`); + } + } catch (e) { + // Ignore non-JSON messages + } + }); + + this.ws.on("error", (err) => { + console.error(`❌ Player ${this.id} WebSocket error:`, err.message); + reject(err); + }); + + this.ws.on("close", () => { + this.connected = false; + console.log(`🔌 Player ${this.id} disconnected`); + }); + }); + } + + send(type, content) { + if (!this.connected || !this.ws) return; + this.ws.send(JSON.stringify({ type, content })); + } + + sendPosition() { + if (!this.connected) return; + + // Simulate movement + this.pos.x += (Math.random() - 0.5) * 0.1; + this.pos.z += (Math.random() - 0.5) * 0.1; + this.rot.y += Math.random() * 2; + + this.send("1v1:move", { + pos: this.pos, + rot: this.rot + }); + } + + disconnect() { + if (this.ws) { + this.ws.close(); + this.connected = false; + } + } + + getStats() { + return { + id: this.id, + handle: this.handle, + wsId: this.wsId, + connected: this.connected, + receivedMoves: this.receivedMoves + }; + } +} + +async function runTest() { + // Create fake players + for (let i = 0; i < NUM_FAKE_PLAYERS; i++) { + players.push(new FakePlayer(i)); + } + + // Connect all players + console.log("🔗 Connecting players...\n"); + try { + await Promise.all(players.map(p => p.connect())); + } catch (err) { + console.error("❌ Failed to connect all players:", err.message); + process.exit(1); + } + + console.log("\n✅ All players connected!\n"); + console.log("📤 Starting position updates...\n"); + + // Start sending position updates + const updateInterval = setInterval(() => { + players.forEach(p => p.sendPosition()); + }, UPDATE_INTERVAL_MS); + + // Run for 5 seconds then print stats + await new Promise(resolve => setTimeout(resolve, 5000)); + + clearInterval(updateInterval); + + console.log("\n📊 Test Results:"); + console.log("================"); + players.forEach(p => { + const stats = p.getStats(); + console.log(`Player ${stats.id} (${stats.handle}): ${stats.receivedMoves} moves received`); + }); + + // Calculate expected moves + const expectedMovesPerPlayer = (5000 / UPDATE_INTERVAL_MS) * (NUM_FAKE_PLAYERS - 1); + console.log(`\n📈 Expected moves per player: ~${expectedMovesPerPlayer}`); + + const avgReceived = players.reduce((sum, p) => sum + p.getStats().receivedMoves, 0) / players.length; + const successRate = (avgReceived / expectedMovesPerPlayer * 100).toFixed(1); + console.log(`📈 Average received: ${avgReceived.toFixed(0)} (${successRate}% success rate)`); + + // Cleanup + console.log("\n🧹 Cleaning up..."); + players.forEach(p => p.disconnect()); + + console.log("✅ Test complete!\n"); + process.exit(0); +} + +// Handle errors +process.on("unhandledRejection", (err) => { + console.error("❌ Unhandled error:", err); + process.exit(1); +}); + +runTest(); -- knotmirror 0.0.1