import { block_value, chunk_key, default_block_value } from "$/common/utils.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, BlockRegistry, EverythingRegistry, RENDER_LAYERS, RenderLayer, } from "$/common/everything_registry.ts"; 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 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"; import { Camera } from "../camera.ts"; import type { Entity } from "../entity/entity.ts"; import type { ModelJson } from "$/common/block_models.ts"; import type { ItemStack } from "$/common/inventory.ts"; export interface Block { id: string; x: number; y: number; z: number; } export { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE }; export interface Chunk { x: number; z: number; blocks: Uint32Array; dirty: boolean; // bumped on every mesh request so late results from older requests get ignored mesh_version: number; meshes: Partial>; // the lowest and highest y of its meshes, for frustum culling min_y: number; max_y: number; // only for translucent meshes that have to be sorted again as the camera moves translucent_sort?: TranslucentSort; // each column's biome grass color, x then z, then each column's foliage color biome_colors: Uint32Array; // from its last mesh, see get_light. undefined until it's been meshed light?: Uint8Array; } export interface ChunkMesh { vertex_buffer: GPUBuffer; quad_count: number; // the translucent layer's quads sorted back to front, the others are drawn in order index_buffer?: GPUBuffer; // solid and cutout quads by the way they face, see FACE_GROUPS in chunk_messages.ts groups?: FaceGroup[]; } interface TranslucentSort { // the mesh_version of the mesh these are for mesh_version: number; centers: Float32Array; planes: [Float32Array, Float32Array, Float32Array]; // where the camera was for the last sort that was requested camera: number[]; // sorts come back out of order, older ones than what's shown get skipped requested: number; applied: number; } export { chunk_key }; // the block being looked at and which face of it export interface BlockHitResult { x: number; y: number; z: number; block: number; face: Faces; } 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; // block light 0 and sky light 15, packed like Chunk.light export const FULL_SKY_LIGHT = 15; // 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; // world time in ticks, counted here between the server's updates. see common/time.ts time = 0; // 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"); // 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(); // what blocks with item_display show, by chunk_key then position_key "x,y,z" block_items = new Map>(); // 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)); // sent once instead of with every mesh request this.workers.broadcast({ type: "init", 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 }, }); } add_entity(entity: Entity) { this.entities.set(entity.id, entity); } remove_entity(id: string) { this.entities.delete(id); } tick() { this.time += 1; for (const entity of this.entities.values()) { entity.save_previous_position(); entity.tick(); } } // 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 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; } } } // 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(); } get_chunk(x: number, z: number) { return this.chunks.get(chunk_key(x, z)); } // state is the block's state bits, its defaults when not given 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); const chunk = this.get_chunk(block_chunk_x, block_chunk_z); if (!chunk) { return; } const [nid, info] = EverythingRegistry.get_full("blocks", block.id)!; const lx = block.x - block_chunk_x * CHUNK_SIZE; const lz = block.z - block_chunk_z * CHUNK_SIZE; const ly = block.y; const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx; const old_nid = chunk.blocks[index] & ID_MASK; chunk.blocks[index] = state === undefined ? default_block_value(nid, info) : block_value(nid, state); chunk.dirty = true; this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, nid); } // block light << 4 | sky light there, as of its chunk's last mesh. full sky light above the world and where it isn't // known yet, so entities don't go dark while their chunk loads get_light(x: number, y: number, z: number): number { const block_y = Math.floor(y); if (block_y >= CHUNK_HEIGHT) return FULL_SKY_LIGHT; if (block_y < 0) return 0; const chunk_x = Math.floor(x / CHUNK_SIZE); const chunk_z = Math.floor(z / CHUNK_SIZE); const light = this.get_chunk(chunk_x, chunk_z)?.light; if (!light) return FULL_SKY_LIGHT; const lx = Math.floor(x) - chunk_x * CHUNK_SIZE; const lz = Math.floor(z) - chunk_z * CHUNK_SIZE; return light[block_y * CHUNK_AREA + lz * CHUNK_SIZE + lx]; } // the id with its state bits, VOID outside loaded chunks get_block_value(x: number, y: number, z: number) { 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); if (!chunk) { return VOID; } return chunk.blocks[y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)] ?? AIR; } get_block(x: number, y: number, z: number) { 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); if (!chunk) { return VOID; } const lx = x - chunk_x * CHUNK_SIZE; const lz = z - chunk_z * CHUNK_SIZE; const ly = y; const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx; return chunk.blocks[index] & ID_MASK; } // whether entities bump into the block there. unloaded chunks count as solid, so nothing falls out of the world has_collision(x: number, y: number, z: number) { const block = this.get_block(x, y, z); return block === VOID || (block !== AIR && (this.#blocks[block]?.has_collision ?? true)); } // only changes what this client shows, drops and everything else happen on the server break_block(x: number, y: number, z: number) { const block_chunk_x = Math.floor(x / CHUNK_SIZE); const block_chunk_z = Math.floor(z / CHUNK_SIZE); const chunk = this.get_chunk(block_chunk_x, block_chunk_z); if (!chunk) { return; } const lx = x - block_chunk_x * CHUNK_SIZE; const lz = z - block_chunk_z * CHUNK_SIZE; const ly = y; const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx; const old_nid = chunk.blocks[index] & ID_MASK; chunk.blocks[index] = AIR; chunk.dirty = true; this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, AIR); } // a block that lets through or gives off a different amount of light changes the light up to 15 blocks // away, so in every neighbor. otherwise only a block on a chunk's edge matters, for its neighbor's faces #mark_neighbors_dirty( block_chunk_x: number, block_chunk_z: number, lx: number, lz: number, old_nid: number, new_nid: number, ) { const old_block = this.#blocks[old_nid]; const new_block = this.#blocks[new_nid]; if ( block_light_opacity(old_block) !== block_light_opacity(new_block) || block_light_emission(old_block) !== block_light_emission(new_block) ) { for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) { const n = this.get_chunk(block_chunk_x + dx, block_chunk_z + dz); if (n) { n.dirty = true; } } return; } if (lx === 0) { const n = this.get_chunk(block_chunk_x - 1, block_chunk_z); if (n) { n.dirty = true; } } else if (lx === CHUNK_SIZE - 1) { const n = this.get_chunk(block_chunk_x + 1, block_chunk_z); if (n) { n.dirty = true; } } if (lz === 0) { const n = this.get_chunk(block_chunk_x, block_chunk_z - 1); if (n) { n.dirty = true; } } else if (lz === CHUNK_SIZE - 1) { const n = this.get_chunk(block_chunk_x, block_chunk_z + 1); if (n) { n.dirty = true; } } } index_to_xyz(index: number) { const y = Math.floor(index / CHUNK_AREA); const rem = index % CHUNK_AREA; const z = Math.floor(rem / CHUNK_SIZE); const x = rem % CHUNK_SIZE; return [x, y, z]; } // 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) { return; } const current = this.get_block(x, y, z); if (id === AIR_ID) { if (current !== AIR) { this.break_block(x, y, z); } return; } const nid = EverythingRegistry.get_id("blocks", id); if (nid === undefined || block_value(nid, state) === this.get_block_value(x, y, z)) { return; } this.add_block({ x, y, z, id }, state); } // also what forget_level_chunk does unload_chunk(cx: number, cz: number) { const key = chunk_key(cx, cz); const chunk = this.chunks.get(key); if (!chunk) { return; } this.delete_chunk_mesh(chunk); this.chunks.delete(key); this.block_items.delete(key); } // see set_block_item in common/protocol.ts set_block_item(x: number, y: number, z: number, item: ItemStack | undefined) { const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)); let items = this.block_items.get(key); if (item) { if (!this.chunks.has(key)) return; if (!items) { items = new Map(); this.block_items.set(key, items); } items.set(`${x},${y},${z}`, { x, y, z, item }); } else { items?.delete(`${x},${y},${z}`); if (items?.size === 0) this.block_items.delete(key); } } // 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) { for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) { if (!this.get_chunk(chunk.x + dx, chunk.z + dz)) { return false; } } return true; } // sends every dirty chunk that can be meshed to the workers request_meshes(camera: Camera) { for (const chunk of this.chunks.values()) { if (!chunk.dirty || !this.can_mesh(chunk)) { continue; } chunk.dirty = false; chunk.mesh_version += 1; // copies, the worker lights the whole 3x3 area const chunks: (Uint32Array | null)[] = []; const biome_colors: (Uint32Array | null)[] = []; for (let dz = -1; dz <= 1; dz++) { for (let dx = -1; dx <= 1; dx++) { const neighbor = this.get_chunk(chunk.x + dx, chunk.z + dz); chunks.push(neighbor?.blocks.slice() ?? null); biome_colors.push(neighbor?.biome_colors ?? null); } } this.workers.post({ type: "mesh", chunk_x: chunk.x, chunk_z: chunk.z, version: chunk.mesh_version, chunks, biome_colors, camera: [camera.x, camera.y, camera.z], }, chunks.filter((blocks) => blocks !== null).map((blocks) => blocks.buffer)); } } // like sodium, a chunk's translucent quads only change order when the camera crosses one of the // planes they lie on, so that's the only time they get sorted again update_translucent_sorting(camera: Camera) { const position = [camera.x, camera.y, camera.z]; for (const chunk of this.chunks.values()) { const sort = chunk.translucent_sort; if (!sort || !crosses_planes(sort.planes, sort.camera, position)) { continue; } sort.camera = position; sort.requested += 1; this.workers.post({ type: "sort", chunk_x: chunk.x, chunk_z: chunk.z, version: sort.mesh_version, sort_version: sort.requested, centers: sort.centers, camera: position, }); } } #on_worker_message(message: FromChunkWorker) { if (message.type === "meshed") { this.#on_meshed(message); } else { this.#on_sorted(message); } } #on_meshed(message: Extract) { const chunk = this.get_chunk(message.chunk_x, message.chunk_z); // unloaded, or remeshed again since this was requested if (!chunk || chunk.mesh_version !== message.version) { return; } this.delete_chunk_mesh(chunk); chunk.light = message.light; chunk.min_y = message.min_y; chunk.max_y = message.max_y; for (const layer of RENDER_LAYERS) { const { vertices, quad_count, groups } = message[layer]; if (quad_count === 0) { continue; } chunk.meshes[layer] = { vertex_buffer: create_vertex_buffer(vertices), quad_count, groups }; } const translucent = message.translucent; if (translucent.quad_count === 0) { return; } chunk.meshes.translucent!.index_buffer = create_index_buffer(translucent.indices); if (translucent.sort_type === "dynamic") { chunk.translucent_sort = { mesh_version: message.version, centers: translucent.centers, planes: translucent.planes, camera: message.camera, requested: 0, applied: 0, }; } } #on_sorted(message: Extract) { const chunk = this.get_chunk(message.chunk_x, message.chunk_z); const sort = chunk?.translucent_sort; const mesh = chunk?.meshes.translucent; // remeshed since, or a newer sort already came back if (!sort || !mesh || sort.mesh_version !== message.version || message.sort_version <= sort.applied) { return; } sort.applied = message.sort_version; if (mesh.index_buffer) { destroy_buffer(mesh.index_buffer); } mesh.index_buffer = create_index_buffer(message.indices); } delete_chunk_mesh(chunk: Chunk) { for (const mesh of Object.values(chunk.meshes)) { destroy_buffer(mesh.vertex_buffer); if (mesh.index_buffer) { destroy_buffer(mesh.index_buffer); } } chunk.meshes = {}; chunk.translucent_sort = undefined; } // the closest entity whose box is along the view of something at x/y/z looking at yaw/pitch, within max_distance. // only the ones filter allows pick_entity( x: number, y: number, z: number, yaw: number, pitch: number, max_distance: number, filter: (entity: Entity) => boolean, ): { entity: Entity; distance: number } | undefined { const cos_pitch = Math.cos(pitch); const direction = [-Math.sin(yaw) * cos_pitch, Math.sin(pitch), -Math.cos(yaw) * cos_pitch]; const origin = [x, y, z]; let closest: { entity: Entity; distance: number } | undefined; for (const entity of this.entities.values()) { if (!filter(entity)) continue; const half = entity.width / 2; const min = [entity.x - half, entity.y, entity.z - half]; const max = [entity.x + half, entity.y + entity.height, entity.z + half]; // where the ray enters and leaves the box, one axis at a time let enter = 0; let leave = closest?.distance ?? max_distance; for (let axis = 0; axis < 3 && enter <= leave; axis++) { if (Math.abs(direction[axis]) < 1e-9) { if (origin[axis] < min[axis] || origin[axis] > max[axis]) enter = Infinity; continue; } const a = (min[axis] - origin[axis]) / direction[axis]; const b = (max[axis] - origin[axis]) / direction[axis]; enter = Math.max(enter, Math.min(a, b)); leave = Math.min(leave, Math.max(a, b)); } if (enter <= leave) { closest = { entity, distance: enter }; } } return closest; } // the first block along the view of something at x/y/z looking at yaw/pitch, like minecraft's pick pick( x: number, y: number, z: number, yaw: number, pitch: number, max_distance = 6, step = 0.05, ): BlockHitResult | undefined { const cos_pitch = Math.cos(pitch); const dx = -Math.sin(yaw) * cos_pitch; const dy = Math.sin(pitch); const dz = -Math.cos(yaw) * cos_pitch; let prev_bx = Math.floor(x); let prev_by = Math.floor(y); let prev_bz = Math.floor(z); let dist = 0; while (dist <= max_distance) { x += dx * step; y += dy * step; z += dz * step; dist += step; const bx = Math.floor(x); const by = Math.floor(y); const bz = Math.floor(z); if (bx === prev_bx && by === prev_by && bz === prev_bz) { continue; } const block = this.get_block(bx, by, bz); if (block && block !== AIR && block !== VOID) { let face: Faces; if (bx > prev_bx) { face = "west"; } else if (bx < prev_bx) { face = "east"; } else if (by > prev_by) { face = "bottom"; } else if (by < prev_by) { face = "top"; } else if (bz > prev_bz) { face = "north"; } else { face = "south"; } return { x: bx, y: by, z: bz, face, block }; } prev_bx = bx; prev_by = by; prev_bz = bz; } return undefined; } } // functions cant be sent to workers // deno-lint-ignore no-explicit-any function strip_functions>(obj: T): T { // deno-lint-ignore no-explicit-any const out: any = Array.isArray(obj) ? [] : {}; for (const k in obj) { const v = obj[k]; if (typeof v === "function") continue; if (v && typeof v === "object") { out[k] = strip_functions(v); } else { out[k] = v; } } return out; }