import { type Chunk, CHUNK_SIZE, type ChunkMesh, ClientLevel } from "$/client/level/client_level.ts"; import { profiler } from "$/client/profiler.ts"; import { Camera } from "$/client/camera.ts"; import { AssetManager } from "$/client/assets.ts"; import { get_sprite_region } from "$/client/sprites.ts"; import type { MultiPlayerGameMode } from "$/client/game_mode.ts"; import type { Entity } from "$/client/entity/entity.ts"; import { RemotePlayer } from "$/client/entity/remote_player.ts"; import { ItemEntity } from "$/client/entity/item_entity.ts"; import { render_block_items, render_item_entity } from "./item_renderer.ts"; import { HURT_TINT, player_pose, render_player } from "./player_renderer.ts"; import { render_worn } from "./worn_renderer.ts"; import type { PlayerPose } from "./player_model.ts"; import type { Vec3 } from "./model_math.ts"; import { render_mod_entity } from "./entity_renderer.ts"; import { entity_tint } from "./entity_light.ts"; import { RemoteEntity } from "$/client/entity/remote_entity.ts"; import { draw_terrain, flush_batch, get_current_texture, push_vertex, set_current_texture, Texture, view_projection, white_tex, } from "$/client/renderer/mod.ts"; import { type BlockRegistry, EverythingRegistry, type RenderLayer } from "$/common/everything_registry.ts"; import { bake_block, type BakedQuad, FACE_INDEX, looks_by_state, type ModelJson } from "$/common/block_models.ts"; import { ID_MASK } from "$/common/constants.ts"; import { type Shape, shape_at } from "$/common/block_shapes.ts"; import type { BlockHitResult } from "$/client/level/client_level.ts"; import { FACE_GROUPS, UNALIGNED_GROUP } from "$/client/workers/chunk_messages.ts"; import { FACE_AXIS, FACE_NORMALS } from "$/client/workers/translucent_sort.ts"; import { Frustum } from "./frustum.ts"; // draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities export class LevelRenderer { frustum = new Frustum(); // chunks in view this frame, worked out once for all the layers #visible: Chunk[] = []; // what to draw, switched off in the f3 performance window to see what each costs draw = { solid: true, cutout: true, translucent: true, entities: true }; get visible_chunks() { return this.#visible.length; } // solid and cutout terrain, drawn before entities render_opaque(level: ClientLevel, camera: Camera) { profiler.section("chunk upkeep", () => this.#find_visible(level, camera)); set_current_texture(level.image.tex); for (const layer of ["solid", "cutout"] as const) { if (!this.draw[layer]) continue; profiler.section(layer, () => { for (const chunk of this.#visible) { const mesh = chunk.meshes[layer]; if (mesh) { draw_facing_camera(layer, mesh, camera); } } }); } } // asks for meshes and sorting, then works out which chunks are in view, near to far #find_visible(level: ClientLevel, camera: Camera) { level.request_meshes(camera); level.update_translucent_sorting(camera); this.frustum.update(view_projection()); this.#visible.length = 0; for (const chunk of level.chunks.values()) { if (Object.keys(chunk.meshes).length > 0 && this.#in_view(chunk)) { this.#visible.push(chunk); } } // near to far, like sodium, so what's in front fills the depth buffer first and the gpu can skip shading what's // behind it const distance_sq = (chunk: Chunk) => { const dx = (chunk.x + 0.5) * CHUNK_SIZE - camera.x; const dz = (chunk.z + 0.5) * CHUNK_SIZE - camera.z; return dx * dx + dz * dz; }; this.#visible.sort((a, b) => distance_sq(a) - distance_sq(b)); } // translucent terrain, drawn after entities so they show through water and glass. // chunks go back to front, and each chunk's quads are already sorted back to front render_translucent(_level: ClientLevel, camera: Camera) { if (!this.draw.translucent) return; const distance_sq = (x: number, z: number) => { const dx = (x + 0.5) * CHUNK_SIZE - camera.x; const dz = (z + 0.5) * CHUNK_SIZE - camera.z; return dx * dx + dz * dz; }; const chunks = this.#visible .filter((chunk) => chunk.meshes.translucent) .map((chunk) => ({ mesh: chunk.meshes.translucent!, distance: distance_sq(chunk.x, chunk.z) })) .sort((a, b) => b.distance - a.distance); for (const { mesh } of chunks) { draw_terrain("translucent", mesh.vertex_buffer, 0, mesh.quad_count, mesh.index_buffer); } } #in_view(chunk: Chunk) { const x = chunk.x * CHUNK_SIZE; const z = chunk.z * CHUNK_SIZE; return this.frustum.intersects_box(x, chunk.min_y, z, x + CHUNK_SIZE, chunk.max_y, z + CHUNK_SIZE); } // every entity but the one the camera is in render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity, partial_tick: number) { if (!this.draw.entities) return; flush_batch(); const default_skin = AssetManager.instance.get("bworld:skin"); // what they wear is drawn with the atlas, after every skin const posed: { player: RemotePlayer; pose: PlayerPose; tint: Vec3 }[] = []; for (const entity of level.entities.values()) { if (entity !== camera_entity && entity instanceof RemotePlayer) { const skin = entity.skin ?? default_skin; if (get_current_texture() !== skin.tex) { flush_batch(); set_current_texture(skin.tex); } const tint = entity_tint(entity, partial_tick, entity.hurt_time > 0 ? HURT_TINT : undefined); const pose = player_pose(entity, partial_tick); render_player(skin, pose, tint); posed.push({ player: entity, pose, tint }); } } flush_batch(); set_current_texture(level.image.tex); for (const { player, pose, tint } of posed) render_worn(player, pose, tint); for (const entity of level.entities.values()) { if (entity instanceof ItemEntity) { render_item_entity(entity, partial_tick); } else if (entity instanceof RemoteEntity) { render_mod_entity(entity, camera, partial_tick); } } render_block_items(level); flush_batch(); } // the cracks on the block being broken, drawn over its model's faces like minecraft's crumbling overlay, so a slab // or a plant cracks where it is and not on a whole cube around it render_destroy_progress(level: ClientLevel, game_mode: MultiPlayerGameMode) { const block = game_mode.destroy_pos; if (!block) { return; } const progress = Math.max(0, Math.min(1, game_mode.destroy_progress / game_mode.destroy_time)); const stage = Math.round(progress * 8); if (Number.isNaN(stage)) { return; } const value = level.get_block_value(block.x, block.y, block.z); const info = EverythingRegistry.get_by_id("blocks", value & ID_MASK); if (!info) { return; } const tex = AssetManager.instance.get("bworld:textures"); const region = get_sprite_region(`engine:break_${stage}`); for (const quad of this.#destroy_quads(info, value)) { push_decal_quad(tex, quad, block.x, block.y, block.z, region); } } // the edges of the shape of the block being looked at, like minecraft's block outline: thin dark lines that keep // the same width on screen however far away it is render_block_outline(level: ClientLevel, hit: BlockHitResult | undefined, camera: Camera) { if (!hit) { return; } const value = level.get_block_value(hit.x, hit.y, hit.z); const info = EverythingRegistry.get_by_id("blocks", value & ID_MASK); if (!info) { return; } const previous = get_current_texture(); flush_batch(); set_current_texture(white_tex!); const eye = [camera.x, camera.y, camera.z]; for (const edge of shape_edges(shape_at(info, value))) { push_line( [hit.x + edge[0], hit.y + edge[1], hit.z + edge[2]], [hit.x + edge[3], hit.y + edge[4], hit.z + edge[5]], eye, ); } flush_batch(); if (previous) set_current_texture(previous); } // the block's model at a value, baked once #destroy_quads(block: BlockRegistry, value: number): BakedQuad[] { const key = looks_by_state(block) ? value : value & ID_MASK; let quads = this.#baked.get(key); if (!quads) { quads = bake_block(block, value, Object.fromEntries(EverythingRegistry.entries("models"))); this.#baked.set(key, quads); } return quads; } #baked = new Map(); } // minecraft's outline is black at 40% const OUTLINE_COLOR = [0, 0, 0, 0.4] as const; // half the line's width for each block it is away from the camera, about a pixel on a 1080p screen const OUTLINE_HALF_WIDTH = 0.0012; // how far out the outline is from the block's faces, so they don't hide it const OUTLINE_GROW = 0.002; // the 12 edges of each box of a shape, grown out a little, as [x1, y1, z1, x2, y2, z2]. edges two boxes share are // drawn once export function shape_edges(shape: Shape): number[][] { const edges = new Map(); for (const box of shape) { const min = [box[0] - OUTLINE_GROW, box[1] - OUTLINE_GROW, box[2] - OUTLINE_GROW]; const max = [box[3] + OUTLINE_GROW, box[4] + OUTLINE_GROW, box[5] + OUTLINE_GROW]; // along each axis, from each of the 4 corners of the box's face at the low end of it for (let axis = 0; axis < 3; axis++) { const [a, b] = [(axis + 1) % 3, (axis + 2) % 3]; for (const [ea, eb] of [[0, 0], [0, 1], [1, 0], [1, 1]]) { const from = [0, 0, 0]; from[axis] = min[axis]; from[a] = ea ? max[a] : min[a]; from[b] = eb ? max[b] : min[b]; const to = [...from]; to[axis] = max[axis]; const edge = [...from, ...to]; edges.set(edge.map((v) => v.toFixed(4)).join(","), edge); } } } return [...edges.values()]; } // a line from a to b as a thin quad turned to face the eye, as wide on screen at both ends function push_line(a: number[], b: number[], eye: number[]) { const direction = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; const length = Math.hypot(direction[0], direction[1], direction[2]); if (length === 0) return; const mid = [(a[0] + b[0]) / 2 - eye[0], (a[1] + b[1]) / 2 - eye[1], (a[2] + b[2]) / 2 - eye[2]]; // across the line and across the view const side = [ direction[1] * mid[2] - direction[2] * mid[1], direction[2] * mid[0] - direction[0] * mid[2], direction[0] * mid[1] - direction[1] * mid[0], ]; const side_length = Math.hypot(side[0], side[1], side[2]); if (side_length === 0) return; // each end as wide as its distance needs, and a half width longer so lines meet at the corners const end = (point: number[], sign: number) => { const distance = Math.hypot(point[0] - eye[0], point[1] - eye[1], point[2] - eye[2]); const half = OUTLINE_HALF_WIDTH * distance; const p = point.map((v, i) => v + direction[i] / length * half * sign); const s = side.map((v) => v / side_length * half); return [p.map((v, i) => v - s[i]), p.map((v, i) => v + s[i])]; }; const [a0, a1] = end(a, -1); const [b0, b1] = end(b, 1); const [r, g, bl, alpha] = OUTLINE_COLOR; const vertex = (p: number[]) => push_vertex(p[0], p[1], p[2], 0, 0, r, g, bl, alpha); // both ways round, since which way it faces depends on where the eye is for (const corners of [[a0, b0, b1, a1], [a1, b1, b0, a0]]) { vertex(corners[0]); vertex(corners[1]); vertex(corners[2]); vertex(corners[0]); vertex(corners[2]); vertex(corners[3]); } } // how far out from the face the cracks are drawn, so they don't fight the block's own face for depth const DECAL_OFFSET = 1e-3; // a quad of a block's model with a texture laid over it the way it lies on a full block's face, like minecraft's // SheetedDecalTextureGenerator: the texture doesn't stretch to the quad, the quad shows the part of it where it is function push_decal_quad( texture: Texture, quad: BakedQuad, x: number, y: number, z: number, region: { x: number; y: number; width: number; height: number }, ) { const p = quad.positions; const e1 = [p[3] - p[0], p[4] - p[1], p[5] - p[2]]; const e2 = [p[9] - p[0], p[10] - p[1], p[11] - p[2]]; const normal = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; const length = Math.hypot(normal[0], normal[1], normal[2]) || 1; const offset = normal.map((n) => n / length * DECAL_OFFSET); const pad = 0.5; const corner = (k: number) => { const [px, py, pz] = [p[k * 3], p[k * 3 + 1], p[k * 3 + 2]]; const [u, v] = decal_uv(quad.face, px, py, pz).map((t) => Math.min(Math.max(t, 0), 1)); push_vertex( x + px + offset[0], y + py + offset[1], z + pz + offset[2], (region.x + pad + u * (region.width - 2 * pad)) / texture.width, (region.y + pad + v * (region.height - 2 * pad)) / texture.height, ); }; corner(0); corner(1); corner(2); corner(0); corner(2); corner(3); } // where a point on a face is on the texture, 0 to 1, the same way default model uvs wrap a texture around the block function decal_uv(face: number, x: number, y: number, z: number): [number, number] { switch (face) { case FACE_INDEX.top: return [x, z]; case FACE_INDEX.bottom: return [x, 1 - z]; case FACE_INDEX.south: return [x, 1 - y]; case FACE_INDEX.north: return [1 - x, 1 - y]; case FACE_INDEX.west: return [z, 1 - y]; default: return [1 - z, 1 - y]; } } // only the face groups that can face the camera: quads facing +x can only be seen from beyond the lowest x plane any // of them lie on. neighboring groups that are both drawn go in one draw call function draw_facing_camera(layer: RenderLayer, mesh: ChunkMesh, camera: Camera) { const groups = mesh.groups; if (!groups) { draw_terrain(layer, mesh.vertex_buffer, 0, mesh.quad_count); return; } let start = 0; let end = 0; for (let g = 0; g < FACE_GROUPS; g++) { const group = groups[g]; if (group.count === 0 || !group_faces_camera(g, group.min, group.max, camera)) { continue; } if (group.first !== end) { draw_terrain(layer, mesh.vertex_buffer, start, end - start); start = group.first; } end = group.first + group.count; } draw_terrain(layer, mesh.vertex_buffer, start, end - start); } export function group_faces_camera( group: number, min: number, max: number, camera: { x: number; y: number; z: number }, ) { if (group === UNALIGNED_GROUP) { return true; } const axis = FACE_AXIS[group]; const position = axis === 0 ? camera.x : axis === 1 ? camera.y : camera.z; return FACE_NORMALS[group][axis] > 0 ? position > min : position < max; }