781 lines
24 KiB
TypeScript
781 lines
24 KiB
TypeScript
import {
|
|
block_value,
|
|
chunk_key,
|
|
default_block_value,
|
|
is_waterlogged,
|
|
liquid_block,
|
|
liquid_in_cell,
|
|
} from "$/common/utils.ts";
|
|
import { AIR_ID } from "$/common/protocol.ts";
|
|
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
|
|
import { DEFAULT_WATER_COLOR, foliage_color, grass_color, water_color } from "$/common/worldgen/biome_colors.ts";
|
|
import {
|
|
block_light_emission,
|
|
block_light_opacity,
|
|
BlockRegistry,
|
|
EverythingRegistry,
|
|
is_liquid_block,
|
|
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 { clip_shape, collision_shape_at, FULL_SHAPE, type Shape, shape_at } from "$/common/block_shapes.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<Record<RenderLayer, ChunkMesh>>;
|
|
// 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, then water 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;
|
|
// where the view went into the block, 0 to 1 on each axis
|
|
hit: [number, number, number];
|
|
}
|
|
|
|
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<number, Chunk>();
|
|
// the chunks request_meshes and update_translucent_sorting look at, so they don't go through every chunk each frame
|
|
#dirty = new Set<Chunk>();
|
|
#sorted = new Set<Chunk>();
|
|
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<BlockRegistry>("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<string, Entity>();
|
|
// what blocks with item_display show, by chunk_key then position_key "x,y,z"
|
|
block_items = new Map<number, Map<string, { x: number; y: number; z: number; item: ItemStack }>>();
|
|
|
|
// 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<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 },
|
|
});
|
|
}
|
|
|
|
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 * 3);
|
|
biomes.forEach((biome, column) => {
|
|
biome_colors[column] = grass_color(biome);
|
|
biome_colors[CHUNK_AREA + column] = foliage_color(biome);
|
|
biome_colors[CHUNK_AREA * 2 + column] = water_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;
|
|
this.#mark_dirty(chunk);
|
|
} else {
|
|
const chunk: Chunk = {
|
|
x,
|
|
z,
|
|
blocks,
|
|
biome_colors,
|
|
dirty: true,
|
|
mesh_version: 0,
|
|
meshes: {},
|
|
min_y: 0,
|
|
max_y: 0,
|
|
};
|
|
this.chunks.set(chunk_key(x, z), chunk);
|
|
this.#dirty.add(chunk);
|
|
}
|
|
// 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) {
|
|
this.#mark_dirty(neighbor);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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.#dirty.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<BlockRegistry>("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);
|
|
this.#mark_dirty(chunk);
|
|
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));
|
|
}
|
|
|
|
// what entities bump into there, see common/physics.ts. unloaded chunks are full blocks, like has_collision
|
|
collision_shape(x: number, y: number, z: number): boolean | Shape {
|
|
const value = this.get_block_value(x, y, z);
|
|
const nid = value & ID_MASK;
|
|
if (nid === VOID) return true;
|
|
if (nid === AIR) return false;
|
|
const block = this.#blocks[nid];
|
|
return block ? collision_shape_at(block, value) : true;
|
|
}
|
|
|
|
// the biome's water color at a column as 0xRRGGBB, see "tint". plains' in unloaded chunks
|
|
water_color(x: 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 DEFAULT_WATER_COLOR;
|
|
return chunk
|
|
.biome_colors[CHUNK_AREA * 2 + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
|
|
}
|
|
|
|
// the liquid there and how high it is, for liquids pushing things along. unloaded chunks have none
|
|
liquid_at(x: number, y: number, z: number) {
|
|
const value = this.get_block_value(x, y, z);
|
|
const nid = value & ID_MASK;
|
|
return nid === VOID || nid === AIR ? undefined : liquid_in_cell(value, this.#blocks[nid]);
|
|
}
|
|
|
|
// water, or a block waterlogged with it, see liquid_block. unloaded chunks aren't
|
|
is_liquid(x: number, y: number, z: number) {
|
|
const value = this.get_block_value(x, y, z);
|
|
const block = value & ID_MASK;
|
|
return block !== VOID && block !== AIR && liquid_block(value, this.#blocks[block]) !== undefined;
|
|
}
|
|
|
|
// 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_value = chunk.blocks[index];
|
|
const old_nid = old_value & ID_MASK;
|
|
const old_block = this.#blocks[old_nid];
|
|
// a waterlogged block leaves its liquid, like the server's destroy_block
|
|
const liquid = is_waterlogged(old_value, old_block)
|
|
? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR
|
|
: AIR;
|
|
chunk.blocks[index] = liquid;
|
|
this.#mark_dirty(chunk);
|
|
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, liquid);
|
|
}
|
|
|
|
// 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) {
|
|
this.#mark_dirty(n);
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (lx === 0) {
|
|
const n = this.get_chunk(block_chunk_x - 1, block_chunk_z);
|
|
if (n) {
|
|
this.#mark_dirty(n);
|
|
}
|
|
} else if (lx === CHUNK_SIZE - 1) {
|
|
const n = this.get_chunk(block_chunk_x + 1, block_chunk_z);
|
|
if (n) {
|
|
this.#mark_dirty(n);
|
|
}
|
|
}
|
|
if (lz === 0) {
|
|
const n = this.get_chunk(block_chunk_x, block_chunk_z - 1);
|
|
if (n) {
|
|
this.#mark_dirty(n);
|
|
}
|
|
} else if (lz === CHUNK_SIZE - 1) {
|
|
const n = this.get_chunk(block_chunk_x, block_chunk_z + 1);
|
|
if (n) {
|
|
this.#mark_dirty(n);
|
|
}
|
|
}
|
|
}
|
|
|
|
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.#dirty.delete(chunk);
|
|
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;
|
|
}
|
|
|
|
// meshes asked of the workers that haven't come back, for the f3 performance window
|
|
meshes_in_flight = 0;
|
|
|
|
// sends every dirty chunk that can be meshed to the workers
|
|
request_meshes(camera: Camera) {
|
|
for (const chunk of this.#dirty) {
|
|
if (!this.can_mesh(chunk)) {
|
|
continue;
|
|
}
|
|
chunk.dirty = false;
|
|
this.#dirty.delete(chunk);
|
|
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.meshes_in_flight += 1;
|
|
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.#sorted) {
|
|
const sort = chunk.translucent_sort!;
|
|
if (!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<FromChunkWorker, { type: "meshed" }>) {
|
|
this.meshes_in_flight -= 1;
|
|
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") {
|
|
this.#sorted.add(chunk);
|
|
chunk.translucent_sort = {
|
|
mesh_version: message.version,
|
|
centers: translucent.centers,
|
|
planes: translucent.planes,
|
|
camera: message.camera,
|
|
requested: 0,
|
|
applied: 0,
|
|
};
|
|
}
|
|
}
|
|
|
|
#on_sorted(message: Extract<FromChunkWorker, { type: "sorted" }>) {
|
|
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;
|
|
this.#sorted.delete(chunk);
|
|
}
|
|
|
|
// chunks that need meshing, some waiting on their neighbors to load
|
|
get dirty_count() {
|
|
return this.#dirty.size;
|
|
}
|
|
|
|
#mark_dirty(chunk: Chunk) {
|
|
chunk.dirty = true;
|
|
this.#dirty.add(chunk);
|
|
}
|
|
|
|
// 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. it has to go
|
|
// into one of the block's boxes (see common/block_shapes.ts), so it looks past the empty half of a slab. it looks
|
|
// through liquids unless liquids is set, see ItemRegistry.targets_liquids
|
|
pick(
|
|
x: number,
|
|
y: number,
|
|
z: number,
|
|
yaw: number,
|
|
pitch: number,
|
|
max_distance = 6,
|
|
liquids = false,
|
|
step = 0.05,
|
|
): BlockHitResult | 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 prev_bx = Math.floor(x);
|
|
let prev_by = Math.floor(y);
|
|
let prev_bz = Math.floor(z);
|
|
|
|
// a little past the end, so a block whose cell the steps reach after max_distance is still tried
|
|
for (let dist = step; dist <= max_distance + step; dist += step) {
|
|
const bx = Math.floor(origin[0] + direction[0] * dist);
|
|
const by = Math.floor(origin[1] + direction[1] * dist);
|
|
const bz = Math.floor(origin[2] + direction[2] * dist);
|
|
|
|
if (bx === prev_bx && by === prev_by && bz === prev_bz) {
|
|
continue;
|
|
}
|
|
prev_bx = bx;
|
|
prev_by = by;
|
|
prev_bz = bz;
|
|
|
|
const value = this.get_block_value(bx, by, bz);
|
|
const block = value & ID_MASK;
|
|
if (block === AIR || block === VOID) {
|
|
continue;
|
|
}
|
|
const info = this.#blocks[block];
|
|
if (!liquids && is_liquid_block(info)) {
|
|
continue;
|
|
}
|
|
// aimed at liquids, the source in a waterlogged block covers it, like the server's raycast_shape
|
|
const covered = liquids && is_waterlogged(value, info);
|
|
const hit = clip_shape(
|
|
!info || covered ? FULL_SHAPE : shape_at(info, value),
|
|
bx,
|
|
by,
|
|
bz,
|
|
origin,
|
|
direction,
|
|
max_distance,
|
|
);
|
|
if (!hit) {
|
|
continue;
|
|
}
|
|
// the side of the box it went in by
|
|
const face: Faces = hit.axis === 0
|
|
? (hit.sign > 0 ? "west" : "east")
|
|
: hit.axis === 1
|
|
? (hit.sign > 0 ? "bottom" : "top")
|
|
: (hit.sign > 0 ? "north" : "south");
|
|
const at = [0, 1, 2].map((axis) =>
|
|
Math.min(Math.max(origin[axis] + direction[axis] * hit.distance - [bx, by, bz][axis], 0), 1)
|
|
);
|
|
return { x: bx, y: by, z: bz, face, block, hit: [at[0], at[1], at[2]] };
|
|
}
|
|
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
// functions cant be sent to workers
|
|
// deno-lint-ignore no-explicit-any
|
|
function strip_functions<T extends Record<string, any>>(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;
|
|
}
|