From 60188ff735b49ccdfbe238210d834f03402c25a8 Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 27 Sep 2026 12:01:52 -0300 Subject: [PATCH] Player skins ! --- client/entity/player.ts | 18 ++++++++ client/entity/remote_player.ts | 3 ++ client/packet_listener.ts | 8 ++++ client/rendering/level_renderer.ts | 10 +++-- client/skins.ts | 18 ++++++++ common/protocol.ts | 6 ++- server/game/game_server.ts | 53 +++++++++++++++++++++++ server/game/host_protocol.ts | 8 +++- server/game/player.ts | 19 +++++++- server/game/skins.ts | 32 ++++++++++++++ server/game/worker.ts | 19 ++++++++ server/host.ts | 62 +++++++++++++++++++++++++++ tests/helpers.ts | 8 +++- tests/skin_test.ts | 69 ++++++++++++++++++++++++++++++ 14 files changed, 325 insertions(+), 8 deletions(-) create mode 100644 client/skins.ts create mode 100644 server/game/skins.ts create mode 100644 tests/skin_test.ts diff --git a/client/entity/player.ts b/client/entity/player.ts index cb3877a..70e6606 100644 --- a/client/entity/player.ts +++ b/client/entity/player.ts @@ -1,9 +1,14 @@ import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts"; import type { ClientLevel } from "../level/client_level.ts"; +import type { Texture } from "../renderer/mod.ts"; +import { decode_skin } from "../skins.ts"; import { Entity } from "./entity.ts"; export abstract class Player extends Entity { name: string; + // undefined draws the default skin + skin: Texture | undefined; + #skin_version = 0; // how far the limbs have swung and how hard they swing (0 to 1), like minecraft's WalkAnimationState walk_position = 0; @@ -15,6 +20,19 @@ export abstract class Player extends Entity { this.name = name; } + // a base64 png from the server, or undefined for the default. the old skin stays until the new one is decoded + async set_skin(skin: string | undefined) { + const version = ++this.#skin_version; + const texture = skin ? await decode_skin(skin) : undefined; + if (version !== this.#skin_version) { + // a newer skin came while this one was decoding + texture?.tex.destroy(); + return; + } + this.skin?.tex.destroy(); + this.skin = texture; + } + // after moving each tick. full speed is 5 blocks per second, a bit faster than walking update_walk_animation() { const moved = Math.hypot(this.x - this.prev_x, this.z - this.prev_z); diff --git a/client/entity/remote_player.ts b/client/entity/remote_player.ts index 2b151b4..5273387 100644 --- a/client/entity/remote_player.ts +++ b/client/entity/remote_player.ts @@ -20,6 +20,9 @@ export class RemotePlayer extends Player { this.target_z = info.z; this.yaw = info.yaw; this.pitch = info.pitch; + if (info.skin) { + this.set_skin(info.skin); + } } lerp_to(x: number, y: number, z: number, yaw: number, pitch: number) { diff --git a/client/packet_listener.ts b/client/packet_listener.ts index a07d10a..3883085 100644 --- a/client/packet_listener.ts +++ b/client/packet_listener.ts @@ -5,6 +5,7 @@ import { GuiContainer } from "./gui/gui_container.ts"; import { GuiChat } from "./gui/gui_chat.ts"; import { RemotePlayer } from "./entity/remote_player.ts"; import { ItemEntity } from "./entity/item_entity.ts"; +import { Player } from "./entity/player.ts"; // applies what the server sends, like minecraft's ClientPacketListener. messages queue up on the connection and // get handled here once per frame, inside the game loop @@ -50,6 +51,13 @@ export class ClientPacketListener { } break; } + case "player_skin": { + const player = level.entities.get(message.id); + if (player instanceof Player) { + player.set_skin(message.skin); + } + break; + } case "add_entity": level.add_entity(new ItemEntity(level, message.entity)); break; diff --git a/client/rendering/level_renderer.ts b/client/rendering/level_renderer.ts index edf8914..7bbceba 100644 --- a/client/rendering/level_renderer.ts +++ b/client/rendering/level_renderer.ts @@ -12,6 +12,7 @@ import { render_player } from "./player_renderer.ts"; import { draw_terrain, flush_batch, + get_current_texture, push_back_face, push_bottom_face, push_front_face, @@ -94,11 +95,14 @@ export class LevelRenderer { // every entity but the one the camera is in render_entities(level: ClientLevel, camera_entity: Entity, partial_tick: number) { flush_batch(); - const skin = AssetManager.instance.get("bworld:skin"); - set_current_texture(skin.tex); - + const default_skin = AssetManager.instance.get("bworld:skin"); for (const entity of level.entities.values()) { if (entity !== camera_entity && entity instanceof RemotePlayer) { + const skin = entity.skin ?? default_skin; + if (get_current_texture() !== skin.tex) { + flush_batch(); + set_current_texture(skin.tex); + } render_player(entity, skin, partial_tick); } } diff --git a/client/skins.ts b/client/skins.ts new file mode 100644 index 0000000..285c6e5 --- /dev/null +++ b/client/skins.ts @@ -0,0 +1,18 @@ +import { load_texture, type Texture } from "./renderer/mod.ts"; + +// a player's skin as the server sends it (a base64 64x64 png), undefined when it can't be decoded +export async function decode_skin(skin: string): Promise { + try { + const bytes = Uint8Array.from(atob(skin), (char) => char.charCodeAt(0)); + // as stored, so pngs with a color profile look the same as in an editor that ignores it, like minecraft + const image = await createImageBitmap(new Blob([bytes], { type: "image/png" }), { + colorSpaceConversion: "none", + premultiplyAlpha: "none", + }); + const texture = image.width === 64 && image.height === 64 ? load_texture(image) : undefined; + image.close(); + return texture; + } catch { + return undefined; + } +} diff --git a/common/protocol.ts b/common/protocol.ts index e81d89d..1682e0f 100644 --- a/common/protocol.ts +++ b/common/protocol.ts @@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air"; // bump when a client and server of different versions can't play together. // the server rejects a different version before the client downloads anything -export const PROTOCOL_VERSION = 6; +export const PROTOCOL_VERSION = 7; export interface PlayerInfo { id: string; @@ -17,6 +17,8 @@ export interface PlayerInfo { z: number; yaw: number; pitch: number; + // a 64x64 png as base64, see /skin. the default skin when there isn't one + skin?: string; } // an entity that isn't a player, as the server first sends it. players have their own messages @@ -108,6 +110,8 @@ export type ServerMessage = | { type: "player_join"; player: PlayerInfo } | { type: "player_leave"; id: string } | { type: "player_move"; id: string; x: number; y: number; z: number; yaw: number; pitch: number } + // a player changed their skin, including the one receiving it. without skin it's back to the default + | { type: "player_skin"; id: string; skin?: string } | { type: "add_entity"; entity: EntityInfo } | { type: "move_entity"; id: string; x: number; y: number; z: number } // a dropped item's stack changed, like when two stacks merge diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 768d9b9..5cdbccd 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -43,6 +43,7 @@ import { import type { GameLoop } from "./game_loop.ts"; import { consume_recipe_items, update_crafting_result } from "./crafting.ts"; import { OpenScreen, SavedPlayer, ServerPlayer } from "./player.ts"; +import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts"; import { ServerWorld, Tile } from "./world.ts"; import { BLOCK_DROP_PICKUP_DELAY, @@ -86,6 +87,8 @@ const READY_TIMEOUT_TICKS = 60 * TICKS_PER_SECOND; export interface GameHost { send(conn: number, data: string): void; close(conn: number): void; + // fetches a url, failing with a message for players when it can't or it's more than max_bytes + download(url: string, max_bytes: number): Promise; } export interface SavedWorld { @@ -1017,6 +1020,21 @@ export class GameServer { }), ); + register( + literal("skin") + .describe("Changes your skin to a 64x64 png from the web, or back to the default without a url") + .executes((context) => { + this.set_skin(context.source.server_player, undefined); + context.source.send_message("Your skin is back to the default"); + }) + .then( + argument("url", word()) + .executes((context) => + this.#download_skin(context.source.server_player, context.get("url")) + ), + ), + ); + // every command's usage, or one's. aliases like /mod:name aren't listed twice const commands = this.mods.commands; const help = (context: CommandContext, only?: string) => { @@ -1045,6 +1063,41 @@ export class GameServer { ); } + // a base64 png, or undefined for the default skin. everyone is told, the player too + set_skin(player: ServerPlayer, skin: string | undefined) { + player.skin = skin; + this.world.dirty = true; + this.#broadcast({ type: "player_skin", id: player.id, skin }); + } + + // the host downloads it, which takes a while, so the player hears back later + #download_skin(player: ServerPlayer, url: string) { + if (player.downloading_skin) { + throw new CommandError("Your last skin is still downloading"); + } + player.downloading_skin = true; + this.send_chat(player, "Downloading your skin..."); + + const online = () => this.#players.get(player.conn) === player; + this.#host.download(url, MAX_SKIN_BYTES) + .then((bytes) => { + const problem = skin_problem(bytes); + if (problem) { + throw new Error(problem); + } + if (online()) { + this.set_skin(player, encode_skin(bytes)); + this.send_chat(player, "Skin changed"); + } + }) + .catch((e) => { + if (online()) { + this.send_chat(player, `Couldn't change your skin: ${e instanceof Error ? e.message : e}`); + } + }) + .finally(() => player.downloading_skin = false); + } + #close_screen(player: ServerPlayer) { const screen = player.screen; player.screen = undefined; diff --git a/server/game/host_protocol.ts b/server/game/host_protocol.ts index a226496..08380fe 100644 --- a/server/game/host_protocol.ts +++ b/server/game/host_protocol.ts @@ -14,11 +14,15 @@ export type HostToGame = | { type: "message"; conn: number; data: string } | { type: "disconnect"; conn: number } // save now and say when it's done, for shutting down - | { type: "shutdown" }; + | { type: "shutdown" } + // answers download, with the bytes or why it failed + | { type: "downloaded"; id: number; bytes?: Uint8Array; error?: string }; export type GameToHost = | { type: "ready"; seed: string } | { type: "failed"; error: string } | { type: "send"; conn: number; data: string } | { type: "close"; conn: number } - | { type: "save"; data: string; final: boolean }; + | { type: "save"; data: string; final: boolean } + // the worker can't use the network, so the host fetches urls for it, like skins + | { type: "download"; id: number; url: string; max_bytes: number }; diff --git a/server/game/player.ts b/server/game/player.ts index ef4fb39..64c87ef 100644 --- a/server/game/player.ts +++ b/server/game/player.ts @@ -29,6 +29,8 @@ export interface SavedPlayer { inventory: (ItemData | null)[]; // players saved before health and hunger start full vitals?: SavedVitals; + // base64 png, see /skin + skin?: string; } export class ServerPlayer { @@ -52,6 +54,10 @@ export class ServerPlayer { cursor: Cursor = { item: undefined }; selected_slot = 0; screen: OpenScreen | undefined; + // base64 png, see /skin. undefined is the default skin + skin: string | undefined; + // a /skin download is on its way, one at a time + downloading_skin = false; // last json sent for each synced thing, so only changes get sent sent = new Map(); @@ -66,7 +72,16 @@ export class ServerPlayer { } info(): PlayerInfo { - return { id: this.id, name: this.name, x: this.x, y: this.y, z: this.z, yaw: this.yaw, pitch: this.pitch }; + return { + id: this.id, + name: this.name, + x: this.x, + y: this.y, + z: this.z, + yaw: this.yaw, + pitch: this.pitch, + skin: this.skin, + }; } save(): SavedPlayer { @@ -79,6 +94,7 @@ export class ServerPlayer { selected_slot: this.selected_slot, inventory: this.inventory.to_data(), vitals: this.vitals.save(), + skin: this.skin, }; } @@ -91,5 +107,6 @@ export class ServerPlayer { this.selected_slot = saved.selected_slot; this.inventory.load(saved.inventory); this.vitals.load(saved.vitals); + this.skin = saved.skin; } } diff --git a/server/game/skins.ts b/server/game/skins.ts new file mode 100644 index 0000000..99959e9 --- /dev/null +++ b/server/game/skins.ts @@ -0,0 +1,32 @@ +// player skins set with /skin: 64x64 pngs in minecraft 1.8's layout, see client/rendering/player_renderer.ts + +// minecraft skins are a few KB, this leaves room for ones with extra metadata +export const MAX_SKIN_BYTES = 64 * 1024; +export const SKIN_SIZE = 64; + +const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; + +// why the bytes can't be a skin, for the player. only the header is checked, clients decode the rest and fall back +// to the default skin if they can't +export function skin_problem(bytes: Uint8Array): string | undefined { + const is_png = bytes.length >= 24 && PNG_SIGNATURE.every((byte, i) => bytes[i] === byte) && + String.fromCharCode(...bytes.subarray(12, 16)) === "IHDR"; + if (!is_png) { + return "That isn't a png"; + } + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const width = view.getUint32(16); + const height = view.getUint32(20); + if (width !== SKIN_SIZE || height !== SKIN_SIZE) { + return `Skins have to be ${SKIN_SIZE}x${SKIN_SIZE} (it's ${width}x${height})`; + } + return undefined; +} + +export function encode_skin(bytes: Uint8Array): string { + let binary = ""; + for (const byte of bytes) { + binary += String.fromCharCode(byte); + } + return btoa(binary); +} diff --git a/server/game/worker.ts b/server/game/worker.ts index c023926..596bb39 100644 --- a/server/game/worker.ts +++ b/server/game/worker.ts @@ -10,6 +10,9 @@ const SAVE_INTERVAL_MS = 30_000; let game: GameServer | undefined; let starting: Promise | undefined; +// downloads waiting for the host, by id +const downloads = new Map void; reject: (error: Error) => void }>(); +let next_download = 1; function post(message: GameToHost) { self.postMessage(message); @@ -22,6 +25,16 @@ self.onmessage = async (event: MessageEvent) => { starting = init(message); return; } + if (message.type === "downloaded") { + const pending = downloads.get(message.id); + downloads.delete(message.id); + if (message.bytes) { + pending?.resolve(message.bytes); + } else { + pending?.reject(new Error(message.error ?? "Couldn't download it")); + } + return; + } // players can connect while mods are still loading await starting; @@ -51,6 +64,12 @@ async function init(message: Extract) { { send: (conn, data) => post({ type: "send", conn, data }), close: (conn) => post({ type: "close", conn }), + download: (url, max_bytes) => + new Promise((resolve, reject) => { + const id = next_download++; + downloads.set(id, { resolve, reject }); + post({ type: "download", id, url, max_bytes }); + }), }, message.save, message.default_seed, diff --git a/server/host.ts b/server/host.ts index 07585ba..7cc37e8 100644 --- a/server/host.ts +++ b/server/host.ts @@ -9,6 +9,7 @@ const MAX_MESSAGE_SIZE = 4096; // in build/, see build.ts export const ENGINE_TEXTURES_INDEX = "assets/textures/index.json"; const SHUTDOWN_TIMEOUT_MS = 5000; +const DOWNLOAD_TIMEOUT_MS = 10_000; export interface HostOptions { // what deno task build made: the client and the engine's assets @@ -70,6 +71,13 @@ export async function start_host(options: HostOptions): Promise { on_final_save?.(); } break; + case "download": + download(message.url, message.max_bytes).then( + (bytes) => post({ type: "downloaded", id: message.id, bytes }), + (e) => + post({ type: "downloaded", id: message.id, error: e instanceof Error ? e.message : String(e) }), + ); + break; } }; game.onerror = (event) => { @@ -157,6 +165,60 @@ export async function start_host(options: HostOptions): Promise { }; } +// for the game worker, which has no network access. errors are told to players, so they say what went wrong simply +async function download(url: string, max_bytes: number): Promise { + let parsed: URL; + try { + parsed = new URL(url); + } catch { + throw new Error("That isn't a url"); + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + throw new Error("Only http and https urls work"); + } + + let response: Response; + try { + response = await fetch(parsed, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) }); + } catch { + throw new Error("Couldn't download it"); + } + if (!response.ok || !response.body) { + await response.body?.cancel(); + throw new Error(`Couldn't download it (${response.status})`); + } + + // read up to the limit instead of trusting content-length + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + while (true) { + let chunk: ReadableStreamReadResult; + try { + chunk = await reader.read(); + } catch { + throw new Error("Couldn't download it"); + } + if (chunk.done) { + break; + } + size += chunk.value.length; + if (size > max_bytes) { + await reader.cancel(); + throw new Error(`It's bigger than ${Math.floor(max_bytes / 1024)} KB`); + } + chunks.push(chunk.value); + } + + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.length; + } + return bytes; +} + function read_world(file: string): string | undefined { try { return Deno.readTextFileSync(file); diff --git a/tests/helpers.ts b/tests/helpers.ts index f780d17..e116a7b 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -41,6 +41,8 @@ export async function test_game(mods_dir: string, save?: string, seed = "test-se EverythingRegistry.clear(); const outbox = new Map(); const closed = new Set(); + // what host.download gives back, by url. other urls fail + const downloads = new Map(); const host = { send: (conn: number, data: string) => { if (!outbox.has(conn)) outbox.set(conn, []); @@ -49,6 +51,10 @@ export async function test_game(mods_dir: string, save?: string, seed = "test-se close(conn: number) { closed.add(conn); }, + download(url: string) { + const bytes = downloads.get(url); + return bytes ? Promise.resolve(bytes) : Promise.reject(new Error("Couldn't download it")); + }, }; const game: GameServer = await start_game(host, save, seed, mod_sources(mods_dir)); // deno-lint-ignore no-explicit-any @@ -65,7 +71,7 @@ export async function test_game(mods_dir: string, save?: string, seed = "test-se send(conn, { type: "ready" }); return take(conn).find((m) => m.type === "join"); }; - return { game, take, send, join, closed }; + return { game, take, send, join, closed, downloads }; } export function copy_dir(from: string, to: string) { diff --git a/tests/skin_test.ts b/tests/skin_test.ts new file mode 100644 index 0000000..84efc00 --- /dev/null +++ b/tests/skin_test.ts @@ -0,0 +1,69 @@ +import { assertEquals } from "@std/assert"; +import { encode_skin } from "$/server/game/skins.ts"; +import { test_game } from "./helpers.ts"; + +const SKIN = Deno.readFileSync("assets/sprites/skin_template.png"); +// the downloads resolve on a later turn of the event loop +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); + +// deno-lint-ignore no-explicit-any +const chat = (messages: any[]) => messages.filter((m) => m.type === "chat").map((m) => m.text); + +Deno.test("/skin downloads a png, tells everyone and is saved with the player", async () => { + const t = await test_game("mods"); + t.downloads.set("https://example.com/skin.png", SKIN); + t.join(1, "alice"); + t.join(2, "bob"); + t.take(1); + t.take(2); + + t.send(1, { type: "chat", text: "/skin https://example.com/skin.png" }); + await settle(); + + const skin = encode_skin(SKIN); + const alice_id = t.game.players().find((p) => p.name === "alice")!.id; + const to_alice = t.take(1); + assertEquals(chat(to_alice), ["Downloading your skin...", "Skin changed"]); + assertEquals(to_alice.find((m) => m.type === "player_skin"), { type: "player_skin", id: alice_id, skin }); + assertEquals(t.take(2).find((m) => m.type === "player_skin"), { type: "player_skin", id: alice_id, skin }); + + // players joining later get it with the rest of alice's info, and it's still there after a restart + const loaded = await test_game("mods", t.game.save()); + loaded.join(1, "alice"); + const join = loaded.join(2, "bob"); + assertEquals(join.players.find((p: { name: string }) => p.name === "alice").skin, skin); +}); + +Deno.test("/skin says why a download can't be a skin, and /skin alone goes back to the default", async () => { + const t = await test_game("mods"); + const wide = SKIN.slice(); + new DataView(wide.buffer).setUint32(20, 32); + t.downloads.set("https://example.com/old.png", wide); + t.downloads.set("https://example.com/page.html", new TextEncoder().encode("")); + t.join(1, "alice"); + t.take(1); + + const skin_messages = async (text: string) => { + t.send(1, { type: "chat", text }); + await settle(); + const messages = t.take(1); + return { chat: chat(messages), skins: messages.filter((m) => m.type === "player_skin") }; + }; + + assertEquals((await skin_messages("/skin https://example.com/old.png")).chat, [ + "Downloading your skin...", + "Couldn't change your skin: Skins have to be 64x64 (it's 64x32)", + ]); + assertEquals( + (await skin_messages("/skin https://example.com/page.html")).chat.at(-1), + "Couldn't change your skin: That isn't a png", + ); + const missing = await skin_messages("/skin https://example.com/nothing.png"); + assertEquals(missing.chat.at(-1), "Couldn't change your skin: Couldn't download it"); + assertEquals(missing.skins, []); + + const reset = await skin_messages("/skin"); + assertEquals(reset.chat, ["Your skin is back to the default"]); + assertEquals(reset.skins.length, 1); + assertEquals(reset.skins[0].skin, undefined); +});