Send chunks to players connected to server
This commit is contained in:
+11
-6
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
+10
-4
@@ -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<Join> {
|
||||
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<Join> {
|
||||
socket.send({ type: "ready", view_distance });
|
||||
const answer = await socket.next("join", "rejected");
|
||||
if (answer.type === "rejected") {
|
||||
socket.close();
|
||||
|
||||
+87
-207
@@ -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<number, Chunk>();
|
||||
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<string, Map<string, BlockChange>>();
|
||||
// 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<BlockRegistry>("blocks");
|
||||
// chunks being generated by a worker, by chunk key
|
||||
pending_generation = new Map<number, { x: number; z: number }>();
|
||||
// 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<string, Entity>();
|
||||
|
||||
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<BlockRegistry>("blocks");
|
||||
const block_ids: Record<string, number> = {};
|
||||
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<BlockRegistry>("blocks")),
|
||||
models: Object.fromEntries(EverythingRegistry.entries<ModelJson>("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<BlockRegistry>("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<FromChunkWorker, { type: "meshed" }>) {
|
||||
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);
|
||||
|
||||
+2
-1
@@ -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();
|
||||
|
||||
@@ -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));
|
||||
|
||||
+4
-5
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<string, number>;
|
||||
// mods' block models by id, the engine's are built in
|
||||
models: Record<string, ModelJson>;
|
||||
textures_info: Record<string, SpriteRegion>;
|
||||
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;
|
||||
|
||||
@@ -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<RenderLayer, number> = { solid: SOLID, cutout: CUTOUT, translucent: TRANSLUCENT };
|
||||
|
||||
let blocks_registry: BlockRegistry[] = [];
|
||||
let block_ids: Record<string, number> = {};
|
||||
// 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<number, MeshQuad[]>();
|
||||
|
||||
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<void> = Promise.resolve();
|
||||
|
||||
self.onmessage = async (event: MessageEvent<ToChunkWorker>) => {
|
||||
self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
||||
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;
|
||||
|
||||
Reference in New Issue
Block a user