// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later import { type Chunk, CHUNK_SIZE, type ChunkMesh, ClientLevel, type RenderSection, } 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, render_debug, set_current_texture, set_face_culling, Texture, use_texture, view_projection, white_tex, } from "@/client/renderer/mod.ts"; import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; import { bake_block, type BakedQuad, FACE_INDEX, looks_by_state, type ModelJson } from "@/common/block_models.ts"; import { BREAK_STAGES, 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"; import { draw_visuals } from "./visuals.ts"; import { reachable_sections } from "./occlusion.ts"; import { REGION_LAYERS, type RegionLayer, type RenderRegion } from "@/client/level/render_region.ts"; import { SECTION_HEIGHT } from "@/common/world_shape.ts"; // draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities export class LevelRenderer { frustum = new Frustum(); // sections in view this frame, near to far, worked out once for all the layers #visible: RenderSection[] = []; // the chunks they're in, and the regions with the ones in each, the regions near to far too #visible_chunks = new Set(); #visible_regions = new Map(); // what the camera could see the last time it was searched for, which only changes when it moves to another section // or the sections change, see occlusion.ts #reachable: { sections: RenderSection[] | undefined; level: ClientLevel; version: number; key: string } | undefined; // what to draw, switched off in the f3 performance window to see what each costs draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true }; // entities drawn this frame, for the f3 performance window #drawn_entities = 0; get visible_sections() { return this.#visible.length; } get drawn_entities() { return this.#drawn_entities; } // 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 REGION_LAYERS) { if (!this.draw[layer]) continue; profiler.section(layer, () => { for (const section of this.#visible) { const mesh = section.meshes[layer]; if (mesh?.vertex_buffer) draw_facing_camera(layer, mesh.vertex_buffer, mesh, camera); } for (const [region, sections] of this.#visible_regions) draw_region(layer, region, sections, camera); }); } } // asks for meshes and sorting, then works out which sections are in view, 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 #find_visible(level: ClientLevel, camera: Camera) { level.request_meshes(camera); level.update_translucent_sorting(camera); level.use_render_regions(render_debug.render_regions); level.update_regions(); this.frustum.update(view_projection()); this.#visible_chunks.clear(); this.#visible_regions.clear(); const reachable = this.#reachable_sections(level, camera); if (reachable) { this.#visible = reachable.filter((section) => this.#in_view(section)); } else { // the camera's chunk isn't loaded, so there's nothing to search from this.#visible = [...level.drawn].filter((section) => this.#in_view(section)) .map((section) => ({ section, distance: distance_sq(section, camera) })) .sort((a, b) => a.distance - b.distance) .map(({ section }) => section); } for (const section of this.#visible) { this.#visible_chunks.add(section.chunk); const in_region = this.#visible_regions.get(section.region); if (in_region) in_region.push(section); else this.#visible_regions.set(section.region, [section]); } } #reachable_sections(level: ClientLevel, camera: Camera) { const key = `${Math.floor(camera.x / CHUNK_SIZE)},${Math.floor(camera.y / SECTION_HEIGHT)},${ Math.floor(camera.z / CHUNK_SIZE) }`; const last = this.#reachable; if (last?.level === level && last.version === level.sections_version && last.key === key) return last.sections; const sections = profiler.section( "occlusion", () => reachable_sections(level, camera.x, camera.y, camera.z), ); this.#reachable = { sections, level, version: level.sections_version, key }; return sections; } // translucent terrain, drawn after entities so they show through water and glass. sections go back to front, and // each section's quads are already sorted back to front render_translucent(_level: ClientLevel, camera: Camera) { if (!this.draw.translucent) return; const sections = this.#visible .filter((section) => section.meshes.translucent) .map((section) => ({ mesh: section.meshes.translucent!, distance: distance_sq(section, camera) })) .sort((a, b) => b.distance - a.distance); for (const { mesh } of sections) { draw_terrain("translucent", mesh.vertex_buffer!, 0, mesh.quad_count, mesh.index_buffer); } } #in_view(section: RenderSection) { const x = section.chunk.x * CHUNK_SIZE; const z = section.chunk.z * CHUNK_SIZE; return this.frustum.intersects_box(x, section.min_y, z, x + CHUNK_SIZE, section.max_y, z + CHUNK_SIZE); } // every entity in view but the one the camera is in render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity | undefined, partial_tick: number) { this.#drawn_entities = 0; if (!this.draw.entities) return; flush_batch(); const default_skin = AssetManager.instance.get("cubi: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 && this.#entity_in_view(entity, partial_tick) ) { const skin = entity.skin ?? default_skin; use_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 && this.#entity_in_view(entity, partial_tick)) { render_item_entity(entity, partial_tick); } } set_face_culling(false); for (const entity of level.entities.values()) { if (entity instanceof RemoteEntity && this.#entity_in_view(entity, partial_tick)) { render_mod_entity(entity, camera, partial_tick); } } set_face_culling(true); render_block_items(level); flush_batch(); } // whether an entity's box, grown by ENTITY_CULL_MARGIN, is in view. entities are drawn on the cpu every frame, so // the ones out of view are skipped #entity_in_view(entity: Entity, partial_tick: number) { const { x, y, z } = entity.render_position(partial_tick); const half = entity.width / 2 + ENTITY_CULL_MARGIN; const in_view = this.frustum.intersects_box( x - half, y - ENTITY_CULL_MARGIN, z - half, x + half, y + entity.height + ENTITY_CULL_MARGIN, z + half, ); if (in_view) this.#drawn_entities += 1; return in_view; } // blocks drawn with code, see client/rendering/visuals.ts. the ones in chunks in view get their on_frame first render_visuals(level: ClientLevel, camera: Camera, partial_tick: number) { if (!this.draw.visuals) return; level.visuals.frame(this.#visible_chunks, level.ticks + partial_tick); flush_batch(); set_current_texture(level.image.tex); draw_visuals(level.visuals, level.image, [camera.x, camera.y, camera.z]); } // the cracks on the block being broken, and on the ones machines are breaking, drawn over their models' 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 | undefined) { for (const { x, y, z, stage } of level.break_progress.values()) this.#draw_cracks(level, x, y, z, stage); const block = game_mode?.destroy_pos; if (!game_mode || !block) { return; } const progress = Math.max(0, Math.min(1, game_mode.destroy_progress / game_mode.destroy_time)); const stage = Math.round(progress * BREAK_STAGES); if (!Number.isNaN(stage)) this.#draw_cracks(level, block.x, block.y, block.z, stage); } #draw_cracks(level: ClientLevel, x: number, y: number, z: number, stage: number) { const value = level.get_block_value(x, y, z); const info = EverythingRegistry.get_by_id("blocks", value & ID_MASK); if (!info) { return; } const tex = AssetManager.instance.get("cubi:textures"); const region = get_sprite_region(`cubi:break_${stage}`); for (const quad of this.#destroy_quads(info, value)) { push_decal_quad(tex, quad, x, y, 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(); } // from the camera to the middle of the section's bounds, squared function distance_sq(section: RenderSection, camera: Camera) { const dx = (section.chunk.x + 0.5) * CHUNK_SIZE - camera.x; const dy = (section.min_y + section.max_y) / 2 - camera.y; const dz = (section.chunk.z + 0.5) * CHUNK_SIZE - camera.z; return dx * dx + dy * dy + dz * dz; } // how far models can stick out of their entity's box, like a swinging arm or a dropped item bobbing const ENTITY_CULL_MARGIN = 0.5; // 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: RegionLayer, buffer: GPUBuffer, mesh: ChunkMesh, camera: Camera) { const groups = mesh.groups!; 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, buffer, start, end - start); start = group.first; } end = group.first + group.count; } draw_terrain(layer, buffer, start, end - start); } // a region's sections in view, a face group at a time (see render_region.ts), only where the group can face the camera: // quads facing +x can only be seen from beyond the lowest x plane any of them lie on. sections next to each other in the // buffer that are both drawn go in one draw call function draw_region(layer: RegionLayer, region: RenderRegion, in_view: RenderSection[], camera: Camera) { const buffer = region.layers[layer].buffer; if (!buffer) return; // in the order they're in the buffer const sections = in_view.filter((section) => section.meshes[layer]?.slot !== undefined) .sort((a, b) => a.meshes[layer]!.slot! - b.meshes[layer]!.slot!); for (let g = 0; g < FACE_GROUPS; g++) { let start = 0; let end = 0; for (const section of sections) { const group = section.meshes[layer]!.groups![g]; if (group.count === 0 || !group_faces_camera(g, group.min, group.max, camera)) continue; if (group.first !== end) { draw_terrain(layer, buffer, start, end - start); start = group.first; } end = group.first + group.count; } draw_terrain(layer, 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; }