Player skins !
This commit is contained in:
@@ -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<Uint8Array>;
|
||||
}
|
||||
|
||||
export interface SavedWorld {
|
||||
@@ -1017,6 +1020,21 @@ export class GameServer {
|
||||
}),
|
||||
);
|
||||
|
||||
register(
|
||||
literal<ServerCommandSource>("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<string, ServerCommandSource>("url", word())
|
||||
.executes((context) =>
|
||||
this.#download_skin(context.source.server_player, context.get<string>("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<ServerCommandSource>, 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;
|
||||
|
||||
@@ -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 };
|
||||
|
||||
+18
-1
@@ -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<string, string>();
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -10,6 +10,9 @@ const SAVE_INTERVAL_MS = 30_000;
|
||||
|
||||
let game: GameServer | undefined;
|
||||
let starting: Promise<void> | undefined;
|
||||
// downloads waiting for the host, by id
|
||||
const downloads = new Map<number, { resolve: (bytes: Uint8Array) => 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<HostToGame>) => {
|
||||
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<HostToGame, { type: "init" }>) {
|
||||
{
|
||||
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,
|
||||
|
||||
@@ -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<Host> {
|
||||
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<Host> {
|
||||
};
|
||||
}
|
||||
|
||||
// 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<Uint8Array> {
|
||||
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<Uint8Array>;
|
||||
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);
|
||||
|
||||
Reference in New Issue
Block a user