Rendering performace on F3
This commit is contained in:
+103
-25
@@ -2,6 +2,7 @@ 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";
|
||||
|
||||
export let device: GPUDevice;
|
||||
export let canvas: HTMLCanvasElement;
|
||||
@@ -11,7 +12,11 @@ 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
|
||||
@@ -73,6 +78,23 @@ 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
|
||||
export const render_debug = { msaa: false, split_passes: 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 passes starting now are timed as
|
||||
let gpu_label = "other";
|
||||
|
||||
const shader_src = /* wgsl */ `
|
||||
struct Uniforms {
|
||||
mvp: mat4x4<f32>,
|
||||
@@ -151,8 +173,12 @@ fn vs_terrain(
|
||||
|
||||
fn lit(in: VertexOut) -> vec4<f32> {
|
||||
let texel = textureSample(texture0, sampler0, in.tex_coord);
|
||||
let light = textureSample(lightmap, lightmap_sampler, in.light).rgb;
|
||||
return vec4<f32>(texel.rgb * in.color.rgb * light, texel.a * in.color.a);
|
||||
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
|
||||
@@ -161,14 +187,26 @@ 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
|
||||
// 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 color = lit(in);
|
||||
if (color.a < 0.1) {
|
||||
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>(color.rgb, 1.0);
|
||||
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), 1.0);
|
||||
}
|
||||
|
||||
@fragment
|
||||
@@ -193,7 +231,10 @@ export async function init_window(canvas_element: HTMLCanvasElement) {
|
||||
if (!adapter) {
|
||||
throw new Error("No WebGPU adapter found");
|
||||
}
|
||||
device = await adapter.requestDevice();
|
||||
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);
|
||||
});
|
||||
@@ -266,6 +307,15 @@ export function update_lightmap(daylight = 1) {
|
||||
}
|
||||
|
||||
export function begin_drawing() {
|
||||
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();
|
||||
@@ -287,8 +337,10 @@ export function end_drawing() {
|
||||
|
||||
pass!.end();
|
||||
pass = undefined;
|
||||
gpu_timer?.resolve(encoder!);
|
||||
device.queue.submit([encoder!.finish()]);
|
||||
encoder = undefined;
|
||||
gpu_timer?.read();
|
||||
|
||||
for (const buffer of pending_destroy) {
|
||||
buffer.destroy();
|
||||
@@ -310,6 +362,16 @@ function update_2d_mvp() {
|
||||
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 };
|
||||
@@ -445,6 +507,8 @@ export function draw_terrain(
|
||||
|
||||
render_pass.setVertexBuffer(0, vertex_buffer);
|
||||
render_pass.drawIndexed(quad_count * 6, 1, first * 6);
|
||||
frame_stats.draw_calls += 1;
|
||||
frame_stats.quads[layer] += quad_count;
|
||||
}
|
||||
|
||||
// the camera's view and projection, for frustum culling. only meaningful in 3d mode
|
||||
@@ -620,6 +684,7 @@ function draw(buffer: GPUBuffer, offset: number, vertex_count: number) {
|
||||
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 {
|
||||
@@ -627,10 +692,11 @@ function ensure_pass(): GPURenderPassEncoder {
|
||||
return pass;
|
||||
}
|
||||
|
||||
const multisampled = sample_count > 1;
|
||||
pass = encoder!.beginRenderPass({
|
||||
colorAttachments: [{
|
||||
view: msaa_texture!.createView(),
|
||||
resolveTarget: frame_view,
|
||||
view: multisampled ? msaa_texture!.createView() : frame_view,
|
||||
resolveTarget: multisampled ? frame_view : undefined,
|
||||
clearValue: clear_color,
|
||||
loadOp: pending_color_clear ? "clear" : "load",
|
||||
storeOp: "store",
|
||||
@@ -641,7 +707,9 @@ function ensure_pass(): GPURenderPassEncoder {
|
||||
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;
|
||||
@@ -652,8 +720,8 @@ function ensure_pass(): GPURenderPassEncoder {
|
||||
}
|
||||
|
||||
function apply_scissor(render_pass: GPURenderPassEncoder) {
|
||||
const target_width = msaa_texture!.width;
|
||||
const target_height = msaa_texture!.height;
|
||||
const target_width = depth_texture!.width;
|
||||
const target_height = depth_texture!.height;
|
||||
|
||||
if (!scissor) {
|
||||
render_pass.setScissorRect(0, 0, target_width, target_height);
|
||||
@@ -673,23 +741,29 @@ function ensure_render_targets() {
|
||||
const width = canvas.width;
|
||||
const height = canvas.height;
|
||||
|
||||
if (msaa_texture && msaa_texture.width === width && msaa_texture.height === height) {
|
||||
if (
|
||||
depth_texture && depth_texture.width === width && depth_texture.height === height &&
|
||||
depth_texture.sampleCount === sample_count
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
msaa_texture?.destroy();
|
||||
depth_texture?.destroy();
|
||||
|
||||
msaa_texture = device.createTexture({
|
||||
size: [width, height],
|
||||
format: canvas_format,
|
||||
sampleCount: SAMPLE_COUNT,
|
||||
usage: GPUTextureUsage.RENDER_ATTACHMENT,
|
||||
});
|
||||
// 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,
|
||||
sampleCount: sample_count,
|
||||
usage: GPUTextureUsage.RENDER_ATTACHMENT,
|
||||
});
|
||||
}
|
||||
@@ -734,14 +808,15 @@ function update_camera() {
|
||||
function create_pipelines() {
|
||||
const module = device.createShaderModule({ code: shader_src });
|
||||
|
||||
uniform_layout = device.createBindGroupLayout({
|
||||
// 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: 64 },
|
||||
}],
|
||||
});
|
||||
texture_layout = device.createBindGroupLayout({
|
||||
texture_layout ??= device.createBindGroupLayout({
|
||||
entries: [
|
||||
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: {} },
|
||||
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
|
||||
@@ -772,7 +847,7 @@ function create_pipelines() {
|
||||
},
|
||||
}],
|
||||
};
|
||||
const multisample: GPUMultisampleState = { count: SAMPLE_COUNT };
|
||||
const multisample: GPUMultisampleState = { count: sample_count };
|
||||
|
||||
pipeline_2d = device.createRenderPipeline({
|
||||
layout,
|
||||
@@ -821,18 +896,21 @@ 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) =>
|
||||
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: { ...multisample, alphaToCoverageEnabled },
|
||||
primitive: primitive_3d,
|
||||
depthStencil: depth_3d,
|
||||
});
|
||||
terrain_pipelines = {
|
||||
solid: terrain_pipeline("fs_solid"),
|
||||
cutout: terrain_pipeline("fs_cutout"),
|
||||
// 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", {
|
||||
color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
||||
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// how long the gpu spends on each render pass, with timestamp queries, for the f3 performance window. passes are
|
||||
// labeled with the section they started in (see gpu_section in core.ts), and the results come back a few frames
|
||||
// later, when the gpu is done. chrome rounds timestamps to 0.1 ms unless it's started with
|
||||
// --enable-webgpu-developer-features
|
||||
|
||||
// passes timed per frame, the rest of a frame's aren't
|
||||
const MAX_PASSES = 32;
|
||||
// frames whose results can be on their way back at once. when they all are, the next frame isn't timed
|
||||
const READBACK_BUFFERS = 3;
|
||||
const WINDOW_MS = 1000;
|
||||
|
||||
export class GpuTimer {
|
||||
readonly supported: boolean;
|
||||
// ms per frame by label, averaged over the last window
|
||||
results = new Map<string, number>();
|
||||
total = 0;
|
||||
|
||||
#device: GPUDevice;
|
||||
#query_set: GPUQuerySet | undefined;
|
||||
#resolve_buffer: GPUBuffer | undefined;
|
||||
#free: GPUBuffer[] = [];
|
||||
#created = 0;
|
||||
// this frame's
|
||||
#labels: string[] = [];
|
||||
#readback: GPUBuffer | undefined;
|
||||
|
||||
#sums = new Map<string, number>();
|
||||
#frames = 0;
|
||||
#window_start = performance.now();
|
||||
|
||||
constructor(device: GPUDevice) {
|
||||
this.#device = device;
|
||||
this.supported = device.features.has("timestamp-query");
|
||||
if (this.supported) {
|
||||
this.#query_set = device.createQuerySet({ type: "timestamp", count: MAX_PASSES * 2 });
|
||||
this.#resolve_buffer = device.createBuffer({
|
||||
size: MAX_PASSES * 16,
|
||||
usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
begin_frame() {
|
||||
this.#labels = [];
|
||||
this.#readback = undefined;
|
||||
if (!this.supported) return;
|
||||
this.#readback = this.#free.pop();
|
||||
if (!this.#readback && this.#created < READBACK_BUFFERS) {
|
||||
this.#created += 1;
|
||||
this.#readback = this.#device.createBuffer({
|
||||
size: MAX_PASSES * 16,
|
||||
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// for a pass about to begin
|
||||
pass_writes(label: string): GPURenderPassTimestampWrites | undefined {
|
||||
if (!this.#readback || this.#labels.length >= MAX_PASSES) return undefined;
|
||||
const i = this.#labels.length;
|
||||
this.#labels.push(label);
|
||||
return { querySet: this.#query_set!, beginningOfPassWriteIndex: i * 2, endOfPassWriteIndex: i * 2 + 1 };
|
||||
}
|
||||
|
||||
// after the last pass ends, before the encoder finishes
|
||||
resolve(encoder: GPUCommandEncoder) {
|
||||
if (!this.#readback || this.#labels.length === 0) return;
|
||||
const count = this.#labels.length * 2;
|
||||
encoder.resolveQuerySet(this.#query_set!, 0, count, this.#resolve_buffer!, 0);
|
||||
encoder.copyBufferToBuffer(this.#resolve_buffer!, 0, this.#readback, 0, count * 8);
|
||||
}
|
||||
|
||||
// after the submit
|
||||
read() {
|
||||
const buffer = this.#readback;
|
||||
if (!buffer) return;
|
||||
const labels = this.#labels;
|
||||
if (labels.length === 0) {
|
||||
this.#free.push(buffer);
|
||||
return;
|
||||
}
|
||||
buffer.mapAsync(GPUMapMode.READ, 0, labels.length * 16).then(() => {
|
||||
const times = new BigUint64Array(buffer.getMappedRange(0, labels.length * 16));
|
||||
const frame = new Map<string, number>();
|
||||
labels.forEach((label, i) => {
|
||||
const ms = Math.max(0, Number(times[i * 2 + 1] - times[i * 2])) / 1e6;
|
||||
frame.set(label, (frame.get(label) ?? 0) + ms);
|
||||
});
|
||||
buffer.unmap();
|
||||
this.#free.push(buffer);
|
||||
this.#add_frame(frame);
|
||||
}).catch(() => {
|
||||
// the device was lost, nothing to time anymore
|
||||
});
|
||||
}
|
||||
|
||||
#add_frame(frame: Map<string, number>) {
|
||||
for (const [label, ms] of frame) this.#sums.set(label, (this.#sums.get(label) ?? 0) + ms);
|
||||
this.#frames += 1;
|
||||
const now = performance.now();
|
||||
if (now - this.#window_start < WINDOW_MS) return;
|
||||
this.results = new Map([...this.#sums].map(([label, ms]) => [label, ms / this.#frames]));
|
||||
this.total = [...this.results.values()].reduce((sum, ms) => sum + ms, 0);
|
||||
this.#sums.clear();
|
||||
this.#frames = 0;
|
||||
this.#window_start = now;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user