Send chunks to players connected to server
This commit is contained in:
+2
-1
@@ -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 };
|
||||
}
|
||||
|
||||
|
||||
@@ -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<ArrayBuffer> {
|
||||
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<number, number>();
|
||||
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));
|
||||
}
|
||||
}
|
||||
+22
-7
@@ -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 }
|
||||
|
||||
Reference in New Issue
Block a user