Pipeline to draw models !

This commit is contained in:
2026-10-14 00:10:58 -03:00
parent 6ad476ac18
commit d7f1b91c0a
9 changed files with 593 additions and 201 deletions
+139 -14
View File
@@ -24,6 +24,18 @@ 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;
@@ -31,6 +43,7 @@ let canvas_format: GPUTextureFormat;
let pipeline_2d: GPURenderPipeline;
let pipeline_3d: GPURenderPipeline;
let terrain_pipelines: Record<RenderLayer, GPURenderPipeline>;
let instance_pipeline: 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;
@@ -53,6 +66,9 @@ 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>();
@@ -139,9 +155,11 @@ fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
}
`;
const terrain_shader_src = /* wgsl */ `
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;
@@ -174,6 +192,43 @@ fn vs_terrain(
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);
@@ -423,6 +478,12 @@ export function light_color(packed: number): [number, number, number] {
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;
}
export function end_mode_3d() {
if (!mode3d) {
return;
@@ -514,6 +575,34 @@ export function draw_terrain(
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
export function draw_instances(model: GPUBuffer, quad_count: number, instances: GPUBuffer, instance_count: number) {
if (!current_texture || quad_count === 0 || instance_count === 0) {
return;
}
ensure_quad_indices(quad_count);
const render_pass = ensure_pass();
if (current_pipeline !== instance_pipeline) {
render_pass.setPipeline(instance_pipeline);
current_pipeline = instance_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, 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;
@@ -788,8 +877,9 @@ function write_mvp() {
uniform_slot = 0;
}
const matrix = mode3d ? mvp : ortho;
device.queue.writeBuffer(uniform_buffer, uniform_slot * UNIFORM_SLOT_SIZE, matrix as Float32Array);
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() {
@@ -824,7 +914,7 @@ function create_pipelines() {
entries: [{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: 64 },
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: UNIFORM_FLOATS * 4 },
}],
});
texture_layout ??= device.createBindGroupLayout({
@@ -907,15 +997,19 @@ function create_pipelines() {
};
// 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) =>
device.createRenderPipeline({
layout: terrain_layout,
vertex: terrain_vertex,
fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] },
multisample: { ...multisample, alphaToCoverageEnabled },
primitive: primitive_3d,
depthStencil: depth_3d,
});
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,
});
terrain_pipelines = {
solid: terrain_pipeline("fs_solid"),
// alpha to coverage needs msaa
@@ -927,8 +1021,39 @@ function create_pipelines() {
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
}),
};
// instances are cut out like cutout terrain
const instance_vertex: GPUVertexState = {
module: terrain_module,
entryPoint: "vs_instance",
buffers: INSTANCED_BUFFERS,
};
instance_pipeline = sample_count > 1
? terrain_pipeline("fs_cutout", undefined, true, instance_vertex)
: terrain_pipeline("fs_cutout_discard", undefined, 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 });
}
@@ -940,7 +1065,7 @@ function create_uniform_buffer(slots: number) {
});
uniform_bind_group = device.createBindGroup({
layout: uniform_layout,
entries: [{ binding: 0, resource: { buffer: uniform_buffer, size: 64 } }],
entries: [{ binding: 0, resource: { buffer: uniform_buffer, size: UNIFORM_FLOATS * 4 } }],
});
}