diff --git a/MODS.md b/MODS.md index ffbdcc6..24c3e20 100644 --- a/MODS.md +++ b/MODS.md @@ -59,7 +59,7 @@ A mod can have up to four scripts, each running in a different place: | `common` | the server and every client, before the others | yes | content: registering blocks, items, models and recipes, and changing other mods' content | | `server` | the server, in a worker | **never** | game logic: block components, ticking, tile data, containers, commands, events | | `client` | every client, main thread | yes | presentation: custom screens, HUD, keybinds | -| `worldgen` | server and client chunk workers | yes | terrain and features, must be deterministic | +| `worldgen` | the server | no | terrain and features, must be deterministic | **The server is the authority.** Clients send what the player is trying to do ("break the block at x, y, z", "click slot 3"). The server checks it, runs mod logic and sends back what happened. For responsiveness, clients show the expected @@ -72,9 +72,9 @@ result of breaking and placing immediately, and the server sends a correction if │ ┌───────────────────────────────────┐ │ ws │ + mod common and client │ │ │ game server worker │◄├──────────┤► scripts │ │ │ world, inventories, tile data │ │ protocol │ │ -│ │ + mod common and server scripts │ │ │ chunk workers │ -│ └───────────────────────────────────┘ │ │ + mod worldgen scripts │ -│ chunk workers + mod worldgen scripts │ └──────────────────────────────────┘ +│ │ + mod common and server scripts │ │ chunks │ chunk workers (meshing, light) │ +│ │ + mod worldgen scripts │ │ └──────────────────────────────────┘ +│ └───────────────────────────────────┘ │ └───────────────────────────────────────┘ ``` @@ -87,8 +87,8 @@ server sends its order to clients, and they follow it. common script sees its own data and everything from the mods before it, and can change it. 2. **Freeze.** The registries close: blocks get their numeric ids, block items are created and recipes are indexed. Registering or changing content after this throws. -3. **Scripts.** `server` scripts' `setup` runs on the server, `client` scripts' on each client, and `worldgen` scripts in - every chunk worker. These can read every registry but not change them. +3. **Scripts.** `server` scripts' `setup` runs on the server, `client` scripts' on each client, and `worldgen` scripts + where the server generates chunks. These can read every registry but not change them. 4. The server starts ticking, or the client sends `ready` and joins. **Content has to come out the same on every side.** Common scripts run on the server and on every client, and all of @@ -132,7 +132,7 @@ mods/ common.ts # content, runs on both sides server.ts # game logic, stays on the server client.ts # sent to players - worldgen.ts # sent to players, also runs on the server + worldgen.ts # stays on the server, players get the chunks it makes shared/ # anything several scripts import, bundled into each ``` @@ -175,13 +175,13 @@ Only `manifest.json` is required. Data folders can have subfolders, with one def | `scripts.common` | no | Content entry, run on the server and sent to every player. _Planned, phase 1._ | | `scripts.server` | no | Server entry. Never sent to clients. | | `scripts.client` | no | Client entry, sent to every player. | -| `scripts.worldgen` | no | Worldgen entry, sent to every player and also run on the server. | +| `scripts.worldgen` | no | Worldgen entry, run on the server. Never sent to clients, they get chunks. | | `engine_access` | no | `true` lets the mod's scripts import `bworld/engine`, see [Engine access](#engine-access). _Planned, phase 3._ | | `credits` | no | A markdown file in the mod, shown on the Credits screen. For asset licenses and thanks. | Scripts can be `.js` or `.ts`. The build bundles each entry separately into one ES module. Code imported by several -entries is copied into each bundle, so **don't import secrets into shared code**. Anything the common, client or worldgen -bundles import is visible to players. +entries is copied into each bundle, so **don't import secrets into shared code**. Anything the common or client bundles +import is visible to players. ## Identifiers @@ -812,8 +812,8 @@ first minute of the night and dawn the last, so it's bright all day. `common/tim `is_day` and `daylight` for turning it into something readable. Client scripts can read it as `ctx.world.time`, and players can use `/time`, `/time set ` and `/time add `. -The server loads chunks around every player (its simulation distance) and generates them itself with the same generator -as the clients. Blocks in unloaded chunks can't be read or changed, and don't tick. +The server loads chunks around every player (its simulation distance) and generates them itself, then sends them to +players whole (see [Chunks](#chunks)). Blocks in unloaded chunks can't be read or changed, and don't tick. ### Commands @@ -1209,8 +1209,9 @@ ctx.net.send("copper_tools:reset_stats", {}); ## World generation -Chunks are generated from the world seed by chunk workers on **both** the server and every client, and all of them must -produce identical terrain. So worldgen scripts must be **deterministic**. +Chunks are generated from the world seed on the server only, and players get the finished chunks (see +[Chunks](#chunks)). Saves only keep what players changed on top of generated terrain, so a chunk has to come out the +same every time it's generated: worldgen scripts must be **deterministic**. Each chunk is generated in three passes: @@ -1417,9 +1418,8 @@ function hook(target: T, method: K, handlers: { - JavaScript's `#private` members can't be hooked or read. The engine keeps things that mods should be able to change as normal members, and `#private` for things with rules that must hold (like a container's slots). Making something hookable is an ordinary engine change, and asking for one is how the Game API grows. -- Hooks reach one JavaScript realm: the game server worker for server scripts, the page for client scripts, and one - chunk worker for worldgen scripts. Each chunk worker runs its own copy of the engine, so a hook in a client script - doesn't change meshing; a worldgen script with engine access can. +- Hooks reach one JavaScript realm: the game server worker for server and worldgen scripts, and the page for client + scripts. Each chunk worker runs its own copy of the engine, so a hook in a client script doesn't change meshing. ### Rules @@ -1467,8 +1467,8 @@ textures, the ids it uses from other mods, and that its dependencies are there. from starting, saying which mod and what's wrong, so the game never runs with some mods missing. Then it sorts them so dependencies load first. -Players get each mod as a `.bmod` too, **without its server script**: the server makes a copy without -`scripts/server.js` and serves it at `/mods/.bmod`, named by its hash so it can be cached forever. The code is in +Players get each mod as a `.bmod` too, **without its server and worldgen scripts**: the server makes a copy without +`scripts/server.js` and `scripts/worldgen.js` and serves it at `/mods/.bmod`, named by its hash so it can be cached forever. The code is in `common/bmod.ts` (reading and writing), `tools/pack_mod.ts` and `server/load_bmods.ts`. The engine's own files (the client, its UI sprites and font, and the `engine:` textures) aren't in any mod. They're in @@ -1480,7 +1480,7 @@ The engine's own files (the client, its UI sprites and font, and the `engine:` t client server │ hello { name, protocol } │ ├────────────────────────────────────────►│ a different protocol gets rejected { reason } - │ welcome { protocol, seed, mods[] } │ mods[i] = { id, name, version, sha256, file, size } + │ welcome { protocol, mods[] } │ mods[i] = { id, name, version, sha256, file, size } │◄────────────────────────────────────────┤ file is the .bmod's path on the server │ │ │ [cross-origin: confirm screen] │ @@ -1489,10 +1489,12 @@ client server │ content in the listed order, run │ │ client setup(), start chunk workers │ │ │ - │ ready { registry_hash } │ a different hash gets rejected { reason } + │ ready { view_distance, registry_hash } │ a different hash gets rejected { reason } ├────────────────────────────────────────►│ │ join { id, name, players, entities, │ the player is created here, player_join fires, - │ changes, spawn, selected_slot } │ and their inventory follows as container messages + │ blocks, spawn, selected_slot } │ and their inventory follows as container messages + │◄────────────────────────────────────────┤ + │ set_center_chunk, then chunk batches │ see Chunks │◄────────────────────────────────────────┤ ``` @@ -1513,6 +1515,29 @@ client server from other origins. - Leaving a server reloads the page, so one server's mod code never stays loaded while playing on another. +### Chunks + +The server sends the world the way Minecraft Java does since 1.20.2. Clients never generate terrain, so worldgen +scripts stay on the server and clients can't be handed a world that differs from the server's. The code is in +`common/chunk_streaming.ts`, `server/game/player_chunks.ts` and `client/level/client_level.ts`. + +- **Whole chunks.** A `level_chunk` is a binary websocket message holding every block of a 16×256×16 chunk and its + columns' biomes, deflated. Blocks are in 16 sections of 16×16×16, each a paletted container like Minecraft's: one + value when the section is all one block, a palette and 1, 2, 4 or 8 bits per block up to 256 kinds, and whole values + past that. Light isn't sent, clients light chunks themselves when they mesh them. +- **Numeric ids.** Chunks use the server's numeric block ids, and `join.blocks` lists the string id for each, like + Minecraft's registry sync. Clients turn them into their own numbers as a chunk loads. +- **The view.** Players send their view distance with `ready` and `view_distance` when it changes. The server uses up + to 10 chunks, and sends chunks in a round area around the player plus the ring just past it, which clients need to + mesh and light the edge of what they show (Minecraft's `ChunkTrackingView`). When a player moves into another chunk + the server sends `set_center_chunk`, and `forget_level_chunk` for each chunk that left the view. +- **Batches.** Chunks go out nearest first, between `chunk_batch_start` and `chunk_batch_finished { size }`. The client + times how long it took to load them and answers `chunk_batch_received { chunks_per_tick }`: as many chunks as fit in + 7 ms a tick. Until the first answer there's one batch of 9 in flight, after it up to 10. The server also stops + building chunks for a tick after 20 ms, so players loading far away don't slow the game down. +- **Changes.** `set_block` only goes to players that have the chunk. Everyone else gets the change with the chunk when + they come close. + ## Security **Client scripts.** Mod client code runs in the game page with the page's full access. How much that matters depends on @@ -1781,7 +1806,7 @@ any order after them. - Move the ore table to `mods/bworld/worldgen/ores.json`, and take the content out of `common/generation.ts`, leaving the passes and noise helpers. - The server refuses to start without a terrain generator, naming the mods that could provide one. -- Check: `terrain.json` matches exactly, client and server terrain still agree, and old saves load unchanged. +- Check: `terrain.json` matches exactly, and old saves load unchanged. **Done when:** @@ -1794,9 +1819,6 @@ any order after them. ## Open questions -- **Chunk delivery.** Clients generate terrain from the seed, which needs deterministic worldgen and trusts clients to - run the same generator. Sending chunks from the server instead (like Minecraft) removes both problems but costs - bandwidth, roughly 5–15 KB per chunk compressed. It could be worth it once the server generates terrain anyway. - **Client-only mods.** Should players be able to install their own client mods (minimaps, UI tweaks, shaders) that work on any server, like Fabric's client mods? They'd need a separate `"side": "client"` kind of mod that can't add content or change the registry hash, and servers might want to forbid them. diff --git a/client/client.ts b/client/client.ts index 230b7f6..288ed6e 100644 --- a/client/client.ts +++ b/client/client.ts @@ -45,6 +45,8 @@ export class Client { // whether the attack button is held on a block, breaking it advances every tick #attacking = false; #stopped = false; + // the render distance the server was last told, it sends chunks for it + #sent_view_distance: number; // called once when the connection drops, with why #on_disconnect: (message: string) => void; @@ -52,11 +54,9 @@ export class Client { this.connection = connection; this.#on_disconnect = on_disconnect; - this.level = new ClientLevel(connection.seed); + this.level = new ClientLevel(connection.server_blocks, this.options.render_distance); this.level.time = connection.time; - for (const [x, y, z, id, state] of connection.initial_changes) { - this.level.record_change(x, y, z, id, state); - } + this.#sent_view_distance = this.options.render_distance; const spawn = connection.spawn; this.player = new LocalPlayer(this, connection.id, connection.name); @@ -128,7 +128,7 @@ export class Client { this.game_renderer.render(this, this.#pending_time / TICK_DELTA); } - // one step of the game: what the server sent, breaking, chunk loading, then every entity + // one step of the game: what the server sent (chunks included), breaking, then every entity tick() { this.packet_listener.handle_packets(); if (this.connection.closed) { @@ -141,7 +141,12 @@ export class Client { this.game_mode.continue_destroy_block(this.hit_result); } - this.level.update_loaded_chunks(this.player.x, this.player.z, this.options.render_distance); + const view_distance = Math.round(this.options.render_distance); + if (view_distance !== this.#sent_view_distance) { + this.#sent_view_distance = view_distance; + this.level.view_distance = view_distance; + this.connection.send({ type: "view_distance", distance: view_distance }); + } this.level.tick(); } diff --git a/client/handshake.ts b/client/handshake.ts index 484bf94..4bc5906 100644 --- a/client/handshake.ts +++ b/client/handshake.ts @@ -76,8 +76,14 @@ export class ServerSocket { constructor(socket: WebSocket) { this.socket = socket; + socket.binaryType = "arraybuffer"; socket.addEventListener("message", (event) => { - this.messages.push(JSON.parse(event.data)); + // the only binary messages are chunks, decoded by the packet listener so it can time them + this.messages.push( + typeof event.data === "string" + ? JSON.parse(event.data) + : { type: "level_chunk", data: new Uint8Array(event.data) }, + ); this.#wake(); }); socket.addEventListener("close", () => { @@ -151,9 +157,9 @@ export async function connect( return { socket: server, welcome: answer }; } -// tell the server everything's loaded and wait to be let in -export async function join(socket: ServerSocket): Promise { - socket.send({ type: "ready" }); +// tell the server everything's loaded and wait to be let in. view_distance is in chunks +export async function join(socket: ServerSocket, view_distance: number): Promise { + socket.send({ type: "ready", view_distance }); const answer = await socket.next("join", "rejected"); if (answer.type === "rejected") { socket.close(); diff --git a/client/level/client_level.ts b/client/level/client_level.ts index 9a70af8..34ec01a 100644 --- a/client/level/client_level.ts +++ b/client/level/client_level.ts @@ -1,5 +1,7 @@ import { block_value, chunk_key, default_block_value } from "$/common/utils.ts"; -import { AIR_ID, BlockChange } from "$/common/protocol.ts"; +import { AIR_ID } from "$/common/protocol.ts"; +import { decode_level_chunk } from "$/common/chunk_streaming.ts"; +import { foliage_color, grass_color } from "$/common/worldgen/biome_colors.ts"; import { block_light_emission, block_light_opacity, @@ -11,7 +13,6 @@ import { import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts"; import { AssetManager } from "../assets.ts"; import { ChunkWorkerPool } from "../chunk_workers.ts"; -import { worldgen_mods } from "../mods.ts"; import type { FaceGroup, FromChunkWorker } from "../workers/chunk_messages.ts"; import { create_index_buffer, create_vertex_buffer, destroy_buffer, Texture } from "../renderer/mod.ts"; import { crosses_planes } from "../workers/translucent_sort.ts"; @@ -32,7 +33,6 @@ export interface Chunk { x: number; z: number; blocks: Uint32Array; - generated: boolean; dirty: boolean; // bumped on every mesh request so late results from older requests get ignored mesh_version: number; @@ -42,11 +42,8 @@ export interface Chunk { max_y: number; // only for translucent meshes that have to be sorted again as the camera moves translucent_sort?: TranslucentSort; - // blocks its generation put in neighboring chunks (leaves), as x, y, z, numeric id. kept so a neighbor that - // generates later, or unloads and comes back, still gets them - spills?: Int32Array; - // each column's biome grass then foliage color, once it's generated - biome_colors?: Uint32Array; + // each column's biome grass color, x then z, then each column's foliage color + biome_colors: Uint32Array; } export interface ChunkMesh { @@ -84,46 +81,54 @@ export interface BlockHitResult { const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1]] as const; // light spreads diagonally too, so meshing and lighting need all 8 const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-1, -1], [1, -1], [-1, 1], [1, 1]] as const; +// how far past the view distance chunks are kept, like minecraft's ClientChunkCache. the server tells the client +// which ones to forget, this only catches the ones it didn't +const STORAGE_MARGIN = 3; -// what minecraft calls the ClientLevel: this client's copy of the world, its chunks and the entities in it +// what minecraft calls the ClientLevel: this client's copy of the world, its chunks and the entities in it. the +// chunks are what the server sent, see common/chunk_streaming.ts export class ClientLevel { image: Texture = AssetManager.instance.get("bworld:textures"); chunks = new Map(); second_timer = 0; tick_timer = 0; - seed: string; // world time in ticks, counted here between the server's updates. see common/time.ts time = 0; - - // blocks players changed from the generated terrain, per chunk, so they survive reloading chunks - changes = new Map>(); + // in chunks, what the server was asked to send + view_distance: number; + // the chunk the server says the player is in + center: { x: number; z: number } | undefined; workers: ChunkWorkerPool; #blocks = EverythingRegistry.get_registry("blocks"); - // chunks being generated by a worker, by chunk key - pending_generation = new Map(); + // the server's numeric block ids to this client's + #to_local: Uint32Array; // every entity this client knows about, the local player included, by id entities = new Map(); - constructor(seed = "seed") { - this.seed = seed; + // server_blocks is the server's block id for each of its numeric ids + constructor(server_blocks: string[], view_distance: number) { + this.view_distance = view_distance; + this.#to_local = new Uint32Array(server_blocks.length); + server_blocks.forEach((id, nid) => { + if (!id) return; + const local = id === AIR_ID ? AIR : EverythingRegistry.get_id("blocks", id); + if (local === undefined) { + console.warn(`The server has a block this client doesn't: ${id}`); + } + this.#to_local[nid] = local ?? AIR; + }); this.workers = new ChunkWorkerPool((message) => this.#on_worker_message(message)); - const blocks_registry = EverythingRegistry.get_registry("blocks"); - const block_ids: Record = {}; - blocks_registry.forEach((block, nid) => block_ids[block.id] = nid); // sent once instead of with every mesh request this.workers.broadcast({ type: "init", - blocks_registry: strip_functions(blocks_registry), - block_ids, + blocks_registry: strip_functions(EverythingRegistry.get_registry("blocks")), models: Object.fromEntries(EverythingRegistry.entries("models")), textures_info: AssetManager.instance.get("bworld:textures_info"), image: { width: this.image.width, height: this.image.height }, - worldgen_scripts: worldgen_mods.scripts, - ores: worldgen_mods.ores, }); } @@ -143,72 +148,72 @@ export class ClientLevel { } } - // generates the chunks around a position and forgets the ones too far away. one extra ring past the render - // distance gets generated so the edge has neighbors to mesh against - update_loaded_chunks(x: number, z: number, render_distance: number) { - const center_x = Math.floor(x / CHUNK_SIZE); - const center_z = Math.floor(z / CHUNK_SIZE); - const load_distance = render_distance + 1; - const out_of_range = (cx: number, cz: number) => - Math.max(Math.abs(cx - center_x), Math.abs(cz - center_z)) > load_distance; - - // collect first, deleting from the map while iterating it skips entries - const to_unload = [...this.chunks.values()].filter((chunk) => out_of_range(chunk.x, chunk.z)); - for (const chunk of to_unload) { - this.unload_chunk(chunk.x, chunk.z); - } - for (const pending of [...this.pending_generation.values()]) { - if (out_of_range(pending.x, pending.z)) { - this.cancel_chunk_request(pending.x, pending.z); - } - } - - // dont queue up the whole area at once, so walking somewhere new gets the close chunks first - const max_in_flight = this.workers.size * 2; - if (this.pending_generation.size >= max_in_flight) { + // a level_chunk from the server: the whole chunk, replacing it if it was already here + load_chunk(data: Uint8Array) { + const { x, z, blocks, biomes } = decode_level_chunk( + data, + (value) => this.#to_local[value & ID_MASK] | (value & ~ID_MASK), + ); + if (!this.#in_storage_range(x, z)) { return; } + const biome_colors = new Uint32Array(CHUNK_AREA * 2); + biomes.forEach((biome, column) => { + biome_colors[column] = grass_color(biome); + biome_colors[CHUNK_AREA + column] = foliage_color(biome); + }); - const missing: { x: number; z: number; distance: number }[] = []; - for (let cx = center_x - load_distance; cx <= center_x + load_distance; cx += 1) { - for (let cz = center_z - load_distance; cz <= center_z + load_distance; cz += 1) { - if (!this.is_generated(cx, cz) && !this.is_generating(cx, cz)) { - const dx = cx - center_x; - const dz = cz - center_z; - missing.push({ x: cx, z: cz, distance: dx * dx + dz * dz }); - } + const chunk = this.get_chunk(x, z); + if (chunk) { + // its old mesh stays up until the new one is ready + chunk.blocks = blocks; + chunk.biome_colors = biome_colors; + chunk.dirty = true; + } else { + this.chunks.set(chunk_key(x, z), { + x, + z, + blocks, + biome_colors, + dirty: true, + mesh_version: 0, + meshes: {}, + min_y: 0, + max_y: 0, + }); + } + // their border faces and light depend on this one + for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) { + const neighbor = this.get_chunk(x + dx, z + dz); + if (neighbor) { + neighbor.dirty = true; } } - missing.sort((a, b) => a.distance - b.distance); + } - for (const chunk of missing.slice(0, max_in_flight - this.pending_generation.size)) { - this.request_chunk(chunk.x, chunk.z); + // the server moved the player's view, chunks far outside it go even if the server didn't say + set_center(x: number, z: number) { + this.center = { x, z }; + const far = [...this.chunks.values()].filter((chunk) => !this.#in_storage_range(chunk.x, chunk.z)); + for (const chunk of far) { + this.unload_chunk(chunk.x, chunk.z); } } + #in_storage_range(x: number, z: number) { + if (!this.center) { + return true; + } + const range = Math.max(2, this.view_distance) + STORAGE_MARGIN; + return Math.max(Math.abs(x - this.center.x), Math.abs(z - this.center.z)) <= range; + } + dispose() { this.workers.terminate(); for (const chunk of this.chunks.values()) { this.delete_chunk_mesh(chunk); } this.chunks.clear(); - this.pending_generation.clear(); - } - - add_chunk(x: number, z: number, blocks: Uint32Array = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT)) { - const chunk: Chunk = { - x, - z, - blocks, - dirty: true, - generated: false, - mesh_version: 0, - meshes: {}, - min_y: 0, - max_y: 0, - }; - this.chunks.set(chunk_key(x, z), chunk); - return chunk; } get_chunk(x: number, z: number) { @@ -219,9 +224,9 @@ export class ClientLevel { add_block(block: Block, state?: number) { const block_chunk_x = Math.floor(block.x / CHUNK_SIZE); const block_chunk_z = Math.floor(block.z / CHUNK_SIZE); - let chunk = this.get_chunk(block_chunk_x, block_chunk_z); + const chunk = this.get_chunk(block_chunk_x, block_chunk_z); if (!chunk) { - chunk = this.add_chunk(block_chunk_x, block_chunk_z); + return; } const [nid, info] = EverythingRegistry.get_full("blocks", block.id)!; @@ -354,20 +359,10 @@ export class ClientLevel { return [x, y, z]; } - record_change(x: number, y: number, z: number, id: string, state = 0) { - const chunk_key = `${Math.floor(x / CHUNK_SIZE)},${Math.floor(z / CHUNK_SIZE)}`; - let chunk_changes = this.changes.get(chunk_key); - if (!chunk_changes) { - chunk_changes = new Map(); - this.changes.set(chunk_key, chunk_changes); - } - chunk_changes.set(`${x},${y},${z}`, [x, y, z, id, state]); - } - - // set a block the server told us about + // set a block the server told us about. the server only sends them for chunks this client has apply_change(x: number, y: number, z: number, id: string, state = 0) { const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)); - if (!chunk || !chunk.generated) { + if (!chunk) { return; } @@ -386,34 +381,7 @@ export class ClientLevel { this.add_block({ x, y, z, id }, state); } - apply_chunk_changes(cx: number, cz: number) { - for (const [x, y, z, id, state] of this.changes.get(`${cx},${cz}`)?.values() ?? []) { - this.apply_change(x, y, z, id, state); - } - } - - is_generated(cx: number, cz: number) { - return this.get_chunk(cx, cz)?.generated ?? false; - } - - is_generating(cx: number, cz: number) { - return this.pending_generation.has(chunk_key(cx, cz)); - } - - // generation happens in a worker, the chunk shows up in #on_generated - request_chunk(cx: number, cz: number) { - const key = chunk_key(cx, cz); - if (this.pending_generation.has(key) || this.chunks.get(key)?.generated) { - return; - } - this.pending_generation.set(key, { x: cx, z: cz }); - this.workers.post({ type: "generate", chunk_x: cx, chunk_z: cz, seed: this.seed }); - } - - cancel_chunk_request(cx: number, cz: number) { - this.pending_generation.delete(chunk_key(cx, cz)); - } - + // also what forget_level_chunk does unload_chunk(cx: number, cz: number) { const key = chunk_key(cx, cz); const chunk = this.chunks.get(key); @@ -427,11 +395,8 @@ export class ClientLevel { // a chunk is only meshed once all its neighbors exist, otherwise its border faces and light would be // wrong and it would have to be meshed again as each neighbor loads can_mesh(chunk: Chunk) { - if (!chunk.generated) { - return false; - } for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) { - if (!this.is_generated(chunk.x + dx, chunk.z + dz)) { + if (!this.get_chunk(chunk.x + dx, chunk.z + dz)) { return false; } } @@ -492,66 +457,13 @@ export class ClientLevel { } #on_worker_message(message: FromChunkWorker) { - if (message.type === "generated") { - this.#on_generated(message.chunk_x, message.chunk_z, message.blocks, message.spills, message.biome_colors); - } else if (message.type === "meshed") { + if (message.type === "meshed") { this.#on_meshed(message); } else { this.#on_sorted(message); } } - #on_generated(cx: number, cz: number, blocks: Uint32Array, spills: Int32Array, biome_colors: Uint32Array) { - const key = chunk_key(cx, cz); - // unloaded or cancelled while the worker was busy - if (!this.pending_generation.delete(key)) { - return; - } - - let chunk = this.chunks.get(key); - if (chunk) { - // blocks placed here before it generated, keep them where generation left air - const existing = chunk.blocks; - for (let i = 0; i < blocks.length; i++) { - if (blocks[i] !== AIR) { - existing[i] = blocks[i]; - } - } - } else { - chunk = this.add_chunk(cx, cz, blocks); - } - chunk.generated = true; - chunk.dirty = true; - chunk.spills = spills; - chunk.biome_colors = biome_colors; - - // the same rules as the server (server/game/world.ts): a chunk's own blocks, then what its neighbors' - // features put in it, only where it has air. both ways, since the neighbors may have generated first - for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) { - const neighbor_spills = this.get_chunk(cx + dx, cz + dz)?.spills; - if (neighbor_spills) { - this.#apply_spills(neighbor_spills, chunk); - } - } - for (let i = 0; i < spills.length; i += 4) { - this.#set_block_raw(spills[i], spills[i + 1], spills[i + 2], spills[i + 3]); - } - - for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) { - const neighbor = this.get_chunk(cx + dx, cz + dz); - if (neighbor && neighbor.generated) { - neighbor.dirty = true; - } - } - - // features spill into neighboring chunks, so their changes need reapplying too - for (let dx = -1; dx <= 1; dx++) { - for (let dz = -1; dz <= 1; dz++) { - this.apply_chunk_changes(cx + dx, cz + dz); - } - } - } - #on_meshed(message: Extract) { const chunk = this.get_chunk(message.chunk_x, message.chunk_z); // unloaded, or remeshed again since this was requested @@ -603,38 +515,6 @@ export class ClientLevel { mesh.index_buffer = create_index_buffer(message.indices); } - // blocks a neighbor's features put here, only fill air so the result doesn't depend on which chunk loaded first. - // the server builds chunks the same way (server/game/world.ts) - #set_block_raw(x: number, y: number, z: number, nid: number) { - if (y < 0 || y >= CHUNK_HEIGHT) { - return; - } - const chunk_x = Math.floor(x / CHUNK_SIZE); - const chunk_z = Math.floor(z / CHUNK_SIZE); - const chunk = this.get_chunk(chunk_x, chunk_z); - // a chunk that isn't generated yet takes it from our spills when it is - if (!chunk?.generated) { - return; - } - const lx = x - chunk_x * CHUNK_SIZE; - const lz = z - chunk_z * CHUNK_SIZE; - const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx; - if (chunk.blocks[index] === AIR) { - chunk.blocks[index] = nid; - chunk.dirty = true; - this.#mark_neighbors_dirty(chunk_x, chunk_z, lx, lz, AIR, nid & ID_MASK); - } - } - - // the spills that land in chunk - #apply_spills(spills: Int32Array, chunk: Chunk) { - for (let i = 0; i < spills.length; i += 4) { - if (Math.floor(spills[i] / CHUNK_SIZE) === chunk.x && Math.floor(spills[i + 2] / CHUNK_SIZE) === chunk.z) { - this.#set_block_raw(spills[i], spills[i + 1], spills[i + 2], spills[i + 3]); - } - } - } - delete_chunk_mesh(chunk: Chunk) { for (const mesh of Object.values(chunk.meshes)) { destroy_buffer(mesh.vertex_buffer); diff --git a/client/main.ts b/client/main.ts index 1e05d03..c4c136b 100644 --- a/client/main.ts +++ b/client/main.ts @@ -2,6 +2,7 @@ import { AssetManager } from "./assets.ts"; import { Client } from "./client.ts"; import { InputManager } from "./input_manager.ts"; import { Connection } from "./network.ts"; +import { Options } from "./options.ts"; import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress } from "./handshake.ts"; import { build_atlas, engine_textures } from "./atlas.ts"; import { confirm_mods } from "./confirm_mods.ts"; @@ -143,7 +144,7 @@ async function join_server(address: ServerAddress, name: string, status: (text: console.log(`Mods: ${welcome.mods.map((mod) => `${mod.id} ${mod.version}`).join(", ") || "none"}`); status("Joining..."); - const joined = await join(socket); + const joined = await join(socket, new Options().render_distance); return new Connection(socket, welcome, joined); } catch (e) { socket.close(); diff --git a/client/mods.ts b/client/mods.ts index 65a06e9..5d03e52 100644 --- a/client/mods.ts +++ b/client/mods.ts @@ -5,7 +5,6 @@ import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/e import type { ClientContext, InventoryOverlay } from "$/common/mod_api/client.ts"; import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts"; import { type Bmod, read_bmod } from "$/common/bmod.ts"; -import type { OreJson } from "$/common/mod_data.ts"; import { display_name } from "$/common/utils.ts"; import { AIR_ID } from "$/common/protocol.ts"; import type { Client } from "./client.ts"; @@ -14,9 +13,6 @@ import { code_url, fetch_verified } from "./handshake.ts"; // each loaded mod's credits file, for the credits screen export const mod_credits: { name: string; version: string; text: string }[] = []; -// what the chunk workers need to generate the same world as the server -export const worldgen_mods: { scripts: { mod: string; url: string }[]; ores: OreJson[] } = { scripts: [], ores: [] }; - // set once the game is running, mods can't look at it during setup let client: Client | undefined; @@ -60,11 +56,6 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) { mod_names.clear(); for (const listing of listings) mod_names.set(listing.id, listing.name); - worldgen_mods.ores = recipes.ores; - worldgen_mods.scripts = bmods.flatMap((bmod) => - bmod.scripts.worldgen ? [{ mod: bmod.manifest.id, url: script_url(bmod.scripts.worldgen) }] : [] - ); - for (const [i, bmod] of bmods.entries()) { if (!bmod.scripts.client) continue; const module = await import(script_url(bmod.scripts.client)); diff --git a/client/network.ts b/client/network.ts index 2277a17..23bc94c 100644 --- a/client/network.ts +++ b/client/network.ts @@ -1,4 +1,4 @@ -import { BlockChange, ClientMessage, EntityInfo, PlayerInfo, ServerMessage } from "$/common/protocol.ts"; +import { ClientMessage, EntityInfo, PlayerInfo, ServerMessage } from "$/common/protocol.ts"; import type { ModListing } from "$/common/mod_loader.ts"; import type { Join, ServerSocket, Welcome } from "./handshake.ts"; @@ -6,9 +6,9 @@ export class Connection { #server: ServerSocket; id: string; name: string; - seed: string; mods: ModListing[]; - initial_changes: BlockChange[]; + // the server's block id for each of its numeric ids, for reading chunks + server_blocks: string[]; spawn: { x: number; y: number; z: number; yaw: number; pitch: number }; selected_slot: number; time: number; @@ -20,9 +20,8 @@ export class Connection { this.#server = server; this.id = join.id; this.name = join.name; - this.seed = welcome.seed; this.mods = welcome.mods; - this.initial_changes = join.changes; + this.server_blocks = join.blocks; this.spawn = join.spawn; this.selected_slot = join.selected_slot; this.time = join.time; diff --git a/client/packet_listener.ts b/client/packet_listener.ts index d076e77..b3607ac 100644 --- a/client/packet_listener.ts +++ b/client/packet_listener.ts @@ -7,10 +7,45 @@ import { RemotePlayer } from "./entity/remote_player.ts"; import { ItemEntity } from "./entity/item_entity.ts"; import { Player } from "./entity/player.ts"; +// minecraft's ChunkBatchSizeCalculator: how long loading a chunk takes here, so the server sends as many a tick as +// fit in CHUNK_BUDGET_MS +const CHUNK_BUDGET_MS = 7; +const MAX_OLD_SAMPLES_WEIGHT = 49; +// a batch's time per chunk counts for at most this many times the average, or a hitch would stop chunks coming +const CLAMP_COEFFICIENT = 3; + +class ChunkBatchSizeCalculator { + #ms_per_chunk = 2; + #old_samples_weight = 1; + #batch_start = performance.now(); + + on_batch_start() { + this.#batch_start = performance.now(); + } + + on_batch_finished(size: number) { + if (size <= 0) { + return; + } + const per_chunk = (performance.now() - this.#batch_start) / size; + const clamped = Math.min( + Math.max(per_chunk, this.#ms_per_chunk / CLAMP_COEFFICIENT), + this.#ms_per_chunk * CLAMP_COEFFICIENT, + ); + this.#ms_per_chunk = (this.#ms_per_chunk * this.#old_samples_weight + clamped) / (this.#old_samples_weight + 1); + this.#old_samples_weight = Math.min(MAX_OLD_SAMPLES_WEIGHT, this.#old_samples_weight + 1); + } + + get chunks_per_tick() { + return CHUNK_BUDGET_MS / this.#ms_per_chunk; + } +} + // 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 export class ClientPacketListener { client: Client; + #chunk_batch = new ChunkBatchSizeCalculator(); constructor(client: Client) { this.client = client; @@ -89,9 +124,31 @@ export class ClientPacketListener { break; } case "set_block": - level.record_change(message.x, message.y, message.z, message.id, message.state); level.apply_change(message.x, message.y, message.z, message.id, message.state); break; + case "chunk_batch_start": + this.#chunk_batch.on_batch_start(); + break; + case "level_chunk": + try { + level.load_chunk(message.data); + } catch (e) { + console.error("Couldn't read a chunk from the server:", e); + } + break; + case "chunk_batch_finished": + this.#chunk_batch.on_batch_finished(message.size); + client.connection.send({ + type: "chunk_batch_received", + chunks_per_tick: this.#chunk_batch.chunks_per_tick, + }); + break; + case "forget_level_chunk": + level.unload_chunk(message.x, message.z); + break; + case "set_center_chunk": + level.set_center(message.x, message.z); + break; case "chat": client.chat.add(message.from ? `<${message.from}> ${message.text}` : message.text); break; diff --git a/client/workers/chunk_messages.ts b/client/workers/chunk_messages.ts index 61dee45..60c0d7e 100644 --- a/client/workers/chunk_messages.ts +++ b/client/workers/chunk_messages.ts @@ -1,6 +1,5 @@ import type { BlockRegistry } from "$/common/everything_registry.ts"; import type { SpriteRegion } from "$/common/constants.ts"; -import type { OreJson } from "$/common/mod_data.ts"; import type { ModelJson } from "$/common/block_models.ts"; import type { SortType } from "./translucent_sort.ts"; @@ -29,16 +28,11 @@ export type ToChunkWorker = type: "init"; // the blocks registry without its functions, indexed by numeric id blocks_registry: BlockRegistry[]; - block_ids: Record; // mods' block models by id, the engine's are built in models: Record; textures_info: Record; image: { width: number; height: number }; - // mods' worldgen scripts and ores, so generation matches the server - worldgen_scripts: { mod: string; url: string }[]; - ores: OreJson[]; } - | { type: "generate"; chunk_x: number; chunk_z: number; seed: string } | { type: "mesh"; chunk_x: number; @@ -46,7 +40,7 @@ export type ToChunkWorker = version: number; // copies of the blocks of the 3x3 chunks around it, going +x then +z from -x -z, for lighting chunks: (Uint32Array | null)[]; - // the same chunks' biome colors (see "generated"), blended across their edges + // the same chunks' biome colors (see Chunk.biome_colors in client_level.ts), blended across their edges biome_colors: (Uint32Array | null)[]; // where the camera is, to sort the translucent quads camera: number[]; @@ -70,16 +64,6 @@ export interface LayerMesh { } export type FromChunkWorker = - | { - type: "generated"; - chunk_x: number; - chunk_z: number; - blocks: Uint32Array; - // blocks that landed in other chunks (from features like a mod's trees), flattened as x, y, z, numeric id - spills: Int32Array; - // each column's biome grass color as 0xRRGGBB, x then z, then each column's foliage color - biome_colors: Uint32Array; - } | { type: "meshed"; chunk_x: number; diff --git a/client/workers/chunk_worker.ts b/client/workers/chunk_worker.ts index 1403f82..49cd57e 100644 --- a/client/workers/chunk_worker.ts +++ b/client/workers/chunk_worker.ts @@ -25,10 +25,7 @@ import { type ToChunkWorker, UNALIGNED_GROUP, } from "./chunk_messages.ts"; -import { generate_raw_chunk, WorldgenSetup } from "$/common/generation.ts"; -import { foliage_color, grass_color } from "$/common/worldgen/biome_colors.ts"; -import { load_worldgen } from "$/common/worldgen_loader.ts"; -import { default_block_value, get_state_value } from "$/common/utils.ts"; +import { get_state_value } from "$/common/utils.ts"; import { bake_model, block_variant, @@ -86,7 +83,6 @@ const TRANSLUCENT = 2; const LAYER_IDS: Record = { solid: SOLID, cutout: CUTOUT, translucent: TRANSLUCENT }; let blocks_registry: BlockRegistry[] = []; -let block_ids: Record = {}; // by numeric id, looked up for every face. like sodium's light data cache, everything the mesher asks about a // block is worked out once instead of per face const TABLE_SIZE = ID_MASK + 1; @@ -123,31 +119,17 @@ const baked = new Map(); let textures_info: TexturesInfo = {}; let image: Texture; -let worldgen: WorldgenSetup | undefined; -// numeric id to what a generated block stores, with its default states. matches the server -let default_values: number[] = []; -// generating has to wait for mods' worldgen scripts, or this worker's terrain wouldn't match the server's -let worldgen_ready: Promise = Promise.resolve(); -self.onmessage = async (event: MessageEvent) => { +self.onmessage = (event: MessageEvent) => { const message = event.data; switch (message.type) { case "init": blocks_registry = message.blocks_registry; - block_ids = message.block_ids; models = message.models; baked.clear(); build_block_tables(); textures_info = message.textures_info; image = message.image as Texture; - default_values = blocks_registry.map((block, nid) => default_block_value(nid, block)); - worldgen_ready = load_worldgen(message.worldgen_scripts, message.ores).then((setup) => { - worldgen = setup; - }); - break; - case "generate": - await worldgen_ready; - generate(message.chunk_x, message.chunk_z, message.seed); break; case "mesh": { region.fill(message.chunks); @@ -203,20 +185,6 @@ function post(message: FromChunkWorker, transfer: Transferable[]) { self.postMessage(message, transfer); } -function generate(chunk_x: number, chunk_z: number, seed: string) { - const { blocks, spills, biomes } = generate_raw_chunk(chunk_x, chunk_z, seed, block_ids, worldgen, default_values); - const biome_colors = new Uint32Array(CHUNK_AREA * 2); - biomes.forEach((biome, column) => { - biome_colors[column] = grass_color(biome); - biome_colors[CHUNK_AREA + column] = foliage_color(biome); - }); - post({ type: "generated", chunk_x, chunk_z, blocks, spills, biome_colors }, [ - blocks.buffer, - spills.buffer, - biome_colors.buffer, - ]); -} - // like minecraft's biome blend at its default radius: each column's grass and foliage color is the average of the 5x5 // columns around it, so biome edges fade instead of being a line. neighbors that aren't there are left out const BLEND_RADIUS = 2; diff --git a/common/bmod.ts b/common/bmod.ts index bff53a9..79f3611 100644 --- a/common/bmod.ts +++ b/common/bmod.ts @@ -173,10 +173,11 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod { return { manifest, data, scripts, textures, credits }; } -// the same mod with its server script taken out, what players get +// the same mod without its server and worldgen scripts, what players get. the server sends them the world export function client_copy(bmod: Bmod): Bmod { const scripts = { ...bmod.scripts }; delete scripts.server; + delete scripts.worldgen; return { ...bmod, scripts }; } diff --git a/common/chunk_streaming.ts b/common/chunk_streaming.ts new file mode 100644 index 0000000..8fd7823 --- /dev/null +++ b/common/chunk_streaming.ts @@ -0,0 +1,255 @@ +// how the server streams the world to clients, like minecraft java since 1.20.2: whole chunks in batches around each +// player, and which chunks are in a player's view. see "Chunks" in MODS.md +import { deflateSync, inflateSync } from "fflate"; +import { CHUNK_AREA, CHUNK_HEIGHT } from "./constants.ts"; + +// the view distances clients can ask for, in chunks, like minecraft's +export const MIN_VIEW_DISTANCE = 2; +export const MAX_VIEW_DISTANCE = 32; + +export const SECTION_HEIGHT = 16; +const SECTION_VOLUME = CHUNK_AREA * SECTION_HEIGHT; +const SECTIONS = CHUNK_HEIGHT / SECTION_HEIGHT; +const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT; + +// the first byte of a binary message, the only kind there is so far +export const LEVEL_CHUNK = 1; + +// bits per block of a section's indirect palette, the smallest that fits. more than 256 kinds are stored directly +const PALETTE_BITS = [1, 2, 4, 8]; +const DIRECT_BITS = 32; + +// minecraft's ChunkTrackingView.isWithinDistance: a round view, with the ring of chunks around it (outer) that the +// client needs to mesh and light the edge of what it shows +export function is_within_view( + center_x: number, + center_z: number, + view_distance: number, + x: number, + z: number, + outer = true, +) { + const dx = Math.max(0, Math.abs(x - center_x) - 1); + const dz = Math.max(0, Math.abs(z - center_z) - 1); + const far = Math.max(0, Math.max(dx, dz) - (outer ? 1 : 0)); + const near = Math.min(dx, dz); + return near * near + far * far < view_distance * view_distance; +} + +export interface LevelChunk { + x: number; + z: number; + // block values (numeric id | state bits << 16) in the sender's numbering, y then z then x + blocks: Uint32Array; + // each column's biome, x then z + biomes: string[]; +} + +// a level_chunk message, like minecraft's ClientboundLevelChunkWithLightPacket without the light (clients light +// chunks themselves). sent as a binary websocket message, little-endian: +// +// u8 LEVEL_CHUNK +// i32 chunk x, i32 chunk z +// the rest deflated: +// u16 biome palette size, then each biome: u8 length and the id as utf-8 +// u8 each column's biome palette index, x then z. left out when there's one biome +// 16 sections of 16x16x16 blocks, bottom first, each a paletted container like minecraft's: +// u8 bits per block +// 0: u32 the value of every block +// 1, 2, 4, 8: u16 palette size, u32 each value, then each block's palette index packed from the low bits up +// 32: u32 each block's value +export function encode_level_chunk(chunk: LevelChunk): Uint8Array { + const writer = new Writer(); + + const biome_palette = [...new Set(chunk.biomes)]; + writer.u16(biome_palette.length); + for (const biome of biome_palette) writer.string(biome); + if (biome_palette.length > 1) { + for (const biome of chunk.biomes) writer.u8(biome_palette.indexOf(biome)); + } + + for (let section = 0; section < SECTIONS; section++) { + write_section(writer, chunk.blocks.subarray(section * SECTION_VOLUME, (section + 1) * SECTION_VOLUME)); + } + + const body = deflateSync(writer.bytes()); + const bytes = new Uint8Array(9 + body.length); + const view = new DataView(bytes.buffer); + bytes[0] = LEVEL_CHUNK; + view.setInt32(1, chunk.x, true); + view.setInt32(5, chunk.z, true); + bytes.set(body, 9); + return bytes; +} + +function write_section(writer: Writer, blocks: Uint32Array) { + const palette: number[] = []; + const index_of = new Map(); + for (const value of blocks) { + if (!index_of.has(value)) { + index_of.set(value, palette.length); + palette.push(value); + } + } + + if (palette.length === 1) { + writer.u8(0); + writer.u32(palette[0]); + return; + } + const bits = PALETTE_BITS.find((bits) => palette.length <= 1 << bits); + if (bits === undefined) { + writer.u8(DIRECT_BITS); + for (const value of blocks) writer.u32(value); + return; + } + + writer.u8(bits); + writer.u16(palette.length); + for (const value of palette) writer.u32(value); + const per_byte = 8 / bits; + for (let i = 0; i < SECTION_VOLUME; i += per_byte) { + let byte = 0; + for (let j = 0; j < per_byte; j++) byte |= index_of.get(blocks[i + j])! << (j * bits); + writer.u8(byte); + } +} + +// throws when the bytes aren't a level_chunk. map turns each block value into the receiver's numbering +export function decode_level_chunk(bytes: Uint8Array, map: (value: number) => number = (value) => value): LevelChunk { + if (bytes[0] !== LEVEL_CHUNK || bytes.length < 9) throw new Error("Not a level_chunk"); + const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const x = header.getInt32(1, true); + const z = header.getInt32(5, true); + const reader = new Reader(inflateSync(bytes.subarray(9))); + + const biome_palette: string[] = []; + const biome_count = reader.u16(); + if (biome_count === 0) throw new Error("No biomes"); + for (let i = 0; i < biome_count; i++) biome_palette.push(reader.string()); + const biomes: string[] = new Array(CHUNK_AREA); + for (let column = 0; column < CHUNK_AREA; column++) { + const index = biome_count > 1 ? reader.u8() : 0; + if (index >= biome_count) throw new Error("Bad biome index"); + biomes[column] = biome_palette[index]; + } + + const blocks = new Uint32Array(CHUNK_VOLUME); + for (let section = 0; section < SECTIONS; section++) { + read_section(reader, blocks.subarray(section * SECTION_VOLUME, (section + 1) * SECTION_VOLUME), map); + } + if (!reader.done) throw new Error("Wrong size"); + return { x, z, blocks, biomes }; +} + +function read_section(reader: Reader, blocks: Uint32Array, map: (value: number) => number) { + const bits = reader.u8(); + if (bits === 0) { + blocks.fill(map(reader.u32())); + return; + } + if (bits === DIRECT_BITS) { + for (let i = 0; i < SECTION_VOLUME; i++) blocks[i] = map(reader.u32()); + return; + } + if (!PALETTE_BITS.includes(bits)) throw new Error(`Bad bits per block ${bits}`); + + const palette: number[] = []; + const size = reader.u16(); + if (size > 1 << bits) throw new Error("Bad palette"); + for (let i = 0; i < size; i++) palette.push(map(reader.u32())); + const per_byte = 8 / bits; + const mask = (1 << bits) - 1; + for (let i = 0; i < SECTION_VOLUME; i += per_byte) { + const byte = reader.u8(); + for (let j = 0; j < per_byte; j++) { + const index = (byte >> (j * bits)) & mask; + if (index >= size) throw new Error("Bad palette index"); + blocks[i + j] = palette[index]; + } + } +} + +class Writer { + #bytes = new Uint8Array(16 * 1024); + #view = new DataView(this.#bytes.buffer); + #length = 0; + + #reserve(size: number) { + if (this.#length + size <= this.#bytes.length) return; + const bytes = new Uint8Array(Math.max(this.#bytes.length * 2, this.#length + size)); + bytes.set(this.#bytes); + this.#bytes = bytes; + this.#view = new DataView(bytes.buffer); + } + + u8(value: number) { + this.#reserve(1); + this.#bytes[this.#length++] = value; + } + + u16(value: number) { + this.#reserve(2); + this.#view.setUint16(this.#length, value, true); + this.#length += 2; + } + + u32(value: number) { + this.#reserve(4); + this.#view.setUint32(this.#length, value, true); + this.#length += 4; + } + + string(text: string) { + const bytes = new TextEncoder().encode(text); + if (bytes.length > 255) throw new Error(`${text} is too long to send`); + this.u8(bytes.length); + this.#reserve(bytes.length); + this.#bytes.set(bytes, this.#length); + this.#length += bytes.length; + } + + bytes() { + return this.#bytes.subarray(0, this.#length); + } +} + +class Reader { + #bytes: Uint8Array; + #view: DataView; + #offset = 0; + + constructor(bytes: Uint8Array) { + this.#bytes = bytes; + this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + } + + get done() { + return this.#offset === this.#bytes.length; + } + + #take(size: number) { + if (this.#offset + size > this.#bytes.length) throw new Error("Too short"); + const offset = this.#offset; + this.#offset += size; + return offset; + } + + u8() { + return this.#bytes[this.#take(1)]; + } + + u16() { + return this.#view.getUint16(this.#take(2), true); + } + + u32() { + return this.#view.getUint32(this.#take(4), true); + } + + string() { + const length = this.u8(); + const offset = this.#take(length); + return new TextDecoder().decode(this.#bytes.subarray(offset, offset + length)); + } +} diff --git a/common/protocol.ts b/common/protocol.ts index bb9c5f3..e4b1a88 100644 --- a/common/protocol.ts +++ b/common/protocol.ts @@ -1,4 +1,4 @@ -// messages sent between the client and the server, as json over a websocket +// messages sent between the client and the server, as json over a websocket. chunks are binary, see level_chunk import type { Faces } from "./constants.ts"; import type { ItemData } from "./inventory.ts"; import type { ModListing } from "./mod_loader.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 = 7; +export const PROTOCOL_VERSION = 8; export interface PlayerInfo { id: string; @@ -63,8 +63,13 @@ export interface ScreenLayout { // clients send what the player is trying to do, the server decides what happens export type ClientMessage = | { type: "hello"; name: string; protocol: number } - // sent once the client has downloaded, checked and loaded everything in welcome - | { type: "ready" } + // sent once the client has downloaded, checked and loaded everything in welcome. view_distance is in chunks, the + // server may use less + | { type: "ready"; view_distance?: number } + // the player changed their view distance, like minecraft's client information + | { type: "view_distance"; distance: number } + // answers chunk_batch_finished once the batch is loaded, with how many chunks a tick the client can take + | { type: "chunk_batch_received"; chunks_per_tick: number } | { type: "move"; x: number; y: number; z: number; yaw: number; pitch: number } | { type: "break_block"; x: number; y: number; z: number } // the player started hitting a block, for on_click @@ -88,7 +93,6 @@ export type ServerMessage = | { type: "welcome"; protocol: number; - seed: string; // in load order, the client downloads and loads them before joining the world mods: ModListing[]; } @@ -103,12 +107,22 @@ export type ServerMessage = players: PlayerInfo[]; // items on the ground entities: EntityInfo[]; - changes: BlockChange[]; + // the server's block id for each of its numeric ids, which level_chunk uses. clients number blocks their own way + blocks: string[]; spawn: { x: number; y: number; z: number; yaw: number; pitch: number }; selected_slot: number; // world time in ticks, see common/time.ts time: number; } + // a whole chunk, sent as a binary message and not json. data is what common/chunk_streaming.ts decodes + | { type: "level_chunk"; data: Uint8Array } + // the client can drop the chunk, it's out of view. the server won't send changes to it anymore + | { type: "forget_level_chunk"; x: number; z: number } + // the chunk the player is in, sent when it changes. chunks come in around it + | { type: "set_center_chunk"; x: number; z: number } + // level_chunk messages come between these, size is how many. the client answers with chunk_batch_received + | { type: "chunk_batch_start" } + | { type: "chunk_batch_finished"; size: number } | { 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 } @@ -121,7 +135,8 @@ export type ServerMessage = | { type: "remove_entity"; id: string } // a player picked up an item, it flies to them and goes away | { type: "take_entity"; id: string; player: string } - // also sent to the player who caused it, which corrects anything their client predicted wrong + // to the players who have the chunk, including the one who caused it, which corrects anything their client + // predicted wrong | { type: "set_block"; x: number; y: number; z: number; id: string; state?: number } | { type: "chat"; from?: string; text: string } | { type: "teleport"; x: number; y: number; z: number } diff --git a/server/game/game_server.ts b/server/game/game_server.ts index eabafda..1481f43 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -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): 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; @@ -132,6 +138,8 @@ export class GameServer { #players = new Map(); // connections that got welcome and are downloading mods, by conn #pending = new Map(); + // 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 = {}; #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 && diff --git a/server/game/host_protocol.ts b/server/game/host_protocol.ts index 6552797..da5245e 100644 --- a/server/game/host_protocol.ts +++ b/server/game/host_protocol.ts @@ -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 } | { type: "close"; conn: number } // level.json and the chunks that changed | { type: "save"; save: Required; final: boolean } diff --git a/server/game/player.ts b/server/game/player.ts index c78106f..accc60f 100644 --- a/server/game/player.ts +++ b/server/game/player.ts @@ -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(); + // 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 { diff --git a/server/game/player_chunks.ts b/server/game/player_chunks.ts new file mode 100644 index 0000000..9a12458 --- /dev/null +++ b/server/game/player_chunks.ts @@ -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(); + // in view and not sent yet + #pending = new Map(); + + #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; + } +} diff --git a/server/game/worker.ts b/server/game/worker.ts index bf8674f..ec45c61 100644 --- a/server/game/worker.ts +++ b/server/game/worker.ts @@ -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); } diff --git a/server/game/world.ts b/server/game/world.ts index 4d68243..00cb28f 100644 --- a/server/game/world.ts +++ b/server/game/world.ts @@ -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(RAW_CACHE_SIZE); #chunks = new LruMap(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>(); // chunks changed since they were last saved, by chunk_key #unsaved = new Map(); @@ -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 { + 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; diff --git a/tests/bmod_test.ts b/tests/bmod_test.ts index d08f3ed..2ab9dda 100644 --- a/tests/bmod_test.ts +++ b/tests/bmod_test.ts @@ -110,6 +110,7 @@ Deno.test("the server loads every .bmod in its folder, dependencies first, and p assertEquals([...digest].map((b) => b.toString(16).padStart(2, "0")).join(""), mod.listing.sha256); const copy = read_bmod(mod.client_bytes, mod.listing.file); assertEquals(copy.scripts.server, undefined, "server scripts never go to players"); + assertEquals(copy.scripts.worldgen, undefined, "players get the world from the server, not its generator"); assertEquals(copy.data, mod.bmod.data); } assert(mods[1].bmod.scripts.server, "the server still has it"); diff --git a/tests/chunk_streaming_test.ts b/tests/chunk_streaming_test.ts new file mode 100644 index 0000000..44e387f --- /dev/null +++ b/tests/chunk_streaming_test.ts @@ -0,0 +1,132 @@ +// the server sends the world in whole chunks, like minecraft java: nearest first, in batches the client paces, and +// only to players who can see them +import { assert, assertEquals } from "@std/assert"; +import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts"; +import { decode_level_chunk, encode_level_chunk, is_within_view } from "$/common/chunk_streaming.ts"; +import { PROTOCOL_VERSION } from "$/common/protocol.ts"; +import { sent_block, test_game } from "./helpers.ts"; + +Deno.test("a chunk comes back as it was encoded, whatever its sections hold", () => { + const blocks = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT); + const section = CHUNK_AREA * 16; + // section 0 is all one block, 1 has 3 kinds, 2 has 16, 3 has 300 (more than a palette holds), the rest air + blocks.fill(7, 0, section); + for (let i = 0; i < section; i++) { + blocks[section + i] = [1, 2 | (3 << 16), 5][i % 3]; + blocks[2 * section + i] = i % 16; + blocks[3 * section + i] = (i % 300) | ((i % 7) << 16); + } + const biomes = Array.from({ length: CHUNK_AREA }, (_, i) => i < 100 ? "bworld:plains" : "bworld:desert"); + + const decoded = decode_level_chunk(encode_level_chunk({ x: -3, z: 70000, blocks, biomes })); + assertEquals(decoded.x, -3); + assertEquals(decoded.z, 70000); + assertEquals(decoded.blocks, blocks); + assertEquals(decoded.biomes, biomes); + + // one biome, and the receiver's numbering + const one = decode_level_chunk( + encode_level_chunk({ x: 0, z: 0, blocks, biomes: biomes.map(() => "bworld:plains") }), + (value) => value === 7 ? 70 : value, + ); + assertEquals(one.biomes, biomes.map(() => "bworld:plains")); + assertEquals(one.blocks[0], 70); + assertEquals(one.blocks[section], 1); +}); + +Deno.test("the view is round, with a ring of chunks past it for meshing its edge", () => { + assert(is_within_view(0, 0, 2, 0, 0)); + assert(is_within_view(0, 0, 2, 3, 0), "the outer ring"); + assert(!is_within_view(0, 0, 2, 3, 0, false)); + assert(!is_within_view(0, 0, 2, 4, 0)); + assert(is_within_view(0, 0, 2, 2, 2)); + assert(!is_within_view(0, 0, 2, 3, 3), "corners are cut off"); + assert(is_within_view(10, -10, 2, 12, -12)); +}); + +// every chunk around cx, cz a view distance of 2 covers +function view(cx: number, cz: number) { + const chunks: string[] = []; + for (let x = cx - 4; x <= cx + 4; x++) { + for (let z = cz - 4; z <= cz + 4; z++) { + if (is_within_view(cx, cz, 2, x, z)) chunks.push(`${x},${z}`); + } + } + return chunks.sort(); +} + +Deno.test("chunks come in batches, nearest first, as fast as the client says it can take them", async () => { + const { game, take, send } = await test_game("mods"); + game.on_connect(1); + send(1, { type: "hello", name: "alice", protocol: PROTOCOL_VERSION }); + send(1, { type: "ready", view_distance: 2 }); + send(1, { type: "move", x: 8, y: 100, z: 8, yaw: 0, pitch: 0 }); + const joined = take(1); + assert(joined.some((m) => m.type === "set_center_chunk" && m.x === 0 && m.z === 0)); + assert(!joined.some((m) => m.type === "level_chunk"), "chunks come with ticks"); + + // the first batch before the client has said anything: minecraft's 9 chunks + game.tick(); + let messages = take(1).filter((m) => m.type.includes("chunk")); + assertEquals(messages[0].type, "chunk_batch_start"); + assertEquals(messages.at(-1), { type: "chunk_batch_finished", size: 9 }); + const first = messages.filter((m) => m.type === "level_chunk"); + assertEquals(first.length, 9); + assertEquals(`${first[0].x},${first[0].z}`, "0,0"); + for (const chunk of first) assert(Math.abs(chunk.x) <= 1 && Math.abs(chunk.z) <= 1, "nearest first"); + + // nothing more until the client has it + game.tick(); + assertEquals(take(1).filter((m) => m.type === "level_chunk"), []); + + // then the rest, each chunk in view once + const sent = first.map((m) => `${m.x},${m.z}`); + for (let i = 0; i < 20; i++) { + send(1, { type: "chunk_batch_received", chunks_per_tick: 4 }); + game.tick(); + messages = take(1).filter((m) => m.type === "level_chunk"); + assert(messages.length <= 4); + sent.push(...messages.map((m) => `${m.x},${m.z}`)); + } + assertEquals(sent.sort(), view(0, 0)); + + // walking off: a new center, the chunks out of view are forgotten and the new ones come + send(1, { type: "move", x: 8 + 16 * 3, y: 100, z: 8, yaw: 0, pitch: 0 }); + messages = take(1); + assertEquals(messages.find((m) => m.type === "set_center_chunk"), { type: "set_center_chunk", x: 3, z: 0 }); + const forgotten = messages.filter((m) => m.type === "forget_level_chunk").map((m) => `${m.x},${m.z}`); + assertEquals(forgotten.sort(), view(0, 0).filter((key) => !view(3, 0).includes(key))); + const more: string[] = []; + for (let i = 0; i < 20; i++) { + send(1, { type: "chunk_batch_received", chunks_per_tick: 64 }); + game.tick(); + more.push(...take(1).filter((m) => m.type === "level_chunk").map((m) => `${m.x},${m.z}`)); + } + assertEquals(more.sort(), view(3, 0).filter((key) => !view(0, 0).includes(key))); +}); + +Deno.test("block changes only go to players who have the chunk, the others get them with it", async () => { + const { game, take, send, join } = await test_game("mods"); + const alice = join(1, "alice"); + send(1, { type: "move", x: 8, y: 100, z: 8, yaw: 0, pitch: 0 }); + const bob = join(2, "bob"); + send(2, { type: "move", x: 8 + 16 * 100, y: 100, z: 8, yaw: 0, pitch: 0 }); + game.tick(); + take(1); + take(2); + + game.set_block(3, 120, 5, "bworld:stone"); + assert(take(1).some((m) => m.type === "set_block" && m.x === 3 && m.id === "bworld:stone")); + assertEquals(take(2).filter((m) => m.type === "set_block"), [], "bob is too far away to have it"); + + // bob walks over and gets the chunk with the stone in it + send(2, { type: "move", x: 8, y: 100, z: 8, yaw: 0, pitch: 0 }); + send(2, { type: "chunk_batch_received", chunks_per_tick: 9 }); + game.tick(); + assertEquals(sent_block(take(2), bob, 3, 120, 5), ["bworld:stone", 0]); + + // the chunk the server sends is what it has, with the ids join listed + assertEquals(alice.blocks[game.world.block_ids["bworld:stone"]], "bworld:stone"); + const chunk = decode_level_chunk(game.world.level_chunk(0, 0)); + assertEquals(chunk.blocks[120 * CHUNK_AREA + 5 * CHUNK_SIZE + 3], game.world.get_block_value(3, 120, 5)); +}); diff --git a/tests/helpers.ts b/tests/helpers.ts index 90a22f2..1089489 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -5,6 +5,8 @@ import type { ServerModSource } from "$/server/game/load_mods.ts"; import { GameServer } from "$/server/game/game_server.ts"; import { start_game } from "$/server/game/load_mods.ts"; import { PROTOCOL_VERSION } from "$/common/protocol.ts"; +import { decode_level_chunk } from "$/common/chunk_streaming.ts"; +import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts"; import type { WorldSave } from "$/server/game/saves.ts"; // mods straight from their source folders, skipping the build: scripts are imported as typescript @@ -45,9 +47,12 @@ export async function test_game(mods_dir: string, save?: WorldSave, seed = "test // what host.download gives back, by url. other urls fail const downloads = new Map(); const host = { - send: (conn: number, data: string) => { + // chunks come out decoded, as { type: "level_chunk", x, z, blocks, biomes } + send: (conn: number, data: string | Uint8Array) => { if (!outbox.has(conn)) outbox.set(conn, []); - outbox.get(conn)!.push(JSON.parse(data)); + outbox.get(conn)!.push( + typeof data === "string" ? JSON.parse(data) : { type: "level_chunk", ...decode_level_chunk(data) }, + ); }, close(conn: number) { closed.add(conn); @@ -58,6 +63,7 @@ export async function test_game(mods_dir: string, save?: WorldSave, seed = "test }, }; const game: GameServer = await start_game(host, save, seed, mod_sources(mods_dir)); + game.chunk_send_budget_ms = Infinity; // deno-lint-ignore no-explicit-any const take = (conn: number): any[] => { const messages = outbox.get(conn) ?? []; @@ -75,6 +81,18 @@ export async function test_game(mods_dir: string, save?: WorldSave, seed = "test return { game, take, send, join, closed, downloads }; } +// the block id and state bits at x, y, z in the chunks among messages, read the way a client does with the table +// join sent. undefined when no chunk there was sent +// deno-lint-ignore no-explicit-any +export function sent_block(messages: any[], join: { blocks: string[] }, x: number, y: number, z: number) { + const chunk_x = Math.floor(x / CHUNK_SIZE); + const chunk_z = Math.floor(z / CHUNK_SIZE); + const chunk = messages.findLast((m) => m.type === "level_chunk" && m.x === chunk_x && m.z === chunk_z); + if (!chunk) return undefined; + const value = chunk.blocks[y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)]; + return [join.blocks[value & ID_MASK], value >>> 16]; +} + export function copy_dir(from: string, to: string) { if (Deno.statSync(from).isDirectory) { Deno.mkdirSync(to, { recursive: true }); diff --git a/tests/server_scripts_test.ts b/tests/server_scripts_test.ts index d53477c..28936be 100644 --- a/tests/server_scripts_test.ts +++ b/tests/server_scripts_test.ts @@ -1,5 +1,5 @@ import { assert, assertEquals } from "@std/assert"; -import { copy_dir, test_game } from "./helpers.ts"; +import { copy_dir, sent_block, test_game } from "./helpers.ts"; import type { WorldSave } from "$/server/game/saves.ts"; // a mod that uses every part of the server api worth testing, and writes down what happened in its storage @@ -218,6 +218,8 @@ Deno.test("block states start at their defaults, can be changed, and are synced send(1, { type: "chat", text: `/state ${args}` }); return take(1).filter((m) => m.type === "chat").map((m) => m.text).at(-1); }; + // alice gets the chunks around her, and from then on changes to them + game.tick(); game.set_block(5, 100, 5, "testmod:lamp"); take(1); assertEquals(state("5 100 5 power"), "state 2"); @@ -232,13 +234,15 @@ Deno.test("block states start at their defaults, can be changed, and are synced assert(state("5 100 5 power 8").startsWith('error testmod:lamp state "power" has 3 bits')); assert(state("5 100 5 color").startsWith('error testmod:lamp has no state "color"')); - // saved and loaded, and new players get it with the world's changes + // saved and loaded, and new players get it in the chunk const saved = game.save(); Deno.removeSync(dir, { recursive: true }); const again = await setup(saved); assertEquals(again.game.world.get_block_value(5, 100, 5) >>> 16, 5 | (1 << 3)); const joined = again.join(2, "bob"); - assert(joined.changes.some((c: unknown[]) => c[0] === 5 && c[3] === "testmod:lamp" && c[4] === (5 | (1 << 3)))); + again.send(2, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); + again.game.tick(); + assertEquals(sent_block(again.take(2), joined, 5, 100, 5), ["testmod:lamp", 5 | (1 << 3)]); Deno.removeSync(again.dir, { recursive: true }); }); diff --git a/tests/terrain_culling_test.ts b/tests/terrain_culling_test.ts index f2c1af1..e6a28e4 100644 --- a/tests/terrain_culling_test.ts +++ b/tests/terrain_culling_test.ts @@ -6,6 +6,7 @@ import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry. import { Frustum } from "$/client/rendering/frustum.ts"; import { group_faces_camera } from "$/client/rendering/level_renderer.ts"; import { FACE_GROUPS, type LayerMesh, TERRAIN_VERTEX_BYTES } from "$/client/workers/chunk_messages.ts"; +import { decode_level_chunk } from "$/common/chunk_streaming.ts"; import { test_game } from "./helpers.ts"; // the matrix the renderer makes for a camera, see update_camera in client/renderer/core.ts @@ -29,12 +30,10 @@ Deno.test("the frustum keeps what's in front of the camera and drops what's behi assert(!frustum.intersects_box(-8, 60, -1100, 8, 80, -1090), "past the far plane"); }); -// real chunks from the chunk worker, meshed the way the client does it +// real chunks as the server sends them, meshed the way the client does it async function mesh_chunks(radius: number) { const { game } = await test_game("mods", undefined, "culling-seed"); const blocks = EverythingRegistry.get_registry("blocks"); - const block_ids: Record = {}; - blocks.forEach((b, nid) => block_ids[b.id] = nid); const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); // deno-lint-ignore no-explicit-any const replies = new Map void>(); @@ -53,19 +52,15 @@ async function mesh_chunks(radius: number) { worker.postMessage({ type: "init", blocks_registry: JSON.parse(JSON.stringify(blocks)), - block_ids, models: {}, textures_info: { "engine:missing": { x: 0, y: 0 } }, image: { width: 1024, height: 1024 }, - worldgen_scripts: [], - ores: game.recipes.ores, }); const generated = new Map(); for (let x = -radius - 1; x <= radius + 1; x++) { for (let z = -radius - 1; z <= radius + 1; z++) { - const reply = await ask({ type: "generate", chunk_x: x, chunk_z: z, seed: "culling-seed" }, "generated"); - generated.set(`${x},${z}`, reply.blocks); + generated.set(`${x},${z}`, decode_level_chunk(game.world.level_chunk(x, z)).blocks); } } const meshes = []; diff --git a/tests/tint_test.ts b/tests/tint_test.ts index 46d03ca..b855b65 100644 --- a/tests/tint_test.ts +++ b/tests/tint_test.ts @@ -20,12 +20,9 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors | worker.postMessage({ type: "init", blocks_registry: JSON.parse(JSON.stringify(blocks)), - block_ids, models: {}, textures_info: { "engine:missing": { x: 0, y: 0 } }, image: { width: 1024, height: 1024 }, - worldgen_scripts: [], - ores: [], }); const chunk = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT); diff --git a/tests/world_save_test.ts b/tests/world_save_test.ts index e65a3db..1fccd77 100644 --- a/tests/world_save_test.ts +++ b/tests/world_save_test.ts @@ -2,7 +2,7 @@ import { assert, assertEquals, assertNotEquals } from "@std/assert"; import { AIR_ID } from "$/common/protocol.ts"; import { CHUNK_VOLUME, decode_chunk, encode_chunk, is_changed, SavedChunk } from "$/server/game/saves.ts"; import { read_regions, region_file, write_chunks } from "$/server/regions.ts"; -import { test_game } from "./helpers.ts"; +import { sent_block, test_game } from "./helpers.ts"; function chunk_data(seed: number, palette_size = 3) { const palette: [string, number][] = []; @@ -77,9 +77,11 @@ Deno.test("changed blocks are saved as whole chunks, and only chunks that change assertEquals(loaded.game.world.get_block_id(3, 120, 5), "bworld:stone"); assertEquals(loaded.game.world.get_block_id(-20, 120, 40), "bworld:planks"); assertEquals(loaded.game.world.get_block_value(-20, 121, 40) >>> 16, 1); - // players get the changes, not the whole chunks + // players get the whole chunks, with what was saved in them const join = loaded.join(1, "alice"); - assertEquals(join.changes.length, 3); + loaded.send(1, { type: "move", x: 3.5, y: 130, z: 5.5, yaw: 0, pitch: 0 }); + loaded.game.tick(); + assertEquals(sent_block(loaded.take(1), join, 3, 120, 5), ["bworld:stone", 0]); // nothing to save again after loading assertEquals(loaded.game.save().chunks, []); }); @@ -108,10 +110,9 @@ Deno.test("when world generation is the same, blocks it made come from it", asyn Deno.test("when world generation changed, saved chunks keep their terrain and are saved again", async () => { const { saved, level } = await saved_with_old_terrain(); saved.level = JSON.stringify({ ...level, worldgen: "older" }); - const { game, join } = await test_game("mods", saved); + const { game } = await test_game("mods", saved); assertEquals(game.world.get_block_id(3, 121, 5), "bworld:stone"); assertEquals(game.world.get_block_id(3, 120, 5), "bworld:stone"); - assertEquals(join(1, "alice").changes.length, 2); const again = game.save(); assertNotEquals(JSON.parse(again.level).worldgen, "older");