commit 44f4e564b17375cce4edc54a20fc0cf18cfbc4c1 Author: unknown Date: Sun Mar 8 03:34:30 2026 -0400 Initial commit diff --git a/.assets/screenshot1.png b/.assets/screenshot1.png new file mode 100644 index 0000000..967043b Binary files /dev/null and b/.assets/screenshot1.png differ diff --git a/.assets/screenshot2.png b/.assets/screenshot2.png new file mode 100644 index 0000000..f8762b1 Binary files /dev/null and b/.assets/screenshot2.png differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40b878d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules/ \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..dc92764 --- /dev/null +++ b/README.md @@ -0,0 +1,187 @@ +# Legacy Cross Play + +**This project allows Legacy Console Edition clients to join a vanilla 1.8 Java Edition server!** +![](https://raw.githubusercontent.com/DeveloperExotic/LegacyCrossPlay/refs/heads/main/.assets/screenshot1.png) +![](https://raw.githubusercontent.com/DeveloperExotic/LegacyCrossPlay/refs/heads/main/.assets/screenshot2.png) + +# How to Install + +**Code modifications to the client source code is required for multiplayer to function properly** + +- Install [NodeJS](https://nodejs.org/en/download), you may need to restart your computer after +- Start a localhost Java Edition server running on port 25564, and in offline mode (you can edit these in `server.properties`) +- Run the file `install_dependencies.bat`, - you only need to run this file one time. +- Run `start.bat`, the Java Edition server will appear in the join tab on Legacy Console Edition! You can configure the server IP / PORT in `constants.js`. + +# Known issues, will be fixed + +- You're unable to dismount while riding +- Chunk lighting is always lit +- Death animation plays when a Java player leaves +- You're unable to craft in survival mode +- You're unable to accept villager trades + +--- + +# TODO + +## Chunks + +- [x] Java → LCE chunks + - [x] Blocks + - [x] Metadata + - [x] Lighting + - [x] Biomes + +## Inventory Syncing + +- [x] Held item +- [x] Item dropping +- [x] Creative items +- [x] Creative clear +- [x] Moved items + +## Sync Gamemode / XP / Health / Hunger + +- [x] Damage knockback / sound + +## Respawn + +- [x] Death animation +- [x] Respawn handling + +## Environment + +### Time + +- [x] Sync Time +- [x] DoDaylightCycle fix + +### Weather + +- [x] Sync Weather + +## Sound + +- [x] Sound effects + +--- + +# Entities + +## Base Entities + +- [x] Java edition players +- [x] Items +- [x] Mobs + +### Mob Features + +- [x] Ageable entities +- [x] Entity metadata (e.g. size, type) +- [x] Nametags +- [x] Mob inventory +- [x] Animations (e.g. bats) + +## Entity Attachments + +- [x] Attach to entities (e.g. riding pig, minecart, boat) + +### Damage Translation + +#### LCE Damage → Java Entity + +- [x] Entity +- [x] Player + +#### Java Damage → LCE Entity + +- [x] Mobs +- [x] Players +- [x] Hurt sound +- [x] Entity velocity knockback + +### Critical Hits + +- [x] Normal critical +- [x] Magical critical + +### Other Entity Systems + +- [x] Fix minecart metadata (e.g. tnt minecart) +- [x] Arrows + - [x] Fix arrow bug when colliding with player / low bow pull +- [x] Falling block entities (e.g. sand, gravel, anvil) +- [x] Fireball + +--- + +# Server + +## Chat + +- [x] Receive server chat +- [x] Send server chat +- [x] Fix chat commands (e.g. /say, /tellraw) +- [x] Java edition english chat translations + +## Disconnections + +- [x] Our LCE client disconnects +- [ ] Our java player disconnects + +--- + +# Player Animations + +## LCE → Java + +- [x] Crouch +- [x] Sprint +- [x] Attack (swing) +- [x] Riding +- [x] Sword blocking + +## Java → LCE + +- [x] Crouch +- [x] Sprint +- [x] Attack + - [x] Entity + - [x] Player +- [x] Eating +- [x] Sleeping + +--- + +# Block Updates + +## Java → LCE + +- [x] Creative +- [x] Survival +- [x] Explosions + +## LCE → Java + +- [x] Creative +- [x] Survival + +--- + +# World + +- [x] Particles +- [x] Nether and End dimensions + +--- + +# UI + +- [ ] Crafting _(Hard to implement, may require server plugin)_ +- [ ] Brewing stand +- [ ] Furnace +- [x] Villager trading + - [ ] Accept trade _(Hard to implement, may require server plugin)_ +- [x] Anvils +- [x] Chests \ No newline at end of file diff --git a/constants.js b/constants.js new file mode 100644 index 0000000..f0d9e0d --- /dev/null +++ b/constants.js @@ -0,0 +1,17 @@ +const GAME_PORT = 25565; +const WIN64_LAN_DISCOVERY_PORT = 25566; +const MINECRAFT_NET_VERSION = 560; +const JAVA_SERVER_HOST = "localhost"; +const JAVA_SERVER_PORT = 25564; +const PROXY_NAME = JAVA_SERVER_HOST + ":" + JAVA_SERVER_PORT; + +module.exports = { + GAME_PORT, + WIN64_LAN_DISCOVERY_PORT, + MINECRAFT_NET_VERSION, + USE_LEGACY_USERNAME: false, // you can use your legacy edition username, or a custom username below. + CUSTOM_USERNAME: "LCE_Player", + JAVA_SERVER_HOST, + JAVA_SERVER_PORT, + PROXY_NAME, +}; \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..a61b37b --- /dev/null +++ b/index.js @@ -0,0 +1,15 @@ +process.removeAllListeners("warning"); +process.on("warning", (warning) => { + if (warning.name === "DeprecationWarning") return; + console.warn(warning.name, warning.message); +}); + +const LCEProxy = require("./src/LCEProxy"); + +const proxy = new LCEProxy(); +proxy.start(); + +process.on("SIGINT", () => { + proxy.stop(); + process.exit(0); +}); \ No newline at end of file diff --git a/install_dependencies.bat b/install_dependencies.bat new file mode 100644 index 0000000..13fddd4 --- /dev/null +++ b/install_dependencies.bat @@ -0,0 +1,3 @@ +@echo off +npm install minecraft-protocol +pause \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..42d0bf2 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,822 @@ +{ + "name": "lce-proxy", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "lce-proxy", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "minecraft-protocol": "^1.64.0" + } + }, + "node_modules/@azure/msal-common": { + "version": "14.16.1", + "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-14.16.1.tgz", + "integrity": "sha512-nyxsA6NA4SVKh5YyRpbSXiMr7oQbwark7JU9LMeg6tJYTSPyAGkdx61wPT4gyxZfxlSxMMEyAsWaubBlNyIa1w==", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@azure/msal-node": { + "version": "2.16.3", + "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-2.16.3.tgz", + "integrity": "sha512-CO+SE4weOsfJf+C5LM8argzvotrXw252/ZU6SM2Tz63fEblhH1uuVaaO4ISYFuN4Q6BhTo7I3qIdi8ydUQCqhw==", + "license": "MIT", + "dependencies": { + "@azure/msal-common": "14.16.1", + "jsonwebtoken": "^9.0.0", + "uuid": "^8.3.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/@types/node": { + "version": "25.3.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.3.3.tgz", + "integrity": "sha512-DpzbrH7wIcBaJibpKo9nnSQL0MTRdnWttGyE5haGwK86xgMOkFLp7vEyfQPGLOJh5wNYiJ3V9PmUMDhV9u8kkQ==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/@types/node-rsa": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@types/node-rsa/-/node-rsa-1.1.4.tgz", + "integrity": "sha512-dB0ECel6JpMnq5ULvpUTunx3yNm8e/dIkv8Zu9p2c8me70xIRUUG3q+qXRwcSf9rN3oqamv4116iHy90dJGRpA==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/readable-stream": { + "version": "4.0.23", + "resolved": "https://registry.npmjs.org/@types/readable-stream/-/readable-stream-4.0.23.tgz", + "integrity": "sha512-wwXrtQvbMHxCbBgjHaMGEmImFTQxxpfMOR/ZoQnXxB1woqkUbdLGFDgauo00Py9IudiaqSeiBiulSV9i6XIPig==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@xboxreplay/errors": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@xboxreplay/errors/-/errors-0.1.0.tgz", + "integrity": "sha512-Tgz1d/OIPDWPeyOvuL5+aai5VCcqObhPnlI3skQuf80GVF3k1I0lPCnGC+8Cm5PV9aLBT5m8qPcJoIUQ2U4y9g==", + "license": "MIT" + }, + "node_modules/@xboxreplay/xboxlive-auth": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/@xboxreplay/xboxlive-auth/-/xboxlive-auth-3.3.3.tgz", + "integrity": "sha512-j0AU8pW10LM8O68CTZ5QHnvOjSsnPICy0oQcP7zyM7eWkDQ/InkiQiirQKsPn1XRYDl4ccNu0WM582s3UKwcBg==", + "license": "MIT", + "dependencies": { + "@xboxreplay/errors": "^0.1.0", + "axios": "^0.21.1" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/aes-js": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.1.2.tgz", + "integrity": "sha512-e5pEa2kBnBOgR4Y/p20pskXI74UEz7de8ZGVo58asOtvSVG5YAbJeELPZxOmt+Bnz3rX753YKhfIn4X4l1PPRQ==", + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/asn1": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", + "integrity": "sha512-6i37w/+EhlWlGUJff3T/Q8u1RGmP5wgbiwYnOnbOqvtrPxT63/sYFyP9RcpxtxGymtfA075IvmOnL7ycNOWl3w==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "0.21.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz", + "integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.14.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "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/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "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": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/buffer-equal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal/-/buffer-equal-1.0.1.tgz", + "integrity": "sha512-QoV3ptgEaQpvVwbXdSO39iqPQTCxSF7A5U99AxbHYqUdCizL/lH2Z0A2y6nbZucxMEOtNyZfG2s6gsVugGpKkg==", + "license": "MIT", + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/discontinuous-range": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz", + "integrity": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==", + "license": "MIT" + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/endian-toggle": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/endian-toggle/-/endian-toggle-0.0.0.tgz", + "integrity": "sha512-ShfqhXeHRE4TmggSlHXG8CMGIcsOsqDw/GcoPcosToE59Rm9e4aXaMhEQf2kPBsBRrKem1bbOAv5gOKnkliMFQ==", + "license": "MIT" + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "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": "BSD-3-Clause" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, + "node_modules/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", + "license": "MIT", + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "node_modules/lodash.reduce": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.reduce/-/lodash.reduce-4.6.0.tgz", + "integrity": "sha512-6raRe2vxCYBhpBu+B+TtNGUzah+hQjVdu3E17wfusjyrXBka2nBS8OH/gjVZ5PvHOhWmIZTYri09Z6n/QfnNMw==", + "license": "MIT" + }, + "node_modules/macaddress": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/macaddress/-/macaddress-0.5.4.tgz", + "integrity": "sha512-i8xVWoUjj2woYU8kbpQby86Kq7uF7xl2brtKREXUBWpfgqx1fKXEeYzDiVMVxA/IufC1d3xxwJRHtFCX+9IspA==", + "license": "MIT" + }, + "node_modules/minecraft-data": { + "version": "3.105.0", + "resolved": "https://registry.npmjs.org/minecraft-data/-/minecraft-data-3.105.0.tgz", + "integrity": "sha512-4bu0PYcd7qFDmLHYA0wzFYS9jqO4EpbbD4ntzdNg/wsLgqpQ/Mku8UbQcQFdap0X2zN+7Eiio0GYq2SOEoOCfg==", + "license": "MIT" + }, + "node_modules/minecraft-folder-path": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minecraft-folder-path/-/minecraft-folder-path-1.2.0.tgz", + "integrity": "sha512-qaUSbKWoOsH9brn0JQuBhxNAzTDMwrOXorwuRxdJKKKDYvZhtml+6GVCUrY5HRiEsieBEjCUnhVpDuQiKsiFaw==", + "license": "MIT" + }, + "node_modules/minecraft-protocol": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/minecraft-protocol/-/minecraft-protocol-1.64.0.tgz", + "integrity": "sha512-SM6M9016NuBp30YGOBsP+Xfs8WdsDOxaGFQ/YE/BtxpAI0rfO8l6T5jFAJ4vEvFwHvLEjpGcfnvKh8LUUWoqEA==", + "license": "BSD-3-Clause", + "dependencies": { + "@types/node-rsa": "^1.1.4", + "@types/readable-stream": "^4.0.0", + "aes-js": "^3.1.2", + "buffer-equal": "^1.0.0", + "debug": "^4.3.2", + "endian-toggle": "^0.0.0", + "lodash.merge": "^4.3.0", + "minecraft-data": "^3.78.0", + "minecraft-folder-path": "^1.2.0", + "node-fetch": "^2.6.1", + "node-rsa": "^0.4.2", + "prismarine-auth": "^2.2.0", + "prismarine-chat": "^1.10.0", + "prismarine-nbt": "^2.5.0", + "prismarine-realms": "^1.2.0", + "protodef": "^1.17.0", + "readable-stream": "^4.1.0", + "uuid-1345": "^1.0.1", + "yggdrasil": "^1.4.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/mojangson": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/mojangson/-/mojangson-2.0.4.tgz", + "integrity": "sha512-HYmhgDjr1gzF7trGgvcC/huIg2L8FsVbi/KacRe6r1AswbboGVZDS47SOZlomPuMWvZLas8m9vuHHucdZMwTmQ==", + "license": "MIT", + "dependencies": { + "nearley": "^2.19.5" + } + }, + "node_modules/moo": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.3.tgz", + "integrity": "sha512-m2fmM2dDm7GZQsY7KK2cme8agi+AAljILjQnof7p1ZMDe6dQ4bdnSMx0cPppudoeNv5hEFQirN6u+O4fDE0IWA==", + "license": "BSD-3-Clause" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nearley": { + "version": "2.20.1", + "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.20.1.tgz", + "integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==", + "license": "MIT", + "dependencies": { + "commander": "^2.19.0", + "moo": "^0.5.0", + "railroad-diagrams": "^1.0.0", + "randexp": "0.4.6" + }, + "bin": { + "nearley-railroad": "bin/nearley-railroad.js", + "nearley-test": "bin/nearley-test.js", + "nearley-unparse": "bin/nearley-unparse.js", + "nearleyc": "bin/nearleyc.js" + }, + "funding": { + "type": "individual", + "url": "https://nearley.js.org/#give-to-nearley" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-rsa": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/node-rsa/-/node-rsa-0.4.2.tgz", + "integrity": "sha512-Bvso6Zi9LY4otIZefYrscsUpo2mUpiAVIEmSZV2q41sP8tHZoert3Yu6zv4f/RXJqMNZQKCtnhDugIuCma23YA==", + "license": "MIT", + "dependencies": { + "asn1": "0.2.3" + } + }, + "node_modules/prismarine-auth": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/prismarine-auth/-/prismarine-auth-2.7.0.tgz", + "integrity": "sha512-L8wTF6sdtnN6hViPNy+Nx39a8iQBwR5iO92AWCiym5cSXp/92pmnuwnTdcmNDWyqq6zY4hbibVGYhgLA1Ox8sQ==", + "license": "MIT", + "dependencies": { + "@azure/msal-node": "^2.0.2", + "@xboxreplay/xboxlive-auth": "^3.3.3", + "debug": "^4.3.3", + "smart-buffer": "^4.1.0", + "uuid-1345": "^1.0.2" + } + }, + "node_modules/prismarine-biome": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/prismarine-biome/-/prismarine-biome-1.3.0.tgz", + "integrity": "sha512-GY6nZxq93mTErT7jD7jt8YS1aPrOakbJHh39seYsJFXvueIOdHAmW16kYQVrTVMW5MlWLQVxV/EquRwOgr4MnQ==", + "license": "MIT", + "peerDependencies": { + "minecraft-data": "^3.0.0", + "prismarine-registry": "^1.1.0" + } + }, + "node_modules/prismarine-block": { + "version": "1.22.0", + "resolved": "https://registry.npmjs.org/prismarine-block/-/prismarine-block-1.22.0.tgz", + "integrity": "sha512-SKVTm+CHR5mY/d+delryqzB2hMH8HIPse8b0O51Ez2R5zPFtKVCLGk5NG71kCDKbMzhhev2iF0O4UC/fWDXhRw==", + "license": "MIT", + "dependencies": { + "minecraft-data": "^3.38.0", + "prismarine-biome": "^1.1.0", + "prismarine-chat": "^1.5.0", + "prismarine-item": "^1.10.1", + "prismarine-nbt": "^2.0.0", + "prismarine-registry": "^1.1.0" + } + }, + "node_modules/prismarine-chat": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/prismarine-chat/-/prismarine-chat-1.12.0.tgz", + "integrity": "sha512-+1QBUn4WGXbAGwoGwJy31/FvH6JtTBHh//yU0xwOiVnBO71+6Ij0hYMd9PzTTAwR9bySfl/YLltGPBftUAOYOA==", + "license": "MIT", + "dependencies": { + "mojangson": "^2.0.1", + "prismarine-nbt": "^2.0.0", + "prismarine-registry": "^1.4.0" + } + }, + "node_modules/prismarine-item": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/prismarine-item/-/prismarine-item-1.17.0.tgz", + "integrity": "sha512-wN1OjP+f+Uvtjo3KzeCkVSy96CqZ8yG7cvuvlGwcYupQ6ct7LtNkubHp0AHuLMJ0vbbfAC0oZ2bWOgI1DYp8WA==", + "license": "MIT", + "dependencies": { + "prismarine-nbt": "^2.0.0", + "prismarine-registry": "^1.4.0" + } + }, + "node_modules/prismarine-nbt": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/prismarine-nbt/-/prismarine-nbt-2.8.0.tgz", + "integrity": "sha512-5D6FUZq0PNtf3v/41ImDlwThVesOv5adyqCRMZLzmkUGEmRJNNh5C6AsnvrClBftXs+IF0yqPnZoj8kcNPiMGg==", + "license": "MIT", + "dependencies": { + "protodef": "^1.18.0" + } + }, + "node_modules/prismarine-realms": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/prismarine-realms/-/prismarine-realms-1.4.1.tgz", + "integrity": "sha512-WmElIrwN4H/f0460HPnNYRJkRMVNjAmnZUOkZC+tn2Hg2IOsxRlHH5yJ/E2go1hEeFj+NlcYrGDOOhldSXnxSA==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.3", + "node-fetch": "^2.6.1" + } + }, + "node_modules/prismarine-registry": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/prismarine-registry/-/prismarine-registry-1.11.0.tgz", + "integrity": "sha512-uTvWE+bILxYv4i5MrrlxPQ0KYWINv1DJ3P2570GLC8uCdByDiDLBFfVyk4BrqOZBlDBft9CnaJMeOsC1Ly1iXw==", + "license": "MIT", + "dependencies": { + "minecraft-data": "^3.70.0", + "prismarine-block": "^1.17.1", + "prismarine-nbt": "^2.0.0" + } + }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/protodef": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/protodef/-/protodef-1.19.0.tgz", + "integrity": "sha512-94f3GR7pk4Qi5YVLaLvWBfTGUIzzO8hyo7vFVICQuu5f5nwKtgGDaeC1uXIu49s5to/49QQhEYeL0aigu1jEGA==", + "license": "MIT", + "dependencies": { + "lodash.reduce": "^4.6.0", + "protodef-validator": "^1.3.0", + "readable-stream": "^4.4.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/protodef-validator": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/protodef-validator/-/protodef-validator-1.4.0.tgz", + "integrity": "sha512-2y2coBolqCEuk5Kc3QwO7ThR+/7TZiOit4FrpAgl+vFMvq8w76nDhh09z08e2NQOdrgPLsN2yzXsvRvtADgUZQ==", + "license": "MIT", + "dependencies": { + "ajv": "^6.5.4" + }, + "bin": { + "protodef-validator": "cli.js" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/railroad-diagrams": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz", + "integrity": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A==", + "license": "CC0-1.0" + }, + "node_modules/randexp": { + "version": "0.4.6", + "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.4.6.tgz", + "integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==", + "license": "MIT", + "dependencies": { + "discontinuous-range": "1.0.0", + "ret": "~0.1.10" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/readable-stream": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz", + "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", + "license": "MIT", + "engines": { + "node": ">=0.12" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "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/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "license": "MIT" + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/uuid-1345": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/uuid-1345/-/uuid-1345-1.0.2.tgz", + "integrity": "sha512-bA5zYZui+3nwAc0s3VdGQGBfbVsJLVX7Np7ch2aqcEWFi5lsAEcmO3+lx3djM1npgpZI8KY2FITZ2uYTnYUYyw==", + "license": "MIT", + "dependencies": { + "macaddress": "^0.5.1" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/yggdrasil": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/yggdrasil/-/yggdrasil-1.7.0.tgz", + "integrity": "sha512-QBIo5fiNd7688G3FqXXYGr36uyrYzczlNuzpWFy2zL3+R+3KT2lF+wFxm51synfA3l3z6IBiGOc1/EVXWCYY1Q==", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.6.1", + "uuid": "^8.2.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..c209be3 --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "name": "lce-proxy", + "version": "1.0.0", + "description": "Minecraft Legacy Console Edition LAN Proxy", + "main": "proxy.js", + "scripts": { + "start": "node proxy.js" + }, + "keywords": [ + "minecraft", + "lce", + "proxy", + "lan" + ], + "author": "", + "license": "MIT", + "dependencies": { + "minecraft-protocol": "^1.64.0" + } +} diff --git a/src/JavaClientHandler.js b/src/JavaClientHandler.js new file mode 100644 index 0000000..d1c2078 --- /dev/null +++ b/src/JavaClientHandler.js @@ -0,0 +1,2076 @@ +const mc = require("minecraft-protocol"); +const { + JAVA_SERVER_HOST, + JAVA_SERVER_PORT, + USE_LEGACY_USERNAME, + CUSTOM_USERNAME, +} = require("../constants"); +const PacketWriter = require("./PacketWriter"); +const { mapJavaItemToLCE, mapJavaBlockToLCE } = require("./mappings"); +const { mapJavaSoundToLCE } = require("./mappings/soundMapping"); +const { parseChatComponent } = require("./utils/chat"); +const { countSetBits, compressRLE } = require("./utils/chunk"); +const zlib = require("zlib"); + +function connectToJavaServer(proxy, client) { + const javaClient = mc.createClient({ + host: JAVA_SERVER_HOST, + port: JAVA_SERVER_PORT, + username: !USE_LEGACY_USERNAME + ? CUSTOM_USERNAME + : client.username || "undefined", + auth: "offline", + version: "1.8.9", + }); + + client.javaClient = javaClient; + client._lastJavaPackets = []; + + javaClient.on("error", (err) => { + if (!client._removing) { + client._removing = true; + const index = proxy.clients.indexOf(client); + if (index > -1) { + proxy.clients.splice(index, 1); + } + if (client.smallId) { + proxy.usedSmallIds.delete(client.smallId); + } + client.javaClient = null; + if (client.socket && !client.socket.destroyed) { + try { + client.socket.destroy(); + } catch (err) { + /* do nothing */ + } + } + } + }); + + javaClient.on("end", () => { + if (proxy.clients.indexOf(client) > -1 && !client._removing) { + proxy.removeClient(client); + } + }); + + javaClient.on("login", (packet) => { + client.javaGameMode = packet.gameMode; + client.gameMode = packet.gameMode; + client.javaDimension = packet.dimension; + client.javaPlayerEntityId = packet.entityId; + + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("settings", { + locale: "en_US", + viewDistance: 10, + chatFlags: 0, + chatColors: true, + skinParts: 127, + }); + + const brandData = Buffer.concat([ + Buffer.from([0x0e]), + Buffer.from("LCE Cross Play", "utf8"), + ]); + client.javaClient.write("custom_payload", { + channel: "MC|Brand", + data: brandData, + }); + + client.javaClient.write("held_item_slot", { + slotId: 0, + }); + } catch (err) { + /* do nothing */ + } + } + }); + + javaClient.on("chat", (packet) => { + if (client.state === "play") { + try { + let chatText = ""; + + chatText = parseChatComponent(packet.message); + + if (chatText && chatText.length > 0) { + if (chatText.length > 100) { + chatText = chatText.substring(0, 97) + "..."; + } + + const chatWriter = new PacketWriter(); + chatWriter.writeShort(0); + chatWriter.writeShort(0x10); + chatWriter.writeString(chatText); + + const buffer = chatWriter.toBuffer(); + proxy.sendPacket(client, 0x03, buffer); + } + } catch (err) { + /* do nothing */ + } + } + }); + + javaClient.on("game_state_change", (packet) => { + if (client.state === "play") { + if (packet.reason === 1) { + const gameEventWriter = new PacketWriter(); + gameEventWriter.writeByte(1); //start rain + gameEventWriter.writeByte(0); + proxy.sendPacket(client, 0x46, gameEventWriter.toBuffer()); + } else if (packet.reason === 2) { + const gameEventWriter = new PacketWriter(); + gameEventWriter.writeByte(2); //stop rain (why tf does it rain so much on 1.8 lol) + gameEventWriter.writeByte(0); + proxy.sendPacket(client, 0x46, gameEventWriter.toBuffer()); + } else if (packet.reason === 3) { + const newGameMode = packet.gameMode; + client.javaGameMode = newGameMode; + client.gameMode = newGameMode; + + const gameEventWriter = new PacketWriter(); + gameEventWriter.writeByte(3); //change gamemode + gameEventWriter.writeByte(newGameMode); //0=survival, 1=creative, 2=adventure + proxy.sendPacket(client, 0x46, gameEventWriter.toBuffer()); + } + } + }); + + javaClient.on("abilities", (packet) => { + if (client.state === "play") { + const flags = packet.flags; + const invulnerable = (flags & 0x01) !== 0; + const flying = (flags & 0x02) !== 0; + const canFly = (flags & 0x04) !== 0; + const instabuild = client.gameMode === 1; //for some reason this controls if you're able to shoot bows without an arrow + + if (!client.abilities) client.abilities = {}; + client.abilities.invulnerable = invulnerable; + client.abilities.flying = flying; + client.abilities.canFly = canFly; + client.abilities.instabuild = instabuild; + + const abilitiesWriter = new PacketWriter(); + let bitfield = 0; + if (invulnerable) bitfield |= 1; + if (flying) bitfield |= 2; + if (canFly) bitfield |= 4; + if (instabuild) bitfield |= 8; + abilitiesWriter.writeByte(bitfield); + abilitiesWriter.writeFloat(packet.flyingSpeed || 0.05); + abilitiesWriter.writeFloat(packet.walkingSpeed || 0.1); + proxy.sendPacket(client, 202, abilitiesWriter.toBuffer()); + } + }); + + javaClient.on("window_items", (packet) => { + if (client.state === "play") { + if (packet.windowId < 0) { + return; + } + + if (packet.windowId === 0) { + if (!client.inventory) client.inventory = {}; + for (let i = 0; i < packet.items.length; i++) { + client.inventory[i] = packet.items[i]; + } + } + + let isNetworkedChest = false; + let chestData = null; + if ( + client._currentChest && + client._currentChest.windowId === packet.windowId + ) { + const posKey = client._currentChest.posKey; + chestData = proxy.openChests.get(posKey); + if (chestData && chestData.clients.size > 1) { + isNetworkedChest = true; + chestData.items = packet.items.slice(); + } + } + + const invWriter = new PacketWriter(); + invWriter.writeByte(packet.windowId); + invWriter.writeShort(packet.items.length); + + for (let i = 0; i < packet.items.length; i++) { + proxy.writeItem(invWriter, packet.items[i]); + } + + const payload = invWriter.toBuffer(); + + if (isNetworkedChest && chestData) { + for (const otherClient of chestData.clients) { + if ( + otherClient._currentChest && + otherClient._currentChest.posKey === client._currentChest.posKey + ) { + proxy.sendPacket(otherClient, 0x68, payload); + } + } + } else { + proxy.sendPacket(client, 0x68, payload); + } + } + }); + + javaClient.on("craft_progress_bar", (packet) => { + if (client.state === "play") { + const windowId = packet.windowId; + const property = packet.property; + const value = packet.value; + + const writer = new PacketWriter(); + writer.writeByte(windowId & 0xff); + writer.writeShort(property); + writer.writeShort(value); + + proxy.sendPacket(client, 0x69, writer.toBuffer()); + } + }); + + javaClient.on("set_slot", (packet) => { + if (client.state === "play") { + //idk why LCE sends negative window ids + if (packet.windowId < 0) { + return; + } + + if (packet.windowId >= 0) { + if (!client._windowInventories) { + client._windowInventories = {}; + } + if (!client._windowInventories[packet.windowId]) { + client._windowInventories[packet.windowId] = {}; + } + client._windowInventories[packet.windowId][packet.slot] = packet.item; + } + + if (packet.windowId === 0) { + if (!client.inventory) client.inventory = {}; + client.inventory[packet.slot] = packet.item; + } + + let isNetworkedChest = false; + let chestData = null; + if ( + client._currentChest && + client._currentChest.windowId === packet.windowId + ) { + const posKey = client._currentChest.posKey; + chestData = proxy.openChests.get(posKey); + if (chestData && chestData.clients.size > 1) { + isNetworkedChest = true; + if (packet.slot < chestData.items.length) { + chestData.items[packet.slot] = packet.item; + } + } + } + + const slotWriter = new PacketWriter(); + slotWriter.writeByte(packet.windowId); + slotWriter.writeShort(packet.slot); + proxy.writeItem(slotWriter, packet.item); + + const payload = slotWriter.toBuffer(); + + if (isNetworkedChest && chestData) { + for (const otherClient of chestData.clients) { + if ( + otherClient._currentChest && + otherClient._currentChest.posKey === client._currentChest.posKey + ) { + proxy.sendPacket(otherClient, 0x67, payload); + } + } + } else { + proxy.sendPacket(client, 0x67, payload); + } + } + }); + + javaClient.on("update_time", (packet) => { + if (client.state === "play") { + //fucking java edition sends a negative time value when doDayLightCycle is false + const timeWriter = new PacketWriter(); + timeWriter.writeLong(packet.age); + const dayTime = packet.time < 0n ? -packet.time : packet.time; + timeWriter.writeLong(dayTime); + proxy.sendPacket(client, 0x04, timeWriter.toBuffer()); + + const timeNum = Number(packet.time); + if ( + !client.lastTimeUpdate || + Math.abs(timeNum - client.lastTimeUpdate) > 100 + ) { + client.lastTimeUpdate = timeNum; + } + } + }); + + javaClient.on("experience", (packet) => { + if (client.state === "play") { + const xpWriter = new PacketWriter(); + xpWriter.writeFloat(packet.experienceBar); + xpWriter.writeShort(packet.level); + xpWriter.writeShort(packet.totalExperience); + proxy.sendPacket(client, 0x2b, xpWriter.toBuffer()); + } + }); + + javaClient.on("update_health", (packet) => { + if (client.state === "play") { + const healthWriter = new PacketWriter(); + healthWriter.writeFloat(packet.health); + healthWriter.writeShort(packet.food); + healthWriter.writeFloat(packet.foodSaturation); + healthWriter.writeByte(0); + proxy.sendPacket(client, 0x08, healthWriter.toBuffer()); + } + }); + + javaClient.on("respawn", (packet) => { + if (client.state === "play") { + client.javaDimension = packet.dimension; + + if (client.loadedChunks) { + client.loadedChunks.clear(); + } + + if (client.javaPlayers) { + for (const [uuid, player] of client.javaPlayers) { + player.spawned = false; + } + } + + if (client.javaEntities) { + const entityIdsToRemove = []; + for (const [javaEntityId, entity] of client.javaEntities) { + if (entity.lceEntityId) { + entityIdsToRemove.push(entity.lceEntityId); + } + } + + if (entityIdsToRemove.length > 0) { + const maxPerPacket = 255; + for (let i = 0; i < entityIdsToRemove.length; i += maxPerPacket) { + const batch = entityIdsToRemove.slice(i, i + maxPerPacket); + const removeWriter = new PacketWriter(); + removeWriter.writeByte(batch.length); + for (const id of batch) { + removeWriter.writeInt(id); + } + proxy.sendPacket(client, 0x1d, removeWriter.toBuffer()); + } + } + + client.javaEntities.clear(); + } + + const respawnWriter = new PacketWriter(); + respawnWriter.writeByte(packet.dimension & 0xff); + const currentGameMode = client.javaGameMode || 0; + respawnWriter.writeByte(currentGameMode); + //nether/end uses 128 height, whilst the overworld uses 256 + const mapHeight = packet.dimension === 0 ? 256 : 128; + respawnWriter.writeShort(mapHeight); //mapHeight + respawnWriter.writeString(packet.levelType || "default"); //levelType + respawnWriter.writeLong(0); //mapSeed + respawnWriter.writeByte(packet.difficulty || client.javaDifficulty || 1); //difficulty + respawnWriter.writeBoolean(false); //newSeaLevel + respawnWriter.writeShort(0); //newEntityId + respawnWriter.writeShort(864); //xzSize + respawnWriter.writeByte(8); //hellScale + proxy.sendPacket(client, 0x09, respawnWriter.toBuffer()); + + //we need to update the gamemode after respawn + //otherwise the game puts you in survival + //unfortunately on LCE this shows an annoying gamemode change message + const gameEventWriter = new PacketWriter(); + gameEventWriter.writeByte(3); + gameEventWriter.writeByte(currentGameMode); + proxy.sendPacket(client, 0x46, gameEventWriter.toBuffer()); + + const abilitiesWriter = new PacketWriter(); + const invulnerable = client.abilities?.invulnerable || false; + const flying = client.abilities?.flying || false; + const canFly = + client.abilities?.canFly || + currentGameMode === 1 || + currentGameMode === 3; + const instabuild = currentGameMode === 1; + let bitfield = 0; + if (invulnerable) bitfield |= 1; + if (flying) bitfield |= 2; + if (canFly) bitfield |= 4; + if (instabuild) bitfield |= 8; + abilitiesWriter.writeByte(bitfield); + abilitiesWriter.writeFloat(0.05); //flySpeed + abilitiesWriter.writeFloat(0.1); //walkSpeed + proxy.sendPacket(client, 202, abilitiesWriter.toBuffer()); + } + }); + + javaClient.on("player_info", (packet) => { + if (true) { + if (packet.action === 0 || packet.action === "add_player") { + if (packet.data && packet.data.length > 0) { + for (const playerData of packet.data) { + const uuid = playerData.UUID || playerData.uuid; + if (uuid) { + const existingPlayer = client.javaPlayers.get(uuid); + const wasAlreadySpawned = + existingPlayer && existingPlayer.spawned; + + const updatedPlayer = { + name: playerData.name || "Player", + gamemode: playerData.gamemode || 0, + ping: playerData.ping || 0, + entityId: existingPlayer ? existingPlayer.entityId : null, + javaEntityId: existingPlayer + ? existingPlayer.javaEntityId + : null, + x: existingPlayer ? existingPlayer.x : 0, + y: existingPlayer ? existingPlayer.y : 0, + z: existingPlayer ? existingPlayer.z : 0, + yaw: existingPlayer ? existingPlayer.yaw : 0, + pitch: existingPlayer ? existingPlayer.pitch : 0, + spawned: existingPlayer ? existingPlayer.spawned : false, + readyToSpawn: existingPlayer + ? existingPlayer.readyToSpawn + : false, + needsSpawn: wasAlreadySpawned, + }; + + client.javaPlayers.set(uuid, updatedPlayer); + + if ( + updatedPlayer.readyToSpawn && + !updatedPlayer.spawned && + updatedPlayer.entityId + ) { + updatedPlayer.spawned = true; + proxy.sendAddPlayerPacket(client, updatedPlayer); + } + } + } + } + } else if (packet.action === 4 || packet.action === "remove_player") { + if (packet.data && packet.data.length > 0) { + for (const playerData of packet.data) { + const uuid = playerData.UUID || playerData.uuid; + if (uuid && client.javaPlayers.has(uuid)) { + const player = client.javaPlayers.get(uuid); + if (player.spawned && player.entityId) { + const removeWriter = new PacketWriter(); + removeWriter.writeByte(1); + removeWriter.writeInt(player.entityId); + proxy.sendPacket(client, 0x1d, removeWriter.toBuffer()); + } + client.javaPlayers.delete(uuid); + } + } + } + } + } + }); + + javaClient.on("named_entity_spawn", (packet) => { + if (client.state === "play") { + const uuid = packet.playerUUID; + let playerInfo = client.javaPlayers.get(uuid); + + let playerName = "Player"; + if (packet.metadata && Array.isArray(packet.metadata)) { + const nameEntry = packet.metadata.find( + (m) => m.key === 2 && m.type === 4, + ); + if (nameEntry && nameEntry.value) { + playerName = nameEntry.value; + } + } + + if (!playerInfo) { + playerInfo = { + name: playerName, + gamemode: 0, + ping: 0, + entityId: packet.entityId, + spawned: false, + }; + client.javaPlayers.set(uuid, playerInfo); + } else { + if (playerName !== "Player") { + playerInfo.name = playerName; + } + } + + const lceEntityId = proxy.mapJavaEntityIdToLce(client, packet.entityId); + + playerInfo.entityId = lceEntityId; + playerInfo.javaEntityId = packet.entityId; + playerInfo.x = packet.x / 32; + playerInfo.y = packet.y / 32; + playerInfo.z = packet.z / 32; + playerInfo.yaw = (packet.yaw / 256) * 360; + playerInfo.pitch = (packet.pitch / 256) * 360; + + if (playerInfo.name && playerInfo.name !== "Player") { + playerInfo.spawned = true; + try { + proxy.sendAddPlayerPacket(client, playerInfo); + } catch (err) { + /* do nothing */ + } + } else { + playerInfo.spawned = false; + playerInfo.readyToSpawn = true; + } + } + }); + + javaClient.on("open_window", (packet) => { + if (client.state === "play") { + const windowType = packet.inventoryType || packet.windowType; + + proxy.sendContainerOpenPacket(client, packet); + client.openWindowId = packet.windowId; + client.openWindowType = windowType; + + const isChest = + windowType === "minecraft:chest" || + windowType === "minecraft:container"; + + if (isChest && client._lastBlockClicked) { + const pos = client._lastBlockClicked; + const posKey = `${pos.x},${pos.y},${pos.z}`; + + if (!proxy.openChests.has(posKey)) { + proxy.openChests.set(posKey, { + clients: new Set(), + items: new Array(27).fill(null), + windowId: packet.windowId, + position: pos, + }); + } + + const chestData = proxy.openChests.get(posKey); + chestData.clients.add(client); + + if (!proxy.clientChests.has(client)) { + proxy.clientChests.set(client, new Set()); + } + proxy.clientChests.get(client).add(posKey); + + client._currentChest = { posKey, windowId: packet.windowId }; + } + } + }); + + javaClient.on("custom_payload", (packet) => { + if (client.state === "play" && packet.channel === "MC|TrList") { + proxy.sendVillagerTrades(client, packet.data); + } + }); + + javaClient.on("close_window", (packet) => { + if (client.state === "play") { + if ( + client._currentChest && + client._currentChest.windowId === packet.windowId + ) { + const posKey = client._currentChest.posKey; + const chestData = proxy.openChests.get(posKey); + + if (chestData) { + chestData.clients.delete(client); + + if (chestData.clients.size === 0) { + proxy.openChests.delete(posKey); + } + } + + if (proxy.clientChests.has(client)) { + proxy.clientChests.get(client).delete(posKey); + } + + delete client._currentChest; + } + + const writer = new PacketWriter(); + writer.writeByte(packet.windowId & 0xff); + proxy.sendPacket(client, 0x65, writer.toBuffer()); + } + }); + + javaClient.on("transaction", (packet) => { + if (client.state === "play") { + const writer = new PacketWriter(); + writer.writeByte(packet.windowId & 0xff); + writer.writeShort(packet.action); + writer.writeBoolean(packet.accepted); + proxy.sendPacket(client, 0x6a, writer.toBuffer()); + } + }); + + javaClient.on("block_change", (packet) => { + if (client.state === "play") { + if (!packet.location) { + return; + } + + const x = packet.location.x; + const y = packet.location.y; + const z = packet.location.z; + + const blockStateId = packet.type; + const javaBlockId = blockStateId >> 4; + const metadata = blockStateId & 0xf; + + let lceBlockId = proxy.mapJavaBlockToLCE(javaBlockId); + let lceMetadata = metadata; + + if (javaBlockId === 162 || javaBlockId === 163) { + lceBlockId = 17; + lceMetadata = metadata & 0x3; + } else if ( + javaBlockId === 31 || + javaBlockId === 175 || + javaBlockId === 32 + ) { + lceBlockId = 31; + lceMetadata = 1; + } + + if (lceBlockId < 0 || lceBlockId > 170) { + lceBlockId = 0; + lceMetadata = 0; + } + + proxy.sendTileUpdatePacket(client, x, y, z, lceBlockId, lceMetadata); + } + }); + + javaClient.on("block_action", (packet) => { + if (client.state === "play") { + if (!packet.location) { + return; + } + + const x = packet.location.x; + const y = packet.location.y; + const z = packet.location.z; + const actionType = packet.byte1; //b0 in LCE + const actionParam = packet.byte2; //b1 in LCE + const blockId = packet.blockId; + + const lceBlockId = proxy.mapJavaBlockToLCE(blockId); + + const writer = new PacketWriter(); + writer.writeInt(x); + writer.writeShort(y & 0xffff); + writer.writeInt(z); + writer.writeByte(actionType & 0xff); + writer.writeByte(actionParam & 0xff); + writer.writeShort(lceBlockId & 0xffff); + const tileEventPacket = writer.toBuffer(); + + if ( + actionType === 1 && + (blockId === 54 || blockId === 130 || blockId === 146) + ) { + //chest, ender chest, trapped chest + const posKey = `${x},${y},${z}`; + const chestData = proxy.openChests.get(posKey); + + if (chestData && chestData.clients.size > 0) { + for (const otherClient of chestData.clients) { + proxy.sendPacket(otherClient, 0x36, tileEventPacket); + } + } else { + proxy.sendPacket(client, 0x36, tileEventPacket); + } + } else { + proxy.sendPacket(client, 0x36, tileEventPacket); //TileEventPacket + } + } + }); + + javaClient.on("world_event", (packet) => { + if (client.state === "play") { + if (packet.effectId === 2001 && packet.location) { + const blockId = packet.data & 0xfff; + const metadata = (packet.data >> 12) & 0xf; + const x = packet.location.x; + const y = packet.location.y; + const z = packet.location.z; + + if (blockId <= 0 || blockId > 255) { + return; + } + + //const particleName = `blockcrack_${blockId}_${metadata}`; + //proxy.sendLevelParticlesPacket( + // client, + // particleName, + // x + 0.5, + // y + 0.5, + // z + 0.5, + // 0.4, + // 0.4, + // 0.4, + // 0.0, + // 30, + //); + } + } + }); + + javaClient.on("world_particles", (packet) => { + if (client.state === "play") { + const particleName = proxy.mapJavaParticleToLCE(packet.particleId); + if (!particleName) { + return; + } + + if (!particleName || particleName.trim().length === 0) { + return; + } + + if ( + particleName.startsWith("blockcrack_") || + particleName.startsWith("iconcrack_") + ) { + const parts = particleName.split("_"); + if (parts.length >= 3) { + const id = parseInt(parts[1]); + if (isNaN(id) || id < 0 || id > 255) { + return; + } + } + } + + //proxy.sendLevelParticlesPacket( + // client, + // particleName, + // packet.x, + // packet.y, + // packet.z, + // packet.offsetX, + // packet.offsetY, + // packet.offsetZ, + // packet.particleData, + // packet.particleCount, + //); + } + }); + + javaClient.on("multi_block_change", (packet) => { + if (client.state === "play") { + if (!packet.records || packet.records.length === 0) { + return; + } + + for (const record of packet.records) { + const horizontalPos = record.horizontalPos; + const localX = (horizontalPos >> 4) & 0xf; + const localZ = horizontalPos & 0xf; + const x = (packet.chunkX << 4) + localX; + const z = (packet.chunkZ << 4) + localZ; + const y = record.y; + + const blockStateId = record.blockId; + const javaBlockId = blockStateId >> 4; + const metadata = blockStateId & 0xf; + + let lceBlockId = proxy.mapJavaBlockToLCE(javaBlockId); + let lceMetadata = metadata; + + if (javaBlockId === 162 || javaBlockId === 163) { + lceBlockId = 17; + lceMetadata = metadata & 0x3; + } else if ( + javaBlockId === 31 || + javaBlockId === 175 || + javaBlockId === 32 + ) { + lceBlockId = 31; + lceMetadata = 1; + } + + if (lceBlockId < 0 || lceBlockId > 170) { + lceBlockId = 0; + lceMetadata = 0; + } + + proxy.sendTileUpdatePacket(client, x, y, z, lceBlockId, lceMetadata); + } + } + }); + + //who tf doesn't like explosions?? + javaClient.on("explosion", (packet) => { + if (client.state === "play") { + const writer = new PacketWriter(60); + + writer.writeBoolean(false); + + writer.writeDouble(packet.x); + writer.writeDouble(packet.y); + writer.writeDouble(packet.z); + + writer.writeFloat(packet.radius); + + writer.writeInt(packet.affectedBlockOffsets.length); + + for (const offset of packet.affectedBlockOffsets) { + writer.writeSignedByte(offset.x); + writer.writeSignedByte(offset.y); + writer.writeSignedByte(offset.z); + } + + writer.writeFloat(packet.playerMotionX); + writer.writeFloat(packet.playerMotionY); + writer.writeFloat(packet.playerMotionZ); + + proxy.sendPacket(client, 60, writer.toBuffer()); + } + }); + + javaClient.on("spawn_entity_living", (packet) => { + if (client.state === "play") { + const javaType = proxy.getJavaEntityType(packet.type); + const lceEntityType = proxy.javaEntityTypeMapping[javaType]; + + if (!lceEntityType) { + return; + } + + if (lceEntityType < 0 || lceEntityType > 200) { + return; + } + + const lceEntityId = proxy.mapJavaEntityIdToLce(client, packet.entityId); + + const entityInfo = { + entityId: lceEntityId, + javaEntityId: packet.entityId, + type: lceEntityType, + javaType: javaType, + x: packet.x / 32, + y: packet.y / 32, + z: packet.z / 32, + yaw: (packet.yaw / 256) * 360, + pitch: (packet.pitch / 256) * 360, + headYaw: (packet.headPitch / 256) * 360, + prevYaw: (packet.yaw / 256) * 360, + prevPitch: (packet.pitch / 256) * 360, + velocityX: packet.velocityX / 8000, + velocityY: packet.velocityY / 8000, + velocityZ: packet.velocityZ / 8000, + metadata: packet.metadata || [], + }; + + entityInfo.spawnTime = Date.now(); + + client.javaEntities.set(packet.entityId, entityInfo); + + try { + proxy.sendAddMobPacket(client, entityInfo); + } catch (err) { + return; + } + + const relevantMetadata = entityInfo.metadata.filter((m) => { + return [12, 13, 16].includes(m.key) && m.type !== 5; + }); + + if (relevantMetadata.length > 0) { + try { + proxy.sendEntityMetadataPacket(client, entityInfo, relevantMetadata); + } catch (err) { + /* do nothing */ + } + } + } + }); + + javaClient.on("spawn_entity", (packet) => { + if (client.state === "play") { + let lceEntityType = packet.type; + + if (packet.type === 10) { + lceEntityType = 10; + const minecartSubtype = packet.intField || 0; + const minecartTypes = [ + "Rideable", + "Chest", + "Furnace", + "TNT", + "Spawner", + "Hopper", + ]; + const minecartType = minecartTypes[minecartSubtype] || "Unknown"; + } + + let fallingBlockData = null; + if (packet.type === 70) { + const javaBlockId = packet.intField & 0xfff; + const metadata = (packet.intField >> 12) & 0xf; + + const lceBlockId = proxy.mapJavaBlockToLCE(javaBlockId); + + fallingBlockData = lceBlockId | (metadata << 16); + } + + if (lceEntityType < 0 || lceEntityType > 200) { + return; + } + + const lceEntityId = proxy.mapJavaEntityIdToLce(client, packet.entityId); + + let velocityX = 0, + velocityY = 0, + velocityZ = 0; + if (packet.objectData) { + velocityX = packet.objectData.velocityX || 0; + velocityY = packet.objectData.velocityY || 0; + velocityZ = packet.objectData.velocityZ || 0; + } + + let arrowData = -1; + if (lceEntityType === 60) { + arrowData = lceEntityId; + const javaYaw = (packet.yaw / 256) * 360; + const javaPitch = (packet.pitch / 256) * 360; + } + + let fishingHookData = -1; + if (lceEntityType === 90) { + const javaOwnerId = packet.intField || packet.entityId; + + if (javaOwnerId === client.javaPlayerEntityId) { + fishingHookData = client.lcePlayerEntityId || 1; + } else { + fishingHookData = + proxy.mapJavaEntityIdToLce(client, javaOwnerId) || lceEntityId; + } + } + + const entityInfo = { + entityId: lceEntityId, + javaEntityId: packet.entityId, + type: lceEntityType, + x: packet.x / 32, + y: packet.y / 32, + z: packet.z / 32, + yaw: lceEntityType === 60 ? 0 : (packet.yaw / 256) * 360, + pitch: lceEntityType === 60 ? 0 : (packet.pitch / 256) * 360, + data: + lceEntityType === 2 + ? 1 + : lceEntityType === 60 + ? arrowData + : lceEntityType === 90 + ? fishingHookData + : lceEntityType === 63 || lceEntityType === 64 + ? 0 + : lceEntityType === 70 + ? fallingBlockData + : lceEntityType === 10 + ? packet.intField || 0 + : packet.objectData?.intField || -1, + velocityX: velocityX, + velocityY: velocityY, + velocityZ: velocityZ, + }; + + entityInfo.spawnTime = Date.now(); + + client.javaEntities.set(packet.entityId, entityInfo); + + try { + proxy.sendAddEntityPacket(client, entityInfo); + } catch (err) { + return; + } + + if (lceEntityType === 2) { + entityInfo.waitingForItemData = true; + } + + if (lceEntityType === 10) { + const minecartMetadata = []; + const minecartSubtype = packet.intField || 0; + let displayBlockId = 0; + switch (minecartSubtype) { + case 1: + displayBlockId = 54; + break; //chest + case 2: + displayBlockId = 61; + break; //furnace + case 3: + displayBlockId = 46; + break; //tNT + case 5: + displayBlockId = 154; + break; //hopper + case 4: + displayBlockId = 52; + break; //spawner + default: + displayBlockId = 0; + break; //no display + } + if (displayBlockId > 0) { + minecartMetadata.push({ key: 20, type: 2, value: displayBlockId }); + minecartMetadata.push({ key: 21, type: 2, value: 6 }); + minecartMetadata.push({ key: 22, type: 0, value: 1 }); + proxy.sendEntityMetadataPacket(client, entityInfo, minecartMetadata); + const minecartTypes = [ + "Rideable", + "Chest", + "Furnace", + "TNT", + "Spawner", + "Hopper", + ]; + const cartType = minecartTypes[minecartSubtype] || "Unknown"; + } + } + } + }); + + javaClient.on("rel_entity_move", (packet) => { + if (client.state === "play") { + let isPlayer = false; + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === packet.entityId && player.spawned) { + player.x += packet.dX / 32; + player.y += packet.dY / 32; + player.z += packet.dZ / 32; + + proxy.sendMoveEntityPacket(client, player); + isPlayer = true; + break; + } + } + + if (!isPlayer && client.javaEntities.has(packet.entityId)) { + const entity = client.javaEntities.get(packet.entityId); + entity.x += packet.dX / 32; + entity.y += packet.dY / 32; + entity.z += packet.dZ / 32; + + proxy.sendMoveEntityPacketForEntity( + client, + entity, + packet.dX, + packet.dY, + packet.dZ, + ); + } + } + }); + + javaClient.on("entity_move_look", (packet) => { + if (client.state === "play") { + let isPlayer = false; + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === packet.entityId && player.spawned) { + player.x += packet.dX / 32; + player.y += packet.dY / 32; + player.z += packet.dZ / 32; + player.yaw = (packet.yaw / 256) * 360; + player.pitch = (packet.pitch / 256) * 360; + + proxy.sendMoveEntityPacket(client, player); + isPlayer = true; + break; + } + } + + if (!isPlayer && client.javaEntities.has(packet.entityId)) { + const entity = client.javaEntities.get(packet.entityId); + entity.x += packet.dX / 32; + entity.y += packet.dY / 32; + entity.z += packet.dZ / 32; + entity.yaw = (packet.yaw / 256) * 360; + entity.pitch = (packet.pitch / 256) * 360; + + proxy.sendMoveEntityPacketForEntity( + client, + entity, + packet.dX, + packet.dY, + packet.dZ, + true, + ); + proxy.sendRotateHeadPacketForEntity(client, entity); + } + } + }); + + javaClient.on("entity_head_rotation", (packet) => { + if (client.state === "play" && client.javaEntities.has(packet.entityId)) { + const entity = client.javaEntities.get(packet.entityId); + entity.headYaw = (packet.headYaw / 256) * 360; + + proxy.sendRotateHeadPacketForEntity(client, entity); + } + }); + + javaClient.on("entity_look", (packet) => { + if (client.state === "play") { + let isPlayer = false; + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === packet.entityId && player.spawned) { + player.yaw = (packet.yaw / 256) * 360; + player.pitch = (packet.pitch / 256) * 360; + + proxy.sendMoveEntityPacket(client, player); + isPlayer = true; + break; + } + } + + if (!isPlayer && client.javaEntities.has(packet.entityId)) { + const entity = client.javaEntities.get(packet.entityId); + entity.yaw = (packet.yaw / 256) * 360; + entity.pitch = (packet.pitch / 256) * 360; + if (entity.headYaw === undefined) { + entity.headYaw = entity.yaw; + } + + proxy.sendRotateEntityPacketForEntity(client, entity); + proxy.sendRotateHeadPacketForEntity(client, entity); + } + } + }); + + javaClient.on("entity_teleport", (packet) => { + if (client.state === "play") { + let isPlayer = false; + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === packet.entityId) { + player.x = packet.x / 32; + player.y = packet.y / 32; + player.z = packet.z / 32; + player.yaw = (packet.yaw / 256) * 360; + player.pitch = (packet.pitch / 256) * 360; + + if (!player.spawned) { + if (player.name && player.name !== "undefined") { + const lceEntityId = proxy.mapJavaEntityIdToLce( + client, + packet.entityId, + ); + player.entityId = lceEntityId; + + player.spawned = true; + proxy.sendAddPlayerPacket(client, player); + } + } else { + proxy.sendTeleportEntityPacket(client, player); + } + isPlayer = true; + break; + } + } + + if (!isPlayer && client.javaEntities.has(packet.entityId)) { + const entity = client.javaEntities.get(packet.entityId); + entity.x = packet.x / 32; + entity.y = packet.y / 32; + entity.z = packet.z / 32; + entity.yaw = (packet.yaw / 256) * 360; + entity.pitch = (packet.pitch / 256) * 360; + + proxy.sendTeleportEntityPacketForEntity(client, entity); + } + } + }); + + javaClient.on("bed", (packet) => { + if (client.state === "play") { + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === packet.entityId && player.spawned) { + player.sleeping = true; + player.bedX = packet.location.x; + player.bedY = packet.location.y; + player.bedZ = packet.location.z; + + const sleepWriter = new PacketWriter(); + sleepWriter.writeInt(player.entityId); + sleepWriter.writeByte(0); //0=start sleep + sleepWriter.writeInt(packet.location.x); + sleepWriter.writeByte(packet.location.y & 0xff); + sleepWriter.writeInt(packet.location.z); + proxy.sendPacket(client, 0x11, sleepWriter.toBuffer()); + + break; + } + } + } + }); + + javaClient.on("use_bed", (packet) => { + if (client.state === "play") { + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === packet.entityId && player.spawned) { + player.sleeping = true; + player.bedX = packet.location.x; + player.bedY = packet.location.y; + player.bedZ = packet.location.z; + + const metaWriter = new PacketWriter(); + metaWriter.writeInt(player.entityId); + + metaWriter.writeByte((0 << 5) | 0); + metaWriter.writeByte(0x04); + + metaWriter.writeByte(0x7f); + proxy.sendPacket(client, 0x28, metaWriter.toBuffer()); + + break; + } + } + } + }); + + javaClient.on("entity_status", (packet) => { + if (client.state === "play") { + if (packet.entityId === client.javaPlayerEntityId) { + if (packet.entityStatus === 2 || packet.entityStatus === 3) { + const eventWriter = new PacketWriter(); + eventWriter.writeInt(client.smallId); + eventWriter.writeByte(packet.entityStatus); + proxy.sendPacket(client, 0x26, eventWriter.toBuffer()); + } + return; + } + + if (client.javaEntities.has(packet.entityId)) { + const entity = client.javaEntities.get(packet.entityId); + + if (packet.entityStatus === 3) { + if (!client._deadEntities) client._deadEntities = new Set(); + if (!client._destroyedEntities) client._destroyedEntities = new Set(); + client._deadEntities.add(packet.entityId); + client._destroyedEntities.add(entity.entityId); + } + + proxy.sendEntityEventPacket(client, entity, packet.entityStatus); + } + + let foundPlayer = false; + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === packet.entityId && player.spawned) { + foundPlayer = true; + const fakeEntity = { entityId: player.entityId }; + proxy.sendEntityEventPacket(client, fakeEntity, packet.entityStatus); + + if (packet.entityStatus === 3) { + if (!client._dyingPlayers) client._dyingPlayers = new Map(); + client._dyingPlayers.set(player.javaEntityId, Date.now()); + } + break; + } + } + + //if (!foundPlayer && packet.entityStatus === 3) { + // console.log(`wtf?? a fucking ghost just died ${packet.entityId}`); + //} + } + }); + + javaClient.on("animation", (packet) => { + if (client.state === "play") { + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === packet.entityId && player.spawned) { + //LCE: 1=SWING, 2=HURT, 3=WAKE_UP, 4=CRITICAL_HIT, 5=MAGIC_CRITICAL_HIT + //java: 0=swing, 1=damage, 2=leave_bed, 3=offhand, 4=critical, 5=magic_critical + + let lceAnimation; + switch (packet.animation) { + case 0: + lceAnimation = 1; + break; + case 1: + lceAnimation = 2; + break; + case 2: + lceAnimation = 3; + if (player.sleeping) { + player.sleeping = false; + } + break; + case 3: + lceAnimation = 1; + break; + case 4: + lceAnimation = 6; + break; + case 5: + lceAnimation = 7; + break; + default: + lceAnimation = 1; + break; + } + + const animWriter = new PacketWriter(); + animWriter.writeInt(player.entityId); + animWriter.writeByte(lceAnimation); + proxy.sendPacket(client, 0x12, animWriter.toBuffer()); + break; + } + } + + if (client.javaEntities.has(packet.entityId)) { + const entity = client.javaEntities.get(packet.entityId); + + let lceAnimation; + switch (packet.animation) { + case 0: + lceAnimation = 1; + break; + case 1: + lceAnimation = 2; + break; + case 2: + lceAnimation = 3; + break; + case 3: + lceAnimation = 1; + break; + case 4: + lceAnimation = 6; + break; + case 5: + lceAnimation = 7; + break; + default: + lceAnimation = 1; + break; + } + + const animWriter = new PacketWriter(); + animWriter.writeInt(entity.entityId); + animWriter.writeByte(lceAnimation); + proxy.sendPacket(client, 0x12, animWriter.toBuffer()); + } + } + }); + + javaClient.on("entity_equipment", (packet) => { + if (client.state === "play") { + let handled = false; + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === packet.entityId && player.spawned) { + if ( + packet.item && + packet.item.blockId !== undefined && + packet.item.blockId !== -1 + ) { + proxy.sendSetEquippedItemPacket( + client, + player, + packet.slot, + packet.item, + ); + } else { + proxy.sendSetEquippedItemPacket(client, player, packet.slot, { + blockId: -1, + }); + } + handled = true; + break; + } + } + + if (!handled && client.javaEntities.has(packet.entityId)) { + const entity = client.javaEntities.get(packet.entityId); + + if ( + packet.item && + packet.item.blockId !== undefined && + packet.item.blockId !== -1 + ) { + proxy.sendSetEquippedItemPacket( + client, + entity, + packet.slot, + packet.item, + ); + } + } + } + }); + + javaClient.on("entity_metadata", (packet) => { + if (client.state === "play") { + let isPlayer = false; + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === packet.entityId && player.spawned) { + //0x01=on fire, 0x02=sneaking, 0x04=unused, 0x08=sprinting, 0x10=eating, 0x20=invisible + if (packet.metadata && packet.metadata.length > 0) { + const sharedFlags = packet.metadata.find( + (m) => m.key === 0 && m.type === 0, + ); + if (sharedFlags !== undefined) { + const flags = sharedFlags.value & 0xff; + + const metaWriter = new PacketWriter(); + metaWriter.writeInt(player.entityId); + metaWriter.writeByte((0 << 5) | 0); + metaWriter.writeByte(flags); + metaWriter.writeByte(0x7f); + proxy.sendPacket(client, 0x28, metaWriter.toBuffer()); + } + } + isPlayer = true; + break; + } + } + + if (!isPlayer && client.javaEntities.has(packet.entityId)) { + const entity = client.javaEntities.get(packet.entityId); + entity.metadata = packet.metadata || []; + + if (entity.type === 90 && packet.metadata) { + const hookedEntityMeta = packet.metadata.find((m) => m.key === 6); + if (hookedEntityMeta) { + if (hookedEntityMeta.value > 0) { + const hookedJavaEntityId = hookedEntityMeta.value; + const hookedLceEntityId = proxy.mapJavaEntityIdToLce( + client, + hookedJavaEntityId, + ); + entity.hookedEntityId = hookedLceEntityId; + } + } + } + + //if (entity.type === 10) { + // console.log('minecart', entity.type, entity.entityId, JSON.stringify(packet.metadata)); + //} + + if ( + entity.type === 2 && + entity.waitingForItemData && + packet.metadata && + packet.metadata.length > 0 + ) { + const itemMetadata = packet.metadata.find( + (m) => m.key === 10 && m.type === 5, + ); + if (itemMetadata && itemMetadata.value) { + proxy.sendSetItemDataPacket(client, entity, itemMetadata.value); + entity.waitingForItemData = false; + } + } + + const customNameMeta = packet.metadata.find( + (m) => m.key === 2 && m.type === 4, + ); + const customNameVisibleMeta = packet.metadata.find( + (m) => m.key === 3 && m.type === 0, + ); + + const lceMetadata = []; + + if (customNameMeta && customNameMeta.value) { + lceMetadata.push({ + key: 10, + type: 4, + value: customNameMeta.value, + }); + } + + if (customNameVisibleMeta !== undefined) { + lceMetadata.push({ + key: 11, + type: 0, + value: customNameVisibleMeta.value, + }); + } + + const relevantMetadata = packet.metadata.filter((m) => { + if (entity.type === 10) { + if ([20, 21, 22].includes(m.key)) { + return false; + } + } + + //0=shared flags (e.g. on fire, sneaking, sprinting) + //12=age + //13=skeleton type + //16=villager profession or slime/magma size + //17=batman hanging flag - 0x01 = hanging + return [0, 12, 13, 16, 17].includes(m.key) && m.type !== 5; + }); + + const allMetadata = [...lceMetadata, ...relevantMetadata]; + + if (allMetadata.length > 0 && entity.type !== 2) { + proxy.sendEntityMetadataPacket(client, entity, allMetadata); + } + } + } + }); + + javaClient.on("entity_velocity", (packet) => { + try { + if (client.state === "play") { + if (!packet || packet.entityId === undefined) { + return; + } + + if (packet.entityId === client.javaPlayerEntityId) { + const localPlayerEntity = { + entityId: client.smallId, + velocityX: packet.velocityX, + velocityY: packet.velocityY, + velocityZ: packet.velocityZ, + }; + proxy.sendSetEntityMotionPacket(client, localPlayerEntity); + return; + } + + if (client.javaEntities.has(packet.entityId)) { + const entity = client.javaEntities.get(packet.entityId); + entity.velocityX = packet.velocityX; + entity.velocityY = packet.velocityY; + entity.velocityZ = packet.velocityZ; + + proxy.sendSetEntityMotionPacket(client, entity); + return; + } + + for (const [uuid, player] of client.javaPlayers) { + if ( + player.javaEntityId === packet.entityId && + player.spawned && + player.entityId !== undefined + ) { + const playerEntity = { + entityId: player.entityId, + velocityX: packet.velocityX, + velocityY: packet.velocityY, + velocityZ: packet.velocityZ, + }; + proxy.sendSetEntityMotionPacket(client, playerEntity); + return; + } + } + } + } catch (err) { + /* do nothing */ + } + }); + + javaClient.on("attach_entity", (packet) => { + if (client.state === "play") { + const riderJavaId = packet.entityId; + const vehicleJavaId = packet.vehicleId; + + let riderId = -1; + let riddenId = -1; + + if (riderJavaId === client.javaPlayerEntityId) { + riderId = client.lcePlayerEntityId || client.smallId; + } else { + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === riderJavaId && player.spawned) { + riderId = player.entityId; + break; + } + } + + if (riderId === -1 && client.javaEntities.has(riderJavaId)) { + riderId = client.javaEntities.get(riderJavaId).entityId; + } + } + + if (vehicleJavaId !== -1) { + if (client.javaEntities.has(vehicleJavaId)) { + riddenId = client.javaEntities.get(vehicleJavaId).entityId; + } + } else { + riddenId = -1; + } + + if (riderId !== -1) { + const RIDING = 0; + const LEASH = 1; + const linkType = packet.leash ? LEASH : RIDING; + proxy.sendSetEntityLinkPacket(client, riderId, riddenId, linkType); + } + } + }); + + javaClient.on("entity_destroy", (packet) => { + if (client.state === "play") { + const entityIds = packet.entityIds || []; + const idsToRemove = []; + + if (!client._destroyedEntities) client._destroyedEntities = new Set(); + + for (const entityId of entityIds) { + let isPlayer = false; + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === entityId && player.spawned) { + const deathEvent = { entityId: player.entityId }; + proxy.sendEntityEventPacket(client, deathEvent, 3); + + const lceEntityId = player.entityId; + const javaEntityId = entityId; + + player.spawned = false; + client._destroyedEntities.add(lceEntityId); + + if (client.javaEntities.has(javaEntityId)) { + client.javaEntities.delete(javaEntityId); + } + if (client.javaToLceEntityId.has(javaEntityId)) { + client.javaToLceEntityId.delete(javaEntityId); + } + + setTimeout(() => { + if ( + client._destroyedEntities && + client._destroyedEntities.has(lceEntityId) + ) { + const removeWriter = new PacketWriter(); + removeWriter.writeByte(1); + removeWriter.writeInt(lceEntityId); + proxy.sendPacket(client, 0x1d, removeWriter.toBuffer()); + + client._destroyedEntities.delete(lceEntityId); + } + }, 1050); + + isPlayer = true; + break; + } + } + + if (!isPlayer && client.javaEntities.has(entityId)) { + const entity = client.javaEntities.get(entityId); + idsToRemove.push(entity.entityId); + client._destroyedEntities.add(entity.entityId); + + if (client._lastAttacks) { + client._lastAttacks.delete(entity.entityId); + } + + if (client._pendingAttacks) { + client._pendingAttacks.delete(entityId); + } + + client.javaEntities.delete(entityId); + } + } + + if (idsToRemove.length > 0) { + const maxPerPacket = 255; + for (let i = 0; i < idsToRemove.length; i += maxPerPacket) { + const batch = idsToRemove.slice(i, i + maxPerPacket); + const removeWriter = new PacketWriter(); + removeWriter.writeByte(batch.length); + for (const id of batch) { + removeWriter.writeInt(id); + } + proxy.sendPacket(client, 0x1d, removeWriter.toBuffer()); + } + } + } + }); + + javaClient.on("named_sound_effect", (packet) => { + try { + if (client.state === "play") { + const lceSoundId = mapJavaSoundToLCE(packet.soundName); + + if (lceSoundId !== -1) { + const x = packet.x / 8; + const y = packet.y / 8; + const z = packet.z / 8; + const volume = packet.volume; + const pitch = packet.pitch / 63.0; + + proxy.sendLevelSoundPacket( + client, + lceSoundId, + x, + y, + z, + volume, + pitch, + ); + } + } + } catch (err) { + /* do nothing */ + } + }); + + javaClient.on("position", (packet) => { + client.javaSpawnX = packet.x; + client.javaSpawnY = packet.y; + client.javaSpawnZ = packet.z; + client.javaYaw = packet.yaw; + client.javaPitch = packet.pitch; + + if (client.state === "login") { + client.state = "play"; + client.loadedChunks = new Set(); + client.heldSlot = 0; + client.inventory = {}; + proxy.sendLCELoginResponse(client); + } else if (client.state === "play") { + const lceY = packet.y + 1.65; + const moveWriter = new PacketWriter(); + moveWriter.writeDouble(packet.x); + moveWriter.writeDouble(lceY); + moveWriter.writeDouble(lceY + 1.62); + moveWriter.writeDouble(packet.z); + moveWriter.writeFloat(packet.yaw); + moveWriter.writeFloat(packet.pitch); + moveWriter.writeByte(0x01); + proxy.sendPacket(client, 0x0d, moveWriter.toBuffer()); + + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("position_look", { + x: packet.x, + y: packet.y, + z: packet.z, + yaw: packet.yaw, + pitch: packet.pitch, + onGround: true, + }); + } catch (err) {} + } + } + }); + + javaClient.on("map_chunk", (packet) => { + if (!client.isViaVersion) { + client.isViaVersion = true; + } + + const chunkData = packet.chunkData || packet.data; + if (!chunkData || chunkData.length === 0) { + return; + } + + convertAndSendJavaChunk(proxy, client, { + x: packet.x, + z: packet.z, + bitMap: packet.bitMap, + data: chunkData, + groundUp: packet.groundUp, + }); + }); + + javaClient.on("map_chunk_bulk", (packet) => { + if (!packet.meta || !packet.data) { + return; + } + + let decompressed = packet.data; + + let offset = 0; + for (let i = 0; i < packet.meta.length; i++) { + const chunkMeta = packet.meta[i]; + const chunkX = chunkMeta.x; + const chunkZ = chunkMeta.z; + const bitMap = chunkMeta.bitMap; + + //overworld: 4096 blocks * 2 bytes + 2048 block light + 2048 sky light = 12288 + //nether/end: 4096 blocks * 2 bytes + 2048 block light (no sky light) = 10240 + const sectionsCount = countSetBits(bitMap); + const hasSkyLight = client.javaDimension === 0; + const bytesPerSection = hasSkyLight ? 12288 : 10240; + const chunkDataSize = sectionsCount * bytesPerSection; + const biomeSize = 256; + const totalSize = chunkDataSize + biomeSize; + + if (offset + totalSize > decompressed.length) { + break; + } + + const chunkData = decompressed.slice(offset, offset + totalSize); + offset += totalSize; + + convertAndSendJavaChunk(proxy, client, { + x: chunkX, + z: chunkZ, + bitMap: bitMap, + data: chunkData, + groundUp: true, + }); + //proxy.sendFlatChunk(client, chunkX, chunkZ); + } + }); +} + +function convertAndSendJavaChunk(proxy, client, javaChunk) { + if (!javaChunk || !javaChunk.data || javaChunk.data.length === 0) { + return; + } + + if (!Number.isFinite(javaChunk.x) || !Number.isFinite(javaChunk.z)) { + return; + } + + if (Math.abs(javaChunk.x) > 1875000 || Math.abs(javaChunk.z) > 1875000) { + return; + } + + const visWriter = new PacketWriter(); + visWriter.writeInt(javaChunk.x); + visWriter.writeInt(javaChunk.z); + visWriter.writeByte(1); + proxy.sendPacket(client, 0x32, visWriter.toBuffer()); + + //nether/end uses 128 height, whilst the overworld uses 256 + const chunkHeight = client.javaDimension === 0 ? 256 : 128; + const blockCount = 16 * chunkHeight * 16; + const halfBlockCount = blockCount / 2; + const biomeSize = 16 * 16; + const rawSize = blockCount + 3 * halfBlockCount + biomeSize; + const rawData = Buffer.alloc(rawSize); + + let totalBlocksConverted = 0; + let nonAirBlocks = 0; + + let offset = 0; + + if (javaChunk.bitMap && javaChunk.data) { + const javaData = javaChunk.data; + const bitMap = javaChunk.bitMap; + + let sectionCount = 0; + for (let i = 0; i < 16; i++) { + if (bitMap & (1 << i)) sectionCount++; + } + + const BLOCKS_PER_SECTION = 16 * 16 * 16; + const BYTES_PER_SECTION = BLOCKS_PER_SECTION * 2; + + let dataOffset = 0; + + const lceSections = chunkHeight / 16; + for (let sectionY = 0; sectionY < 16; sectionY++) { + const sectionBit = 1 << sectionY; + + if ((bitMap & sectionBit) === 0) { + continue; + } + + const baseY = sectionY * 16; + + let blocksRead = 0; + const firstBlocksInSection = []; + for (let sy = 0; sy < 16; sy++) { + for (let sz = 0; sz < 16; sz++) { + for (let sx = 0; sx < 16; sx++) { + if (dataOffset + 1 < javaData.length) { + const blockStateId = javaData.readUInt16LE(dataOffset); + const javaBlockId = blockStateId >> 4; + const metadata = blockStateId & 0x0f; + dataOffset += 2; + + if ( + client.javaDimension === -1 && + javaChunk.x === 0 && + javaChunk.z === 0 && + (sectionY === 0 || sectionY === 8) && + blocksRead < 20 + ) { + firstBlocksInSection.push(javaBlockId); + } + blocksRead++; + + let lceBlockId = proxy.mapJavaBlockToLCE(javaBlockId); + let lceMetadata = metadata; + + if (lceBlockId > 170 || lceBlockId < 0) { + lceBlockId = 0; + lceMetadata = 0; + } + + if (javaBlockId === 162 || javaBlockId === 163) { + const orientation = metadata & 0x0c; + lceMetadata = orientation; + } + + if (javaBlockId === 31) { + lceBlockId = 31; + lceMetadata = 1; + } else if (javaBlockId === 175) { + lceBlockId = 31; + lceMetadata = 1; + } else if (javaBlockId === 32) { + lceBlockId = 31; + lceMetadata = 1; + } + + if (lceBlockId < 0 || lceBlockId > 174) { + lceBlockId = 0; + } + if (lceMetadata < 0 || lceMetadata > 15) { + lceMetadata = 0; + } + + totalBlocksConverted++; + if (lceBlockId !== 0) { + nonAirBlocks++; + } + + const absoluteY = baseY + sy; + + if (absoluteY < chunkHeight) { + const blockIdx = (absoluteY * 16 + sz) * 16 + sx; + if (blockIdx < 0 || blockIdx >= blockCount) { + continue; + } + if (lceBlockId < 0 || lceBlockId > 255) { + lceBlockId = 0; + } + rawData[blockIdx] = lceBlockId; + + const metadataOffset = blockCount; + const sectionHeight = 128; + const yEven = absoluteY & 0xfffffffe; + + let nibbleOffset; + if (chunkHeight <= 128 || absoluteY < sectionHeight) { + nibbleOffset = + sx * ((16 * sectionHeight) / 2) + + sz * (sectionHeight / 2) + + yEven / 2; + } else { + const lowerNibbleCount = 16 * 16 * (sectionHeight / 2); + const upperY = absoluteY - sectionHeight; + const upperYEven = upperY & 0xfffffffe; + const upperSectionHeight = chunkHeight - sectionHeight; + nibbleOffset = + lowerNibbleCount + + sx * ((16 * upperSectionHeight) / 2) + + sz * (upperSectionHeight / 2) + + upperYEven / 2; + } + + if ( + metadataOffset + nibbleOffset >= + blockCount + halfBlockCount + ) { + continue; + } + + if (lceMetadata < 0 || lceMetadata > 15) { + lceMetadata = 0; + } + + const isUpperNibble = (absoluteY & 1) === 1; + + if (isUpperNibble) { + rawData[metadataOffset + nibbleOffset] = + (rawData[metadataOffset + nibbleOffset] & 0x0f) | + (lceMetadata << 4); + } else { + rawData[metadataOffset + nibbleOffset] = + (rawData[metadataOffset + nibbleOffset] & 0xf0) | + lceMetadata; + } + } + } + } + } + } + } + + //biome fix! + const biomeOffset = blockCount + 3 * halfBlockCount; + const hasSky = client.javaDimension === 0; + const javaBiomeOffset = sectionCount * (hasSky ? 12288 : 10240); + + if (javaChunk.x === 0 && javaChunk.z === 0) { + const hasSky = client.javaDimension === 0; + const expectedOffset = sectionCount * (hasSky ? 12288 : 10240); + } + + if (javaBiomeOffset + 256 <= javaData.length) { + for (let i = 0; i < biomeSize; i++) { + rawData[biomeOffset + i] = javaData[javaBiomeOffset + i]; + } + + if (javaChunk.x === 0 && javaChunk.z === 0) { + const biomeData = rawData.slice(biomeOffset, biomeOffset + biomeSize); + const uniqueBiomes = new Set(biomeData); + } + } else { + for (let i = 0; i < biomeSize; i++) { + rawData[biomeOffset + i] = 1; + } + } + } + + const skyLightOffset = blockCount + halfBlockCount + halfBlockCount; + for (let i = 0; i < halfBlockCount; i++) { + rawData[skyLightOffset + i] = 0xff; + } + + if (rawData.length !== rawSize) { + return; + } + + const rleCompressed = compressRLE(rawData); + if (!rleCompressed || rleCompressed.length === 0) { + return; + } + + const compressed = zlib.deflateSync(rleCompressed, { level: 6 }); + if (!compressed || compressed.length === 0 || compressed.length > 1000000) { + return; + } + + const writer = new PacketWriter(); + writer.writeByte(0x01); + + const worldX = javaChunk.x * 16; + const worldZ = javaChunk.z * 16; + + writer.writeInt(worldX); + writer.writeShort(0); + writer.writeInt(worldZ); + + writer.writeByte(15); + writer.writeByte(chunkHeight - 1); + writer.writeByte(15); + + const levelIdx = + client.javaDimension === -1 ? 1 : client.javaDimension === 1 ? 2 : 0; + const sizeAndLevel = compressed.length | (levelIdx << 30); + writer.writeInt(sizeAndLevel); + + const payload = writer.toBuffer(); + const fullPayload = Buffer.concat([payload, compressed]); + + const chunkKey = `${javaChunk.x},${javaChunk.z}`; + if (client.loadedChunks) { + client.loadedChunks.add(chunkKey); + } + + proxy.sendPacket(client, 0x33, fullPayload); +} + +module.exports = connectToJavaServer; \ No newline at end of file diff --git a/src/LANBroadcast.js b/src/LANBroadcast.js new file mode 100644 index 0000000..36d5349 --- /dev/null +++ b/src/LANBroadcast.js @@ -0,0 +1,29 @@ +const { + MINECRAFT_NET_VERSION, + GAME_PORT, + PROXY_NAME, +} = require("../constants"); + +class LANBroadcast { + constructor() { + this.buffer = Buffer.allocUnsafe(86); + this.buffer.writeUInt32LE(0x4d434c4e, 0); + this.buffer.writeUInt16LE(MINECRAFT_NET_VERSION, 4); + this.buffer.writeUInt16LE(GAME_PORT, 6); + + const hostName = PROXY_NAME; + for (let i = 0; i < 32; i++) { + const char = i < hostName.length ? hostName.charCodeAt(i) : 0; + this.buffer.writeUInt16LE(char, 8 + i * 2); + } + + this.buffer.writeUInt8(1, 72); //player count including host + this.buffer.writeUInt8(8, 73); //max players + this.buffer.writeUInt32LE(0, 74); //host settings + this.buffer.writeUInt32LE(0, 78); //texture pack ID + this.buffer.writeUInt8(0, 82); //sub texture pack ID + this.buffer.writeUInt8(1, 83); //is joinable + } +} + +module.exports = LANBroadcast; \ No newline at end of file diff --git a/src/LCEProxy.js b/src/LCEProxy.js new file mode 100644 index 0000000..8df8238 --- /dev/null +++ b/src/LCEProxy.js @@ -0,0 +1,2454 @@ +const dgram = require("dgram"); +const net = require("net"); +const mc = require("minecraft-protocol"); +const { + GAME_PORT, + WIN64_LAN_DISCOVERY_PORT, + MINECRAFT_NET_VERSION, + USE_LEGACY_USERNAME, + CUSTOM_USERNAME, + PROXY_NAME, +} = require("../constants"); +const PacketWriter = require("./PacketWriter"); +const PacketReader = require("./PacketReader"); +const LANBroadcast = require("./LANBroadcast"); +const { + createEntityTypeMapping, + createItemMapping, + createBlockMapping, +} = require("./mappings"); +const { compressRLE } = require("./utils/chunk"); +const { encodeVarInt } = require("./utils"); +const { normalizeYaw } = require("./utils/rotation"); +const { readItemInstance } = require("./utils/items"); +const { readItem, writeItem, writeItemNBT } = require("./utils/items"); +const packetSenders = require("./packets/senders"); +const connectToJavaServerFunc = require("./JavaClientHandler"); + +//please stfu node +process.removeAllListeners("warning"); +process.on("warning", (warning) => { + if (warning.name === "DeprecationWarning") return; + console.warn(warning.name, warning.message); +}); + +const zlib = require("zlib"); +const fs = require("fs"); +const path = require("path"); + +class LCEProxy { + constructor() { + this.clients = []; + this.udpSocket = null; + this.tcpServer = null; + this.broadcastInterval = null; + this.nextSmallId = 1; + this.usedSmallIds = new Set(); + + this.openChests = new Map(); + this.clientChests = new Map(); + + this.javaBlockMapping = createBlockMapping(); + this.javaItemMapping = createItemMapping(); + this.javaEntityTypeMapping = createEntityTypeMapping(); + } + + mapJavaBlockToLCE(javaBlockId) { + if (this.javaBlockMapping[javaBlockId] !== undefined) { + return this.javaBlockMapping[javaBlockId]; + } + return 0; + } + + mapJavaParticleToLCE(particleId) { + const particleMap = { + 0: "explode", + 1: "largeexplode", + 2: "hugeexplosion", + 3: "fireworksSpark", + 4: "bubble", + 5: "splash", + 6: "wake", + 7: "suspended", + 8: "depthsuspend", + 9: "crit", + 10: "magicCrit", + 11: "smoke", + 12: "largesmoke", + 13: "spell", + 14: "instantSpell", + 15: "mobSpell", + 16: "mobSpellAmbient", + 17: "witchMagic", + 18: "dripWater", + 19: "dripLava", + 20: "angryVillager", + 21: "happyVillager", + 22: "townaura", + 23: "note", + 24: "portal", + 25: "enchantmenttable", + 26: "flame", + 27: "lava", + 28: "footstep", + 29: "cloud", + 30: "reddust", + 31: "snowballpoof", + 32: "snowshovel", + 33: "slime", + 34: "heart", + 35: "barrier", + 36: "iconcrack", + 37: "blockcrack", + 38: "blockdust", + 39: "droplet", + 40: "take", + 41: "mobappearance", + 42: "dragonbreath", + 43: "endrod", + 44: "damageindicator", + 45: "sweepattack", + }; + + return particleMap[particleId] || null; + } + + mapJavaItemToLCE(javaItemId) { + if (javaItemId >= 0 && javaItemId <= 255) { + return this.mapJavaBlockToLCE(javaItemId); + } + + if (this.javaItemMapping[javaItemId] !== undefined) { + return this.javaItemMapping[javaItemId]; + } + + return 1; + } + + mapLCEItemToJava(lceItemId) { + if (lceItemId >= 0 && lceItemId <= 255) { + return this.mapLCEBlockToJava(lceItemId); + } + + if ( + (lceItemId >= 256 && lceItemId <= 421) || + (lceItemId >= 2256 && lceItemId <= 2267) + ) { + for (const [javaId, lceId] of Object.entries(this.javaItemMapping)) { + if (lceId === lceItemId) { + return parseInt(javaId); + } + } + return lceItemId; + } + + //console.log(`lce to java item ${lceItemId} not found`); + return null; + } + + mapLCEBlockToJava(lceBlockId) { + for (const [javaId, lceId] of Object.entries(this.javaBlockMapping)) { + if (lceId === lceBlockId) { + return parseInt(javaId); + } + } + + if (lceBlockId >= 0 && lceBlockId <= 174) { + return lceBlockId; + } + + return null; + } + + start() { + this.startBroadcasting(); + this.startTCPServer(); + + console.log("\nProxy is now running!"); + console.log( + 'Java Edition server "' + PROXY_NAME + '" should appear on Minecraft.', + ); + console.log("Press Ctrl+C to stop.\n"); + } + + startBroadcasting() { + this.udpSocket = dgram.createSocket("udp4"); + this.udpSocket.bind(() => { + this.udpSocket.setBroadcast(true); + }); + + const broadcast = new LANBroadcast(); + + this.broadcastInterval = setInterval(() => { + this.udpSocket.send( + broadcast.buffer, + 0, + broadcast.buffer.length, + WIN64_LAN_DISCOVERY_PORT, + "255.255.255.255", + ); + }, 1000); + } + + startTCPServer() { + this.tcpServer = net.createServer((socket) => { + socket.setNoDelay(true); + + let smallId = 1; + while (this.usedSmallIds.has(smallId) && smallId <= 8) { + smallId++; + } + + if (smallId > 8) { + socket.destroy(); + return; + } + + this.usedSmallIds.add(smallId); + + const client = { + socket: socket, + smallId: smallId, + buffer: Buffer.alloc(0), + state: "prelogin", + javaClient: null, + breakingBlock: null, + javaPlayers: new Map(), + nextLceEntityId: 100, + javaToLceEntityId: new Map(), + javaEntities: new Map(), + }; + + this.clients.push(client); + + const smallIdBuffer = Buffer.from([smallId]); + socket.write(smallIdBuffer); + + socket.on("data", (data) => { + this.handleClientData(client, data); + }); + + socket.on("end", () => { + this.removeClient(client); + }); + + socket.on("error", (err) => { + this.removeClient(client); + }); + + socket.on("close", () => { + if (this.clients.indexOf(client) > -1) { + this.removeClient(client); + } + }); + }); + + this.tcpServer.listen(GAME_PORT, () => {}); + } + + getPacketDataSize(packetId, data, offset) { + switch (packetId) { + case 0x00: + return 0; + + case 0x0a: + return 10; + + case 0x0b: + let size = 4 + 1 + 4 + 1; + if (offset + size + 2 <= data.length) { + const itemId = data.readInt16BE(offset + size); + size += 2; + if (itemId !== -1) { + size += 1 + 2; + } + size += 4 + 4 + 4; + } + return size; + + case 0x0c: + return data.length - offset >= 7 + 2 ? 7 : 7; + + case 0x0d: + const remaining = data.length - offset; + if (remaining >= 41) return 41; + if (remaining >= 33) return 33; + if (remaining >= 9) return 9; + return remaining; + + case 0x0e: + return 12; + + case 0x07: + return 9; + + //this retarded packet wasted hours of my life because it was being bundled with others... + //for some reason we don't receive this packet if the player is doing nothing besides hitting - 4J what the fuck did you do to this poor packet. + case 0x12: + return 5; + + default: + return null; + } + } + + //thanks 0x12 + calculatePacketSize(packetId, data, offset) { + try { + switch (packetId) { + case 0x00: + return 0; + + case 0x0a: + return 1 + 1; + + case 0x0b: + return 1 + 33; + + case 0x0c: + return 1 + 9; + + case 0x0d: + if (offset >= data.length) return null; + + const remainingInBundle = data.length - offset; + + if (remainingInBundle === 42) return 42; + if (remainingInBundle === 41) return 41; + if (remainingInBundle === 34) return 34; + if (remainingInBundle === 33) return 33; + if (remainingInBundle === 10) return 10; + if (remainingInBundle === 9) return 9; + if (remainingInBundle === 2) return 2; + if (remainingInBundle === 1) return 1; + + return remainingInBundle; + + case 0x0e: + return 1 + 1 + 4 + 1 + 4 + 1; + + case 0x07: + return 1 + 4 + 4 + 1; + + case 0x12: + return 1 + 4 + 1; + + case 0x0f: + let useItemSize = 1 + 4 + 1 + 4 + 1; + if (offset + useItemSize + 2 <= data.length) { + const itemId = data.readInt16BE(offset + useItemSize); + useItemSize += 2; + if (itemId !== -1) { + useItemSize += 1; + useItemSize += 2; + } + } + useItemSize += 1 + 1 + 1; + return useItemSize; + + case 0x10: + return 1 + 2; + + case 0x13: + return 1 + 9; + + case 0x66: + let containerClickSize = 1 + 1 + 2 + 1 + 2 + 1; + if (offset + containerClickSize + 2 <= data.length) { + const itemId = data.readInt16BE(offset + containerClickSize); + containerClickSize += 2; + if (itemId !== -1) { + containerClickSize += 1; + containerClickSize += 2; + } + } + return containerClickSize; + + case 0x6a: + return 1 + 4; + + case 0x6b: + return 1 + 8; + + case 0x65: + return 1 + 1; + + case 0xcd: + return 1 + 1; + + default: + return null; + } + } catch (err) { + return null; + } + } + + handleClientData(client, data) { + client.buffer = Buffer.concat([client.buffer, data]); + + while (client.buffer.length >= 4) { + const packetLength = client.buffer.readUInt32BE(0); + + if (client.buffer.length < 4 + packetLength) { + break; + } + + const packetData = client.buffer.slice(4, 4 + packetLength); + client.buffer = client.buffer.slice(4 + packetLength); + + const packetId = packetData[0]; + + const expectedSize = this.calculatePacketSize(packetId, packetData, 0); + if (expectedSize > 0 && packetData.length > expectedSize) { + let offset = 0; + while (offset < packetData.length) { + const bundledPacketId = packetData[offset]; + const bundledSize = this.calculatePacketSize( + bundledPacketId, + packetData, + offset, + ); + + if (bundledSize <= 0 || offset + bundledSize > packetData.length) { + break; + } + + const singlePacket = packetData.slice(offset, offset + bundledSize); + this.processPacket(client, bundledPacketId, singlePacket, offset > 0); + offset += bundledSize; + } + } else { + this.processPacket(client, packetId, packetData, false); + } + } + } + + processPacket(client, packetId, packetData, isBundled = false) { + switch (packetId) { + case 0x02: //PreLoginPacket + this.handlePreLogin(client, packetData); + break; + case 0x01: //LoginPacket + this.handleLogin(client, packetData); + break; + case 0x00: //KeepAlive + if (client.state === "prelogin") { + this.handleKeepAlive(client, packetData); + } + break; + case 0x07: //InteractPacket - 7 + if (client.state === "play") { + this.handleInteract(client, packetData); + } + break; + case 0x12: //AnimatePacket - 18 + if (client.state === "play") { + this.handleAnimate(client, packetData, isBundled); + } + break; + case 0x0d: //MovePlayerPacket (pos & rot) + if (client.state === "play") { + this.handleMovePlayer(client, packetData); + } + break; + case 0x0a: //base (onGround/isFlying) + case 0x0b: //pos + case 0x0c: //rot + if (client.state === "play") { + this.handlePlayerMovement(client, packetId, packetData); + } + break; + case 0x03: + if (client.state === "play") { + this.handleChat(client, packetData); + } + break; + case 0x0e: + if (client.state === "play") { + this.handlePlayerAction(client, packetData, isBundled); + } + break; + case 0x0f: //UseItemPacket - 15 + if (client.state === "play") { + this.handleUseItem(client, packetData); + } + break; + case 0x10: //SetCarriedItemPacket - 16 + if (client.state === "play") { + this.handleSetCarriedItem(client, packetData); + } + break; + case 0x13: //PlayerCommandPacket - 19 + if (client.state === "play") { + this.handlePlayerCommand(client, packetData); + } + break; + case 0x65: //ContainerClosePacket - 101 + if (client.state === "play") { + this.handleContainerClose(client, packetData); + } + break; + case 0x66: //ContainerClickPacket - 102 + if (client.state === "play") { + this.handleContainerClick(client, packetData); + } + break; + case 0x6a: //ContainerAckPacket - 106 + if (client.state === "play") { + this.handleContainerAck(client, packetData); + } + break; + //maybe we can use a custom JavaCraftingPacket (0x9E) packet with + //crafting grid data because java edition doesn't craft with recipe ids + //case 0x96: + // break; + case 0x97: //TradeItemPacket - 151 + if (client.state === "play") { + this.handleTradeItem(client, packetData); + } + break; + //case 0x9E: //JavaCraftingPacket - 158 + // if (client.state === 'play') { + // this.handleJavaCrafting(client, packetData); + // } + // break; + case 0xfa: //CustomPayloadPacket - 250 + if (client.state === "play") { + this.handleCustomPayload(client, packetData); + } + break; + case 0x6b: //SetCreativeModeSlotPacket - 107 + if (client.state === "play") { + this.handleSetCreativeModeSlot(client, packetData); + } + break; + case 0xcd: //ClientCommandPacket - 205 + if (client.state === "play") { + this.handleClientCommand(client, packetData); + } + break; + case 0xff: //DisconnectPacket - 255 + this.handleDisconnect(client, packetData); + break; + default: + break; + } + } + + handlePreLogin(client, data) { + const reader = new PacketReader(data.slice(1)); + const netcodeVersion = reader.readShort(); + const loginKey = reader.readString(); + + client.state = "login"; + + const writer = new PacketWriter(); + writer.writeShort(MINECRAFT_NET_VERSION); + writer.writeString("SESSION_ID_" + client.smallId); + writer.writeByte(0); //friendsOnly + writer.writeInt(0); //ugcPlayersVersion + writer.writeByte(0); //playerCount + + for (let i = 0; i < 14; i++) writer.writeByte(0); //uniqueSaveName + + let serverSettings = 0; + + //difficulty + //0=Peaceful, 1=Easy, 2=Normal, 3=Hard + serverSettings |= 1; + + //friends of friends (off) + //serverSettings |= 0x00000004; + + //gamertags (on) + serverSettings |= 0x00000008; + + //0=Survival, 1=Creative, 2=Adventure + //survival=leave bits clear (0) + //creative=serverSettings |= 0x00000010; + + //level type (OFF=Default, ON=Flat) + //serverSettings |= 0x00000040; //uncomment for flat + + //structures (on) + serverSettings |= 0x00000080; + + //bonus chest (off) + //serverSettings |= 0x00000100; + + //pvp (on) + serverSettings |= 0x00000400; + + //trust players (on) + serverSettings |= 0x00000800; + + //tnt (on) + serverSettings |= 0x00001000; + + //spread fire (on) + serverSettings |= 0x00002000; + + writer.writeInt(serverSettings); + writer.writeByte(0); //hostIndex + writer.writeInt(0); //texturePackId + + this.sendPacket(client, 0x02, writer.toBuffer()); + } + + handleLogin(client, data) { + const reader = new PacketReader(data.slice(1)); + const clientVersion = reader.readInt(); + const username = reader.readString(); + //console.log(username); + + client.state = "login"; + client.username = !USE_LEGACY_USERNAME ? CUSTOM_USERNAME : username; + + this.connectToJavaServer(client); + } + + sendLCELoginResponse(client) { + const writer = new PacketWriter(); + writer.writeInt(client.smallId); //entityId + + //we use these later + client.lcePlayerEntityId = client.smallId; + writer.writeString(""); //username + writer.writeString("default"); //levelTypeName + writer.writeLong(0); //seed + writer.writeInt(client.javaGameMode || 0); //gamemode (synced from java server) + const dimension = client.javaDimension || 0; + writer.writeByte(dimension & 0xff); //dimension + //nether/end use 128 height, overworld uses 256 + const loginMapHeight = dimension === 0 ? 256 : 128; + writer.writeByte(loginMapHeight - 1); //mapHeight sent as (height - 1) + writer.writeByte(8); //maxPlayers + writer.writeLong(0); //offlineXuid + writer.writeLong(0); //onlineXuid + writer.writeBoolean(false); //friendsOnlyUGC + writer.writeInt(0); //ugcPlayersVersion + writer.writeByte(1); //difficulty (hardcoded to Easy) + writer.writeInt(0); //multiplayerInstanceId + writer.writeByte(0); //playerIndex + writer.writeInt(0); //playerSkinId + writer.writeInt(0); //playerCapeId + writer.writeBoolean(false); //isGuest + writer.writeBoolean(false); //newSeaLevel + writer.writeInt(0); //uiGamePrivileges + writer.writeShort(864); //xzSize + writer.writeByte(8); //hellScale + + this.sendPacket(client, 0x01, writer.toBuffer()); + this.sendPostLoginPackets(client); + } + + sendPostLoginPackets(client) { + const spawnX = Math.floor(client.javaSpawnX || 0); + const spawnY = Math.floor(client.javaSpawnY || 65); + const spawnZ = Math.floor(client.javaSpawnZ || 0); + + const spawnWriter = new PacketWriter(); + spawnWriter.writeInt(spawnX); + spawnWriter.writeInt(spawnY); + spawnWriter.writeInt(spawnZ); + this.sendPacket(client, 6, spawnWriter.toBuffer()); + + const abilitiesWriter = new PacketWriter(); + const invulnerable = client.abilities?.invulnerable || false; + const flying = client.abilities?.flying || false; + const canFly = + client.abilities?.canFly || + client.gameMode === 1 || + client.gameMode === 3; + const instabuild = client.gameMode === 1; //dunno why this controls the bow requiring arrows on LCE, but it does + let bitfield = 0; + if (invulnerable) bitfield |= 1; + if (flying) bitfield |= 2; + if (canFly) bitfield |= 4; + if (instabuild) bitfield |= 8; + abilitiesWriter.writeByte(bitfield); + abilitiesWriter.writeFloat(0.05); //flySpeed + abilitiesWriter.writeFloat(0.1); //walkSpeed + this.sendPacket(client, 202, abilitiesWriter.toBuffer()); + + const carriedWriter = new PacketWriter(); + carriedWriter.writeShort(0); //selectedSlot + this.sendPacket(client, 16, carriedWriter.toBuffer()); + + const lceSpawnY = (client.javaSpawnY || 65.0) + 1.65; //lce has an eye offset of 1.62, added 3 so we don't spawn in the ground + const moveWriter = new PacketWriter(); + moveWriter.writeDouble(client.javaSpawnX || 0.5); + moveWriter.writeDouble(lceSpawnY); //feet position with offset + moveWriter.writeDouble(lceSpawnY + 1.62); //eye height above feet + moveWriter.writeDouble(client.javaSpawnZ || 0.5); + moveWriter.writeFloat(client.javaYaw || 0.0); + moveWriter.writeFloat(client.javaPitch || 0.0); + moveWriter.writeByte(0x01); //onGround + const movePayload = moveWriter.toBuffer(); + + this.sendPacket(client, 0x0d, movePayload); + + //translating between 1.8 and 1.9+ servers for viaversion requires a position packet from the + //client to generate the TeleportConfirm packet that 1.9+ servers expect before accepting movement. + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("position_look", { + x: client.javaSpawnX || 0.5, + y: client.javaSpawnY || 65.0, + z: client.javaSpawnZ || 0.5, + yaw: client.javaYaw || 0.0, + pitch: client.javaPitch || 0.0, + onGround: true, + }); + } catch (err) { + /* do nothing */ + } + } + + const timeWriter = new PacketWriter(); + timeWriter.writeLong(1000); //gameTime (world age) + timeWriter.writeLong(6000); //dayTime + this.sendPacket(client, 4, timeWriter.toBuffer()); + //console.log("YEEEEEEEEEEEEEEEEEEE"); + } + + mapJavaEntityIdToLce(client, javaEntityId) { + if (!client.javaToLceEntityId.has(javaEntityId)) { + const lceEntityId = client.nextLceEntityId++; + if (lceEntityId > 32767) { + return 100; + } + client.javaToLceEntityId.set(javaEntityId, lceEntityId); + } + return client.javaToLceEntityId.get(javaEntityId); + } + + sendMovePlayerPacket(client, x, y, z, yaw, pitch) { + const lceY = y + 1.65; + const moveWriter = new PacketWriter(); + moveWriter.writeDouble(x); + moveWriter.writeDouble(lceY); //feet position with offset + moveWriter.writeDouble(lceY + 1.62); //eye height above feet + moveWriter.writeDouble(z); + moveWriter.writeFloat(yaw); + moveWriter.writeFloat(pitch); + moveWriter.writeByte(0x01); //onGround + this.sendPacket(client, 0x0d, moveWriter.toBuffer()); + } + + sendAddPlayerPacket(client, playerInfo) { + let playerName = playerInfo.name || "undefined"; + if (playerName.length > 16) { + playerName = playerName.substring(0, 16); + } + if (playerName.length === 0) { + playerName = "undefined"; + } + + const writer = new PacketWriter(); + writer.writeInt(playerInfo.entityId); + writer.writeString(playerName); + + //pos + writer.writeInt(Math.floor(playerInfo.x * 32)); + writer.writeInt(Math.floor(playerInfo.y * 32)); + writer.writeInt(Math.floor(playerInfo.z * 32)); + + //rot + const yRotByte = Math.floor(((playerInfo.yaw % 360) / 360) * 256) & 0xff; + const xRotByte = Math.floor(((playerInfo.pitch % 360) / 360) * 256) & 0xff; + writer.writeByte(yRotByte); + writer.writeByte(xRotByte); + writer.writeByte(yRotByte); //yHeadRot + + writer.writeShort(0); //carriedItem + writer.writeLong(0); //xuid + writer.writeLong(0); //OnlineXuid + writer.writeByte(0); //playerIndex + writer.writeInt(0); //skinId + writer.writeInt(0); //capeId + writer.writeInt(0); //uiGamePrivileges + + const sharedFlagsHeader = (0 << 5) | 0; + writer.writeByte(sharedFlagsHeader); + writer.writeByte(0); + + const airSupplyHeader = (1 << 5) | 1; + writer.writeByte(airSupplyHeader); + writer.writeShort(300); + + const healthHeader = (3 << 5) | 6; + writer.writeByte(healthHeader); + writer.writeFloat(20.0); + + const effectColorHeader = (2 << 5) | 7; + writer.writeByte(effectColorHeader); + writer.writeInt(0); + + const effectAmbienceHeader = (0 << 5) | 8; + writer.writeByte(effectAmbienceHeader); + writer.writeByte(0); + + const arrowCountHeader = (0 << 5) | 9; + writer.writeByte(arrowCountHeader); + writer.writeByte(0); + + const playerFlagsHeader = (0 << 5) | 16; + writer.writeByte(playerFlagsHeader); + writer.writeByte(0); + + const absorptionHeader = (3 << 5) | 17; + writer.writeByte(absorptionHeader); + writer.writeFloat(0.0); + + const scoreHeader = (2 << 5) | 18; + writer.writeByte(scoreHeader); + writer.writeInt(0); + + writer.writeByte(0x7f); + + this.sendPacket(client, 0x14, writer.toBuffer()); + } + + sendMoveEntityPacket(client, playerInfo) { + //MoveEntityPacket can only handle movements of ~4 blocks + //just teleport for simplicity + this.sendTeleportEntityPacket(client, playerInfo); + } + + sendTeleportEntityPacket(client, playerInfo) { + const writer = new PacketWriter(); + writer.writeShort(playerInfo.entityId); + + //pos + writer.writeInt(Math.floor(playerInfo.x * 32)); + writer.writeInt(Math.floor(playerInfo.y * 32)); + writer.writeInt(Math.floor(playerInfo.z * 32)); + + //rot + const yRotByte = Math.floor(((playerInfo.yaw % 360) / 360) * 256) & 0xff; + const xRotByte = Math.floor(((playerInfo.pitch % 360) / 360) * 256) & 0xff; + writer.writeByte(yRotByte); + writer.writeByte(xRotByte); + + this.sendPacket(client, 34, writer.toBuffer()); //TeleportEntityPacket + + this.sendRotateHeadPacket(client, playerInfo); + } + + sendRotateHeadPacket(client, playerInfo) { + const writer = new PacketWriter(); + writer.writeInt(playerInfo.entityId); + + const yHeadRotByte = + Math.floor(((playerInfo.yaw % 360) / 360) * 256) & 0xff; + writer.writeByte(yHeadRotByte); + + this.sendPacket(client, 35, writer.toBuffer()); //RotateHeadPacket + } + + getJavaEntityType(typeId) { + const typeMap = { + 50: "Creeper", + 51: "Skeleton", + 52: "Spider", + 53: "Giant", + 54: "Zombie", + 55: "Slime", + 56: "Ghast", + 57: "PigZombie", + 58: "Enderman", + 59: "CaveSpider", + 60: "Silverfish", + 61: "Blaze", + 62: "LavaSlime", + 63: "EnderDragon", + 64: "WitherBoss", + 65: "Bat", + 66: "Witch", + 90: "Pig", + 91: "Sheep", + 92: "Cow", + 93: "Chicken", + 94: "Squid", + 95: "Wolf", + 96: "MushroomCow", + 97: "SnowMan", + 98: "Ozelot", + 99: "VillagerGolem", + 100: "EntityHorse", + 120: "Villager", + }; + return typeMap[typeId] || "Unknown"; + } + + sendAddMobPacket(client, entityInfo) { + return packetSenders.sendAddMobPacket(this, client, entityInfo); + } + sendAddEntityPacket(client, entityInfo) { + return packetSenders.sendAddEntityPacket(this, client, entityInfo); + } + sendMoveEntityPacketForEntity(client, entity, dX, dY, dZ, includeRotation) { + return packetSenders.sendMoveEntityPacketForEntity( + this, + client, + entity, + dX, + dY, + dZ, + includeRotation, + ); + } + sendTeleportEntityPacketForEntity(client, entity) { + return packetSenders.sendTeleportEntityPacketForEntity( + this, + client, + entity, + ); + } + sendRotateEntityPacketForEntity(client, entity) { + return packetSenders.sendRotateEntityPacketForEntity(this, client, entity); + } + sendRotateHeadPacketForEntity(client, entity) { + return packetSenders.sendRotateHeadPacketForEntity(this, client, entity); + } + sendEntityMetadataPacket(client, entity, metadata) { + return packetSenders.sendEntityMetadataPacket( + this, + client, + entity, + metadata, + ); + } + sendSetEntityMotionPacket(client, entity) { + return packetSenders.sendSetEntityMotionPacket(this, client, entity); + } + sendEntityEventPacket(client, entity, eventId) { + return packetSenders.sendEntityEventPacket(this, client, entity, eventId); + } + sendSetEquippedItemPacket(client, entity, slot, item) { + return packetSenders.sendSetEquippedItemPacket( + this, + client, + entity, + slot, + item, + ); + } + sendSetItemDataPacket(client, entity, itemData) { + return packetSenders.sendSetItemDataPacket(this, client, entity, itemData); + } + sendSetEntityDataPacket(client, entity) { + return packetSenders.sendSetEntityDataPacket(this, client, entity); + } + sendUpdateAttributesPacket(client, entity) { + return packetSenders.sendUpdateAttributesPacket(this, client, entity); + } + sendSetEntityLinkPacket(client, sourceId, destId, linkType) { + return packetSenders.sendSetEntityLinkPacket( + this, + client, + sourceId, + destId, + linkType, + ); + } + + sendLevelSoundPacket(client, soundId, x, y, z, volume, pitch) { + return packetSenders.sendLevelSoundPacket( + this, + client, + soundId, + x, + y, + z, + volume, + pitch, + ); + } + sendLevelParticlesPacket( + client, + name, + x, + y, + z, + xDist, + yDist, + zDist, + maxSpeed, + count, + ) { + return packetSenders.sendLevelParticlesPacket( + this, + client, + name, + x, + y, + z, + xDist, + yDist, + zDist, + maxSpeed, + count, + ); + } + sendTileUpdatePacket(client, x, y, z, blockId, metadata) { + return packetSenders.sendTileUpdatePacket( + this, + client, + x, + y, + z, + blockId, + metadata, + ); + } + + sendContainerOpenPacket(client, packet) { + return packetSenders.sendContainerOpenPacket(this, client, packet); + } + + //debug + sendFlatChunk(client, chunkX, chunkZ) { + const xs = 16; + const ys = 256; + const zs = 16; + const blockCount = xs * ys * zs; + const halfBlockCount = blockCount / 2; + const biomeSize = xs * zs; + const rawSize = blockCount + 3 * halfBlockCount + biomeSize; + + const rawData = Buffer.alloc(rawSize); + let offset = 0; + + for (let y = 0; y < ys; y++) { + for (let z = 0; z < zs; z++) { + for (let x = 0; x < xs; x++) { + let blockId = 0; + + if (y < 65) { + blockId = 1; + } + if (y === 64) { + blockId = 2; + } + rawData[offset++] = blockId; + } + } + } + + const metadataOffset = offset; + for (let x = 0; x < xs; x++) { + for (let z = 0; z < zs; z++) { + for (let yPair = 0; yPair < ys / 2; yPair++) { + rawData[offset++] = 0; + } + } + } + + for (let x = 0; x < xs; x++) { + for (let z = 0; z < zs; z++) { + for (let yPair = 0; yPair < ys / 2; yPair++) { + rawData[offset++] = 0; + } + } + } + + for (let x = 0; x < xs; x++) { + for (let z = 0; z < zs; z++) { + for (let yPair = 0; yPair < ys / 2; yPair++) { + rawData[offset++] = 0xff; + } + } + } + for (let i = 0; i < biomeSize; i++) { + rawData[offset++] = 1; + } + + const rleCompressed = compressRLE(rawData); + const compressed = zlib.deflateSync(rleCompressed, { level: 6 }); + + const writer = new PacketWriter(); + + writer.writeByte(0x01); + + const worldX = chunkX * 16; + const worldY = 0; + const worldZ = chunkZ * 16; + + writer.writeInt(worldX); + writer.writeShort(worldY); + writer.writeInt(worldZ); + + writer.writeByte(xs - 1); + writer.writeByte(ys - 1); + writer.writeByte(zs - 1); + + const levelIdx = 0; + const sizeAndLevel = compressed.length | (levelIdx << 30); + writer.writeInt(sizeAndLevel); + + const payload = writer.toBuffer(); + const fullPayload = Buffer.concat([payload, compressed]); + + const visWriter = new PacketWriter(); + visWriter.writeInt(chunkX); + visWriter.writeInt(chunkZ); + visWriter.writeByte(1); + this.sendPacket(client, 0x32, visWriter.toBuffer()); + + const chunkKey = `${chunkX},${chunkZ}`; + if (client.loadedChunks) { + client.loadedChunks.add(chunkKey); + } + + this.sendPacket(client, 0x33, fullPayload); + } + + handleKeepAlive(client, data) { + const reader = new PacketReader(data.slice(1)); + const keepAliveId = reader.readInt(); + + const writer = new PacketWriter(); + writer.writeInt(keepAliveId); + this.sendPacket(client, 0x00, writer.toBuffer()); + } + + handleInteract(client, packetData) { + const reader = new PacketReader(packetData.slice(1)); + const sourceId = reader.readInt(); + const targetId = reader.readInt(); + const action = reader.readByte(); + + if (action === 0) { + const heldSlot = client.heldSlot || 0; + const heldItem = client.inventory + ? client.inventory[36 + heldSlot] + : null; + const heldItemId = heldItem ? heldItem.blockId : -1; + + const nonInteractiveItems = [ + 346, //fishing rod + 261, //bow + //foods + 260, + 297, + 282, + 350, + 349, + 360, + 363, + 365, + 366, + 320, + 357, + 391, + 392, + 393, + 394, + //potions + 373, + 438, + //buckets (except milk) + 326, + 327, + //ender pearl, snowball, egg + 368, + 332, + 344, + ]; + + if (nonInteractiveItems.includes(heldItemId)) { + return; + } + } + + if (client._destroyedEntities && client._destroyedEntities.has(targetId)) { + return; + } + + if (action === 1) { + const now = Date.now(); + if (!client._lastAttacks) client._lastAttacks = new Map(); + + const lastAttackTime = client._lastAttacks.get(targetId) || 0; + if (now - lastAttackTime < 500) { + return; + } + client._lastAttacks.set(targetId, now); + + if (client._lastAttacks.size > 100) { + const oldestEntry = Array.from(client._lastAttacks.entries()).sort( + (a, b) => a[1] - b[1], + )[0]; + client._lastAttacks.delete(oldestEntry[0]); + } + } + + const targetEntity = Array.from(client.javaEntities.values()).find( + (e) => e.entityId === targetId, + ); + const entityType = targetEntity + ? `${targetEntity.javaType}(${targetEntity.type})` + : "UNKNOWN"; + + let targetJavaId = -1; + + for (const [javaId, entity] of client.javaEntities) { + if (entity.entityId === targetId) { + if (client._deadEntities && client._deadEntities.has(javaId)) { + return; + } + targetJavaId = javaId; + break; + } + } + + for (const [uuid, player] of client.javaPlayers) { + if (player.entityId === targetId && player.spawned) { + targetJavaId = player.javaEntityId; + break; + } + } + + if (targetJavaId !== -1 && client.javaClient) { + let entityExists = client.javaEntities.has(targetJavaId); + if (!entityExists) { + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === targetJavaId && player.spawned) { + entityExists = true; + break; + } + } + } + + if (!entityExists) { + return; + } + + if (action === 1) { + if (!client._pendingAttacks) client._pendingAttacks = new Set(); + + if (client._pendingAttacks.has(targetJavaId)) { + return; + } + + client._pendingAttacks.add(targetJavaId); + + setTimeout(() => { + if (client._pendingAttacks) { + client._pendingAttacks.delete(targetJavaId); + } + }, 150); + + client.javaClient.write("use_entity", { + target: targetJavaId, + mouse: 1, + sneaking: false, + }); + } else { + client.javaClient.write("use_entity", { + target: targetJavaId, + mouse: 0, + sneaking: false, + }); + } + } else { + const allEntities = Array.from(client.javaEntities.values()).map( + (e) => `LCE:${e.entityId}=Java:${e.javaEntityId}(${e.javaType})`, + ); + } + } + + handleAnimate(client, packetData, isBundled = false) { + try { + const reader = new PacketReader(packetData.slice(1)); + const entityId = reader.readInt(); + const action = reader.readByte(); + + if (client.javaClient && action === 1) { + client.javaClient.write("arm_animation", { + hand: 0, + }); + + const targetEntity = this.raycastEntity(client); + if (targetEntity) { + const heldSlot = client.heldSlot || 0; + const heldItem = client.inventory + ? client.inventory[36 + heldSlot] + : null; + const heldItemId = heldItem ? heldItem.blockId : -1; + + const useItems = [ + 346, //fishing rod + 261, //bow + ]; + + if (useItems.includes(heldItemId)) { + return; + } + const entity = client.javaEntities.get(targetEntity); + let isPlayer = false; + + if (!entity) { + for (const [uuid, player] of client.javaPlayers) { + if (player.javaEntityId === targetEntity && player.spawned) { + isPlayer = true; + break; + } + } + + if (!isPlayer) { + return; + } + } else { + if (!entity.spawnTime) { + return; + } + + const now = Date.now(); + const timeSinceSpawn = now - entity.spawnTime; + if (timeSinceSpawn < 500) { + return; + } + } + + if (client._deadEntities && client._deadEntities.has(targetEntity)) { + return; + } + + if (!client._pendingAttacks) client._pendingAttacks = new Set(); + if (client._pendingAttacks.has(targetEntity)) { + return; + } + + client._pendingAttacks.add(targetEntity); + setTimeout(() => { + if (client._pendingAttacks) { + client._pendingAttacks.delete(targetEntity); + } + }, 150); + + client.javaClient.write("use_entity", { + target: targetEntity, + mouse: 1, + sneaking: false, + }); + } + } + } catch (err) { + /* do nothing */ + } + } + + raycastEntity(client) { + if (!client.playerX || !client.playerYaw || !client.playerPitch) { + return null; + } + + const playerX = client.playerX; + const playerY = client.playerY + 1.62; //eye height + const playerZ = client.playerZ; + const yaw = client.playerYaw; + const pitch = client.playerPitch; + + const yawRad = ((yaw + 90) * Math.PI) / 180; + const pitchRad = (pitch * Math.PI) / 180; + + const dirX = Math.cos(pitchRad) * Math.cos(yawRad); + const dirY = -Math.sin(pitchRad); + const dirZ = Math.cos(pitchRad) * Math.sin(yawRad); + + //max hit distance + const maxDistance = 10.0; + let closestEntity = null; + let closestDistance = maxDistance; + + for (const [javaId, entity] of client.javaEntities) { + if (!entity.x || !entity.y || !entity.z) continue; + + const isLivingEntity = + (entity.type >= 48 && entity.type <= 66) || //monsters + (entity.type >= 90 && entity.type <= 100) || //animals + entity.type === 120; //villagers + if (!isLivingEntity) continue; + + const entityX = entity.x; + const entityY = entity.y + 1.0; //probably the center + const entityZ = entity.z; + + const toEntityX = entityX - playerX; + const toEntityY = entityY - playerY; + const toEntityZ = entityZ - playerZ; + + const distance = Math.sqrt( + toEntityX * toEntityX + toEntityY * toEntityY + toEntityZ * toEntityZ, + ); + + if (distance > maxDistance || distance > closestDistance) continue; + + const dot = + (toEntityX * dirX + toEntityY * dirY + toEntityZ * dirZ) / distance; + + //hit fov + if (dot > 0.97) { + closestEntity = javaId; + closestDistance = distance; + } + } + + for (const [uuid, player] of client.javaPlayers) { + if (!player.spawned || !player.x || !player.y || !player.z) continue; + if (!player.javaEntityId) continue; + + const playerEntityX = player.x; + const playerEntityY = player.y + 1.0; //probably the center + const playerEntityZ = player.z; + + const toPlayerX = playerEntityX - playerX; + const toPlayerY = playerEntityY - playerY; + const toPlayerZ = playerEntityZ - playerZ; + + const distance = Math.sqrt( + toPlayerX * toPlayerX + toPlayerY * toPlayerY + toPlayerZ * toPlayerZ, + ); + + if (distance > maxDistance || distance > closestDistance) continue; + + const dot = + (toPlayerX * dirX + toPlayerY * dirY + toPlayerZ * dirZ) / distance; + + //hit fov + if (dot > 0.97) { + closestEntity = player.javaEntityId; + closestDistance = distance; + } + } + + return closestEntity; + } + + handleMovePlayer(client, data) { + const reader = new PacketReader(data.slice(1)); + const dataSize = data.length - 1; + + let x, y, yView, z, yRot, xRot, onGround; + + if (dataSize >= 33) { + x = reader.readDouble(); + y = reader.readDouble(); + yView = reader.readDouble(); + z = reader.readDouble(); + + if (dataSize >= 41) { + yRot = reader.readFloat(); + xRot = reader.readFloat(); + } else { + yRot = client.lastYaw || 0; + xRot = client.lastPitch || 0; + } + onGround = reader.readByte(); + } else if (dataSize >= 9) { + yRot = reader.readFloat(); + xRot = reader.readFloat(); + onGround = reader.readByte(); + + x = client.playerX || 0; + y = client.playerY || 0; + yView = y; + z = client.playerZ || 0; + } else { + return; + } + + const normalizedYaw = normalizeYaw(yRot); + + client.playerX = x; + client.playerY = y; + client.playerZ = z; + client.playerYaw = normalizedYaw; + client.playerPitch = xRot; + + client.lastYaw = normalizedYaw; + client.lastPitch = xRot; + + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("position_look", { + x: x, + y: y, + z: z, + yaw: normalizedYaw, + pitch: xRot, + onGround: onGround !== 0, + }); + } catch (err) { + /* do nothing */ + } + } + } + + handleUseItem(client, data) { + const reader = new PacketReader(data.slice(1)); + const x = reader.readInt(); + const y = reader.readByte(); + const z = reader.readInt(); + const face = reader.readByte(); + + const itemId = reader.readShort(); + let itemCount = 0; + let itemAux = 0; + if (itemId !== -1) { + itemCount = reader.readByte(); + itemAux = reader.readShort(); + } + + const clickX = reader.readByte() / 32.0; + const clickY = reader.readByte() / 32.0; + const clickZ = reader.readByte() / 32.0; + + if (x !== -1 && y !== -1 && z !== -1 && face >= 0 && face <= 5) { + client._lastBlockClicked = { x, y, z }; + + if (client.javaClient && client.javaClient.write) { + try { + let javaItemId = -1; + if (itemId !== -1) { + javaItemId = this.mapLCEItemToJava(itemId); + } + + let heldItem; + if (javaItemId !== -1 && javaItemId !== 0) { + heldItem = { + blockId: javaItemId, + itemCount: itemCount || 1, + itemDamage: itemAux || 0, + }; + } else { + heldItem = { + blockId: -1, + itemCount: 0, + itemDamage: 0, + }; + } + + const javaFace = face; + + const cursorX = Math.floor(clickX * 16); + const cursorY = Math.floor(clickY * 16); + const cursorZ = Math.floor(clickZ * 16); + + client.javaClient.write("block_place", { + location: { x: x, y: y, z: z }, + direction: javaFace, + heldItem: heldItem, + cursorX: cursorX, + cursorY: cursorY, + cursorZ: cursorZ, + }); + } catch (err) { + /* do nothing */ + } + } + } else { + //LCE also sends InteractPacket separately for entity interaction, so we ignore that + if (client.javaClient) { + if (itemId !== -1) { + client._lastHeldItem = { + itemId: itemId, + itemCount: itemCount, + itemAux: itemAux, + }; + } + + const useItemId = + itemId !== -1 + ? itemId + : client._lastHeldItem + ? client._lastHeldItem.itemId + : -1; + const useItemCount = + itemId !== -1 + ? itemCount + : client._lastHeldItem + ? client._lastHeldItem.itemCount + : 0; + const useItemAux = + itemId !== -1 + ? itemAux + : client._lastHeldItem + ? client._lastHeldItem.itemAux + : 0; + + if (useItemId !== -1) { + const javaItemId = this.mapLCEItemToJava(useItemId); + + if (javaItemId !== -1 && javaItemId !== 0) { + const continuousUseItems = { 261: "bow", 346: "fishing_rod" }; + const itemName = continuousUseItems[javaItemId]; + + if (itemName) { + if (!client._itemUseState) client._itemUseState = {}; + const now = Date.now(); + const lastUse = client._itemUseState[javaItemId] || 0; + + if (now - lastUse > 100) { + const heldItem = { + blockId: javaItemId, + itemCount: useItemCount || 1, + itemDamage: useItemAux || 0, + }; + + client.javaClient.write("block_place", { + location: { x: -1, y: 255, z: -1 }, + direction: -1, + heldItem: heldItem, + cursorX: 0, + cursorY: 0, + cursorZ: 0, + }); + + client._itemUseState[javaItemId] = now; + } + } else { + const heldItem = { + blockId: javaItemId, + itemCount: useItemCount || 1, + itemDamage: useItemAux || 0, + }; + + try { + const blockPlacePacket = { + location: { x: -1, y: 255, z: -1 }, + direction: -1, + heldItem: heldItem, + cursorX: 0, + cursorY: 0, + cursorZ: 0, + }; + client.javaClient.write("block_place", blockPlacePacket); + } catch (err) { + /* do nothing */ + } + } + } + } + } + } + } + + handleChat(client, data) { + const reader = new PacketReader(data.slice(1)); + const messageType = reader.readShort(); + const packedCounts = reader.readShort(); + + const stringCount = (packedCounts >> 4) & 0xf; + const intCount = (packedCounts >> 0) & 0xf; + + if (stringCount > 0) { + const message = reader.readString(); + + if ( + client.javaClient && + client.javaClient.write && + message && + message.length > 0 + ) { + try { + client.javaClient.write("chat", { + message: message, + }); + } catch (err) { + /* do nothing */ + } + } + } + } + + handlePlayerAction(client, data, isBundled = false) { + const reader = new PacketReader(data.slice(1)); + const action = reader.readByte(); + const x = reader.readInt(); + const y = reader.readByte(); + const z = reader.readInt(); + const face = reader.readByte(); + + //0=START_DESTROY_BLOCK + //1=ABORT_DESTROY_BLOCK + //2=STOP_DESTROY_BLOCK + //3=DROP_ALL_ITEMS + //4=DROP_ITEM + //5=RELEASE_USE_ITEM + + if (action === 0) { + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("block_dig", { + status: 0, + location: { x: x, y: y, z: z }, + face: face >= 0 ? face : 1, + }); + } catch (err) { + /* do nothing */ + } + } + } else if (action === 1) { + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("block_dig", { + status: 1, + location: { x: x, y: y, z: z }, + face: face >= 0 ? face : 1, + }); + } catch (err) { + /* do nothing */ + } + } + } else if (action === 2) { + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("block_dig", { + status: 2, + location: { x: x, y: y, z: z }, + face: face >= 0 ? face : 1, + }); + } catch (err) { + /* do nothing */ + } + } + } else if (action === 3 || action === 4) { + if (client.javaClient && client.javaClient.write) { + try { + const javaStatus = action === 4 ? 4 : 3; + const packet = { + status: javaStatus, + location: { x: 0, y: 0, z: 0 }, + face: 0, + }; + client.javaClient.write("block_dig", packet); + } catch (err) { + /* do nothing */ + } + } + } else if (action === 5) { + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("block_dig", { + status: 5, + location: { x: x, y: y, z: z }, + face: face, + }); + } catch (err) { + /* do nothing */ + } + } + } + } + + handleSetCarriedItem(client, data) { + const reader = new PacketReader(data.slice(1)); + const slot = reader.readShort(); + + if (slot < 0 || slot > 8) { + return; + } + + client.heldSlot = slot; + + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("held_item_slot", { + slotId: slot, + }); + } catch (err) { + /* do nothing */ + } + } + } + + handlePlayerInput(client, data) { + const reader = new PacketReader(data.slice(1)); + const xxa = reader.readFloat(); + const yya = reader.readFloat(); + const isJumping = reader.readBoolean(); + const isSneaking = reader.readBoolean(); + + client.isSneaking = isSneaking; + + //broken + if (isSneaking && client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("steer_vehicle", { + sideways: 0, + forward: 0, + jump: false, + unmount: true, + }); + } catch (err) { + /* do nothing */ + } + } + } + + handlePlayerCommand(client, data) { + const reader = new PacketReader(data.slice(1)); + const entityId = reader.readInt(); + const action = reader.readByte(); + const actionData = reader.readInt(); + + const actionNames = { + 1: "START_SNEAKING", + 2: "STOP_SNEAKING", + 3: "STOP_SLEEPING", + 4: "START_SPRINTING", + 5: "STOP_SPRINTING", + 6: "START_IDLEANIM", + 7: "STOP_IDLEANIM", + 8: "RIDING_JUMP", + 9: "OPEN_INVENTORY", + }; + + if (client.javaClient && client.javaClient.write) { + try { + let javaAction = -1; + + if (action === 1) { + javaAction = 0; //java: START_SNEAKING + } else if (action === 2) { + javaAction = 1; //java: STOP_SNEAKING + } else if (action === 3) { + javaAction = 2; //java: LEAVE_BED + } else if (action === 4) { + javaAction = 3; //java: START_SPRINTING + } else if (action === 5) { + javaAction = 4; //java: STOP_SPRINTING + } else if (action === 8) { + javaAction = 5; //java: RIDING_JUMP (open horse inventory) + } else if (action === 9) { + javaAction = 6; //java: OPEN_INVENTORY + } + + if (javaAction !== -1) { + client.javaClient.write("entity_action", { + entityId: entityId, + actionId: javaAction, + jumpBoost: actionData || 0, + }); + } + } catch (err) { + /* do nothing */ + } + } + } + + handleContainerClose(client, data) { + const reader = new PacketReader(data.slice(1)); + const containerId = reader.readByte(); + + if (client._currentChest && client._currentChest.windowId === containerId) { + const posKey = client._currentChest.posKey; + const chestData = this.openChests.get(posKey); + + if (chestData) { + chestData.clients.delete(client); + + if (chestData.clients.size === 0) { + this.openChests.delete(posKey); + } + } + + if (this.clientChests.has(client)) { + this.clientChests.get(client).delete(posKey); + } + + delete client._currentChest; + } + + //LCE uses special window IDs + //-1=crafting table in inventory + //-2=creative inventory + //java doesn't send close packets for these, so we'll just skip them + if (containerId < 0) { + return; + } + + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("close_window", { + windowId: containerId, + }); + } catch (err) { + /* do nothing */ + } + } + } + + handleCustomPayload(client, data) { + const reader = new PacketReader(data.slice(1)); + const identifier = reader.readString(); + const length = reader.readShort(); + + const stringByteLength = identifier.length * 2; + const offset = 1 + 2 + stringByteLength + 2; + const payloadData = data.slice(offset, offset + length); + + if (identifier === "MC|ItemName") { + const nameLength = payloadData.readUInt16BE(0); + const nameData = payloadData.slice(2, 2 + nameLength); + const itemName = nameData.toString("utf8"); + + if (client.javaClient && client.javaClient.write) { + try { + const stringBytes = Buffer.from(itemName, "utf8"); + + const varintLength = encodeVarInt(stringBytes.length); + const stringBuffer = Buffer.concat([varintLength, stringBytes]); + + client._anvilItemName = itemName; + + try { + const payloadPacket = { + channel: "MC|ItemName", + data: stringBuffer, + }; + client.javaClient.write("custom_payload", payloadPacket); + } catch (writeErr) { + throw writeErr; + } + } catch (err) { + /* do nothing */ + } + } + } else if (identifier === "MC|TrSel") { + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("custom_payload", { + channel: "MC|TrSel", + data: payloadData, + }); + } catch (err) { + /* do nothing */ + } + } + } else if (identifier === "MC|BEdit" || identifier === "MC|BSign") { + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("custom_payload", { + channel: identifier, + data: payloadData, + }); + } catch (err) { + /* do nothing */ + } + } + } + } + + placeTradeItems(client, windowId, tradeInfo, offerIndex) { + //very broken, java requires you to send clicks with the current item in the slot + //we have to track inventory and update it after each click, but this is complicated + //maybe in the future we can write a server plugin that handles this + if (!client.javaClient) return; + + if (!client._windowInventories || !client._windowInventories[windowId]) { + return; + } + + const inventory = client._windowInventories[windowId]; + + const findItem = (requiredItem) => { + for (let slot = 3; slot <= 38; slot++) { + const item = inventory[slot]; + if (item && item.blockId === requiredItem.blockId) { + if (item.itemCount >= requiredItem.itemCount) { + return slot; + } + } + } + return null; + }; + + const input1Slot = tradeInfo.input1 ? findItem(tradeInfo.input1) : null; + const input2Slot = tradeInfo.input2 ? findItem(tradeInfo.input2) : null; + + if (tradeInfo.input1 && !input1Slot) { + console.error(0); + return; + } + + if (tradeInfo.input2 && !input2Slot) { + console.error(1); + return; + } + + const clickSequence = []; + + if (input1Slot) { + const item1 = inventory[input1Slot]; + const hasRemainder = item1.itemCount > tradeInfo.input1.itemCount; + + clickSequence.push( + { + slot: input1Slot, + item: item1, + mode: 0, + desc: `pickup ${item1.itemCount} from slot ${input1Slot}`, + }, + { + slot: 0, + item: null, + mode: 0, + desc: `place ${tradeInfo.input1.itemCount} in trade slot 0`, + }, + ); + + if (hasRemainder) { + clickSequence.push({ + slot: input1Slot, + item: null, + mode: 0, + desc: `return extra to slot ${input1Slot}`, + }); + } + + clickSequence._updateSlot = input1Slot; + clickSequence._updateItem = item1; + clickSequence._usedCount = tradeInfo.input1.itemCount; + } + + let targetSlot = null; + for (let slot = 30; slot <= 38; slot++) { + if (!inventory[slot] || inventory[slot].blockId === -1) { + targetSlot = slot; + break; + } + } + if (!targetSlot) { + for (let slot = 3; slot <= 29; slot++) { + if (!inventory[slot] || inventory[slot].blockId === -1) { + targetSlot = slot; + break; + } + } + } + + if (targetSlot) { + clickSequence.push( + { + slot: 2, + item: tradeInfo.output, + mode: 0, + desc: `pick up trade result from slot 2`, + }, + { + slot: targetSlot, + item: null, + mode: 0, + desc: `place trade result in slot ${targetSlot}`, + }, + ); + } + + let delay = 0; + clickSequence.forEach((click) => { + setTimeout(() => { + const action = client.windowClickAction++; + + try { + let itemParam; + if (click.item) { + itemParam = { + blockId: click.item.blockId, + itemCount: click.item.itemCount, + itemDamage: click.item.itemDamage || 0, + }; + } else { + itemParam = { blockId: -1 }; + } + + const clickMode = click.mode !== undefined ? click.mode : 0; + + client.javaClient.write("window_click", { + windowId: windowId, + slot: click.slot, + mouseButton: 0, + action: action, + mode: clickMode, + item: itemParam, + }); + } catch (err) { + /* do nothing */ + } + }, delay); + delay += 75; + }); + + if (clickSequence._updateSlot) { + const remainingCount = + clickSequence._updateItem.itemCount - clickSequence._usedCount; + if (remainingCount > 0) { + inventory[clickSequence._updateSlot] = { + blockId: clickSequence._updateItem.blockId, + itemCount: remainingCount, + itemDamage: clickSequence._updateItem.itemDamage, + }; + } else { + delete inventory[clickSequence._updateSlot]; + } + } + + const totalDelay = delay; + setTimeout(() => { + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("window_click", { + windowId: windowId, + slot: -999, + mouseButton: 0, + action: client.windowClickAction++, + mode: 0, + item: { blockId: -1 }, + }); + } catch (err) { + /* do nothing */ + } + } + + setTimeout(() => { + client._tradeInProgress = false; + }, 200); + }, totalDelay + 100); + } + + //LCE uses recipe ids to craft, whilst java edition requires grid data + //we should write a server plugin that sends the recipe data when crafting because lazy + handleCraftItem(client, data) { + /* do nothing */ + } + handleJavaCrafting(client, data) { + /* do nothing */ + } + placeCraftingItems( + client, + windowId, + itemsToPlace, + inventoryWindow, + startAction, + ) { + /* do nothing */ + } + + //LCE automatically accepts a trade, whilst java requires items in specific slots + //we should write a server plugin that handles this because lazy + handleTradeItem(client, data) { + /* do nothing */ + } + + handleContainerAck(client, data) { + const reader = new PacketReader(data.slice(1)); + const windowId = reader.readByte(); + const action = reader.readShort(); + const accepted = reader.readBoolean(); + + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("transaction", { + windowId: windowId, + action: action, + accepted: accepted, + }); + } catch (err) { + /* do nothing */ + } + } + } + + handleContainerClick(client, data) { + const reader = new PacketReader(data.slice(1)); + const containerId = reader.readByte(); + const slotNum = reader.readShort(); + const buttonNum = reader.readByte(); + const uid = reader.readShort(); + const clickType = reader.readByte(); + + const item = this.readItem(reader); + + //0=Normal click + //1=Shift click + //2=Number key (hotbar swap) + //3=Middle click (creative) + //4=Drop + //5=Drag + //6=Double click + + let javaItem = null; + if (item) { + const javaItemId = this.mapLCEItemToJava(item.blockId); + if (javaItemId !== null) { + javaItem = { + blockId: javaItemId, + itemCount: item.itemCount, + itemDamage: item.itemDamage, + }; + } + } + + if (client.javaClient && client.javaClient.write) { + try { + //luckily both LCE and java use slot -999 for dropping items outside inventory window + let finalMode = clickType; + let finalButton = buttonNum; + + const clickPacket = { + windowId: containerId, + slot: slotNum, + mouseButton: finalButton, + action: uid, + mode: finalMode, + item: javaItem || { blockId: -1 }, + }; + client.javaClient.write("window_click", clickPacket); + } catch (err) { + /* do nothing */ + } + } + } + + handleSetCreativeModeSlot(client, data) { + const reader = new PacketReader(data.slice(1)); + const slotNum = reader.readShort(); + const item = this.readItem(reader); + + let javaItem = null; + if (item) { + const javaItemId = this.mapLCEItemToJava(item.blockId); + if (javaItemId !== null) { + javaItem = { + blockId: javaItemId, + itemCount: item.itemCount, + itemDamage: item.itemDamage, + }; + } + } + + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("set_creative_slot", { + slot: slotNum, + item: javaItem || { blockId: -1 }, + }); + } catch (err) { + /* do nothing */ + } + } + } + + handleClientCommand(client, data) { + const reader = new PacketReader(data.slice(1)); + const action = reader.readByte(); + + if (action === 1) { + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("client_command", { + payload: 0, + }); + } catch (err) { + /* do nothing */ + } + } + } + } + + handleDisconnect(client, data) { + const reader = new PacketReader(data.slice(1)); + const reason = reader.readInt(); + + if (this.clientChests.has(client)) { + const openChestKeys = this.clientChests.get(client); + for (const posKey of openChestKeys) { + const chestData = this.openChests.get(posKey); + if (chestData) { + chestData.clients.delete(client); + + if (chestData.clients.size === 0) { + this.openChests.delete(posKey); + } + } + } + this.clientChests.delete(client); + } + + this.removeClient(client); + + if (client.socket && !client.socket.destroyed) { + client.socket.destroy(); + } + } + + handlePlayerMovement(client, packetId, data) { + const reader = new PacketReader(data.slice(1)); + const dataSize = data.length - 1; + + let x, y, yView, z, yRot, xRot, onGround; + + switch (packetId) { + case 0x0b: //MovePlayerPacket (pos) + if (dataSize < 33) { + return; + } + x = reader.readDouble(); + y = reader.readDouble(); + yView = reader.readDouble(); + z = reader.readDouble(); + onGround = reader.readByte(); + + client.playerX = x; + client.playerY = y; + client.playerZ = z; + + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("position_look", { + x: x, + y: y, + z: z, + yaw: client.lastYaw || 0, + pitch: client.lastPitch || 0, + onGround: onGround !== 0, + }); + } catch (err) { + /* do nothing */ + } + } + break; + + case 0x0c: //MovePlayerPacket (rot) + if (dataSize < 9) { + return; + } + yRot = reader.readFloat(); + xRot = reader.readFloat(); + onGround = reader.readByte(); + + const normalizedYaw = normalizeYaw(yRot); + + client.playerYaw = normalizedYaw; + client.playerPitch = xRot; + + client.lastYaw = normalizedYaw; + client.lastPitch = xRot; + + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("look", { + yaw: normalizedYaw, + pitch: xRot, + onGround: onGround !== 0, + }); + } catch (err) { + /* do nothing */ + } + } + break; + } + } + + readItem(reader) { + return readItem(reader); + } + + writeItemNBT(writer, item) { + return writeItemNBT(writer, item); + } + + writeItem(writer, item) { + return writeItem(writer, item, this.mapJavaItemToLCE.bind(this)); + } + + sendPacket(client, packetId, payload) { + const packetData = Buffer.concat([Buffer.from([packetId]), payload]); + const lengthPrefix = Buffer.allocUnsafe(4); + lengthPrefix.writeUInt32BE(packetData.length, 0); + + const fullPacket = Buffer.concat([lengthPrefix, packetData]); + + const success = client.socket.write(fullPacket); + } + + removeClient(client) { + if (client._removing) { + return; + } + client._removing = true; + + if (this.clientChests.has(client)) { + const openChestKeys = this.clientChests.get(client); + for (const posKey of openChestKeys) { + const chestData = this.openChests.get(posKey); + if (chestData) { + chestData.clients.delete(client); + + if (chestData.clients.size === 0) { + this.openChests.delete(posKey); + } + } + } + this.clientChests.delete(client); + } + + const index = this.clients.indexOf(client); + if (index > -1) { + this.clients.splice(index, 1); + } + + if (client.smallId) { + this.usedSmallIds.delete(client.smallId); + } + + if (client.javaClient) { + try { + client.javaClient.removeAllListeners("error"); + client.javaClient.removeAllListeners("end"); + client.javaClient.removeAllListeners(); + client.javaClient.end(); + } catch (err) { + /* do nothing */ + } + client.javaClient = null; + } + + if (client.socket && !client.socket.destroyed) { + try { + client.socket.destroy(); + } catch (err) { + /* do nothing */ + } + } + } + + connectToJavaServer(client) { + return connectToJavaServerFunc(this, client); + } + + stop() { + if (this.broadcastInterval) { + clearInterval(this.broadcastInterval); + } + + if (this.udpSocket) { + this.udpSocket.close(); + } + + if (this.tcpServer) { + this.tcpServer.close(); + } + + this.clients.forEach((client) => { + client.socket.end(); + }); + } +} + +module.exports = LCEProxy; \ No newline at end of file diff --git a/src/PacketReader.js b/src/PacketReader.js new file mode 100644 index 0000000..67f6fb5 --- /dev/null +++ b/src/PacketReader.js @@ -0,0 +1,75 @@ +class PacketReader { + constructor(buffer) { + this.buffer = buffer; + this.offset = 0; + } + + readByte() { + const value = this.buffer.readInt8(this.offset); + this.offset += 1; + return value; + } + + readUnsignedByte() { + const value = this.buffer.readUInt8(this.offset); + this.offset += 1; + return value; + } + + readShort() { + const value = this.buffer.readInt16BE(this.offset); + this.offset += 2; + return value; + } + + readInt() { + const value = this.buffer.readInt32BE(this.offset); + this.offset += 4; + return value; + } + + readLong() { + const value = this.buffer.readBigInt64BE(this.offset); + this.offset += 8; + return value; + } + + readFloat() { + const value = this.buffer.readFloatBE(this.offset); + this.offset += 4; + return value; + } + + readBoolean() { + return this.readByte() !== 0; + } + + readString() { + const length = this.readShort(); + let str = ""; + for (let i = 0; i < length; i++) { + const charCode = this.buffer.readUInt16BE(this.offset); + this.offset += 2; + str += String.fromCharCode(charCode); + } + return str; + } + + readDouble() { + const value = this.buffer.readDoubleBE(this.offset); + this.offset += 8; + return value; + } + + readFloat() { + const value = this.buffer.readFloatBE(this.offset); + this.offset += 4; + return value; + } + + skip(bytes) { + this.offset += bytes; + } +} + +module.exports = PacketReader; \ No newline at end of file diff --git a/src/PacketWriter.js b/src/PacketWriter.js new file mode 100644 index 0000000..de9fe16 --- /dev/null +++ b/src/PacketWriter.js @@ -0,0 +1,89 @@ +class PacketWriter { + constructor() { + this.buffers = []; + } + + writeByte(value) { + const buf = Buffer.allocUnsafe(1); + buf.writeUInt8(value, 0); + this.buffers.push(buf); + } + + writeSignedByte(value) { + const buf = Buffer.allocUnsafe(1); + buf.writeInt8(value, 0); + this.buffers.push(buf); + } + + writeSignedByte(value) { + const buf = Buffer.allocUnsafe(1); + buf.writeInt8(value, 0); + this.buffers.push(buf); + } + + writeShort(value) { + const buf = Buffer.allocUnsafe(2); + buf.writeInt16BE(value, 0); + this.buffers.push(buf); + } + + writeInt(value) { + const buf = Buffer.allocUnsafe(4); + buf.writeInt32BE(value, 0); + this.buffers.push(buf); + } + + writeLong(value) { + const buf = Buffer.allocUnsafe(8); + buf.writeBigInt64BE(BigInt(value), 0); + this.buffers.push(buf); + } + + writeDouble(value) { + const buf = Buffer.allocUnsafe(8); + buf.writeDoubleBE(value, 0); + this.buffers.push(buf); + } + + writeFloat(value) { + const buf = Buffer.allocUnsafe(4); + buf.writeFloatBE(value, 0); + this.buffers.push(buf); + } + + writeBoolean(value) { + this.writeByte(value ? 1 : 0); + } + + writeUTF(str) { + const utf8Buffer = Buffer.from(str, "utf8"); + this.writeShort(utf8Buffer.length); + this.buffers.push(utf8Buffer); + } + + writeString(str) { + this.writeShort(str.length); + for (let i = 0; i < str.length; i++) { + const buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(str.charCodeAt(i), 0); + this.buffers.push(buf); + } + } + + writeUtf(str) { + this.writeShort(str.length); + for (let i = 0; i < str.length; i++) { + this.writeShort(str.charCodeAt(i)); + } + } + + writeBytes(buffer) { + this.buffers.push(buffer); + } + + toBuffer() { + return Buffer.concat(this.buffers); + } +} + +module.exports = PacketWriter; \ No newline at end of file diff --git a/src/mappings/blockMapping.js b/src/mappings/blockMapping.js new file mode 100644 index 0000000..e8cd6a4 --- /dev/null +++ b/src/mappings/blockMapping.js @@ -0,0 +1,176 @@ +function createBlockMapping() { + return { + 0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 4, + 5: 5, + 6: 6, + 7: 7, + 8: 8, + 9: 9, + 10: 10, + 11: 11, + 12: 12, + 13: 13, + 14: 14, + 15: 15, + 16: 16, + 17: 17, + 18: 18, + 19: 19, + 20: 20, + 21: 21, + 22: 22, + 23: 23, + 24: 24, + 25: 25, + 26: 26, + 27: 27, + 28: 28, + 29: 29, + 30: 30, + 31: 31, + 32: 32, + 33: 33, + 34: 34, + 35: 35, + 36: 36, + 37: 37, + 38: 38, + 39: 39, + 40: 40, + 41: 41, + 42: 42, + 43: 43, + 44: 44, + 45: 45, + 46: 46, + 47: 47, + 48: 48, + 49: 49, + 50: 50, + 51: 51, + 52: 52, + 53: 53, + 54: 54, + 55: 55, + 56: 56, + 57: 57, + 58: 58, + 59: 59, + 60: 60, + 61: 61, + 62: 62, + 63: 63, + 64: 64, + 65: 65, + 66: 66, + 67: 67, + 68: 68, + 69: 69, + 70: 70, + 71: 71, + 72: 72, + 73: 73, + 74: 74, + 75: 75, + 76: 76, + 77: 77, + 78: 78, + 79: 79, + 80: 80, + 81: 81, + 82: 82, + 83: 83, + 84: 84, + 85: 85, + 86: 86, + 87: 87, + 88: 88, + 89: 89, + 90: 90, + 91: 91, + 92: 92, + 93: 93, + 94: 94, + 95: 95, + 96: 96, + 97: 97, + 98: 98, + 99: 99, + 100: 100, + 101: 101, + 102: 102, + 103: 103, + 104: 104, + 105: 105, + 106: 106, + 107: 107, + 108: 108, + 109: 109, + 110: 110, + 111: 111, + 112: 112, + 113: 113, + 114: 114, + 115: 115, + 116: 116, + 117: 117, + 118: 118, + 119: 119, + 120: 120, + 121: 121, + 122: 122, + 123: 123, + 124: 124, + 125: 125, + 126: 126, + 127: 127, + 128: 128, + 129: 129, + 130: 130, + 131: 131, + 132: 132, + 133: 133, + 134: 134, + 135: 135, + 136: 136, + 137: 137, + 138: 138, + 139: 139, + 140: 140, + 141: 141, + 142: 142, + 143: 143, + 144: 144, + 145: 145, + 146: 146, + 147: 147, + 148: 148, + 149: 149, + 150: 150, + 151: 151, + 152: 152, + 153: 153, + 154: 154, + 155: 155, + 156: 156, + 157: 157, + 158: 158, + 159: 159, + 160: 160, + 161: 18, + 162: 17, + 163: 17, + 170: 170, + 171: 171, + 172: 172, + 173: 173, + 174: 174, + 175: 31, + }; +} + +module.exports = { createBlockMapping }; \ No newline at end of file diff --git a/src/mappings/entityMapping.js b/src/mappings/entityMapping.js new file mode 100644 index 0000000..01bc901 --- /dev/null +++ b/src/mappings/entityMapping.js @@ -0,0 +1,67 @@ +function createEntityTypeMapping() { + return { + //monsters + Creeper: 50, + Skeleton: 51, + Spider: 52, + Giant: 53, + Zombie: 54, + Slime: 55, + Ghast: 56, + PigZombie: 57, + Enderman: 58, + CaveSpider: 59, + Silverfish: 60, + Blaze: 61, + LavaSlime: 62, + EnderDragon: 63, + WitherBoss: 64, + Bat: 65, + Witch: 66, + + //animals + Pig: 90, + Sheep: 91, + Cow: 92, + Chicken: 93, + Squid: 94, + Wolf: 95, + MushroomCow: 96, + SnowMan: 97, + Ozelot: 98, + VillagerGolem: 99, + EntityHorse: 100, + + //npcs + Villager: 120, + + //projectile & entities + Item: 1, + XPOrb: 2, + Painting: 9, + Arrow: 10, + Snowball: 11, + Fireball: 12, + SmallFireball: 13, + ThrownEnderpearl: 14, + EyeOfEnderSignal: 15, + ThrownPotion: 16, + ThrownExpBottle: 17, + ItemFrame: 18, + WitherSkull: 19, + PrimedTnt: 20, + FallingSand: 21, + FireworksRocketEntity: 22, + + //transport + Boat: 41, + MinecartRideable: 42, + MinecartChest: 43, + MinecartFurnace: 44, + MinecartTNT: 45, + MinecartHopper: 46, + MinecartSpawner: 47, + }; +} + +module.exports = { createEntityTypeMapping }; \ No newline at end of file diff --git a/src/mappings/idMappers.js b/src/mappings/idMappers.js new file mode 100644 index 0000000..9738a8d --- /dev/null +++ b/src/mappings/idMappers.js @@ -0,0 +1,27 @@ +const { mapJavaBlockToLCE: mapBlockId } = require("./mappers"); + +function mapJavaEntityIdToLce(client, javaEntityId) { + if (!client.javaToLceEntityId.has(javaEntityId)) { + const lceEntityId = client.nextLceEntityId++; + if (lceEntityId > 32767) { + return 100; + } + client.javaToLceEntityId.set(javaEntityId, lceEntityId); + } + return client.javaToLceEntityId.get(javaEntityId); +} + +function mapJavaBlockToLCE(javaBlockId) { + return mapBlockId(javaBlockId); +} + +function mapJavaParticleToLCE(particleId) { + const particleMap = {}; + return particleMap[particleId] || ""; +} + +module.exports = { + mapJavaEntityIdToLce, + mapJavaBlockToLCE, + mapJavaParticleToLCE, +}; \ No newline at end of file diff --git a/src/mappings/index.js b/src/mappings/index.js new file mode 100644 index 0000000..59284c2 --- /dev/null +++ b/src/mappings/index.js @@ -0,0 +1,21 @@ +const { createEntityTypeMapping } = require("./entityMapping"); +const { createItemMapping } = require("./itemMapping"); +const { createBlockMapping } = require("./blockMapping"); +const { + mapJavaBlockToLCE, + mapJavaParticleToLCE, + mapJavaItemToLCE, + mapLCEItemToJava, + mapLCEBlockToJava, +} = require("./mappers"); + +module.exports = { + createEntityTypeMapping, + createItemMapping, + createBlockMapping, + mapJavaBlockToLCE, + mapJavaParticleToLCE, + mapJavaItemToLCE, + mapLCEItemToJava, + mapLCEBlockToJava, +}; \ No newline at end of file diff --git a/src/mappings/itemMapping.js b/src/mappings/itemMapping.js new file mode 100644 index 0000000..b262668 --- /dev/null +++ b/src/mappings/itemMapping.js @@ -0,0 +1,174 @@ +function createItemMapping() { + return { + 256: 256, //iron_shovel + 257: 257, //iron_pickaxe + 258: 258, //iron_axe + 259: 259, //flint_and_steel + 260: 260, //apple + 261: 261, //bow + 262: 262, //arrow + 263: 263, //coal + 264: 264, //diamond + 265: 265, //iron_ingot + 266: 266, //gold_ingot + 267: 267, //iron_sword + 268: 268, //wooden_sword + 269: 269, //wooden_shovel + 270: 270, //wooden_pickaxe + 271: 271, //wooden_axe + 272: 272, //stone_sword + 273: 273, //stone_shovel + 274: 274, //stone_pickaxe + 275: 275, //stone_axe + 276: 276, //diamond_sword + 277: 277, //diamond_shovel + 278: 278, //diamond_pickaxe + 279: 279, //diamond_axe + 280: 280, //stick + 281: 281, //bowl + 282: 282, //mushroom_stew + 283: 283, //golden_sword + 284: 284, //golden_shovel + 285: 285, //golden_pickaxe + 286: 286, //golden_axe + 287: 287, //string + 288: 288, //feather + 289: 289, //gunpowder + 290: 290, //wooden_hoe + 291: 291, //stone_hoe + 292: 292, //iron_hoe + 293: 293, //diamond_hoe + 294: 294, //golden_hoe + 295: 295, //wheat_seeds + 296: 296, //wheat + 297: 297, //bread + 298: 298, //leather_helmet + 299: 299, //leather_chestplate + 300: 300, //leather_leggings + 301: 301, //leather_boots + 302: 302, //chainmail_helmet + 303: 303, //chainmail_chestplate + 304: 304, //chainmail_leggings + 305: 305, //chainmail_boots + 306: 306, //iron_helmet + 307: 307, //iron_chestplate + 308: 308, //iron_leggings + 309: 309, //iron_boots + 310: 310, //diamond_helmet + 311: 311, //diamond_chestplate + 312: 312, //diamond_leggings + 313: 313, //diamond_boots + 314: 314, //golden_helmet + 315: 315, //golden_chestplate + 316: 316, //golden_leggings + 317: 317, //golden_boots + 318: 318, //flint + 319: 319, //porkchop + 320: 320, //cooked_porkchop + 321: 321, //painting + 322: 322, //golden_apple + 323: 323, //sign + 324: 324, //wooden_door + 325: 325, //bucket + 326: 326, //water_bucket + 327: 327, //lava_bucket + 328: 328, //minecart + 329: 329, //saddle + 330: 330, //iron_door + 331: 331, //redstone + 332: 332, //snowball + 333: 333, //boat + 334: 334, //leather + 335: 335, //milk_bucket + 336: 336, //brick + 337: 337, //clay_ball + 338: 338, //reeds (sugar_cane) + 339: 339, //paper + 340: 340, //book + 341: 341, //slime_ball + 342: 342, //chest_minecart + 343: 343, //furnace_minecart + 344: 344, //egg + 345: 345, //compass + 346: 346, //fishing_rod + 347: 347, //clock + 348: 348, //glowstone_dust + 349: 349, //fish (raw) + 350: 350, //cooked_fish + 351: 351, //dye + 352: 352, //bone + 353: 353, //sugar + 354: 354, //cake + 355: 355, //bed + 356: 356, //repeater + 357: 357, //cookie + 358: 358, //filled_map + 359: 359, //shears + 360: 360, //melon + 361: 361, //pumpkin_seeds + 362: 362, //melon_seeds + 363: 363, //beef + 364: 364, //cooked_beef + 365: 365, //chicken + 366: 366, //cooked_chicken + 367: 367, //rotten_flesh + 368: 368, //ender_pearl + 369: 369, //blaze_rod + 370: 370, //ghast_tear + 371: 371, //gold_nugget + 372: 372, //nether_wart + 373: 373, //potion + 374: 374, //glass_bottle + 375: 375, //spider_eye + 376: 376, //fermented_spider_eye + 377: 377, //blaze_powder + 378: 378, //magma_cream + 379: 379, //brewing_stand + 380: 380, //cauldron + 381: 381, //ender_eye + 382: 382, //speckled_melon + 383: 383, //spawn_egg + 384: 384, //experience_bottle + 385: 385, //fire_charge + 388: 388, //emerald + 389: 389, //item_frame + 390: 390, //flower_pot + 391: 391, //carrot + 392: 392, //potato + 393: 393, //baked_potato + 394: 394, //poisonous_potato + 395: 395, //map (empty_map) + 396: 396, //golden_carrot + 397: 397, //skull + 398: 398, //carrot_on_a_stick + 399: 399, //nether_star + 400: 400, //pumpkin_pie + 401: 401, //fireworks (firework_rocket) + 402: 402, //firework_charge (firework_star) + 403: 403, //enchanted_book + 404: 404, //comparator + 405: 405, //netherbrick (nether_brick item) + 406: 406, //quartz + 407: 407, //tnt_minecart + 408: 408, //hopper_minecart + 417: 417, //iron_horse_armor + 418: 418, //golden_horse_armor + 419: 419, //diamond_horse_armor + 420: 420, //lead + 421: 421, //name_tag + 2256: 2256, //record_13 + 2257: 2257, //record_cat + 2258: 2258, //record_blocks + 2259: 2259, //record_chirp + 2260: 2260, //record_far + 2261: 2261, //record_mall + 2262: 2262, //record_mellohi + 2263: 2263, //record_stal + 2264: 2264, //record_strad + 2265: 2265, //record_ward + 2266: 2266, //record_11 + 2267: 2267, //record_wait (4J exclusive!!) + }; +} + +module.exports = { createItemMapping }; diff --git a/src/mappings/mappers.js b/src/mappings/mappers.js new file mode 100644 index 0000000..74cc1c3 --- /dev/null +++ b/src/mappings/mappers.js @@ -0,0 +1,121 @@ +function mapJavaBlockToLCE(javaBlockId, javaBlockMapping) { + if (javaBlockMapping[javaBlockId] !== undefined) { + return javaBlockMapping[javaBlockId]; + } + return 0; +} + +function mapJavaParticleToLCE(particleId) { + const particleMap = { + 0: "explode", + 1: "largeexplode", + 2: "hugeexplosion", + 3: "fireworksSpark", + 4: "bubble", + 5: "splash", + 6: "wake", + 7: "suspended", + 8: "depthsuspend", + 9: "crit", + 10: "magicCrit", + 11: "smoke", + 12: "largesmoke", + 13: "spell", + 14: "instantSpell", + 15: "mobSpell", + 16: "mobSpellAmbient", + 17: "witchMagic", + 18: "dripWater", + 19: "dripLava", + 20: "angryVillager", + 21: "happyVillager", + 22: "townaura", + 23: "note", + 24: "portal", + 25: "enchantmenttable", + 26: "flame", + 27: "lava", + 28: "footstep", + 29: "cloud", + 30: "reddust", + 31: "snowballpoof", + 32: "snowshovel", + 33: "slime", + 34: "heart", + 35: "barrier", + 36: "iconcrack", + 37: "blockcrack", + 38: "blockdust", + 39: "droplet", + 40: "take", + 41: "mobappearance", + 42: "dragonbreath", + 43: "endrod", + 44: "damageindicator", + 45: "sweepattack", + }; + + return particleMap[particleId] || null; +} + +function mapJavaItemToLCE(javaItemId) { + if (javaItemId >= 0 && javaItemId <= 255) { + return this.mapJavaBlockToLCE(javaItemId); + } + + if (this.javaItemMapping[javaItemId] !== undefined) { + return this.javaItemMapping[javaItemId]; + } + + if ( + (javaItemId >= 256 && javaItemId <= 421) || + (javaItemId >= 2256 && javaItemId <= 2267) + ) { + return javaItemId; + } + + return 1; +} + +function mapLCEItemToJava(lceItemId) { + if (lceItemId >= 0 && lceItemId <= 255) { + return this.mapLCEBlockToJava(lceItemId); + } + + if ( + (lceItemId >= 256 && lceItemId <= 421) || + (lceItemId >= 2256 && lceItemId <= 2267) + ) { + for (const [javaId, lceId] of Object.entries(this.javaItemMapping)) { + if (lceId === lceItemId) { + return parseInt(javaId); + } + } + + return lceItemId; + } + + return null; +} + +function mapLCEBlockToJava(lceBlockId) { + for (const [javaId, lceId] of Object.entries(this.javaBlockMapping)) { + if (lceId === lceBlockId) { + return parseInt(javaId); + } + } + + if (lceBlockId >= 0 && lceBlockId <= 174) { + return lceBlockId; + } + + return null; +} + +module.exports = { + mapJavaBlockToLCE, + mapJavaParticleToLCE, + mapJavaItemToLCE, + mapLCEItemToJava, + mapLCEBlockToJava, +}; \ No newline at end of file diff --git a/src/mappings/soundMapping.js b/src/mappings/soundMapping.js new file mode 100644 index 0000000..8c88d29 --- /dev/null +++ b/src/mappings/soundMapping.js @@ -0,0 +1,229 @@ +function mapJavaSoundToLCE(soundName) { + const soundMap = { + "mob.chicken.say": 0, + "mob.chicken": 0, + "entity.chicken.ambient": 0, + "entity.chicken.step": 0, + "mob.chicken.hurt": 1, + "entity.chicken.hurt": 1, + "mob.chicken.plop": 2, + "mob.cow.say": 3, + "mob.cow": 3, + "mob.cow.hurt": 4, + "mob.pig.say": 5, + "mob.pig": 5, + "mob.pig.death": 6, + "mob.sheep.say": 7, + "mob.sheep": 7, + "mob.sheep.death": 7, + "mob.wolf.growl": 8, + "mob.wolf.whine": 9, + "mob.wolf.panting": 10, + "mob.wolf.bark": 11, + "mob.wolf.hurt": 12, + "mob.wolf.death": 13, + "mob.wolf.shake": 14, + "mob.blaze.breathe": 15, + "mob.blaze.hit": 16, + "mob.blaze.death": 17, + "mob.ghast.moan": 18, + "mob.ghast.scream": 19, + "mob.ghast.death": 20, + "mob.ghast.fireball": 21, + "mob.ghast.charge": 22, + "mob.endermen.idle": 23, + "mob.endermen.hit": 24, + "mob.endermen.death": 25, + "mob.endermen.portal": 26, + "mob.zombiepig.zpig": 27, + "mob.zombiepig.zpighurt": 28, + "mob.zombiepig.zpigdeath": 29, + "mob.zombiepig.zpigangry": 30, + "mob.silverfish.say": 31, + "mob.silverfish.hit": 32, + "mob.silverfish.kill": 33, + "mob.silverfish.step": 34, + "mob.skeleton.say": 35, + "mob.skeleton": 35, + "mob.skeleton.hurt": 36, + "mob.spider.say": 37, + "mob.spider.death": 38, + "mob.slime.small": 39, + "mob.slime.attack": 40, + "mob.creeper.say": 41, + "mob.creeper.death": 42, + "mob.zombie.say": 43, + "mob.zombie.hurt": 44, + "mob.zombie.death": 45, + "mob.zombie.wood": 46, + "mob.zombie.woodbreak": 47, + "mob.zombie.metal": 48, + "mob.magmacube.big": 49, + "mob.magmacube.small": 50, + "mob.cat.purr": 51, + "mob.cat.purreow": 52, + "mob.cat.meow": 52, + "mob.cat.hiss": 53, + "random.bow": 55, + "random.bowhit": 56, + "random.explode": 57, + "random.fizz": 58, + "random.pop": 59, + "entity.item.pickup": 59, + "item.pickup": 59, + "random.fuse": 60, + "random.drink": 61, + "random.eat": 62, + "random.burp": 63, + "random.splash": 64, + "random.click": 65, + "dig.glass": 66, + "random.orb": 67, + "random.break": 68, + "random.chestopen": 69, + "random.chestclosed": 70, + "random.door_open": 71, + "random.door_close": 72, + "ambient.weather.rain": 73, + "ambient.weather.thunder": 74, + "ambient.cave.cave": 75, + "portal.portal": 77, + "portal.trigger": 78, + "portal.travel": 79, + "fire.ignite": 80, + "fire.fire": 81, + "damage.hit": 82, + "game.player.hurt": 83, + "game.player.hurt.fall.small": 83, + "game.player.hurt.fall.big": 84, + "game.hostile.hurt.fall.small": 83, + "game.hostile.hurt.fall.big": 84, + "game.neutral.hurt.fall.small": 83, + "game.neutral.hurt.fall.big": 84, + "damage.fallsmall": 83, + "damage.fallbig": 84, + "note.harp": 85, + "note.bd": 86, + "note.snare": 87, + "note.hat": 88, + "note.bassattack": 89, + "note.bass": 89, + "note.pling": 85, + "tile.piston.in": 90, + "tile.piston.out": 91, + "liquid.water": 92, + "liquid.lavapop": 93, + "liquid.lava": 94, + "step.stone": 95, + "step.wood": 96, + "step.gravel": 97, + "step.grass": 98, + "step.metal": 99, + "step.cloth": 100, + "step.sand": 101, + "mob.enderdragon.end": 102, + "mob.enderdragon.growl": 103, + "mob.enderdragon.hit": 104, + "mob.enderdragon.wings": 105, + "mob.irongolem.throw": 106, + "mob.irongolem.hit": 107, + "mob.irongolem.death": 108, + "mob.irongolem.walk": 109, + "damage.thorns": 109, + "random.anvil_break": 110, + "random.anvil_land": 111, + "random.anvil_use": 112, + "mob.villager.haggle": 113, + "mob.villager.idle": 114, + "mob.villager.hit": 115, + "mob.villager.death": 116, + "mob.villager.yes": 117, + "mob.villager.no": 118, + "mob.zombie.infect": 120, + "mob.zombie.unfect": 121, + "mob.zombie.remedy": 122, + "step.snow": 123, + "step.ladder": 124, + "dig.cloth": 124, + "dig.grass": 125, + "dig.gravel": 126, + "dig.sand": 127, + "dig.snow": 128, + "dig.stone": 129, + "dig.wood": 130, + "fireworks.launch": 132, + "fireworks.blast": 133, + "fireworks.blast_far": 134, + "fireworks.largeBlast": 135, + "fireworks.largeBlast_far": 136, + "fireworks.twinkle": 137, + "fireworks.twinkle_far": 138, + "mob.bat.idle": 139, + "mob.bat.hurt": 140, + "mob.bat.death": 141, + "mob.bat.takeoff": 142, + "mob.wither.spawn": 142, + "mob.wither.idle": 143, + "mob.wither.hurt": 144, + "mob.wither.death": 145, + "mob.wither.shoot": 146, + "mob.cow.step": 148, + "step.cow": 148, + "mob.chicken.step": 149, + "step.chicken": 149, + "mob.pig.step": 150, + "step.pig": 150, + "mob.endermen.stare": 151, + "mob.endermen.scream": 152, + "mob.sheep.shear": 153, + "mob.sheep.step": 154, + "mob.skeleton.death": 155, + "mob.skeletondeath": 155, + "mob.skeleton.step": 156, + "mob.spider.step": 157, + "mob.wolf.step": 158, + "mob.zombie.step": 159, + "liquid.swim": 160, + "game.player.swim": 159, + "game.player.swim.splash": 64, + "game.hostile.swim.splash": 64, + "game.neutral.swim.splash": 64, + "game.neutral.swim": 159, + "game.hostile.swim": 159, + "mob.horse.land": 161, + "mob.horse.armor": 162, + "mob.horse.leather": 163, + "mob.horse.zombie.death": 164, + "mob.horse.skeleton.death": 165, + "mob.horse.donkey.death": 166, + "mob.horse.death": 167, + "mob.horse.zombie.hit": 168, + "mob.horse.skeleton.hit": 169, + "mob.horse.donkey.hit": 170, + "mob.horse.hit": 171, + "mob.horse.zombie.idle": 172, + "mob.horse.skeleton.idle": 173, + "mob.horse.donkey.idle": 174, + "mob.horse.idle": 175, + "mob.horse.donkey.angry": 176, + "mob.horse.angry": 177, + "mob.horse.gallop": 178, + "mob.horse.breathe": 179, + "mob.horse.wood": 180, + "mob.horse.soft": 181, + "mob.horse.jump": 182, + "mob.witch.idle": 183, + "mob.witch.hurt": 184, + "mob.witch.death": 185, + "mob.slime.big": 186, + "mob.slime": 187, + eat: 187, + "random.levelup": 188, + "fire.active": 189, + }; + + const result = soundMap[soundName]; + return result !== undefined ? result : -1; +} + +module.exports = { mapJavaSoundToLCE }; \ No newline at end of file diff --git a/src/packets/senders/containerPackets.js b/src/packets/senders/containerPackets.js new file mode 100644 index 0000000..a11170e --- /dev/null +++ b/src/packets/senders/containerPackets.js @@ -0,0 +1,48 @@ +const PacketWriter = require("../../PacketWriter"); + +function sendContainerOpenPacket(proxy, client, packet) { + const windowTypeMapping = { + "minecraft:container": 0, //container + "minecraft:chest": 0, //container + "minecraft:crafting_table": 1, //workbench + "minecraft:furnace": 2, //furnace + "minecraft:dispenser": 3, //trap + "minecraft:enchanting_table": 4, //enchantment + "minecraft:brewing_stand": 5, //brewing_stand + "minecraft:villager": 6, //trader npc + "minecraft:beacon": 7, //beacon + "minecraft:anvil": 8, //repair table + "minecraft:hopper": 9, //hopper + "minecraft:dropper": 10, //dropper + "minecraft:horse": 11, //horse + }; + + const windowType = packet.inventoryType || packet.windowType; + const lceType = windowTypeMapping[windowType] || 0; + const containerId = packet.windowId; + const title = packet.windowTitle + ? JSON.parse(packet.windowTitle).text || "" + : ""; + const size = packet.slotCount || 27; + const customName = title.length > 0; + + const writer = new PacketWriter(); + writer.writeByte(containerId & 0xff); + writer.writeByte(lceType & 0xff); + writer.writeByte(size & 0xff); + writer.writeBoolean(customName); + + if (lceType === 11) { //horse + writer.writeInt(packet.entityId || 0); + } + + if (customName) { + writer.writeUtf(title); + } + + proxy.sendPacket(client, 0x64, writer.toBuffer()); +} + +module.exports = { + sendContainerOpenPacket, +}; \ No newline at end of file diff --git a/src/packets/senders/entityPackets.js b/src/packets/senders/entityPackets.js new file mode 100644 index 0000000..deab4e8 --- /dev/null +++ b/src/packets/senders/entityPackets.js @@ -0,0 +1,544 @@ +const PacketWriter = require("../../PacketWriter"); + +function sendAddMobPacket(proxy, client, entityInfo) { + const entityKey = `${entityInfo.javaEntityId}`; + if (client._sentEntities && client._sentEntities.has(entityKey)) { + return; + } + if (!client._sentEntities) { + client._sentEntities = new Set(); + } + client._sentEntities.add(entityKey); + + const writer = new PacketWriter(); + writer.writeShort(entityInfo.entityId); + writer.writeByte(entityInfo.type & 0xff); + + writer.writeInt(Math.floor(entityInfo.x * 32)); + writer.writeInt(Math.floor(entityInfo.y * 32)); + writer.writeInt(Math.floor(entityInfo.z * 32)); + + const yRotByte = Math.floor(((entityInfo.yaw % 360) / 360) * 256) & 0xff; + const xRotByte = Math.floor(((entityInfo.pitch % 360) / 360) * 256) & 0xff; + const yHeadRotByte = + Math.floor(((entityInfo.headYaw % 360) / 360) * 256) & 0xff; + writer.writeByte(yRotByte); + writer.writeByte(xRotByte); + writer.writeByte(yHeadRotByte); + + let velX = entityInfo.velocityX || 0; + let velY = entityInfo.velocityY || 0; + let velZ = entityInfo.velocityZ || 0; + velX = Math.max(-3.9, Math.min(3.9, velX)); + velY = Math.max(-3.9, Math.min(3.9, velY)); + velZ = Math.max(-3.9, Math.min(3.9, velZ)); + const velocityX = Math.floor(velX * 8000); + const velocityY = Math.floor(velY * 8000); + const velocityZ = Math.floor(velZ * 8000); + writer.writeShort(velocityX); + writer.writeShort(velocityY); + writer.writeShort(velocityZ); + + writer.writeByte((0 << 5) | 0); + writer.writeByte(0); + + writer.writeByte((1 << 5) | 1); + writer.writeShort(300); + + const agableMobTypes = [92, 91, 90, 93, 120]; + if (agableMobTypes.includes(entityInfo.type)) { + const ageMetadata = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 12) + : null; + if (ageMetadata && ageMetadata.value !== undefined) { + writer.writeByte((2 << 5) | 12); + writer.writeInt(ageMetadata.value); + } + } + + if (entityInfo.type === 120) { + const professionMetadata = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 16 && m.type === 2) + : null; + if (professionMetadata && professionMetadata.value !== undefined) { + writer.writeByte((2 << 5) | 16); + writer.writeInt(professionMetadata.value); + } + } + + const customNameMeta = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 2 && m.type === 4) + : null; + if (customNameMeta && customNameMeta.value) { + writer.writeByte((4 << 5) | 10); + writer.writeUtf(customNameMeta.value); + } + + const customNameVisibleMeta = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 3 && m.type === 0) + : null; + if (customNameVisibleMeta && customNameVisibleMeta.value !== undefined) { + writer.writeByte((0 << 5) | 11); + writer.writeByte(customNameVisibleMeta.value & 0xff); + } + + if (entityInfo.type === 55 || entityInfo.type === 62) { + const sizeMetadata = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 16 && m.type === 0) + : null; + if (sizeMetadata && sizeMetadata.value !== undefined) { + writer.writeByte((0 << 5) | 16); + writer.writeByte(sizeMetadata.value & 0xff); + } + } + + if (entityInfo.type === 51) { + const typeMetadata = entityInfo.metadata + ? entityInfo.metadata.find((m) => m.key === 13 && m.type === 0) + : null; + if (typeMetadata && typeMetadata.value !== undefined) { + writer.writeByte((0 << 5) | 13); + writer.writeByte(typeMetadata.value & 0xff); + } + } + + writer.writeByte(0x7f); + + const payload = writer.toBuffer(); + proxy.sendPacket(client, 0x18, payload); +} + +function sendAddEntityPacket(proxy, client, entityInfo) { + const writer = new PacketWriter(); + writer.writeShort(entityInfo.entityId); + writer.writeByte(entityInfo.type); + + writer.writeInt(Math.floor(entityInfo.x * 32)); + writer.writeInt(Math.floor(entityInfo.y * 32)); + writer.writeInt(Math.floor(entityInfo.z * 32)); + + const yRotByte = Math.floor(((entityInfo.yaw % 360) / 360) * 256) & 0xff; + const xRotByte = Math.floor(((entityInfo.pitch % 360) / 360) * 256) & 0xff; + + writer.writeByte(yRotByte); + writer.writeByte(xRotByte); + + const data = entityInfo.data !== undefined ? entityInfo.data : -1; + writer.writeInt(data); + + if (data > -1) { + const velocityX = entityInfo.velocityX || 0; + const velocityY = entityInfo.velocityY || 0; + const velocityZ = entityInfo.velocityZ || 0; + + writer.writeShort(Math.max(-32768, Math.min(32767, velocityX))); + writer.writeShort(Math.max(-32768, Math.min(32767, velocityY))); + writer.writeShort(Math.max(-32768, Math.min(32767, velocityZ))); + } + + proxy.sendPacket(client, 0x17, writer.toBuffer()); +} + +function sendMoveEntityPacketForEntity( + proxy, + client, + entity, + dX, + dY, + dZ, + includeRotation = false, +) { + if (Math.abs(dX) <= 127 && Math.abs(dY) <= 127 && Math.abs(dZ) <= 127) { + const writer = new PacketWriter(); + writer.writeShort(entity.entityId); + writer.writeByte(dX & 0xff); + writer.writeByte(dY & 0xff); + writer.writeByte(dZ & 0xff); + + if (includeRotation) { + const prevYaw = + entity.prevYaw !== undefined ? entity.prevYaw : entity.yaw; + const prevPitch = + entity.prevPitch !== undefined ? entity.prevPitch : entity.pitch; + + let deltaYaw = entity.yaw - prevYaw; + let deltaPitch = entity.pitch - prevPitch; + + while (deltaYaw > 180) deltaYaw -= 360; + while (deltaYaw < -180) deltaYaw += 360; + while (deltaPitch > 180) deltaPitch -= 360; + while (deltaPitch < -180) deltaPitch += 360; + + const dYawByte = Math.floor((deltaYaw / 360) * 256) & 0xff; + const dPitchByte = Math.floor((deltaPitch / 360) * 256) & 0xff; + + writer.writeByte(dYawByte); + writer.writeByte(dPitchByte); + + entity.prevYaw = entity.yaw; + entity.prevPitch = entity.pitch; + + proxy.sendPacket(client, 0x21, writer.toBuffer()); + } else { + proxy.sendPacket(client, 0x1f, writer.toBuffer()); + } + } else { + sendTeleportEntityPacketForEntity(proxy, client, entity); + } +} + +function sendTeleportEntityPacketForEntity(proxy, client, entity) { + const writer = new PacketWriter(); + writer.writeShort(entity.entityId); + + writer.writeInt(Math.floor(entity.x * 32)); + writer.writeInt(Math.floor(entity.y * 32)); + writer.writeInt(Math.floor(entity.z * 32)); + + const yRotByte = Math.floor(((entity.yaw % 360) / 360) * 256) & 0xff; + const xRotByte = Math.floor(((entity.pitch % 360) / 360) * 256) & 0xff; + writer.writeByte(yRotByte); + writer.writeByte(xRotByte); + + proxy.sendPacket(client, 34, writer.toBuffer()); +} + +function sendRotateEntityPacketForEntity(proxy, client, entity) { + const writer = new PacketWriter(); + writer.writeShort(entity.entityId); + + const prevYaw = entity.prevYaw !== undefined ? entity.prevYaw : entity.yaw; + const prevPitch = + entity.prevPitch !== undefined ? entity.prevPitch : entity.pitch; + + let deltaYaw = entity.yaw - prevYaw; + let deltaPitch = entity.pitch - prevPitch; + + while (deltaYaw > 180) deltaYaw -= 360; + while (deltaYaw < -180) deltaYaw += 360; + while (deltaPitch > 180) deltaPitch -= 360; + while (deltaPitch < -180) deltaPitch += 360; + + const dYawByte = Math.floor((deltaYaw / 360) * 256) & 0xff; + const dPitchByte = Math.floor((deltaPitch / 360) * 256) & 0xff; + + writer.writeByte(dYawByte); + writer.writeByte(dPitchByte); + + entity.prevYaw = entity.yaw; + entity.prevPitch = entity.pitch; + + proxy.sendPacket(client, 0x20, writer.toBuffer()); +} + +function sendRotateHeadPacketForEntity(proxy, client, entity) { + const writer = new PacketWriter(); + writer.writeInt(entity.entityId); + + const yHeadRotByte = Math.floor(((entity.headYaw % 360) / 360) * 256) & 0xff; + writer.writeByte(yHeadRotByte); + + proxy.sendPacket(client, 35, writer.toBuffer()); +} + +function sendEntityMetadataPacket(proxy, client, entity, metadata) { + const writer = new PacketWriter(); + writer.writeInt(entity.entityId); + for (const item of metadata) { + if (item.key === 12 && item.type === 0) { + const ageableMobTypes = [ + "Pig", + "Cow", + "Sheep", + "Chicken", + "Wolf", + "Ocelot", + "MushroomCow", + ]; + const isAgeableMob = ageableMobTypes.includes(entity.javaType); + + if (isAgeableMob && item.value === -1) { + const header = (2 << 5) | 12; + writer.writeByte(header); + writer.writeInt(-24000); + continue; + } else if (isAgeableMob && item.value === 0) { + const header = (2 << 5) | 12; + writer.writeByte(header); + writer.writeInt(0); + continue; + } + } + const header = (item.type << 5) | item.key; + writer.writeByte(header); + + switch (item.type) { + case 0: + writer.writeByte(item.value & 0xff); + break; + case 1: + writer.writeShort(item.value); + break; + case 2: + writer.writeInt(item.value); + break; + case 3: + writer.writeFloat(item.value); + break; + case 4: + writer.writeUtf(item.value); + break; + case 5: + continue; + default: + continue; + } + } + writer.writeByte(0x7f); + + proxy.sendPacket(client, 0x28, writer.toBuffer()); +} + +function sendSetEntityMotionPacket(proxy, client, entity) { + if (!entity || entity.entityId === undefined || entity.entityId < 0) { + return; + } + + let xa = entity.velocityX || 0; + let ya = entity.velocityY || 0; + let za = entity.velocityZ || 0; + + const maxVel = 31200; + xa = Math.max(-maxVel, Math.min(maxVel, xa)); + ya = Math.max(-maxVel, Math.min(maxVel, ya)); + za = Math.max(-maxVel, Math.min(maxVel, za)); + + const writer = new PacketWriter(); + + try { + const useBytes = + xa >= -2048 && + xa < 2048 && + ya >= -2048 && + ya < 2048 && + za >= -2048 && + za < 2048; + if (useBytes) { + writer.writeShort((entity.entityId & 0x07ff) | 0x800); + + const xByte = Math.floor(xa / 16); + const yByte = Math.floor(ya / 16); + const zByte = Math.floor(za / 16); + + writer.writeSignedByte(xByte); + writer.writeSignedByte(yByte); + writer.writeSignedByte(zByte); + } else { + writer.writeShort(entity.entityId & 0x07ff); + + writer.writeShort(xa); + writer.writeShort(ya); + writer.writeShort(za); + } + const payload = writer.toBuffer(); + proxy.sendPacket(client, 0x1c, payload); + } catch (err) { + /* do nothing */ + } +} + +function sendEntityEventPacket(proxy, client, entity, eventId) { + const writer = new PacketWriter(); + writer.writeInt(entity.entityId); + writer.writeByte(eventId & 0xff); + + proxy.sendPacket(client, 0x26, writer.toBuffer()); +} + +function sendSetEquippedItemPacket(proxy, client, entity, slot, item) { + const writer = new PacketWriter(); + writer.writeInt(entity.entityId); + writer.writeShort(slot); + + if (!item || item.blockId === undefined || item.blockId === -1) { + writer.writeShort(-1); + proxy.sendPacket(client, 0x05, writer.toBuffer()); + + return; + } + + const javaItemId = item.blockId; + const count = item.itemCount || 1; + let damage = item.itemDamage || 0; + + const lceItemId = proxy.mapJavaItemToLCE(javaItemId); + + if (lceItemId === 1 && javaItemId !== 1) { + damage = 0; + } + + if (lceItemId === -1 || lceItemId === 0) { + writer.writeShort(-1); + proxy.sendPacket(client, 0x05, writer.toBuffer()); + + return; + } + + if ( + (lceItemId >= 1 && lceItemId <= 174) || + (lceItemId >= 256 && lceItemId <= 421) || + (lceItemId >= 2256 && lceItemId <= 2267) + ) { + writer.writeShort(lceItemId); + writer.writeByte(count); + writer.writeShort(damage); + } else { + writer.writeShort(-1); + proxy.sendPacket(client, 0x05, writer.toBuffer()); + return; + } + + writer.writeShort(-1); + + proxy.sendPacket(client, 0x05, writer.toBuffer()); +} + +function sendLevelParticlesPacket( + proxy, + client, + name, + x, + y, + z, + xDist, + yDist, + zDist, + maxSpeed, + count, +) { + const writer = new PacketWriter(); + + writer.writeString(name); + writer.writeFloat(x); + writer.writeFloat(y); + writer.writeFloat(z); + writer.writeFloat(xDist); + writer.writeFloat(yDist); + writer.writeFloat(zDist); + writer.writeFloat(maxSpeed); + writer.writeInt(count); + + const buffer = writer.toBuffer(); + proxy.sendPacket(client, 63, buffer); +} + +function sendTileUpdatePacket(proxy, client, x, y, z, blockId, metadata) { + const writer = new PacketWriter(); + + writer.writeInt(x); + writer.writeByte(y & 0xff); + writer.writeInt(z); + writer.writeShort(blockId & 0xffff); + + const levelIdx = + client.javaDimension === -1 ? 1 : client.javaDimension === 1 ? 2 : 0; + const dataLevel = ((levelIdx & 0xf) << 4) | (metadata & 0xf); + writer.writeByte(dataLevel); + + const buffer = writer.toBuffer(); + proxy.sendPacket(client, 53, buffer); +} + +function sendSetItemDataPacket(proxy, client, entity, itemData) { + const lceItemId = proxy.mapJavaItemToLCE(itemData.blockId); + + if (lceItemId === -1 || lceItemId === 0) { + return; + } + + const writer = new PacketWriter(); + writer.writeInt(entity.entityId); + + writer.writeByte((5 << 5) | 10); + + writer.writeShort(lceItemId); + writer.writeByte(itemData.itemCount); + writer.writeShort(itemData.itemDamage); + + writer.writeShort(-1); + + writer.writeByte(0x7f); + + const payload = writer.toBuffer(); + + proxy.sendPacket(client, 0x28, payload); +} + +function sendSetEntityDataPacket(proxy, client, entity) { + const writer = new PacketWriter(); + writer.writeInt(entity.entityId); + + const sharedFlagsHeader = (0 << 5) | 0; + writer.writeByte(sharedFlagsHeader); + writer.writeByte(0); + + writer.writeByte(0x7f); + + proxy.sendPacket(client, 0x27, writer.toBuffer()); +} + +function sendUpdateAttributesPacket(proxy, client, entity) { + const writer = new PacketWriter(); + writer.writeInt(entity.entityId); + + const attributes = []; + + attributes.push({ id: 0, base: 20.0, modifiers: [] }); + + if (entity.type !== 94) { + attributes.push({ id: 3, base: 0.25, modifiers: [] }); + } + + if (entity.type >= 50 && entity.type <= 66) { + attributes.push({ id: 1, base: 32.0, modifiers: [] }); + attributes.push({ id: 4, base: 2.0, modifiers: [] }); + } + + writer.writeInt(attributes.length); + + for (const attr of attributes) { + writer.writeShort(attr.id); + writer.writeDouble(attr.base); + writer.writeShort(attr.modifiers.length); + } + + const payload = writer.toBuffer(); + + proxy.sendPacket(client, 0x2c, payload); +} + +function sendSetEntityLinkPacket(proxy, client, sourceId, destId, linkType) { + const writer = new PacketWriter(); + writer.writeInt(sourceId); + writer.writeInt(destId); + writer.writeByte(linkType); + const buffer = writer.toBuffer(); + proxy.sendPacket(client, 0x27, buffer); +} + +module.exports = { + sendAddMobPacket, + sendAddEntityPacket, + sendMoveEntityPacketForEntity, + sendTeleportEntityPacketForEntity, + sendRotateEntityPacketForEntity, + sendRotateHeadPacketForEntity, + sendEntityMetadataPacket, + sendSetEntityMotionPacket, + sendEntityEventPacket, + sendSetEquippedItemPacket, + sendSetItemDataPacket, + sendSetEntityDataPacket, + sendUpdateAttributesPacket, + sendSetEntityLinkPacket, +}; \ No newline at end of file diff --git a/src/packets/senders/index.js b/src/packets/senders/index.js new file mode 100644 index 0000000..040b778 --- /dev/null +++ b/src/packets/senders/index.js @@ -0,0 +1,11 @@ +const playerPackets = require("./playerPackets"); +const entityPackets = require("./entityPackets"); +const worldPackets = require("./worldPackets"); +const containerPackets = require("./containerPackets"); + +module.exports = { + ...playerPackets, + ...entityPackets, + ...worldPackets, + ...containerPackets, +}; \ No newline at end of file diff --git a/src/packets/senders/playerPackets.js b/src/packets/senders/playerPackets.js new file mode 100644 index 0000000..b2a69ab --- /dev/null +++ b/src/packets/senders/playerPackets.js @@ -0,0 +1,115 @@ +const PacketWriter = require("../../PacketWriter"); + +function sendMovePlayerPacket(proxy, client, x, y, z, yaw, pitch) { + const lceY = y + 1.65; + const moveWriter = new PacketWriter(); + moveWriter.writeDouble(x); + moveWriter.writeDouble(lceY); + moveWriter.writeDouble(lceY + 1.62); //eye offset + moveWriter.writeDouble(z); + moveWriter.writeFloat(yaw); + moveWriter.writeFloat(pitch); + moveWriter.writeByte(0x01); + proxy.sendPacket(client, 0x0d, moveWriter.toBuffer()); +} + +function sendAddPlayerPacket(proxy, client, playerInfo) { + let playerName = playerInfo.name || "undefined"; + if (playerName.length > 16) { + playerName = playerName.substring(0, 16); + } + if (playerName.length === 0) { + playerName = "undefined"; + } + + const writer = new PacketWriter(); + writer.writeInt(playerInfo.entityId); + writer.writeString(playerName); + + writer.writeInt(Math.floor(playerInfo.x * 32)); + writer.writeInt(Math.floor(playerInfo.y * 32)); + writer.writeInt(Math.floor(playerInfo.z * 32)); + + const yRotByte = Math.floor(((playerInfo.yaw % 360) / 360) * 256) & 0xff; + const xRotByte = Math.floor(((playerInfo.pitch % 360) / 360) * 256) & 0xff; + writer.writeByte(yRotByte); + writer.writeByte(xRotByte); + writer.writeByte(yRotByte); + + writer.writeShort(0); //carriedItem + writer.writeLong(0); //xuid + writer.writeLong(0); //OnlineXuid + writer.writeByte(0); //playerIndex + writer.writeInt(0); //skinId + writer.writeInt(0); //capeId + writer.writeInt(0); //uiGamePrivileges + + writer.writeByte(0x7f); + + proxy.sendPacket(client, 0x14, writer.toBuffer()); +} + +function sendMoveEntityPacket(proxy, client, playerInfo) { + sendTeleportEntityPacket(proxy, client, playerInfo); +} + +function sendTeleportEntityPacket(proxy, client, playerInfo) { + const writer = new PacketWriter(); + writer.writeInt(playerInfo.entityId); + + writer.writeInt(Math.floor(playerInfo.x * 32)); + writer.writeInt(Math.floor(playerInfo.y * 32)); + writer.writeInt(Math.floor(playerInfo.z * 32)); + + const yRotByte = Math.floor(((playerInfo.yaw % 360) / 360) * 256) & 0xff; + const xRotByte = Math.floor(((playerInfo.pitch % 360) / 360) * 256) & 0xff; + writer.writeByte(yRotByte); + writer.writeByte(xRotByte); + writer.writeByte(0x01); //onGround + + proxy.sendPacket(client, 34, writer.toBuffer()); + + sendRotateHeadPacket(proxy, client, playerInfo); +} + +function sendRotateHeadPacket(proxy, client, playerInfo) { + const writer = new PacketWriter(); + writer.writeInt(playerInfo.entityId); + + const yHeadRotByte = Math.floor(((playerInfo.yaw % 360) / 360) * 256) & 0xff; + writer.writeByte(yHeadRotByte); + + proxy.sendPacket(client, 35, writer.toBuffer()); +} + +function sendChatPacket( + proxy, + client, + message, + messageType = 0, + customData = -1, +) { + const writer = new PacketWriter(); + + writer.writeInt(messageType); + + writer.writeInt(1); + writer.writeString(message); + + writer.writeInt(0); + + if (customData !== -1) { + writer.writeInt(customData); + } + + proxy.sendPacket(client, 3, writer.toBuffer()); +} + +module.exports = { + sendMovePlayerPacket, + sendAddPlayerPacket, + sendMoveEntityPacket, + sendTeleportEntityPacket, + sendRotateHeadPacket, + sendChatPacket, +}; \ No newline at end of file diff --git a/src/packets/senders/worldPackets.js b/src/packets/senders/worldPackets.js new file mode 100644 index 0000000..9301c31 --- /dev/null +++ b/src/packets/senders/worldPackets.js @@ -0,0 +1,72 @@ +const PacketWriter = require("../../PacketWriter"); + +function sendLevelSoundPacket(proxy, client, soundId, x, y, z, volume, pitch) { + const safeX = x !== undefined && x !== null && !isNaN(x) ? x : 0; + const safeY = y !== undefined && y !== null && !isNaN(y) ? y : 0; + const safeZ = z !== undefined && z !== null && !isNaN(z) ? z : 0; + const safeVolume = + volume !== undefined && volume !== null && !isNaN(volume) ? volume : 1.0; + const safePitch = + pitch !== undefined && pitch !== null && !isNaN(pitch) ? pitch : 1.0; + + const writer = new PacketWriter(); + writer.writeInt(soundId); + writer.writeInt(Math.floor(safeX * 8.0)); + writer.writeInt(Math.floor(safeY * 8.0)); + writer.writeInt(Math.floor(safeZ * 8.0)); + writer.writeFloat(safeVolume); + writer.writeFloat(safePitch); + + proxy.sendPacket(client, 0x3e, writer.toBuffer()); +} + +function sendLevelParticlesPacket( + proxy, + client, + name, + x, + y, + z, + xDist, + yDist, + zDist, + maxSpeed, + count, +) { + const writer = new PacketWriter(); + + writer.writeString(name); + writer.writeFloat(x); + writer.writeFloat(y); + writer.writeFloat(z); + writer.writeFloat(xDist); + writer.writeFloat(yDist); + writer.writeFloat(zDist); + writer.writeFloat(maxSpeed); + writer.writeInt(count); + + const buffer = writer.toBuffer(); + proxy.sendPacket(client, 63, buffer); +} + +function sendTileUpdatePacket(proxy, client, x, y, z, blockId, metadata) { + const writer = new PacketWriter(); + + writer.writeInt(x); + writer.writeByte(y & 0xff); + writer.writeInt(z); + writer.writeShort(blockId & 0xffff); + const levelIdx = + client.javaDimension === -1 ? 1 : client.javaDimension === 1 ? 2 : 0; + const dataLevel = ((levelIdx & 0xf) << 4) | (metadata & 0xf); + writer.writeByte(dataLevel); + + const buffer = writer.toBuffer(); + proxy.sendPacket(client, 53, buffer); +} + +module.exports = { + sendLevelSoundPacket, + sendLevelParticlesPacket, + sendTileUpdatePacket, +}; \ No newline at end of file diff --git a/src/utils.js b/src/utils.js new file mode 100644 index 0000000..4a4faa1 --- /dev/null +++ b/src/utils.js @@ -0,0 +1,16 @@ +function encodeVarInt(value) { + const bytes = []; + do { + let temp = value & 0x7f; + value >>>= 7; + if (value !== 0) { + temp |= 0x80; + } + bytes.push(temp); + } while (value !== 0); + return Buffer.from(bytes); +} + +module.exports = { + encodeVarInt, +}; \ No newline at end of file diff --git a/src/utils/chat.js b/src/utils/chat.js new file mode 100644 index 0000000..a83912d --- /dev/null +++ b/src/utils/chat.js @@ -0,0 +1,523 @@ +function getTranslation(key, args = []) { + const translations = { + "chat.type.text": (args) => `<${args[0]}> ${args[1]}`, + "chat.type.announcement": (args) => `[${args[0]}] ${args[1]}`, + "chat.type.admin": (args) => `[${args[0]}] ${args[1]}`, + "chat.type.emote": (args) => `* ${args[0]} ${args[1]}`, + + "multiplayer.player.joined": (args) => `${args[0]} joined the game`, + "multiplayer.player.left": (args) => `${args[0]} left the game`, + + "death.attack.mob": (args) => `${args[0]} was slain by ${args[1]}`, + "death.attack.player": (args) => `${args[0]} was slain by ${args[1]}`, + "death.attack.player.item": (args) => + `${args[0]} was slain by ${args[1]} using ${args[2]}`, + "death.attack.arrow": (args) => `${args[0]} was shot by ${args[1]}`, + "death.attack.arrow.item": (args) => + `${args[0]} was shot by ${args[1]} using ${args[2]}`, + "death.attack.fireball": (args) => + `${args[0]} was fireballed by ${args[1]}`, + "death.attack.fireball.item": (args) => + `${args[0]} was fireballed by ${args[1]} using ${args[2]}`, + "death.attack.thrown": (args) => `${args[0]} was pummeled by ${args[1]}`, + "death.attack.thrown.item": (args) => + `${args[0]} was pummeled by ${args[1]} using ${args[2]}`, + "death.attack.indirectMagic": (args) => + `${args[0]} was killed by ${args[1]} using magic`, + "death.attack.indirectMagic.item": (args) => + `${args[0]} was killed by ${args[1]} using ${args[2]}`, + "death.attack.thorns": (args) => + `${args[0]} was killed trying to hurt ${args[1]}`, + "death.attack.fall": (args) => `${args[0]} hit the ground too hard`, + "death.attack.outOfWorld": (args) => `${args[0]} fell out of the world`, + "death.fell.accident.ladder": (args) => `${args[0]} fell off a ladder`, + "death.fell.accident.vines": (args) => `${args[0]} fell off some vines`, + "death.fell.accident.water": (args) => `${args[0]} fell out of the water`, + "death.fell.accident.generic": (args) => + `${args[0]} fell from a high place`, + "death.fell.killer": (args) => `${args[0]} was doomed to fall`, + "death.fell.assist": (args) => + `${args[0]} was doomed to fall by ${args[1]}`, + "death.fell.assist.item": (args) => + `${args[0]} was doomed to fall by ${args[1]} using ${args[2]}`, + "death.fell.finish": (args) => + `${args[0]} fell too far and was finished by ${args[1]}`, + "death.fell.finish.item": (args) => + `${args[0]} fell too far and was finished by ${args[1]} using ${args[2]}`, + "death.attack.lightningBolt": (args) => + `${args[0]} was struck by lightning`, + "death.attack.inFire": (args) => `${args[0]} went up in flames`, + "death.attack.inFire.player": (args) => + `${args[0]} walked into fire whilst fighting ${args[1]}`, + "death.attack.onFire": (args) => `${args[0]} burned to death`, + "death.attack.onFire.player": (args) => + `${args[0]} was burnt to a crisp whilst fighting ${args[1]}`, + "death.attack.lava": (args) => `${args[0]} tried to swim in lava`, + "death.attack.lava.player": (args) => + `${args[0]} tried to swim in lava to escape ${args[1]}`, + "death.attack.inWall": (args) => `${args[0]} suffocated in a wall`, + "death.attack.drown": (args) => `${args[0]} drowned`, + "death.attack.drown.player": (args) => + `${args[0]} drowned whilst trying to escape ${args[1]}`, + "death.attack.starve": (args) => `${args[0]} starved to death`, + "death.attack.cactus": (args) => `${args[0]} was pricked to death`, + "death.attack.cactus.player": (args) => + `${args[0]} walked into a cactus whilst trying to escape ${args[1]}`, + "death.attack.generic": (args) => `${args[0]} died`, + "death.attack.explosion": (args) => `${args[0]} blew up`, + "death.attack.explosion.player": (args) => + `${args[0]} was blown up by ${args[1]}`, + "death.attack.magic": (args) => `${args[0]} was killed by magic`, + "death.attack.wither": (args) => `${args[0]} withered away`, + "death.attack.anvil": (args) => + `${args[0]} was squashed by a falling anvil`, + "death.attack.fallingBlock": (args) => + `${args[0]} was squashed by a falling block`, + + "commands.gamemode.success.self": (args) => + `Set own game mode to ${args[0]}`, + "commands.gamemode.success.other": (args) => + `Set ${args[0]}'s game mode to ${args[1]}`, + "gameMode.survival": () => "Survival Mode", + "gameMode.creative": () => "Creative Mode", + "gameMode.adventure": () => "Adventure Mode", + "gameMode.spectator": () => "Spectator Mode", + "gameMode.changed": () => "Your game mode has been updated", + + "commands.time.set": (args) => + args[0] ? `Set time to ${args[0]}` : "Set the time", + "commands.time.added": (args) => + args[0] ? `Added ${args[0]} to the time` : "Added to the time", + "commands.time.query": (args) => + args[0] ? `The time is ${args[0]}` : "Queried the time", + + "commands.weather.clear": () => "Changed weather to clear", + "commands.weather.rain": () => "Changed weather to rain", + "commands.weather.thunder": () => "Changed weather to thunder", + + "commands.tp.success": (args) => `Teleported ${args[0]} to ${args[1]}`, + "commands.tp.success.coordinates": (args) => + `Teleported ${args[0]} to ${args[1]}, ${args[2]}, ${args[3]}`, + + "commands.give.success": (args) => `Gave ${args[0]} ${args[1]} ${args[2]}`, + + "commands.clear.success": (args) => + `Cleared inventory of ${args[0]}, removing ${args[1]} items`, + + "commands.kill.successful": (args) => `Killed ${args[0]}`, + + "commands.xp.success": (args) => `Gave ${args[0]} experience to ${args[1]}`, + "commands.xp.success.levels": (args) => + `Gave ${args[0]} levels to ${args[1]}`, + + "commands.effect.success": (args) => + `Given ${args[0]} to ${args[1]} for ${args[2]} seconds`, + "commands.effect.success.removed": (args) => + `Took ${args[0]} from ${args[1]}`, + "commands.effect.success.removed.all": (args) => + `Took all effects from ${args[0]}`, + + "commands.difficulty.success": (args) => `Set difficulty to ${args[0]}`, + + "options.difficulty.peaceful": () => "Peaceful", + "options.difficulty.easy": () => "Easy", + "options.difficulty.normal": () => "Normal", + "options.difficulty.hard": () => "Hard", + + "commands.seed.success": (args) => `Seed: ${args[0]}`, + + "commands.setworldspawn.success": (args) => + `Set world spawn to ${args[0]}, ${args[1]}, ${args[2]}`, + + "commands.spawnpoint.success": (args) => + `Set ${args[0]}'s spawn point to ${args[1]}, ${args[2]}, ${args[3]}`, + + "commands.gamerule.success": () => "Game rule has been updated", + + "commands.op.success": (args) => `Made ${args[0]} a server operator`, + "commands.deop.success": (args) => + `Made ${args[0]} no longer a server operator`, + + "commands.ban.success": (args) => `Banned ${args[0]}`, + "commands.unban.success": (args) => `Unbanned ${args[0]}`, + "commands.banip.success": (args) => `Banned IP ${args[0]}`, + + "commands.kick.success": (args) => `Kicked ${args[0]} from the game`, + + "commands.say.usage": () => "Usage: /say ", + + "commands.message.display.incoming": (args) => + `${args[0]} whispers to you: ${args[1]}`, + "commands.message.display.outgoing": (args) => + `You whisper to ${args[0]}: ${args[1]}`, + + "achievement.get": () => "Achievement get!", + "achievement.taken": () => "Taken!", + "achievement.unknown": () => "???", + "achievement.requires": (args) => `Requires '${args[0]}'`, + "achievement.openInventory": () => "Taking Inventory", + "achievement.openInventory.desc": (args) => + `Press '${args[0]}' to open your inventory.`, + "achievement.mineWood": () => "Getting Wood", + "achievement.mineWood.desc": () => + "Attack a tree until a block of wood pops out", + "achievement.buildWorkBench": () => "Benchmarking", + "achievement.buildWorkBench.desc": () => + "Craft a workbench with four blocks of planks", + "achievement.buildPickaxe": () => "Time to Mine!", + "achievement.buildPickaxe.desc": () => + "Use planks and sticks to make a pickaxe", + "achievement.buildFurnace": () => "Hot Topic", + "achievement.buildFurnace.desc": () => + "Construct a furnace out of eight stone blocks", + "achievement.acquireIron": () => "Acquire Hardware", + "achievement.acquireIron.desc": () => "Smelt an iron ingot", + "achievement.buildHoe": () => "Time to Farm!", + "achievement.buildHoe.desc": () => "Use planks and sticks to make a hoe", + "achievement.makeBread": () => "Bake Bread", + "achievement.makeBread.desc": () => "Turn wheat into bread", + "achievement.bakeCake": () => "The Lie", + "achievement.bakeCake.desc": () => "Wheat, sugar, milk and eggs!", + "achievement.buildBetterPickaxe": () => "Getting an Upgrade", + "achievement.buildBetterPickaxe.desc": () => "Construct a better pickaxe", + "achievement.overpowered": () => "Overpowered", + "achievement.overpowered.desc": () => "Build a Notch apple", + "achievement.cookFish": () => "Delicious Fish", + "achievement.cookFish.desc": () => "Catch and cook fish!", + "achievement.onARail": () => "On A Rail", + "achievement.onARail.desc": () => + "Travel by minecart at least 1 km from where you started", + "achievement.buildSword": () => "Time to Strike!", + "achievement.buildSword.desc": () => + "Use planks and sticks to make a sword", + "achievement.killEnemy": () => "Monster Hunter", + "achievement.killEnemy.desc": () => "Attack and destroy a monster", + "achievement.killCow": () => "Cow Tipper", + "achievement.killCow.desc": () => "Harvest some leather", + "achievement.breedCow": () => "Repopulation", + "achievement.breedCow.desc": () => "Breed two cows with wheat", + "achievement.flyPig": () => "When Pigs Fly", + "achievement.flyPig.desc": () => "Fly a pig off a cliff", + "achievement.snipeSkeleton": () => "Sniper Duel", + "achievement.snipeSkeleton.desc": () => + "Kill a skeleton with an arrow from more than 50 meters", + "achievement.diamonds": () => "DIAMONDS!", + "achievement.diamonds.desc": () => "Acquire diamonds with your iron tools", + "achievement.diamondsToYou": () => "Diamonds to you!", + "achievement.diamondsToYou.desc": () => "Throw diamonds at another player.", + "achievement.portal": () => "We Need to Go Deeper", + "achievement.portal.desc": () => "Build a portal to the Nether", + "achievement.ghast": () => "Return to Sender", + "achievement.ghast.desc": () => "Destroy a Ghast with a fireball", + "achievement.blazeRod": () => "Into Fire", + "achievement.blazeRod.desc": () => "Relieve a Blaze of its rod", + "achievement.potion": () => "Local Brewery", + "achievement.potion.desc": () => "Brew a potion", + "achievement.theEnd": () => "The End?", + "achievement.theEnd.desc": () => "Locate the End", + "achievement.theEnd2": () => "The End.", + "achievement.theEnd2.desc": () => "Defeat the Ender Dragon", + "achievement.spawnWither": () => "The Beginning?", + "achievement.spawnWither.desc": () => "Spawn the Wither", + "achievement.killWither": () => "The Beginning.", + "achievement.killWither.desc": () => "Kill the Wither", + "achievement.fullBeacon": () => "Beaconator", + "achievement.fullBeacon.desc": () => "Create a full beacon", + "achievement.exploreAllBiomes": () => "Adventuring Time", + "achievement.exploreAllBiomes.desc": () => "Discover all biomes", + "achievement.enchantments": () => "Enchanter", + "achievement.enchantments.desc": () => + "Use a book, obsidian and diamonds to construct an enchantment table", + "achievement.overkill": () => "Overkill", + "achievement.overkill.desc": () => + "Deal nine hearts of damage in a single hit", + "achievement.bookcase": () => "Librarian", + "achievement.bookcase.desc": () => + "Build some bookshelves to improve your enchantment table", + + "commands.whitelist.add.success": (args) => + `Added ${args[0]} to the whitelist`, + "commands.whitelist.remove.success": (args) => + `Removed ${args[0]} from the whitelist`, + "commands.whitelist.enabled": () => "Whitelist is now turned on", + "commands.whitelist.disabled": () => "Whitelist is now turned off", + + "commands.stop.start": () => "Stopping the server", + + "commands.save.enabled": () => "Turned on world auto-saving", + "commands.save.disabled": () => "Turned off world auto-saving", + "commands.save.success": () => "Saved the world", + + "commands.defaultgamemode.success": (args) => + `Default game mode is now ${args[0]}`, + + "commands.setblock.success": () => "Block placed", + + "commands.fill.success": (args) => `Successfully filled ${args[0]} blocks`, + + "commands.summon.success": () => "Object successfully summoned", + "commands.summon.failed": () => "Unable to summon object", + "commands.summon.outOfWorld": () => + "Cannot summon the object out of the world", + + "commands.me.usage": () => "/me ", + + "commands.help.header": (args) => + `--- Showing help page ${args[0]} of ${args[1]} (/help ) ---`, + "commands.help.footer": () => + "Tip: Use the key while typing a command to auto-complete the command or its arguments", + + "commands.players.list": (args) => + `There are ${args[0]}/${args[1]} players online:`, + + "commands.publish.started": (args) => + `Local game hosted on port ${args[0]}`, + "commands.publish.failed": () => "Unable to host local game", + + "commands.debug.start": () => "Started debug profiling", + "commands.debug.stop": (args) => + `Stopped debug profiling after ${args[0]} seconds (${args[1]} ticks)`, + + "commands.tellraw.jsonException": (args) => `Invalid json: ${args[0]}`, + + "commands.message.sameTarget": () => + "You can't send a private message to yourself!", + + "commands.playsound.success": (args) => + `Played sound '${args[0]}' to ${args[1]}`, + + "commands.particle.success": (args) => `Playing effect ${args[0]}`, + "commands.particle.notFound": (args) => `Unknown effect name (${args[0]})`, + + "commands.generic.exception": () => + "An unknown error occurred while attempting to perform this command", + "commands.generic.permission": () => + "You do not have permission to use this command", + "commands.generic.syntax": () => "Invalid command syntax", + "commands.generic.player.notFound": () => "That player cannot be found", + "commands.generic.entity.notFound": () => "That entity cannot be found", + "commands.generic.notFound": () => + "Unknown command. Try /help for a list of commands", + "commands.generic.num.invalid": (args) => + `'${args[0]}' is not a valid number`, + "commands.generic.num.tooSmall": (args) => + `The number you have entered (${args[0]}) is too small, it must be at least ${args[1]}`, + "commands.generic.num.tooBig": (args) => + `The number you have entered (${args[0]}) is too big, it must be at most ${args[1]}`, + "commands.generic.usage": (args) => `Usage: ${args[0]}`, + + "commands.achievement.unknownAchievement": (args) => + `Unknown achievement or statistic '${args[0]}'`, + "commands.achievement.alreadyHave": (args) => + `Player ${args[0]} already has achievement ${args[1]}`, + "commands.achievement.give.success.one": (args) => + `Successfully given ${args[0]} the stat ${args[1]}`, + "commands.achievement.give.success.all": (args) => + `Successfully given all achievements to ${args[0]}`, + + "commands.testfor.success": (args) => `Found ${args[0]}`, + "commands.testfor.failure": (args) => + `${args[0]} did not match the required data structure`, + + "commands.scoreboard.objectives.add.success": (args) => + `Added new objective '${args[0]}' successfully`, + "commands.scoreboard.objectives.remove.success": (args) => + `Removed objective '${args[0]}' successfully`, + "commands.scoreboard.objectives.setdisplay.successSet": (args) => + `Set the display objective in slot '${args[0]}' to '${args[1]}'`, + "commands.scoreboard.players.set.success": (args) => + `Set score of ${args[1]} for player ${args[0]} to ${args[2]}`, + "commands.scoreboard.players.add.success": (args) => + `Added ${args[2]} to ${args[1]} for ${args[0]} (now ${args[3]})`, + "commands.scoreboard.players.reset.success": (args) => + `Reset scores of player ${args[0]}`, + "commands.scoreboard.teams.add.success": (args) => + `Added new team '${args[0]}' successfully`, + "commands.scoreboard.teams.remove.success": (args) => + `Removed team ${args[0]}`, + "commands.scoreboard.teams.join.success": (args) => + `Added ${args[0]} player(s) to team ${args[1]}: ${args[2]}`, + + "commands.execute.failed": (args) => + `Failed to execute '${args[0]}' as ${args[1]}`, + + "commands.testforblock.success": (args) => + `Successfully found the block at ${args[0]},${args[1]},${args[2]}.`, + "commands.testforblock.failed.tile": (args) => + `The block at ${args[0]},${args[1]},${args[2]} is ${args[3]} (expected: ${args[4]}).`, + + "commands.setblock.success": () => "Block placed", + "commands.setblock.failed": () => "Unable to place block", + + "commands.fill.success": (args) => `Successfully filled ${args[0]} blocks`, + "commands.fill.failed": () => "No blocks filled", + + "commands.clone.success": (args) => `Successfully cloned ${args[0]} blocks`, + "commands.clone.failed": () => "No blocks cloned", + + "commands.blockdata.success": (args) => `Block data updated to: ${args[0]}`, + + "commands.entitydata.success": (args) => + `Entity data updated to: ${args[0]}`, + + "commands.enchant.success": () => "Enchanting succeeded", + "commands.enchant.notFound": (args) => + `There is no such enchantment with ID ${args[0]}`, + + "commands.replaceitem.success": (args) => + `Replaced slot ${args[0]} with ${args[1]} * ${args[2]}`, + "commands.replaceitem.failed": (args) => + `Could not replace slot ${args[0]} with ${args[1]} * ${args[2]}`, + + "commands.stats.success": (args) => + `Storing ${args[0]} stats in ${args[1]} on ${args[2]}`, + + "commands.trigger.success": (args) => + `Trigger ${args[0]} changed with ${args[1]} ${args[2]}`, + + "commands.spreadplayers.success.teams": (args) => + `Successfully spread ${args[0]} teams around ${args[1]},${args[2]}`, + "commands.spreadplayers.success.players": (args) => + `Successfully spread ${args[0]} players around ${args[1]},${args[2]}`, + + "commands.worldborder.set.success": (args) => + `Set world border to ${args[0]} blocks wide (from ${args[1]} blocks)`, + "commands.worldborder.center.success": (args) => + `Set world border center to ${args[0]},${args[1]}`, + + "commands.title.success": () => "Title command successfully executed", + + "entity.Item.name": () => "Item", + "entity.XPOrb.name": () => "Experience Orb", + "entity.SmallFireball.name": () => "Small Fireball", + "entity.Fireball.name": () => "Fireball", + "entity.Arrow.name": () => "Arrow", + "entity.Snowball.name": () => "Snowball", + "entity.Painting.name": () => "Painting", + "entity.ArmorStand.name": () => "Armor Stand", + "entity.Mob.name": () => "Mob", + "entity.Monster.name": () => "Monster", + "entity.Creeper.name": () => "Creeper", + "entity.Skeleton.name": () => "Skeleton", + "entity.Spider.name": () => "Spider", + "entity.Giant.name": () => "Giant", + "entity.Zombie.name": () => "Zombie", + "entity.Slime.name": () => "Slime", + "entity.Ghast.name": () => "Ghast", + "entity.PigZombie.name": () => "Zombie Pigman", + "entity.Enderman.name": () => "Enderman", + "entity.Endermite.name": () => "Endermite", + "entity.Silverfish.name": () => "Silverfish", + "entity.CaveSpider.name": () => "Cave Spider", + "entity.Blaze.name": () => "Blaze", + "entity.LavaSlime.name": () => "Magma Cube", + "entity.MushroomCow.name": () => "Mooshroom", + "entity.Villager.name": () => "Villager", + "entity.VillagerGolem.name": () => "Iron Golem", + "entity.SnowMan.name": () => "Snow Golem", + "entity.EnderDragon.name": () => "Ender Dragon", + "entity.WitherBoss.name": () => "Wither", + "entity.Witch.name": () => "Witch", + "entity.Guardian.name": () => "Guardian", + "entity.Pig.name": () => "Pig", + "entity.Sheep.name": () => "Sheep", + "entity.Cow.name": () => "Cow", + "entity.Chicken.name": () => "Chicken", + "entity.Squid.name": () => "Squid", + "entity.Wolf.name": () => "Wolf", + "entity.Ozelot.name": () => "Ocelot", + "entity.Cat.name": () => "Cat", + "entity.Bat.name": () => "Bat", + "entity.EntityHorse.name": () => "Horse", + "entity.horse.name": () => "Horse", + "entity.donkey.name": () => "Donkey", + "entity.mule.name": () => "Mule", + "entity.skeletonhorse.name": () => "Skeleton Horse", + "entity.zombiehorse.name": () => "Zombie Horse", + "entity.Rabbit.name": () => "Rabbit", + "entity.KillerBunny.name": () => "The Killer Bunny", + "entity.PrimedTnt.name": () => "Block of TNT", + "entity.FallingSand.name": () => "Falling Block", + "entity.Minecart.name": () => "Minecart", + "entity.Boat.name": () => "Boat", + "entity.generic.name": () => "unknown", + + "entity.Villager.farmer": () => "Farmer", + "entity.Villager.fisherman": () => "Fisherman", + "entity.Villager.shepherd": () => "Shepherd", + "entity.Villager.fletcher": () => "Fletcher", + "entity.Villager.librarian": () => "Librarian", + "entity.Villager.cleric": () => "Cleric", + "entity.Villager.armor": () => "Armorer", + "entity.Villager.weapon": () => "Weapon Smith", + "entity.Villager.tool": () => "Tool Smith", + "entity.Villager.butcher": () => "Butcher", + "entity.Villager.leather": () => "Leatherworker", + }; + + const translationFunc = translations[key]; + if (translationFunc) { + return translationFunc(args); + } + + if (args.length > 0) { + return `${key}: ${args.join(" ")}`; + } + return key; +} + +function parseChatComponent(component) { + if (!component) return ""; + + if (typeof component === "string") { + try { + component = JSON.parse(component); + } catch (err) { + try { + const relaxedJson = component.replace( + /([{,])\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:/g, + '$1"$2":', + ); + component = JSON.parse(relaxedJson); + } catch (err2) { + return component.replace(/^"|"$/g, ""); + } + } + } + + let result = ""; + + if (component.translate) { + const args = component.with + ? component.with.map((w) => { + if (typeof w === "string" || typeof w === "number") { + return String(w); + } + return parseChatComponent(w); + }) + : []; + + const translated = getTranslation(component.translate, args); + return translated; + } + + if (component.text !== undefined && component.text !== null) { + result += String(component.text); + } + + if (component.score) { + result += String(component.score.value || ""); + } + + if (component.selector) { + result += component.selector; + } + + if (component.extra && Array.isArray(component.extra)) { + result += component.extra.map((e) => parseChatComponent(e)).join(""); + } + + return result; +} + +module.exports = { getTranslation, parseChatComponent }; \ No newline at end of file diff --git a/src/utils/chunk.js b/src/utils/chunk.js new file mode 100644 index 0000000..ccac770 --- /dev/null +++ b/src/utils/chunk.js @@ -0,0 +1,43 @@ +function compressRLE(data) { + const output = []; + let i = 0; + + while (i < data.length) { + const byte = data[i]; + let count = 1; + + while (i + count < data.length && data[i + count] === byte && count < 256) { + count++; + } + + if (count <= 3) { + if (byte === 0xff) { + output.push(0xff, count - 1); + } else { + for (let j = 0; j < count; j++) { + output.push(byte); + } + } + } else { + output.push(0xff, count - 1, byte); + } + + i += count; + } + + return Buffer.from(output); +} + +function countSetBits(n) { + let count = 0; + while (n) { + count += n & 1; + n >>= 1; + } + return count; +} + +module.exports = { + compressRLE, + countSetBits, +}; \ No newline at end of file diff --git a/src/utils/items.js b/src/utils/items.js new file mode 100644 index 0000000..30e9e7a --- /dev/null +++ b/src/utils/items.js @@ -0,0 +1,159 @@ +function readSlot(reader) { + const id = reader.readShort(); + if (id === -1 || id === 0) { + return null; + } + const count = reader.readUnsignedByte(); + const damage = reader.readShort(); + + const nbtLength = reader.readShort(); + if (nbtLength > 0) { + reader.skip(nbtLength); + } + + return { + blockId: id, + itemCount: count & 0xff, + itemDamage: damage, + }; +} + +function readItemInstance(reader) { + const id = reader.readShort(); + if (id === -1 || id === 0) { + return null; + } + const count = reader.readByte(); + const damage = reader.readShort(); + + const nbtPresent = reader.readByte(); + if (nbtPresent !== 0) { + //for now, just ignore NBT because lazy + } + + return { + blockId: id, + itemCount: count & 0xff, + itemDamage: damage, + }; +} + +function readItem(reader) { + const itemId = reader.readShort(); + + if (itemId === -1) { + return null; + } + + const count = reader.readByte(); + const damage = reader.readShort(); + + return { + blockId: itemId, + itemCount: count, + itemDamage: damage, + }; +} + +function writeItemNBT(writer, item) { + const PacketWriter = require("../PacketWriter"); + + let customName = null; + + if (item.nbtData && item.nbtData.value && item.nbtData.value.display) { + const display = item.nbtData.value.display.value; + if (display.Name) { + customName = display.Name.value; + try { + const parsed = JSON.parse(customName); + if (parsed.text) { + customName = parsed.text; + } else if (typeof parsed === "string") { + customName = parsed; + } + } catch (err) { + /* do nothing */ + } + } + } + + if (!customName) { + writer.writeShort(-1); + return; + } + + const nbtWriter = new PacketWriter(); + + nbtWriter.writeByte(10); + nbtWriter.writeUTF(""); + + nbtWriter.writeByte(10); + nbtWriter.writeUTF("display"); + + nbtWriter.writeByte(8); + nbtWriter.writeUTF("Name"); + nbtWriter.writeUTF(customName); + + nbtWriter.writeByte(0); + + nbtWriter.writeByte(0); + + const nbtData = nbtWriter.toBuffer(); + writer.writeShort(nbtData.length); + writer.writeBytes(nbtData); +} + +function writeItem(writer, item, mapJavaItemToLCE) { + if (!item || item.blockId === -1 || item.itemId === -1 || item === null) { + writer.writeShort(-1); + return; + } + + let javaItemId = + item.itemId !== undefined + ? item.itemId + : item.blockId !== undefined + ? item.blockId + : -1; + + if (javaItemId === -1 || javaItemId === undefined) { + writer.writeShort(-1); + return; + } + + let lceItemId = mapJavaItemToLCE(javaItemId); + let auxValue = + item.itemDamage !== undefined ? item.itemDamage : item.metadata || 0; + + if ( + lceItemId === undefined || + lceItemId === null || + lceItemId === -1 || + lceItemId === 0 + ) { + lceItemId = 1; + auxValue = 0; + } + + if (lceItemId < 0 || lceItemId > 2267) { + lceItemId = 1; + auxValue = 0; + } + + writer.writeShort(lceItemId); + + const count = item.itemCount || item.count || 1; + writer.writeByte(Math.max(1, Math.min(255, count))); + + writer.writeShort(Math.max(0, Math.min(32767, auxValue))); + + writeItemNBT(writer, item); +} + +module.exports = { + readSlot, + readItemInstance, + readItem, + writeItemNBT, + writeItem, +}; \ No newline at end of file diff --git a/src/utils/rotation.js b/src/utils/rotation.js new file mode 100644 index 0000000..df39b6f --- /dev/null +++ b/src/utils/rotation.js @@ -0,0 +1,13 @@ +function normalizeYaw(yaw) { + let normalized = yaw % 360; + if (normalized > 180) { + normalized -= 360; + } else if (normalized < -180) { + normalized += 360; + } + return normalized; +} + +module.exports = { + normalizeYaw, +}; \ No newline at end of file diff --git a/src/utils/translations.js b/src/utils/translations.js new file mode 100644 index 0000000..a7ef926 --- /dev/null +++ b/src/utils/translations.js @@ -0,0 +1,15 @@ +function getTranslation(key, args = []) { + const translations = {}; + + const translationFunc = translations[key]; + if (translationFunc) { + return translationFunc(args); + } + + if (args.length > 0) { + return `${key}: ${args.join(" ")}`; + } + return key; +} + +module.exports = { getTranslation }; \ No newline at end of file diff --git a/start.bat b/start.bat new file mode 100644 index 0000000..e5c7e94 --- /dev/null +++ b/start.bat @@ -0,0 +1,3 @@ +@echo off +node index.js +pause \ No newline at end of file