Files
bworld/client/renderer/core.ts
T

1211 lines
38 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { Camera } from "../camera.ts";
import { mat4 } from "gl-matrix";
import type { RenderLayer } from "@/common/everything_registry.ts";
import { TERRAIN_VERTEX_BYTES } from "../workers/chunk_messages.ts";
import { GpuTimer } from "./gpu_timing.ts";
// what frames are drawn on: the page's canvas, or the desktop app's window (deno's UnsafeWindowSurface). setting
// width and height resizes it, like a canvas
export interface DrawSurface {
width: number;
height: number;
getContext(id: "webgpu"): unknown;
// shows what was drawn, the window's needs it after every frame, a canvas does it by itself
present?(): void;
// a canvas is shown scaled when its size is fixed, see set_canvas_size
style?: { width: string; height: string };
}
export let device: GPUDevice;
export let canvas: DrawSurface;
const MAX_SPRITES = 100000;
const VERTS_PER_SPRITE = 6;
const FLOATS_PER_VERT = 9;
const VERTEX_STRIDE = FLOATS_PER_VERT * 4;
// msaa when it's turned on in the f3 performance window. off by default like minecraft and sodium, it's costly at
// large window sizes
const SAMPLE_COUNT = 4;
// what the pipelines and render targets were made for
let sample_count = 1;
const DEPTH_FORMAT: GPUTextureFormat = "depth24plus";
// dynamic uniform offsets have to be 256 aligned
const UNIFORM_SLOT_SIZE = 256;
// the matrix, then the render time and padding to 16 bytes
const UNIFORM_FLOATS = 20;
// the render time wraps around after this many ticks, so a 32 bit float keeps it precise however long the game runs.
// a whole number of turns for every speed in steps of 0.05 rpm, so those don't jump when it wraps
const RENDER_TIME_PERIOD = 24000;
// a vertex of an instanced model, 24 bytes: position as float32x3, atlas uv as unorm16x2, tint as unorm8x3 with alpha 1
// when the face is shaded by the way it faces, and the face's normal as snorm8x3 and a padding byte
export const MODEL_VERTEX_BYTES = 24;
// an instance, 24 floats: the matrix placing its model in the world (4 columns), the axis it spins around and its rpm,
// then its offset in degrees, its block light and sky light as lightmap coordinates and a padding float
export const INSTANCE_FLOATS = 24;
let context: GPUCanvasContext;
let canvas_format: GPUTextureFormat;
let pipeline_2d: GPURenderPipeline;
let pipeline_3d: GPURenderPipeline;
// the same, drawing both sides of each face, see set_face_culling
let pipeline_3d_no_cull: GPURenderPipeline;
let terrain_pipelines: Record<RenderLayer, GPURenderPipeline>;
let instance_pipelines: { cutout: GPURenderPipeline; translucent: GPURenderPipeline };
// 0 1 2 0 2 3 for every quad, shared by all solid and cutout chunk meshes
let quad_index_buffer: GPUBuffer | undefined;
let quad_index_capacity = 0;
let uniform_layout: GPUBindGroupLayout;
let texture_layout: GPUBindGroupLayout;
let sampler: GPUSampler;
// minecraft's lightmap: the color for every block light (x) and sky light (y) pair, see update_lightmap
let lightmap: GPUTexture;
let lightmap_bind_group: GPUBindGroup;
// the same colors on the cpu, r g b from 0 to 1 by sky * 16 + block, for lighting entities, see light_color
const lightmap_colors = new Float32Array(16 * 16 * 3);
const vertex_data = new Float32Array(MAX_SPRITES * VERTS_PER_SPRITE * FLOATS_PER_VERT);
let vert_index = 0;
// every flush in a frame appends to this, so earlier draws dont get overwritten before the submit
let stream_buffer: GPUBuffer;
let stream_offset = 0;
let uniform_buffer: GPUBuffer;
let uniform_bind_group: GPUBindGroup;
let uniform_slot = -1;
const uniform_data = new Float32Array(UNIFORM_FLOATS);
// in ticks, see set_render_time
let render_time = 0;
const texture_bind_groups = new WeakMap<GPUTexture, GPUBindGroup>();
let current_texture: GPUTexture | null = null;
export let white_tex: GPUTexture | null = null;
let mode3d = false;
let cull_faces = true;
let camera: Camera | undefined;
const ortho = mat4.create();
const proj = mat4.create();
const view = mat4.create();
const mvp = mat4.create();
// per frame state
let encoder: GPUCommandEncoder | undefined;
let pass: GPURenderPassEncoder | undefined;
let frame_view: GPUTextureView;
let msaa_texture: GPUTexture | undefined;
let depth_texture: GPUTexture | undefined;
let current_pipeline: GPURenderPipeline | undefined;
let clear_color: GPUColor = { r: 0, g: 0, b: 0, a: 1 };
let pending_color_clear = false;
let pending_depth_clear = false;
let scissor: { x: number; y: number; width: number; height: number } | undefined;
let pending_destroy: GPUBuffer[] = [];
// switches for finding out what a frame costs, see the f3 performance window. msaa is changed at the start of the next
// frame. split_passes gives each section (see gpu_section) passes of its own so the gpu times them apart, which costs
// a little since every pass loads and stores the render targets. uncapped starts frames back to back instead of with
// the display's refresh, see the game loop in main.ts. render_regions draws terrain by region, see
// ClientLevel.use_render_regions
export const render_debug = { msaa: false, split_passes: false, uncapped: false, render_regions: false };
// what was drawn, for the last whole frame
export interface RenderStats {
draw_calls: number;
passes: number;
quads: Record<RenderLayer, number>;
}
const empty_stats = (): RenderStats => ({ draw_calls: 0, passes: 0, quads: { solid: 0, cutout: 0, translucent: 0 } });
export let render_stats = empty_stats();
let frame_stats = empty_stats();
export let gpu_timer: GpuTimer | undefined;
// what the gpu is, for the benchmark's report
export let adapter_info: GPUAdapterInfo | undefined;
// see set_canvas_size
let fixed_canvas_size: { width: number; height: number } | undefined;
// the space frames are shown in, the page's or the window's, see resize_canvas
let view_size = { width: 1800, height: 900 };
let resize_pending = false;
// what the passes starting now are timed as
let gpu_label = "other";
const shader_src = /* wgsl */ `
struct Uniforms {
mvp: mat4x4<f32>,
}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var texture0: texture_2d<f32>;
@group(1) @binding(1) var sampler0: sampler;
struct VertexOut {
@builtin(position) position: vec4<f32>,
// centroid: with msaa, pixels on a triangle's edge would otherwise sample outside it, past the
// sprite's edge in the atlas, which shows up as dark lines between blocks from far away
@location(0) @interpolate(perspective, centroid) tex_coord: vec2<f32>,
@location(1) @interpolate(perspective, centroid) color: vec4<f32>,
}
@vertex
fn vs_main(
@location(0) position: vec3<f32>,
@location(1) tex_coord: vec2<f32>,
@location(2) color: vec4<f32>,
) -> VertexOut {
var out: VertexOut;
out.position = uniforms.mvp * vec4<f32>(position, 1.0);
out.tex_coord = tex_coord;
out.color = color;
return out;
}
// blended draws. fully clear texels don't write depth, or they would hide what's drawn behind them later
@fragment
fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
let color = textureSample(texture0, sampler0, in.tex_coord) * in.color;
if (color.a < 0.01) {
discard;
}
return color;
}
`;
export const terrain_shader_src = /* wgsl */ `
struct Uniforms {
mvp: mat4x4<f32>,
// ticks, see set_render_time
time: f32,
}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var texture0: texture_2d<f32>;
@group(1) @binding(1) var sampler0: sampler;
@group(2) @binding(0) var lightmap: texture_2d<f32>;
@group(2) @binding(1) var lightmap_sampler: sampler;
struct VertexOut {
@builtin(position) position: vec4<f32>,
@location(0) @interpolate(perspective, centroid) tex_coord: vec2<f32>,
// directional shade times ambient occlusion, and alpha
@location(1) @interpolate(perspective, centroid) color: vec4<f32>,
// block light, sky light, as lightmap coordinates
@location(2) @interpolate(perspective, centroid) light: vec2<f32>,
}
@vertex
fn vs_terrain(
@location(0) position: vec3<f32>,
@location(1) tex_coord: vec2<f32>,
@location(2) color: vec4<f32>,
@location(3) light: vec2<f32>,
) -> VertexOut {
var out: VertexOut;
out.position = uniforms.mvp * vec4<f32>(position, 1.0);
out.tex_coord = tex_coord;
out.color = color;
out.light = light;
return out;
}
// v turned angle radians around axis, counterclockwise seen from the axis's end
fn spun(v: vec3<f32>, axis: vec3<f32>, angle: f32) -> vec3<f32> {
return v * cos(angle) + cross(axis, v) * sin(angle) + axis * dot(axis, v) * (1.0 - cos(angle));
}
// a model drawn many times, once per instance, see client/rendering/visuals.ts. it's turned around its block's middle
// by spin (rpm times a minute, plus the offset) before placement puts it in the world. its faces are shaded by the
// way they face after that, like the chunk mesher's, and lit by the light the instance has
@vertex
fn vs_instance(
@location(0) position: vec3<f32>,
@location(1) tex_coord: vec2<f32>,
@location(2) color: vec4<f32>,
@location(3) normal: vec4<f32>,
@location(4) placement0: vec4<f32>,
@location(5) placement1: vec4<f32>,
@location(6) placement2: vec4<f32>,
@location(7) placement3: vec4<f32>,
// the axis, then rpm
@location(8) spin: vec4<f32>,
// the offset in degrees, then block light and sky light as lightmap coordinates
@location(9) offset_light: vec4<f32>,
) -> VertexOut {
let placement = mat4x4<f32>(placement0, placement1, placement2, placement3);
// in turns first, which fract keeps small. a minute is 1200 ticks
let angle = fract(uniforms.time * spin.w / 1200.0 + offset_light.x / 360.0) * 6.2831853;
let local = spun(position - vec3<f32>(0.5), spin.xyz, angle) + vec3<f32>(0.5);
let n = normalize((placement * vec4<f32>(spun(normal.xyz, spin.xyz, angle), 0.0)).xyz);
let shade = n.x * n.x * 0.6 + n.z * n.z * 0.8 + n.y * n.y * select(0.5, 1.0, n.y > 0.0);
var out: VertexOut;
out.position = uniforms.mvp * placement * vec4<f32>(local, 1.0);
out.tex_coord = tex_coord;
out.color = vec4<f32>(color.rgb * select(1.0, shade, color.a > 0.5), 1.0);
out.light = offset_light.yz;
return out;
}
fn lit(in: VertexOut) -> vec4<f32> {
let texel = textureSample(texture0, sampler0, in.tex_coord);
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), texel.a * in.color.a);
}
// the lightmap has no mipmaps, so a level is the same as textureSample, and it can be read after a branch
fn light_at(in: VertexOut) -> vec3<f32> {
return textureSampleLevel(lightmap, lightmap_sampler, in.light, 0.0).rgb;
}
// no discard, so the gpu can reject hidden fragments before running the shader
@fragment
fn fs_solid(in: VertexOut) -> @location(0) vec4<f32> {
return vec4<f32>(lit(in).rgb, 1.0);
}
// alpha tested instead of blended, so it doesn't need sorting. with msaa on, alpha to coverage instead of discard:
// alpha is 0 or 1, so a texel covers none or all of a pixel's samples, the same as discarding below 0.1, but the gpu
// can still reject hidden fragments before running the shader. clear texels skip the lightmap
@fragment
fn fs_cutout(in: VertexOut) -> @location(0) vec4<f32> {
let texel = textureSample(texture0, sampler0, in.tex_coord);
if (texel.a < 0.1) {
return vec4<f32>(0.0);
}
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), 1.0);
}
// without msaa, the default, there's no alpha to coverage, so clear texels are discarded like minecraft and sodium
@fragment
fn fs_cutout_discard(in: VertexOut) -> @location(0) vec4<f32> {
let texel = textureSample(texture0, sampler0, in.tex_coord);
if (texel.a < 0.1) {
discard;
}
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), 1.0);
}
@fragment
fn fs_translucent(in: VertexOut) -> @location(0) vec4<f32> {
let color = lit(in);
if (color.a < 0.01) {
discard;
}
return color;
}
`;
export async function init_window(surface: DrawSurface) {
canvas = surface;
canvas.width = view_size.width;
canvas.height = view_size.height;
if (!navigator.gpu) {
throw new Error("WebGPU not supported");
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
throw new Error("No WebGPU adapter found");
}
adapter_info = adapter.info;
device = await adapter.requestDevice({
requiredFeatures: adapter.features.has("timestamp-query") ? ["timestamp-query"] : [],
});
gpu_timer = new GpuTimer(device);
device.addEventListener("uncapturederror", (event) => {
console.error("WebGPU error:", (event as GPUUncapturedErrorEvent).error.message);
});
device.lost.then((info) => console.error(`WebGPU device lost: ${info.message}`));
// the dom typings dont know about the webgpu overload yet
const ctx = canvas.getContext("webgpu") as GPUCanvasContext | null;
if (!ctx) {
throw new Error("WebGPU not supported");
}
context = ctx;
canvas_format = navigator.gpu.getPreferredCanvasFormat();
context.configure({ device, format: canvas_format, alphaMode: "opaque" });
create_pipelines();
sampler = device.createSampler({
magFilter: "nearest",
minFilter: "nearest",
addressModeU: "clamp-to-edge",
addressModeV: "clamp-to-edge",
});
stream_buffer = create_stream_buffer(8 * 1024 * 1024);
create_uniform_buffer(64);
create_white_texture();
create_lightmap();
}
// how bright the sky is, 1 at noon. only the lightmap changes, the chunk meshes stay the same
export function update_lightmap(daylight = 1) {
// minecraft's LightTexture, with its default brightness setting and no flicker
const gamma = 0.5;
const brightness = (level: number) => {
const f = level / 15;
return f / (4 - 3 * f);
};
const lerp = (from: number, to: number, t: number) => from + (to - from) * t;
const clamp = (value: number) => Math.min(1, Math.max(0, value));
const not_gamma = (value: number) => 1 - (1 - value) ** 4;
const sky_factor = daylight * 0.95 + 0.05;
// sky light turns blue as it gets dark
const sky_color = [lerp(daylight, 1, 0.35), lerp(daylight, 1, 0.35), 1];
const block_boost = 1.5;
const pixels = new Uint8Array(16 * 16 * 4);
for (let sky = 0; sky < 16; sky++) {
for (let block = 0; block < 16; block++) {
const s = brightness(sky) * sky_factor;
// block light is warm, it loses blue and green faster as it dims
const b = brightness(block) * block_boost;
const color = [
b + sky_color[0] * s,
b * ((b * 0.6 + 0.4) * 0.6 + 0.4) + sky_color[1] * s,
b * (b * b * 0.6 + 0.4) + sky_color[2] * s,
].map((c) => clamp(lerp(c, 0.75, 0.04)))
.map((c) => clamp(lerp(lerp(c, not_gamma(c), gamma), 0.75, 0.04)));
const i = (sky * 16 + block) * 4;
pixels[i] = Math.round(color[0] * 255);
pixels[i + 1] = Math.round(color[1] * 255);
pixels[i + 2] = Math.round(color[2] * 255);
pixels[i + 3] = 255;
for (let c = 0; c < 3; c++) lightmap_colors[(sky * 16 + block) * 3 + c] = pixels[i + c] / 255;
}
}
device.queue.writeTexture({ texture: lightmap }, pixels, { bytesPerRow: 16 * 4 }, [16, 16]);
}
export function begin_drawing() {
if (resize_pending) {
resize_pending = false;
resize_canvas();
}
const wanted_samples = render_debug.msaa ? SAMPLE_COUNT : 1;
if (wanted_samples !== sample_count) {
sample_count = wanted_samples;
create_pipelines();
}
render_stats = frame_stats;
frame_stats = empty_stats();
gpu_label = "other";
gpu_timer?.begin_frame();
encoder = device.createCommandEncoder();
frame_view = context.getCurrentTexture().createView();
ensure_render_targets();
update_2d_mvp();
stream_offset = 0;
uniform_slot = -1;
write_mvp();
pending_color_clear = true;
pending_depth_clear = true;
vert_index = 0;
}
export function end_drawing() {
flush_batch();
// make sure the frame gets cleared even if nothing was drawn
ensure_pass();
pass!.end();
pass = undefined;
gpu_timer?.resolve(encoder!);
device.queue.submit([encoder!.finish()]);
encoder = undefined;
canvas.present?.();
gpu_timer?.read();
for (const buffer of pending_destroy) {
buffer.destroy();
}
pending_destroy = [];
}
function update_2d_mvp() {
const w = canvas.width;
const h = canvas.height;
const l = 0;
const r = w;
const t = 0;
const b = h;
const n = -1;
const f = 1;
mat4.orthoZO(ortho, l, r, b, t, n, f);
}
// what the gpu work recorded from now on is timed as. with render_debug.split_passes the current pass ends here, so
// the next one is timed apart
export function gpu_section(label: string) {
gpu_label = label;
if (!render_debug.split_passes || !pass) return;
flush_batch();
pass.end();
pass = undefined;
}
export function begin_clip(x: number, y: number, width: number, height: number) {
flush_batch();
scissor = { x, y, width, height };
if (pass) {
apply_scissor(pass);
}
}
export function end_clip() {
flush_batch();
scissor = undefined;
if (pass) {
apply_scissor(pass);
}
}
export function begin_mode_3d(new_camera: Camera) {
flush_batch();
mode3d = true;
camera = new_camera;
update_camera();
write_mvp();
}
// 3d drawing in front of the camera instead of in the world, for the item in the player's hand: x right, y up, looking
// down -z. depth is cleared first, so it's never hidden inside a wall, like minecraft's first person hand
export function begin_view_model(fov: number) {
flush_batch();
if (pass) {
pass.end();
pass = undefined;
}
pending_depth_clear = true;
mode3d = true;
mat4.perspectiveZO(mvp, fov, canvas.width / canvas.height, 0.01, 10);
write_mvp();
}
// the lightmap's color for light packed as block light << 4 | sky light (see ClientLevel.get_light), what terrain
// lit like that is multiplied by. entities multiply it into their vertex colors, like minecraft's packed light coords
export function light_color(packed: number): [number, number, number] {
const i = ((packed & 15) * 16 + (packed >> 4)) * 3;
return [lightmap_colors[i], lightmap_colors[i + 1], lightmap_colors[i + 2]];
}
// the time rotating instances turn by, in ticks with the part of the next one (see ClientLevel.ticks). the frame's 3d
// drawing uses the time set before begin_mode_3d
export function set_render_time(ticks: number) {
render_time = ticks % RENDER_TIME_PERIOD;
}
// whether 3d drawing leaves out faces seen from behind, true unless turned off. off draws both sides, like entity
// models do, where a flat cube's one face is seen from either side and an open box shows its inside
export function set_face_culling(cull: boolean) {
if (cull_faces === cull) return;
flush_batch();
cull_faces = cull;
}
export function end_mode_3d() {
if (!mode3d) {
return;
}
flush_batch();
mode3d = false;
write_mvp();
}
export function clear_background(r: number, g: number, b: number, a = 1) {
flush_batch();
clear_color = { r, g, b, a };
// the clear happens when a render pass starts, so start a new one
if (pass) {
pass.end();
pass = undefined;
}
pending_color_clear = true;
}
export function flush_batch() {
if (vert_index === 0 || !current_texture) {
return;
}
const byte_length = vert_index * 4;
if (stream_offset + byte_length > stream_buffer.size) {
// the old buffer might still be used by draws in this frame, destroy it after the submit
pending_destroy.push(stream_buffer);
stream_buffer = create_stream_buffer(Math.max(stream_buffer.size * 2, byte_length));
stream_offset = 0;
}
device.queue.writeBuffer(stream_buffer, stream_offset, vertex_data, 0, vert_index);
draw(stream_buffer, stream_offset, vert_index / FLOATS_PER_VERT);
stream_offset += byte_length;
vert_index = 0;
}
// what's bound for terrain draws in the current pass, so drawing hundreds of chunks doesn't bind the same things
// again for each one. cleared whenever the pipeline changes
let terrain_binds:
| { slot: number; texture: GPUTexture; index_buffer: GPUBuffer; vertex_buffer: GPUBuffer }
| undefined;
// draws quads first to first + quad_count of a chunk mesh (4 vertices each). without an index buffer the quads are
// drawn in order
export function draw_terrain(
layer: RenderLayer,
vertex_buffer: GPUBuffer,
first: number,
quad_count: number,
index_buffer?: GPUBuffer,
) {
if (!current_texture || quad_count === 0) {
return;
}
if (!index_buffer) {
ensure_quad_indices(first + quad_count);
index_buffer = quad_index_buffer!;
}
const render_pass = ensure_pass();
const pipeline = terrain_pipelines[layer];
if (current_pipeline !== pipeline) {
render_pass.setPipeline(pipeline);
current_pipeline = pipeline;
terrain_binds = undefined;
}
if (!terrain_binds) {
render_pass.setBindGroup(2, lightmap_bind_group);
}
if (terrain_binds?.slot !== uniform_slot) {
render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]);
}
if (terrain_binds?.texture !== current_texture) {
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
}
if (terrain_binds?.index_buffer !== index_buffer) {
render_pass.setIndexBuffer(index_buffer, "uint32");
}
if (terrain_binds?.vertex_buffer !== vertex_buffer) {
render_pass.setVertexBuffer(0, vertex_buffer);
}
terrain_binds = { slot: uniform_slot, texture: current_texture, index_buffer, vertex_buffer };
render_pass.drawIndexed(quad_count * 6, 1, first * 6);
frame_stats.draw_calls += 1;
frame_stats.quads[layer] += quad_count;
}
// draws a model's quads (4 vertices each, see MODEL_VERTEX_BYTES) once for each of the first instance_count instances
// in instances (see INSTANCE_FLOATS), in one draw call. cut out like cutout terrain, or blended like translucent
// terrain, which needs drawing back to front
export function draw_instances(
model: GPUBuffer,
quad_count: number,
instances: GPUBuffer,
instance_count: number,
translucent = false,
) {
if (!current_texture || quad_count === 0 || instance_count === 0) {
return;
}
ensure_quad_indices(quad_count);
const render_pass = ensure_pass();
const pipeline = translucent ? instance_pipelines.translucent : instance_pipelines.cutout;
if (current_pipeline !== pipeline) {
render_pass.setPipeline(pipeline);
current_pipeline = pipeline;
terrain_binds = undefined;
}
render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]);
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
render_pass.setBindGroup(2, lightmap_bind_group);
render_pass.setIndexBuffer(quad_index_buffer!, "uint32");
render_pass.setVertexBuffer(0, model);
render_pass.setVertexBuffer(1, instances);
render_pass.drawIndexed(quad_count * 6, instance_count);
frame_stats.draw_calls += 1;
}
// copies data into part of a buffer made with create_vertex_buffer, from data's first to last element
export function write_buffer(
buffer: GPUBuffer,
byte_offset: number,
data: Float32Array | Uint8Array<ArrayBuffer>,
first: number,
count: number,
) {
device.queue.writeBuffer(buffer, byte_offset, data, first, count);
}
// the camera's view and projection, for frustum culling. only meaningful in 3d mode
export function view_projection(): Readonly<Float32Array> {
return mvp as Float32Array;
}
export function create_vertex_buffer(vertices: Float32Array<ArrayBuffer> | Uint8Array<ArrayBuffer>): GPUBuffer {
const buffer = device.createBuffer({
size: Math.max(4, vertices.byteLength),
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(buffer, 0, vertices);
return buffer;
}
// an empty vertex buffer of size bytes that copy_buffer can copy from and to
export function create_copyable_vertex_buffer(size: number): GPUBuffer {
return device.createBuffer({
size: Math.max(4, size),
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC,
});
}
// copies ranges of from into to on the gpu, as from offset, to offset and size in bytes, three numbers each. the copies
// happen before any later draw or write_buffer
export function copy_buffer(from: GPUBuffer, to: GPUBuffer, ranges: number[]) {
if (ranges.length === 0) return;
const copies = device.createCommandEncoder();
for (let i = 0; i < ranges.length; i += 3) {
copies.copyBufferToBuffer(from, ranges[i], to, ranges[i + 1], ranges[i + 2]);
}
device.queue.submit([copies.finish()]);
}
export function create_index_buffer(indices: Uint32Array): GPUBuffer {
const buffer = device.createBuffer({
size: Math.max(4, indices.byteLength),
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(buffer, 0, indices);
return buffer;
}
export function destroy_buffer(buffer: GPUBuffer) {
// it might be used by a draw thats not submitted yet
if (encoder) {
pending_destroy.push(buffer);
} else {
buffer.destroy();
}
}
// the space frames are shown in changed to view_width × view_height, or the fixed size did
export function resize_canvas(view_width = view_size.width, view_height = view_size.height) {
view_size = { width: view_width, height: view_height };
const width = fixed_canvas_size?.width ?? view_width;
const height = fixed_canvas_size?.height ?? view_height;
// a fixed size is shown as big as it fits in the window
const scale = Math.min(view_width / width, view_height / height);
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
// render targets get recreated at the start of the next frame
}
if (canvas.style) {
canvas.style.width = width * scale + "px";
canvas.style.height = height * scale + "px";
}
}
// frames are drawn at this size whatever the window's, like the benchmark's, or at the window's again when it's
// undefined. it changes at the start of the next frame, since resizing the canvas takes away the texture being drawn to
export function set_canvas_size(size: { width: number; height: number } | undefined) {
fixed_canvas_size = size;
resize_pending = true;
}
export function get_current_texture(): GPUTexture | null {
return current_texture;
}
export function set_current_texture(texture: GPUTexture) {
current_texture = texture;
}
// draws with texture from now on, flushing what was batched with another one first
export function use_texture(texture: GPUTexture) {
if (current_texture !== texture) {
flush_batch();
current_texture = texture;
}
}
export function create_texture(width: number, height: number): GPUTexture {
return device.createTexture({
size: [width, height],
format: "rgba8unorm",
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
});
}
export function push_vertex(px: number, py: number, pz: number, u: number, vv: number, r = 1, g = 1, b = 1, a = 1) {
let i = vert_index;
vertex_data[i++] = px;
vertex_data[i++] = py;
vertex_data[i++] = pz;
vertex_data[i++] = u;
vertex_data[i++] = vv;
vertex_data[i++] = r;
vertex_data[i++] = g;
vertex_data[i++] = b;
vertex_data[i++] = a;
vert_index = i;
}
export function push_quad(
dx: number,
dy: number,
dw: number,
dh: number,
u0: number,
v0: number,
u1: number,
v1: number,
r = 1,
g = 1,
b = 1,
a = 1,
) {
const x2 = dx + dw;
const y2 = dy + dh;
// triangle 1
push_vertex(dx, dy, 0, u0, v0, r, g, b, a);
push_vertex(x2, dy, 0, u1, v0, r, g, b, a);
push_vertex(dx, y2, 0, u0, v1, r, g, b, a);
// triangle 2
push_vertex(x2, dy, 0, u1, v0, r, g, b, a);
push_vertex(x2, y2, 0, u1, v1, r, g, b, a);
push_vertex(dx, y2, 0, u0, v1, r, g, b, a);
}
export function push_quad_vertices(
x0: number,
y0: number,
x1: number,
y1: number,
x2: number,
y2: number,
x3: number,
y3: number,
u0: number,
v0: number,
u1: number,
v1: number,
r = 1,
g = 1,
b = 1,
a = 1,
) {
// triangle 1
push_vertex(x0, y0, 0, u0, v0, r, g, b, a);
push_vertex(x1, y1, 0, u1, v0, r, g, b, a);
push_vertex(x2, y2, 0, u1, v1, r, g, b, a);
// triangle 2
push_vertex(x0, y0, 0, u0, v0, r, g, b, a);
push_vertex(x2, y2, 0, u1, v1, r, g, b, a);
push_vertex(x3, y3, 0, u0, v1, r, g, b, a);
}
// internal
function ensure_quad_indices(quad_count: number) {
if (quad_count <= quad_index_capacity) {
return;
}
if (quad_index_buffer) {
destroy_buffer(quad_index_buffer);
}
quad_index_capacity = Math.max(quad_count, quad_index_capacity * 2, 16384);
const indices = new Uint32Array(quad_index_capacity * 6);
for (let q = 0; q < quad_index_capacity; q++) {
const v = q * 4;
const i = q * 6;
indices[i] = v;
indices[i + 1] = v + 1;
indices[i + 2] = v + 2;
indices[i + 3] = v;
indices[i + 4] = v + 2;
indices[i + 5] = v + 3;
}
quad_index_buffer = create_index_buffer(indices);
}
function draw(buffer: GPUBuffer, offset: number, vertex_count: number) {
if (!current_texture || vertex_count === 0) {
return;
}
const render_pass = ensure_pass();
const pipeline = mode3d ? (cull_faces ? pipeline_3d : pipeline_3d_no_cull) : pipeline_2d;
if (current_pipeline !== pipeline) {
render_pass.setPipeline(pipeline);
current_pipeline = pipeline;
}
render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]);
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
render_pass.setVertexBuffer(0, buffer, offset);
render_pass.draw(vertex_count);
frame_stats.draw_calls += 1;
}
function ensure_pass(): GPURenderPassEncoder {
if (pass) {
return pass;
}
const multisampled = sample_count > 1;
pass = encoder!.beginRenderPass({
colorAttachments: [{
view: multisampled ? msaa_texture!.createView() : frame_view,
resolveTarget: multisampled ? frame_view : undefined,
clearValue: clear_color,
loadOp: pending_color_clear ? "clear" : "load",
storeOp: "store",
}],
depthStencilAttachment: {
view: depth_texture!.createView(),
depthClearValue: 1,
depthLoadOp: pending_depth_clear ? "clear" : "load",
depthStoreOp: "store",
},
timestampWrites: gpu_timer?.pass_writes(gpu_label),
});
frame_stats.passes += 1;
pending_color_clear = false;
pending_depth_clear = false;
current_pipeline = undefined;
terrain_binds = undefined;
apply_scissor(pass);
return pass;
}
function apply_scissor(render_pass: GPURenderPassEncoder) {
const target_width = depth_texture!.width;
const target_height = depth_texture!.height;
if (!scissor) {
render_pass.setScissorRect(0, 0, target_width, target_height);
return;
}
// webgpu errors on rects outside the target instead of clipping them
const x0 = Math.min(target_width, Math.max(0, Math.floor(scissor.x)));
const y0 = Math.min(target_height, Math.max(0, Math.floor(scissor.y)));
const x1 = Math.min(target_width, Math.max(x0, Math.ceil(scissor.x + scissor.width)));
const y1 = Math.min(target_height, Math.max(y0, Math.ceil(scissor.y + scissor.height)));
render_pass.setScissorRect(x0, y0, x1 - x0, y1 - y0);
}
function ensure_render_targets() {
const width = canvas.width;
const height = canvas.height;
if (
depth_texture && depth_texture.width === width && depth_texture.height === height &&
depth_texture.sampleCount === sample_count
) {
return;
}
msaa_texture?.destroy();
depth_texture?.destroy();
// without msaa the frame is drawn straight into the canvas
msaa_texture = sample_count > 1
? device.createTexture({
size: [width, height],
format: canvas_format,
sampleCount: sample_count,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
})
: undefined;
depth_texture = device.createTexture({
size: [width, height],
format: DEPTH_FORMAT,
sampleCount: sample_count,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
}
// puts the current matrix in a new uniform slot, earlier draws in the frame keep using theirs
function write_mvp() {
uniform_slot += 1;
if (uniform_slot * UNIFORM_SLOT_SIZE >= uniform_buffer.size) {
pending_destroy.push(uniform_buffer);
create_uniform_buffer((uniform_buffer.size / UNIFORM_SLOT_SIZE) * 2);
uniform_slot = 0;
}
uniform_data.set(mode3d ? mvp : ortho);
uniform_data[16] = render_time;
device.queue.writeBuffer(uniform_buffer, uniform_slot * UNIFORM_SLOT_SIZE, uniform_data);
}
function update_camera() {
if (!camera) {
return;
}
mat4.perspectiveZO(
proj,
camera.fov,
canvas.width / canvas.height,
camera.near,
camera.far,
);
mat4.identity(view);
mat4.rotateZ(view, view, -camera.roll);
mat4.rotateX(view, view, -camera.pitch);
mat4.rotateY(view, view, -camera.yaw);
mat4.translate(view, view, [-camera.x, -camera.y, -camera.z]);
mat4.multiply(mvp, proj, view);
}
function create_pipelines() {
const module = device.createShaderModule({ code: shader_src });
// made once, the bind groups made with them outlive pipelines made again for a new sample count
uniform_layout ??= device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: UNIFORM_FLOATS * 4 },
}],
});
texture_layout ??= device.createBindGroupLayout({
entries: [
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: {} },
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
],
});
const layout = device.createPipelineLayout({ bindGroupLayouts: [uniform_layout, texture_layout] });
const vertex: GPUVertexState = {
module,
entryPoint: "vs_main",
buffers: [{
arrayStride: VERTEX_STRIDE,
attributes: [
{ shaderLocation: 0, offset: 0, format: "float32x3" },
{ shaderLocation: 1, offset: 12, format: "float32x2" },
{ shaderLocation: 2, offset: 20, format: "float32x4" },
],
}],
};
const fragment: GPUFragmentState = {
module,
entryPoint: "fs_main",
targets: [{
format: canvas_format,
blend: {
color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
},
}],
};
const multisample: GPUMultisampleState = { count: sample_count };
pipeline_2d = device.createRenderPipeline({
layout,
vertex,
fragment,
multisample,
primitive: { topology: "triangle-list", cullMode: "none" },
depthStencil: { format: DEPTH_FORMAT, depthWriteEnabled: false, depthCompare: "always" },
});
const primitive_3d: GPUPrimitiveState = { topology: "triangle-list", cullMode: "back", frontFace: "ccw" };
const depth_3d: GPUDepthStencilState = {
format: DEPTH_FORMAT,
depthWriteEnabled: true,
depthCompare: "less-equal",
// same as the old polygonOffset(1, 1)
depthBias: 1,
depthBiasSlopeScale: 1,
};
pipeline_3d = device.createRenderPipeline({
layout,
vertex,
fragment,
multisample,
primitive: primitive_3d,
depthStencil: depth_3d,
});
pipeline_3d_no_cull = device.createRenderPipeline({
layout,
vertex,
fragment,
multisample,
primitive: { ...primitive_3d, cullMode: "none" },
depthStencil: depth_3d,
});
const terrain_module = device.createShaderModule({ code: terrain_shader_src });
const terrain_layout = device.createPipelineLayout({
bindGroupLayouts: [uniform_layout, texture_layout, texture_layout],
});
const terrain_vertex: GPUVertexState = {
module: terrain_module,
entryPoint: "vs_terrain",
buffers: [{
arrayStride: TERRAIN_VERTEX_BYTES,
attributes: [
{ shaderLocation: 0, offset: 0, format: "float32x3" },
{ shaderLocation: 1, offset: 12, format: "unorm16x2" },
{ shaderLocation: 2, offset: 16, format: "unorm8x4" },
{ shaderLocation: 3, offset: 20, format: "unorm8x2" },
],
}],
};
// like sodium and vanilla: solid and cutout don't blend, translucent blends and still writes depth
// since it's drawn sorted back to front
const terrain_pipeline = (
entryPoint: string,
blend?: GPUBlendState,
alphaToCoverageEnabled = false,
vertex = terrain_vertex,
) => device.createRenderPipeline({
layout: terrain_layout,
vertex,
fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] },
multisample: { ...multisample, alphaToCoverageEnabled },
primitive: primitive_3d,
depthStencil: depth_3d,
});
const blend: GPUBlendState = {
color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
};
terrain_pipelines = {
solid: terrain_pipeline("fs_solid"),
// alpha to coverage needs msaa
cutout: sample_count > 1
? terrain_pipeline("fs_cutout", undefined, true)
: terrain_pipeline("fs_cutout_discard"),
translucent: terrain_pipeline("fs_translucent", blend),
};
// instances are cut out like cutout terrain, or blended like translucent terrain, like a fluid's box
const instance_vertex: GPUVertexState = {
module: terrain_module,
entryPoint: "vs_instance",
buffers: INSTANCED_BUFFERS,
};
instance_pipelines = {
cutout: sample_count > 1
? terrain_pipeline("fs_cutout", undefined, true, instance_vertex)
: terrain_pipeline("fs_cutout_discard", undefined, false, instance_vertex),
translucent: terrain_pipeline("fs_translucent", blend, false, instance_vertex),
};
}
// how vs_instance reads a model's vertices and its instances
export const INSTANCED_BUFFERS: GPUVertexBufferLayout[] = [
{
arrayStride: MODEL_VERTEX_BYTES,
attributes: [
{ shaderLocation: 0, offset: 0, format: "float32x3" },
{ shaderLocation: 1, offset: 12, format: "unorm16x2" },
{ shaderLocation: 2, offset: 16, format: "unorm8x4" },
{ shaderLocation: 3, offset: 20, format: "snorm8x4" },
],
},
{
arrayStride: INSTANCE_FLOATS * 4,
stepMode: "instance",
attributes: [4, 5, 6, 7, 8, 9].map((location, i) => ({
shaderLocation: location,
offset: i * 16,
format: "float32x4" as const,
})),
},
];
function create_stream_buffer(size: number) {
return device.createBuffer({ size, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
}
function create_uniform_buffer(slots: number) {
uniform_buffer = device.createBuffer({
size: slots * UNIFORM_SLOT_SIZE,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
uniform_bind_group = device.createBindGroup({
layout: uniform_layout,
entries: [{ binding: 0, resource: { buffer: uniform_buffer, size: UNIFORM_FLOATS * 4 } }],
});
}
function get_texture_bind_group(texture: GPUTexture) {
let bind_group = texture_bind_groups.get(texture);
if (!bind_group) {
bind_group = device.createBindGroup({
layout: texture_layout,
entries: [
{ binding: 0, resource: texture.createView() },
{ binding: 1, resource: sampler },
],
});
texture_bind_groups.set(texture, bind_group);
}
return bind_group;
}
function create_lightmap() {
lightmap = create_texture(16, 16);
// linear, so light fades smoothly between levels across a face like in minecraft
const lightmap_sampler = device.createSampler({
magFilter: "linear",
minFilter: "linear",
addressModeU: "clamp-to-edge",
addressModeV: "clamp-to-edge",
});
lightmap_bind_group = device.createBindGroup({
layout: texture_layout,
entries: [
{ binding: 0, resource: lightmap.createView() },
{ binding: 1, resource: lightmap_sampler },
],
});
update_lightmap();
}
function create_white_texture() {
const tex = create_texture(1, 1);
device.queue.writeTexture({ texture: tex }, new Uint8Array([255, 255, 255, 255]), { bytesPerRow: 4 }, [1, 1]);
white_tex = tex;
}