Send chunks to players connected to server

This commit is contained in:
2026-09-28 11:14:40 -03:00
parent 677ad8115a
commit ded9a7e5d0
26 changed files with 920 additions and 357 deletions
+98 -9
View File
@@ -24,6 +24,7 @@ import {
} from "$/common/protocol.ts";
import type { ModListing, RecipeBook } from "$/common/mod_loader.ts";
import type { WorldgenSetup } from "$/common/generation.ts";
import { MAX_VIEW_DISTANCE, MIN_VIEW_DISTANCE } from "$/common/chunk_streaming.ts";
import { CYCLE_TICKS, format_clock, time_of_day, TIMES_OF_DAY } from "$/common/time.ts";
import { can_place, can_stand_on, display_name, placement_target } from "$/common/utils.ts";
import { EXHAUSTION, MAX_HEALTH } from "./vitals.ts";
@@ -82,10 +83,15 @@ const VOID_DAMAGE_TICKS = 10;
const MAX_CATCH_UP_DAYS = 64;
// how long a client gets between welcome and ready to download and load everything
const READY_TIMEOUT_TICKS = 60 * TICKS_PER_SECOND;
// the furthest the server sends chunks around a player, and what players who don't say get. minecraft's default
const SERVER_VIEW_DISTANCE = 10;
// how long a tick can spend building chunks for players, the rest go out on the next ticks
const CHUNK_SEND_BUDGET_MS = 20;
// everything the game server needs from whatever runs it
export interface GameHost {
send(conn: number, data: string): void;
// text is a json message, bytes a binary one (level_chunk)
send(conn: number, data: string | Uint8Array<ArrayBuffer>): 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>;
@@ -132,6 +138,8 @@ export class GameServer {
#players = new Map<number, ServerPlayer>();
// connections that got welcome and are downloading mods, by conn
#pending = new Map<number, { name: unknown; since: number }>();
// which player gets chunks first next tick, so one with a lot to load doesn't always use up the budget
#next_chunk_player = 0;
#saved_players: Record<string, SavedPlayer> = {};
#tick = 0;
// the last morning new day handlers ran for
@@ -146,6 +154,8 @@ export class GameServer {
recipes: RecipeBook;
// what runs tick(), for /tps. tests call tick() themselves
loop?: GameLoop;
// how long a tick can spend building chunks for players. tests lift it so what gets sent doesn't depend on speed
chunk_send_budget_ms = CHUNK_SEND_BUDGET_MS;
constructor(host: GameHost, save: WorldSave | undefined, default_seed: string, mods: GameMods) {
this.#host = host;
@@ -181,8 +191,19 @@ export class GameServer {
this.world.dirty = !saved || this.world.has_unsaved_chunks();
this.#register_commands();
this.world.on_block_change = (x, y, z, id, state) =>
this.#broadcast(state ? { type: "set_block", x, y, z, id, state } : { type: "set_block", x, y, z, id });
// players without the chunk get the block with it when they do, like minecraft
this.world.on_block_change = (x, y, z, id, state) => {
const data = JSON.stringify(
(state
? { type: "set_block", x, y, z, id, state }
: { type: "set_block", x, y, z, id }) satisfies ServerMessage,
);
for (const player of this.#players.values()) {
if (player.chunks.has_block(x, z)) {
this.#host.send(player.conn, data);
}
}
};
}
// connections
@@ -275,6 +296,7 @@ export class GameServer {
for (const player of this.#players.values()) {
this.#sync(player);
}
this.#send_chunks();
}
// level.json and the chunks changed since the last save
@@ -390,6 +412,7 @@ export class GameServer {
Object.assign(player, { x, y, z });
player.fall_distance = 0;
this.#send(player, { type: "teleport", x, y, z });
this.#update_view(player);
this.#broadcast({ type: "player_move", id: player.id, x, y, z, yaw: player.yaw, pitch: player.pitch }, player);
}
@@ -569,7 +592,6 @@ export class GameServer {
{
type: "welcome",
protocol: PROTOCOL_VERSION,
seed: this.world.seed,
mods: this.#mods.listings,
} satisfies ServerMessage,
),
@@ -583,7 +605,7 @@ export class GameServer {
return;
}
this.#pending.delete(conn);
this.#join(conn, pending.name);
this.#join(conn, pending.name, view_distance(message.view_distance));
}
}
@@ -592,8 +614,8 @@ export class GameServer {
this.#host.close(conn);
}
#join(conn: number, raw_name: unknown) {
const player = new ServerPlayer(conn, this.#unique_name(raw_name));
#join(conn: number, raw_name: unknown, view_distance: number) {
const player = new ServerPlayer(conn, this.#unique_name(raw_name), view_distance);
const saved = this.#saved_players[player.name];
if (saved) {
player.load(saved);
@@ -606,13 +628,15 @@ export class GameServer {
id: player.id,
name: player.name,
players: [...this.#players.values()].map((p) => p.info()),
changes: this.world.all_changes(),
entities: [...this.#entities.values()].map((entity) => entity.info()),
blocks: this.world.block_table(),
spawn: { x: player.x, y: player.y, z: player.z, yaw: player.yaw, pitch: player.pitch },
selected_slot: player.selected_slot,
time: this.world.time,
});
this.#players.set(conn, player);
// the chunks come with the next ticks
this.#update_view(player);
this.#sync(player);
this.#broadcast({ type: "player_join", player: player.info() }, player);
@@ -631,8 +655,20 @@ export class GameServer {
this.#on_move(player, x, y, z);
Object.assign(player, { x, y, z, yaw, pitch });
this.#broadcast({ type: "player_move", id: player.id, x, y, z, yaw, pitch }, player);
this.#update_view(player);
break;
}
case "view_distance":
if (is_int(message.distance)) {
player.chunks.view_distance = view_distance(message.distance);
this.#update_view(player, true);
}
break;
case "chunk_batch_received":
if (is_number(message.chunks_per_tick)) {
player.chunks.on_batch_received(message.chunks_per_tick);
}
break;
case "break_block":
if (is_block_position(message.x, message.y, message.z)) {
this.#break_block(player, message.x, message.y, message.z);
@@ -1413,12 +1449,57 @@ export class GameServer {
// tell the player what's really at a position, undoing anything their client guessed
#correct(player: ServerPlayer, x: number, y: number, z: number) {
if (y < 0 || y >= CHUNK_HEIGHT) {
if (y < 0 || y >= CHUNK_HEIGHT || !player.chunks.has_block(x, z)) {
return;
}
this.#send(player, { type: "set_block", x, y, z, id: this.world.get_block_id(x, y, z) });
}
// chunks
// after the player moved or their view distance changed: tells their client the new center and which chunks to
// drop, the chunks that came into view go out in #send_chunks
#update_view(player: ServerPlayer, force = false) {
const { moved, forget } = player.chunks.move_to(player.x, player.z, force);
if (!moved) {
return;
}
const center = player.chunks.center!;
this.#send(player, { type: "set_center_chunk", x: center.x, z: center.z });
for (const [x, z] of forget) {
this.#send(player, { type: "forget_level_chunk", x, z });
}
}
// every player's next batch, like minecraft's PlayerChunkSender. building chunks is the slow part, so they share
// a time budget and whoever didn't get theirs goes first next tick
#send_chunks() {
const players = [...this.#players.values()];
if (players.length === 0) {
return;
}
const start = performance.now();
const can_send = () => performance.now() - start < this.chunk_send_budget_ms;
const first = this.#next_chunk_player % players.length;
for (let i = 0; i < players.length; i++) {
const player = players[(first + i) % players.length];
if (!can_send()) {
this.#next_chunk_player = first + i;
return;
}
const batch = player.chunks.next_batch(can_send);
if (batch.length === 0) {
continue;
}
this.#send(player, { type: "chunk_batch_start" });
for (const [x, z] of batch) {
this.#host.send(player.conn, this.world.level_chunk(x, z));
}
this.#send(player, { type: "chunk_batch_finished", size: batch.length });
}
this.#next_chunk_player = first + 1;
}
#in_reach(player: ServerPlayer, x: number, y: number, z: number) {
const dx = x + 0.5 - player.x;
const dy = y + 0.5 - (player.y + PLAYER_EYE_HEIGHT);
@@ -1475,6 +1556,14 @@ function is_int(value: unknown): value is number {
return Number.isInteger(value);
}
// what a player asked for, up to the server's
function view_distance(requested: unknown): number {
if (!is_int(requested)) {
return SERVER_VIEW_DISTANCE;
}
return Math.min(SERVER_VIEW_DISTANCE, Math.max(MIN_VIEW_DISTANCE, Math.min(MAX_VIEW_DISTANCE, requested)));
}
// messages are parsed json, so the types in ClientMessage are only what a well behaved client sends
function is_block_position(x: unknown, y: unknown, z: unknown): boolean {
return is_int(x) && is_int(y) && is_int(z) && y >= 0 && y < CHUNK_HEIGHT &&
+2 -1
View File
@@ -22,7 +22,8 @@ export type HostToGame =
export type GameToHost =
| { type: "ready"; seed: string }
| { type: "failed"; error: string }
| { type: "send"; conn: number; data: string }
// text is a json message, bytes a binary one
| { type: "send"; conn: number; data: string | Uint8Array<ArrayBuffer> }
| { type: "close"; conn: number }
// level.json and the chunks that changed
| { type: "save"; save: Required<WorldSave>; final: boolean }
+5 -1
View File
@@ -1,6 +1,7 @@
import { Container, Cursor, ItemData, ItemStack } from "$/common/inventory.ts";
import { PlayerInfo, ScreenLayout } from "$/common/protocol.ts";
import { type SavedVitals, Vitals } from "./vitals.ts";
import { PlayerChunks } from "./player_chunks.ts";
export const INVENTORY_SIZE = 9 * 4;
export const CRAFTING_SIZE = 10;
@@ -64,10 +65,13 @@ export class ServerPlayer {
// last json sent for each synced thing, so only changes get sent
sent = new Map<string, string>();
// the chunks their client has and still needs
chunks: PlayerChunks;
constructor(conn: number, name: string) {
constructor(conn: number, name: string, view_distance: number) {
this.conn = conn;
this.name = name;
this.chunks = new PlayerChunks(view_distance);
}
get held_item(): ItemStack | undefined {
+120
View File
@@ -0,0 +1,120 @@
import { CHUNK_SIZE } from "$/common/constants.ts";
import { is_within_view } from "$/common/chunk_streaming.ts";
import { chunk_key } from "$/common/utils.ts";
// minecraft's PlayerChunkSender numbers
const START_CHUNKS_PER_TICK = 9;
const MIN_CHUNKS_PER_TICK = 0.01;
const MAX_CHUNKS_PER_TICK = 64;
const MAX_UNACKNOWLEDGED_BATCHES = 10;
// which chunks a player's client has and which it still needs, like minecraft's ChunkTrackingView and
// PlayerChunkSender: chunks go out nearest first, in batches as big as the client says it can take
export class PlayerChunks {
view_distance: number;
// the chunk the player is in, undefined until the first update
center: { x: number; z: number } | undefined;
// chunks the client was sent and hasn't been told to forget, by chunk_key
#sent = new Map<number, [number, number]>();
// in view and not sent yet
#pending = new Map<number, [number, number]>();
#chunks_per_tick = START_CHUNKS_PER_TICK;
#batch_quota = 0;
#unacknowledged_batches = 0;
// one batch until the client first answers, so a client that can't keep up isn't flooded
#max_unacknowledged_batches = 1;
constructor(view_distance: number) {
this.view_distance = view_distance;
}
has(chunk_x: number, chunk_z: number) {
return this.#sent.has(chunk_key(chunk_x, chunk_z));
}
// has the chunk the block at x, z is in
has_block(x: number, z: number) {
return this.has(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
}
get pending_count() {
return this.#pending.size;
}
// follows the player to the chunk at x, z (in blocks). returns whether that's a new center, and the chunks the
// client should forget
move_to(x: number, z: number, force = false): { moved: boolean; forget: [number, number][] } {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
if (!force && this.center?.x === chunk_x && this.center.z === chunk_z) {
return { moved: false, forget: [] };
}
this.center = { x: chunk_x, z: chunk_z };
const in_view = (cx: number, cz: number) => is_within_view(chunk_x, chunk_z, this.view_distance, cx, cz);
const forget: [number, number][] = [];
for (const [key, [cx, cz]] of this.#sent) {
if (!in_view(cx, cz)) {
this.#sent.delete(key);
forget.push([cx, cz]);
}
}
for (const [key, [cx, cz]] of this.#pending) {
if (!in_view(cx, cz)) this.#pending.delete(key);
}
// the view plus its outer ring fits in this square
const reach = this.view_distance + 1;
for (let cx = chunk_x - reach; cx <= chunk_x + reach; cx++) {
for (let cz = chunk_z - reach; cz <= chunk_z + reach; cz++) {
const key = chunk_key(cx, cz);
if (in_view(cx, cz) && !this.#sent.has(key)) this.#pending.set(key, [cx, cz]);
}
}
return { moved: true, forget };
}
// the chunks to send this tick, nearest the player first, and counts them as sent. empty when the client is
// still busy with earlier batches. can_send says whether there's time left to build one more
next_batch(can_send: () => boolean = () => true): [number, number][] {
if (this.#unacknowledged_batches >= this.#max_unacknowledged_batches || !this.center) {
return [];
}
this.#batch_quota = Math.min(
this.#batch_quota + this.#chunks_per_tick,
Math.max(1, this.#chunks_per_tick),
);
if (this.#batch_quota < 1 || this.#pending.size === 0) {
return [];
}
const { x, z } = this.center;
const nearest = [...this.#pending.entries()]
.map(([key, [cx, cz]]) => ({ key, cx, cz, distance: (cx - x) ** 2 + (cz - z) ** 2 }))
.sort((a, b) => a.distance - b.distance);
const batch: [number, number][] = [];
for (const { key, cx, cz } of nearest) {
if (batch.length >= Math.floor(this.#batch_quota) || !can_send()) break;
this.#pending.delete(key);
this.#sent.set(key, [cx, cz]);
batch.push([cx, cz]);
}
if (batch.length > 0) {
this.#unacknowledged_batches += 1;
this.#batch_quota -= batch.length;
}
return batch;
}
// the client loaded a batch and says how many chunks a tick it can take
on_batch_received(chunks_per_tick: number) {
this.#unacknowledged_batches = Math.max(0, this.#unacknowledged_batches - 1);
this.#chunks_per_tick = Number.isNaN(chunks_per_tick)
? MIN_CHUNKS_PER_TICK
: Math.min(Math.max(chunks_per_tick, MIN_CHUNKS_PER_TICK), MAX_CHUNKS_PER_TICK);
if (this.#unacknowledged_batches === 0) {
this.#batch_quota = 1;
}
this.#max_unacknowledged_batches = MAX_UNACKNOWLEDGED_BATCHES;
}
}
+5 -1
View File
@@ -16,7 +16,11 @@ let next_download = 1;
function post(message: GameToHost) {
// the chunks are moved to the host, not copied
const transfer = message.type === "save" ? message.save.chunks.map((chunk) => chunk.data.buffer) : [];
const transfer = message.type === "save"
? message.save.chunks.map((chunk) => chunk.data.buffer)
: message.type === "send" && typeof message.data !== "string"
? [message.data.buffer]
: [];
self.postMessage(message, transfer);
}
+19 -6
View File
@@ -5,6 +5,7 @@ import { AIR_ID, BlockChange } from "$/common/protocol.ts";
import { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
import { LruMap } from "./lru.ts";
import { CYCLE_TICKS } from "$/common/time.ts";
import { encode_level_chunk } from "$/common/chunk_streaming.ts";
import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, is_changed, SavedChunk } from "./saves.ts";
// generation only, rebuilt when needed. 256 KB each
@@ -41,7 +42,7 @@ export class ServerWorld {
#raw = new LruMap<number, RawChunk>(RAW_CACHE_SIZE);
#chunks = new LruMap<number, Uint32Array>(CHUNK_CACHE_SIZE);
// changes from generated terrain, per chunk, which is also what clients get sent. saved as whole chunks
// changes from generated terrain, per chunk. saved as whole chunks
#changes = new Map<number, Map<string, BlockChange>>();
// chunks changed since they were last saved, by chunk_key
#unsaved = new Map<number, [number, number]>();
@@ -156,12 +157,24 @@ export class ServerWorld {
this.on_block_change?.(x, y, z, id, state_bits);
}
all_changes(): BlockChange[] {
const all: BlockChange[] = [];
for (const chunk_changes of this.#changes.values()) {
all.push(...chunk_changes.values());
// what clients are sent, the whole chunk as it is now. block values use this world's numeric ids, see block_table
level_chunk(chunk_x: number, chunk_z: number): Uint8Array<ArrayBuffer> {
return encode_level_chunk({
x: chunk_x,
z: chunk_z,
blocks: this.#get_chunk(chunk_x, chunk_z),
biomes: this.#get_raw(chunk_x, chunk_z).biomes,
});
}
// the block id of each numeric id, for clients to read level_chunk with
block_table(): string[] {
const table: string[] = [];
for (const [id, nid] of Object.entries(this.block_ids)) {
table[nid] = id;
}
return all;
table[AIR] = AIR_ID;
return table;
}
#fingerprint: string | undefined;