html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebGPU Static Ground with Light</title>
</head>
<body>
<canvas id="webgpu-canvas"></canvas>
<script type="module">
import * as glMatrix from 'https://cdn.jsdelivr.net/npm/gl-matrix@3.4.3/+esm';
const canvas = document.getElementById('webgpu-canvas');
// WebGPU initialization
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
const context = canvas.getContext('webgpu');
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format,
alphaMode: 'opaque'
});
// Vertex data: quad forming a 6x6 ground (two triangles)
const vertexData = new Float32Array([
// Positions // Normals
-3, 0, 3, 0, 1, 0,
3, 0, 3, 0, 1, 0,
3, 0, -3, 0, 1, 0,
-3, 0, -3, 0, 1, 0
]);
const vertexBuffer = device.createBuffer({
size: vertexData.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
});
device.queue.writeBuffer(vertexBuffer, 0, vertexData);
const indexData = new Uint16Array([0, 1, 2, 0, 2, 3]);
const indexBuffer = device.createBuffer({
size: indexData.byteLength,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST
});
device.queue.writeBuffer(indexBuffer, 0, indexData);
// Uniform buffer
const uniformBufferSize = 112; // 4x4 matrix (64) + 3 vec4 (16 each) = 112 bytes
const uniformBuffer = device.createBuffer({
size: uniformBufferSize,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});
// Vertex Shader
const vsCode = `
struct Uniforms {
mvp: mat4x4<f32>,
lightDir: vec3<f32>,
skyColor: vec3<f32>,
groundColor: vec3<f32>
};
struct VertexInput {
@location(0) position: vec3<f32>,
@location(1) normal: vec3<f32>
};
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@vertex
fn vs_main(input: VertexInput) -> @builtin(position) vec4<f32> {
return uniforms.mvp * vec4<f32>(input.position, 1.0);
}
`;
// Fragment Shader
const fsCode = `
struct Uniforms {
mvp: mat4x4<f32>,
lightDir: vec3<f32>,
skyColor: vec3<f32>,
groundColor: vec3<f32>
};
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@fragment
fn fs_main() -> @location(0) vec4<f32> {
let normal = vec3<f32>(0.0, 1.0, 0.0);
let blend = dot(normalize(normal), normalize(uniforms.lightDir)) * 0.5 + 0.5;
let color = mix(uniforms.groundColor, uniforms.skyColor, blend);
return vec4<f32>(color, 1.0);
}
`;
const vsModule = device.createShaderModule({ code: vsCode });
const fsModule = device.createShaderModule({ code: fsCode });
// Bind group layout
const bindGroupLayout = device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
buffer: { type: 'uniform' }
}]
});
const pipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout]
});
// Render pipeline
const pipeline = device.createRenderPipeline({
layout: pipelineLayout,
vertex: {
module: vsModule,
entryPoint: 'vs_main',
buffers: [{
arrayStride: 6 * 4, // 3 pos + 3 norm = 6 floats
attributes: [
{ shaderLocation: 0, offset: 0, format: 'float32x3' },
{ shaderLocation: 1, offset: 12, format: 'float32x3' }
]
}]
},
fragment: {
module: fsModule,
entryPoint: 'fs_main',
targets: [{ format }]
},
primitive: { topology: 'triangle-list' }
});
// Bind group
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [{
binding: 0,
resource: { buffer: uniformBuffer }
}]
});
// Update uniform buffer
function updateUniforms() {
const view = glMatrix.mat4.create();
glMatrix.mat4.lookAt(view, [0, 5, -5], [0, 0, 0], [0, 1, 0]);
const proj = glMatrix.mat4.create();
glMatrix.mat4.perspective(proj, Math.PI / 4, canvas.width / canvas.height, 0.1, 100);
const mvp = glMatrix.mat4.create();
glMatrix.mat4.multiply(mvp, proj, view);
const uniformData = new Float32Array(28); // 4x4 matrix (16) + 3 vec4 (4 each) = 28 floats
// MVP matrix
uniformData.set(mvp, 0);
// Light direction (0,1,0)
uniformData[16] = 0; uniformData[17] = 1; uniformData[18] = 0; uniformData[19] = 0;
// Sky color
uniformData[20] = 0.8; uniformData[21] = 0.9; uniformData[22] = 1.0; uniformData[23] = 0;
// Ground color
uniformData[24] = 0.1; uniformData[25] = 0.2; uniformData[26] = 0.3; uniformData[27] = 0;
device.queue.writeBuffer(uniformBuffer, 0, uniformData.buffer, uniformData.byteOffset, uniformData.byteLength);
}
updateUniforms();
// Render function
function render() {
const commandEncoder = device.createCommandEncoder();
const texture = context.getCurrentTexture();
const textureView = texture.createView();
const renderPass = commandEncoder.beginRenderPass({
colorAttachments: [{
view: textureView,
clearValue: { r: 0.0, g: 0.0, b: 0.0, a: 1 },
loadOp: 'clear',
storeOp: 'store'
}]
});
renderPass.setPipeline(pipeline);
renderPass.setVertexBuffer(0, vertexBuffer);
renderPass.setIndexBuffer(indexBuffer, 'uint16');
renderPass.setBindGroup(0, bindGroup);
renderPass.drawIndexed(6);
renderPass.end();
device.queue.submit([commandEncoder.finish()]);
}
render();
</script>
</body>
</html>
This code provides a clean and minimal foundation for rendering a lit 3D ground plane using WebGPU and custom shaders .