Okay, let's modify the previous WebGPU example to add mouse-controlled camera rotation around the ground plane. We'll use mouse events to track drag gestures and update the camera's position in a spherical coordinate system around the origin (where the ground is centered).
We'll need to:
- Track mouse state (dragging, previous position).
- Store camera parameters (like distance from origin, and angles for rotation).
- Listen for mouse
mousedown, mousemove, and mouseup events on the canvas.
- In
mousemove when dragging, calculate the mouse movement delta.
- Use the delta to update the camera's angles.
- Convert the camera's angles and distance into a Cartesian position.
- Update the
lookAt matrix in updateUniforms using the new camera position, keeping the look-at point fixed at the origin.
- Re-render the scene.
Here's the updated code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebGPU Static Ground with Light - Mouse Control</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; width: 100vw; height: 100vh; } /* Make canvas fill window */
</style>
</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');
// Ensure canvas size matches window size initially
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// --- WebGPU Initialization ---
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
alert("WebGPU not supported in this browser.");
throw new Error("WebGPU not supported");
}
const device = await adapter.requestDevice();
const context = canvas.getContext('webgpu');
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format,
alphaMode: 'opaque'
});
// --- Geometry Data ---
// Vertex data: quad forming a 6x6 ground (two triangles)
const vertexData = new Float32Array([
// Positions // Normals (all point up, for flat ground)
-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 ---
// MVP Matrix (mat4x4f) -> 16 * 4 = 64 bytes
// Light Direction (vec3f + padding) -> 4 * 4 = 16 bytes
// Sky Color (vec3f + padding) -> 4 * 4 = 16 bytes
// Ground Color (vec3f + padding) -> 4 * 4 = 16 bytes
const uniformBufferSize = 64 + 16 + 16 + 16; // = 112 bytes
const uniformBuffer = device.createBuffer({
size: uniformBufferSize,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});
// --- Shaders ---
const vsCode = `
struct Uniforms {
mvp: mat4x4<f32>,
lightDir: vec3<f32>, // Not used in this VS, but needed for bind group layout
skyColor: vec3<f32>, // Not used
groundColor: vec3<f32> // Not used
};
struct VertexInput {
@location(0) position: vec3<f32>,
@location(1) normal: vec3<f32> // Not used in this VS
};
@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);
}
`;
const fsCode = `
struct Uniforms {
mvp: mat4x4<f32>, // Not used in this FS
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> {
// Ground normal is always (0, 1, 0) in world space
let worldNormal = vec3<f32>(0.0, 1.0, 0.0);
// Basic hemispheric lighting model
// Blend between sky and ground color based on dot product with light direction
// Light direction is expected to be normalized
let lightAmount = dot(worldNormal, normalize(uniforms.lightDir));
// Map dot product (-1 to 1) to blend factor (0 to 1)
let blendFactor = lightAmount * 0.5 + 0.5;
let finalColor = mix(uniforms.groundColor, uniforms.skyColor, blendFactor);
return vec4<f32>(finalColor, 1.0);
}
`;
const vsModule = device.createShaderModule({ code: vsCode });
const fsModule = device.createShaderModule({ code: fsCode });
// --- Pipeline Setup ---
const bindGroupLayout = device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
buffer: { type: 'uniform' }
}]
});
const pipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout]
});
const pipeline = device.createRenderPipeline({
layout: pipelineLayout,
vertex: {
module: vsModule,
entryPoint: 'vs_main',
buffers: [{
// Positions + Normals
arrayStride: (3 + 3) * 4, // 6 floats * 4 bytes/float
attributes: [
{ shaderLocation: 0, offset: 0, format: 'float32x3' }, // Position
{ shaderLocation: 1, offset: 3 * 4, format: 'float32x3' } // Normal
]
}]
},
fragment: {
module: fsModule,
entryPoint: 'fs_main',
targets: [{ format }]
},
primitive: { topology: 'triangle-list' },
// Add depth testing for correct rendering, even though only one object
depthStencil: {
depthWriteEnabled: true,
depthCompare: 'less',
format: 'depth24plus', // Or 'depth32float' depending on device support
},
});
// Create depth texture
let depthTexture = device.createTexture({
size: [canvas.width, canvas.height],
format: 'depth24plus', // Match pipeline format
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
let depthTextureView = depthTexture.createView();
// --- Bind Group ---
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [{
binding: 0,
resource: { buffer: uniformBuffer }
}]
});
// --- Camera and Interaction Variables ---
// Start with initial position similar to [0, 5, -5]
// Convert [0, 5, -5] to spherical coordinates around origin (assuming +Y is up)
// radius = sqrt(0^2 + 5^2 + (-5)^2) = sqrt(50)
// Angle from +Y axis (phi): cos(phi) = y / radius = 5 / sqrt(50) = 1/sqrt(2) => phi = PI/4
// Angle around Y axis (theta): x = radius*sin(phi)*sin(theta), z = radius*sin(phi)*cos(theta)
// 0 = sqrt(50)*sin(PI/4)*sin(theta) => sin(theta)=0
// -5 = sqrt(50)*sin(PI/4)*cos(theta) => -5 = 5*cos(theta) => cos(theta)=-1
// sin(theta)=0, cos(theta)=-1 => theta = PI
let cameraRadius = Math.sqrt(50);
let cameraTheta = Math.PI; // Angle around Y axis (horizontal)
let cameraPhi = Math.PI / 4; // Angle from +Y axis (vertical, 0=up, PI=down)
let isDragging = false;
let lastMouseX = 0;
let lastMouseY = 0;
const mouseSensitivity = 0.005; // How much mouse movement changes angles
const phiMin = 0.01; // Prevent looking directly up/down (avoids issues near poles)
const phiMax = Math.PI - 0.01;
// --- Uniform Data Update Function ---
function updateUniforms() {
// Calculate camera position from spherical coordinates
const x = cameraRadius * Math.sin(cameraPhi) * Math.sin(cameraTheta);
const y = cameraRadius * Math.cos(cameraPhi);
const z = cameraRadius * Math.sin(cameraPhi) * Math.cos(cameraTheta);
const cameraPosition = [x, y, z];
const lookAtPoint = [0, 0, 0]; // Always look at the origin
const upVector = [0, 1, 0]; // Y is up
const view = glMatrix.mat4.create();
glMatrix.mat4.lookAt(view, cameraPosition, lookAtPoint, upVector);
const proj = glMatrix.mat4.create();
// Adjust aspect ratio based on current canvas size
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); // 16 for mat4, 3*4=12 for vec4s (with padding)
uniformData.set(mvp, 0); // MVP Matrix starts at index 0
// Light Direction (vec3, padded to vec4)
uniformData[16] = 0; uniformData[17] = 1; uniformData[18] = 0; uniformData[19] = 0; // {0, 1, 0, 0}
// Sky Color (vec3, padded to vec4)
uniformData[20] = 0.8; uniformData[21] = 0.9; uniformData[22] = 1.0; uniformData[23] = 0; // {0.8, 0.9, 1.0, 0} (light blue)
// Ground Color (vec3, padded to vec4)
uniformData[24] = 0.1; uniformData[25] = 0.2; uniformData[26] = 0.3; uniformData[27] = 0; // {0.1, 0.2, 0.3, 0} (dark grey/blue)
// Write uniform data to the buffer
device.queue.writeBuffer(uniformBuffer, 0, uniformData.buffer, uniformData.byteOffset, uniformData.byteLength);
}
// --- Render Function ---
function render() {
// Recreate depth texture if canvas size changed
if (depthTexture.width !== canvas.width || depthTexture.height !== canvas.height) {
depthTexture.destroy(); // Release old texture
depthTexture = device.createTexture({
size: [canvas.width, canvas.height],
format: 'depth24plus', // Match pipeline format
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
depthTextureView = depthTexture.createView();
// Also update uniforms for correct aspect ratio
updateUniforms();
}
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.0 }, // Clear to black
loadOp: 'clear',
storeOp: 'store'
}],
depthStencilAttachment: {
view: depthTextureView,
depthClearValue: 1.0, // Clear depth to 1.0 (farthest)
depthLoadOp: 'clear',
depthStoreOp: 'store',
},
});
renderPass.setPipeline(pipeline);
renderPass.setVertexBuffer(0, vertexBuffer);
renderPass.setIndexBuffer(indexBuffer, 'uint16');
renderPass.setBindGroup(0, bindGroup);
renderPass.drawIndexed(indexData.length); // Draw 6 indices (2 triangles)
renderPass.end();
device.queue.submit([commandEncoder.finish()]);
}
// --- Event Listeners for Mouse Interaction ---
canvas.addEventListener('mousedown', (e) => {
isDragging = true;
lastMouseX = e.clientX;
lastMouseY = e.clientY;
canvas.style.cursor = 'grabbing'; // Optional: change cursor style
});
canvas.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const dx = e.clientX - lastMouseX;
const dy = e.clientY - lastMouseY;
// Update theta (horizontal rotation around Y axis)
cameraTheta += dx * mouseSensitivity;
// Update phi (vertical rotation from +Y axis)
// Note: Increasing mouse Y typically moves camera down, which increases phi (moves away from +Y)
cameraPhi += dy * mouseSensitivity;
// Clamp phi to prevent flipping (0 to PI range, with small epsilon)
cameraPhi = Math.max(phiMin, Math.min(phiMax, cameraPhi));
// Optional: Wrap theta around 2PI
// cameraTheta = cameraTheta % (2 * Math.PI);
// if (cameraTheta < 0) cameraTheta += 2 * Math.PI;
lastMouseX = e.clientX;
lastMouseY = e.clientY;
// Update uniforms and re-render
updateUniforms();
render();
});
canvas.addEventListener('mouseup', () => {
isDragging = false;
canvas.style.cursor = 'grab'; // Optional: change cursor style back
});
// Handle mouse leaving the canvas while dragging
canvas.addEventListener('mouseleave', () => {
if (isDragging) {
isDragging = false;
canvas.style.cursor = 'grab';
}
});
// Handle window resizing
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// No need to call render here, it's called inside render() when depth texture is updated
// updateUniforms() is also called inside render() for aspect ratio
});
// --- Initial Setup and Render ---
// Set initial cursor style
canvas.style.cursor = 'grab';
// Perform the first update and render
updateUniforms();
render();
</script>
</body>
</html>
Key Changes and Explanations:
- HTML Styling: Added some basic CSS to make the canvas fill the window, which is standard for interactive full-screen graphics.
- Canvas Resizing: Added a
window.addEventListener('resize', ...) to update the canvas dimensions when the window is resized. The render function now checks if the canvas size has changed and recreates the depth texture and updates uniforms accordingly.
- Camera State: Introduced
cameraRadius, cameraTheta, and cameraPhi variables to track the camera's position in spherical coordinates relative to the origin [0,0,0].
cameraRadius: Distance from the origin.
cameraTheta: Horizontal angle around the Y-axis (like longitude).
cameraPhi: Vertical angle from the positive Y-axis (like latitude, 0 is straight up, PI is straight down).
- Initial values are derived from the original
[0, 5, -5] position relative to [0,0,0].
- Mouse State: Added
isDragging, lastMouseX, lastMouseY to manage the drag state.
- Mouse Sensitivity & Clamping:
mouseSensitivity controls how much mouse movement affects rotation speed. phiMin and phiMax are added to clamp the vertical angle (cameraPhi) to prevent the camera from going directly overhead or underneath (which can cause viewing matrix singularities and flipping).
- Mouse Event Listeners:
mousedown: Sets isDragging to true and records the starting mouse position.
mousemove: If isDragging is true, it calculates the horizontal (dx) and vertical (dy) movement since the last event. These deltas are used to update cameraTheta and cameraPhi, applying the mouseSensitivity. cameraPhi is clamped. The last mouse position is updated. Then, updateUniforms() and render() are called to reflect the camera change.
mouseup: Sets isDragging back to false.
mouseleave: Added to stop dragging if the mouse button is released outside the canvas boundary.
- Modification:
Now, when you open this HTML file, you should see the lit ground plane, and you can click and drag on the canvas to orbit the camera around the center of the ground.