Using typescript, webgpu and other necessary libs create 3d Game Of Life. Write code, write shaders, make sure user can move camera around. Here is code I have so far:
async function init()
{
const canvas = document.getElementById('canvas') as HTMLCanvasElement;
const gpuContext = canvas.getContext('webgpu') as GPUCanvasContext;
if (!gpuContext)
{
console.error('WebGPU not supported');
return;
}
const adapter = await navigator.gpu.requestAdapter(
{
powerPreference: "high-performance"
});
if (!adapter) {
console.error('Failed to get GPU adapter');
return;
}
const device = await adapter.requestDevice();
}
init();
Assistant
Creating a 3D Game of Life using TypeScript and WebGPU involves several steps, including initializing WebGPU, setting up buffers and shaders, implementing the Game of Life logic (preferably using compute shaders for performance), rendering the 3D grid, and enabling camera controls for user interaction.
Below is a comprehensive example that demonstrates how to achieve this. This example leverages the gl-matrix library for matrix and vector operations, which simplifies handling transformations and camera movements.
Prerequisites
Browser Support: Ensure you're using a browser that supports WebGPU (e.g., recent versions of Chrome or Edge with WebGPU flags enabled).
Setup a Development Environment: Use a module bundler like Webpack or Parcel to handle TypeScript and module imports.
Install Dependencies:
bash
npm install gl-matrix
HTML Setup (index.html)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>3D Game of Life with WebGPU</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; width: 100vw; height: 100vh; }
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="module" src="main.js"></script>
</body>
</html>
TypeScript Code (main.ts)
typescript
import { mat4, vec3 } from 'gl-matrix';
// Vertex shader (WGSL)
const vertexShaderWGSL = `
struct Uniforms {
modelViewProjectionMatrix : mat4x4<f32>;
};
@binding(0) @group(0) var<uniform> uniforms : Uniforms;
struct VertexInput {
@location(0) position : vec3<f32>;
@location(1) color : vec3<f32>;
};
struct VertexOutput {
@builtin(position) Position : vec4<f32>;
@location(0) color : vec3<f32>;
};
@vertex
fn main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.Position = uniforms.modelViewProjectionMatrix * vec4<f32>(input.position, 1.0);
output.color = input.color;
return output;
}
`;
// Fragment shader (WGSL)
const fragmentShaderWGSL = `
@fragment
fn main(@location(0) color: vec3<f32>) -> @location(0) vec4<f32> {
return vec4<f32>(color, 1.0);
}
`;
// Compute shader for Game of Life (WGSL)
const computeShaderWGSL = `
struct CellGrid {
cells: array<u32>;
};
@binding(0) @group(0) var<storage, read> currentGrid: CellGrid;
@binding(1) @group(0) var<storage, read_write> nextGrid: CellGrid;
fn getNeighborCount(x: u32, y: u32, z: u32, sizeX: u32, sizeY: u32, sizeZ: u32) -> u32 {
var count: u32 = 0;
for(var dz: i32 = -1; dz <= 1; dz = dz + 1) {
for(var dy: i32 = -1; dy <= 1; dy = dy + 1) {
for(var dx: i32 = -1; dx <= 1; dx = dx + 1) {
if(dx == 0 && dy == 0 && dz == 0) { continue; }
let nx = (x + u32(dx) + sizeX) % sizeX;
let ny = (y + u32(dy) + sizeY) % sizeY;
let nz = (z + u32(dz) + sizeZ) % sizeZ;
count = count + currentGrid.cells[nz * sizeY * sizeX + ny * sizeX + nx];
}
}
}
return count;
}
@compute @workgroup_size(8, 8, 8)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let sizeX: u32 = 32;
let sizeY: u32 = 32;
let sizeZ: u32 = 32;
if(id.x >= sizeX || id.y >= sizeY || id.z >= sizeZ) { return; }
let idx = id.z * sizeY * sizeX + id.y * sizeX + id.x;
let cell = currentGrid.cells[idx];
let neighbors = getNeighborCount(id.x, id.y, id.z, sizeX, sizeY, sizeZ);
if(cell == 1) {
if(neighbors < 2 || neighbors > 3) {
nextGrid.cells[idx] = 0;
} else {
nextGrid.cells[idx] = 1;
}
} else {
if(neighbors == 3) {
nextGrid.cells[idx] = 1;
} else {
nextGrid.cells[idx] = 0;
}
}
}
`;
async function init() {
const canvas = document.getElementById('canvas') as HTMLCanvasElement;
const gpuContext = canvas.getContext('webgpu') as GPUCanvasContext;
if (!gpuContext) {
console.error('WebGPU not supported');
return;
}
const adapter = await navigator.gpu.requestAdapter({
powerPreference: "high-performance"
});
if (!adapter) {
console.error('Failed to get GPU adapter');
return;
}
const device = await adapter.requestDevice();
const contextFormat = navigator.gpu.getPreferredCanvasFormat(adapter);
gpuContext.configure({
device: device,
format: contextFormat,
alphaMode: "opaque",
});
// Define the size of the 3D grid
const GRID_SIZE_X = 32;
const GRID_SIZE_Y = 32;
const GRID_SIZE_Z = 32;
const TOTAL_CELLS = GRID_SIZE_X * GRID_SIZE_Y * GRID_SIZE_Z;
// Initialize cell grids
const initialGrid = new Uint32Array(TOTAL_CELLS);
// Initialize with a random configuration
for(let i = 0; i < TOTAL_CELLS; i++) {
initialGrid[i] = Math.random() > 0.8 ? 1 : 0;
}
// Create buffers for current and next grids
const currentGridBuffer = device.createBuffer({
size: initialGrid.byteLength,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC,
mappedAtCreation: true
});
new Uint32Array(currentGridBuffer.getMappedRange()).set(initialGrid);
currentGridBuffer.unmap();
const nextGridBuffer = device.createBuffer({
size: initialGrid.byteLength,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC,
mappedAtCreation: false
});
// Create uniform buffer for camera matrices
const uniformBufferSize = 64; // 4x4 matrix
const uniformBuffer = device.createBuffer({
size: uniformBufferSize,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
// Set up camera parameters
const cameraPosition = vec3.fromValues(0, 0, -100);
const cameraTarget = vec3.fromValues(0, 0, 0);
const up = vec3.fromValues(0, 1, 0);
const projectionMatrix = mat4.create();
const viewMatrix = mat4.create();
const modelMatrix = mat4.create();
const modelViewProjectionMatrix = mat4.create();
const updateCamera = () => {
mat4.lookAt(viewMatrix, cameraPosition, cameraTarget, up);
mat4.perspective(projectionMatrix, Math.PI / 4, canvas.clientWidth / canvas.clientHeight, 0.1, 1000.0);
mat4.multiply(modelViewProjectionMatrix, projectionMatrix, viewMatrix);
device.queue.writeBuffer(uniformBuffer, 0, modelViewProjectionMatrix as Float32Array);
};
updateCamera();
// Create shader modules
const vertexModule = device.createShaderModule({
code: vertexShaderWGSL
});
const fragmentModule = device.createShaderModule({
code: fragmentShaderWGSL
});
const computeModule = device.createShaderModule({
code: computeShaderWGSL
});
// Create bind group layouts
// For rendering
const renderBindGroupLayout = device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: {
type: 'uniform'
}
}]
});
// For compute
const computeBindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: 'read-only-storage'
}
},
{
binding: 1,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: 'read-write-storage'
}
}
]
});
// Create pipeline layouts
const renderPipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [renderBindGroupLayout]
});
const computePipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [computeBindGroupLayout]
});
// Create pipelines
const renderPipeline = device.createRenderPipeline({
layout: renderPipelineLayout,
vertex: {
module: vertexModule,
entryPoint: 'main',
buffers: [
{
arrayStride: 6 * 4, // vec3 position + vec3 color
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x3'
},
{
shaderLocation: 1,
offset: 3 * 4,
format: 'float32x3'
}
]
}
]
},
fragment: {
module: fragmentModule,
entryPoint: 'main',
targets: [
{
format: contextFormat
}
]
},
primitive: {
topology: 'triangle-list',
cullMode: 'back',
},
depthStencil: {
format: 'depth24plus',
depthWriteEnabled: true,
depthCompare: 'less',
}
});
const computePipeline = device.createComputePipeline({
layout: computePipelineLayout,
compute: {
module: computeModule,
entryPoint: 'main'
}
});
// Create bind groups
const renderBindGroup = device.createBindGroup({
layout: renderBindGroupLayout,
entries: [{
binding: 0,
resource: {
buffer: uniformBuffer
}
}]
});
const computeBindGroup = device.createBindGroup({
layout: computeBindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: currentGridBuffer
}
},
{
binding: 1,
resource: {
buffer: nextGridBuffer
}
}
]
});
// Create 3D grid mesh
const positions: number[] = [];
const colors: number[] = [];
const indices: number[] = [];
let index = 0;
for(let z = 0; z < GRID_SIZE_Z; z++) {
for(let y = 0; y < GRID_SIZE_Y; y++) {
for(let x = 0; x < GRID_SIZE_X; x++) {
const posX = x - GRID_SIZE_X / 2;
const posY = y - GRID_SIZE_Y / 2;
const posZ = z - GRID_SIZE_Z / 2;
const alive = initialGrid[z * GRID_SIZE_Y * GRID_SIZE_X + y * GRID_SIZE_X + x];
if(alive) {
// Add a cube for each alive cell
const cubeSize = 1.0;
const cube = createCube(posX, posY, posZ, cubeSize);
positions.push(...cube.positions);
colors.push(...cube.colors);
indices.push(...cube.indices.map(i => i + index));
index += cube.positions.length / 3;
}
}
}
}
// Create buffers for vertex data
const vertexData = new Float32Array([...positions, ...colors]);
const indexData = new Uint32Array(indices);
const vertexBuffer = device.createBuffer({
size: vertexData.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(vertexBuffer, 0, vertexData.buffer, initialGrid.bufferOffset, vertexData.byteLength);
const indexBuffer = device.createBuffer({
size: indexData.byteLength,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(indexBuffer, 0, indexData.buffer, initialGrid.bufferOffset, indexData.byteLength);
// Create depth texture
const depthTexture = device.createTexture({
size: [canvas.clientWidth, canvas.clientHeight],
format: 'depth24plus',
usage: GPUTextureUsage.RENDER_ATTACHMENT
});
// Handle window resize
window.addEventListener('resize', () => {
canvas.width = canvas.clientWidth * window.devicePixelRatio;
canvas.height = canvas.clientHeight * window.devicePixelRatio;
gpuContext.configure({
device: device,
format: contextFormat,
alphaMode: "opaque",
});
// Update depth texture
});
// Handle camera controls
let isDragging = false;
let previousMouseX = 0;
let previousMouseY = 0;
let yaw = 0; // rotation around Y axis
let pitch = 0; // rotation around X axis
canvas.addEventListener('mousedown', (e) => {
isDragging = true;
previousMouseX = e.clientX;
previousMouseY = e.clientY;
});
window.addEventListener('mouseup', () => {
isDragging = false;
});
window.addEventListener('mousemove', (e) => {
if (isDragging) {
const deltaX = e.clientX - previousMouseX;
const deltaY = e.clientY - previousMouseY;
previousMouseX = e.clientX;
previousMouseY = e.clientY;
yaw += deltaX * 0.005;
pitch += deltaY * 0.005;
// Limit pitch
pitch = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, pitch));
// Update camera position based on yaw and pitch
const radius = 100;
cameraPosition[0] = radius * Math.cos(pitch) * Math.sin(yaw);
cameraPosition[1] = radius * Math.sin(pitch);
cameraPosition[2] = radius * Math.cos(pitch) * Math.cos(yaw);
updateCamera();
}
});
// Create command encoder
const commandEncoder = device.createCommandEncoder();
// Main render loop
function frame() {
// Update Game of Life using compute shader
const computePass = commandEncoder.beginComputePass();
computePass.setPipeline(computePipeline);
computePass.setBindGroup(0, computeBindGroup);
const workgroupSizeX = Math.ceil(GRID_SIZE_X / 8);
const workgroupSizeY = Math.ceil(GRID_SIZE_Y / 8);
const workgroupSizeZ = Math.ceil(GRID_SIZE_Z / 8);
computePass.dispatchWorkgroups(workgroupSizeX, workgroupSizeY, workgroupSizeZ);
computePass.end();
// Swap buffers
const temp = currentGridBuffer;
currentGridBuffer = nextGridBuffer;
nextGridBuffer = temp;
// Update bind groups with new buffers
computeBindGroup = device.createBindGroup({
layout: computeBindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: currentGridBuffer
}
},
{
binding: 1,
resource: {
buffer: nextGridBuffer
}
}
]
});
// Render pass
const textureView = gpuContext.getCurrentTexture().createView();
const renderPass = commandEncoder.beginRenderPass({
colorAttachments: [{
view: textureView,
clearValue: { r: 0.1, g: 0.1, b: 0.1, a: 1.0 },
loadOp: 'clear',
storeOp: 'store',
}],
depthStencilAttachment: {
view: depthTexture.createView(),
depthClearValue: 1.0,
depthLoadOp: 'clear',
depthStoreOp: 'store',
}
});
renderPass.setPipeline(renderPipeline);
renderPass.setBindGroup(0, renderBindGroup);
renderPass.setVertexBuffer(0, vertexBuffer);
renderPass.setIndexBuffer(indexBuffer, 'uint32');
renderPass.drawIndexed(indexData.length, 1, 0, 0, 0);
renderPass.end();
device.queue.submit([commandEncoder.finish()]);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
// Utility function to create a cube
function createCube(x: number, y: number, z: number, size: number) {
const hs = size / 2;
const positions = [
// Front face
x - hs, y - hs, z + hs,
x + hs, y - hs, z + hs,
x + hs, y + hs, z + hs,
x - hs, y + hs, z + hs,
// Back face
x - hs, y - hs, z - hs,
x + hs, y - hs, z - hs,
x + hs, y + hs, z - hs,
x - hs, y + hs, z - hs,
];
const colors = [
// Front face (red)
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
// Back face (blue)
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
];
const indices = [
// Front face
0, 1, 2,
2, 3, 0,
// Top face
3, 2, 6,
6, 7, 3,
// Back face
7, 6, 5,
5, 4, 7,
// Bottom face
4, 5, 1,
1, 0, 4,
// Left face
4, 0, 3,
3, 7, 4,
// Right face
1, 5, 6,
6, 2, 1,
];
return { positions, colors, indices };
}
init();
Explanation
Shader Code:
Vertex Shader: Transforms each vertex position using the modelViewProjectionMatrix and passes the color to the fragment shader.
Fragment Shader: Outputs the color received from the vertex shader.
Compute Shader: Implements the Game of Life rules for a 3D grid. It reads from currentGrid, computes the next state based on neighbor counts, and writes to nextGrid.
Initialization:
WebGPU Setup: Retrieves the GPU adapter and device, configures the canvas context, and sets up buffers for the current and next grid states.
Grid Initialization: A 3D grid is initialized with random live (1) or dead (0) cells.
Buffers: Two storage buffers (currentGridBuffer and nextGridBuffer) store the state of the grid. A uniformBuffer holds the camera's combined model-view-projection matrix.
Shaders and Pipelines: Shader modules are created from the WGSL code. Render and compute pipelines are set up with appropriate bind group layouts.
Mesh Creation: For each live cell, a cube is created using the createCube utility function, generating vertex positions, colors, and indices.
Camera Controls: Basic mouse-based camera controls allow the user to rotate around the grid. The camera's position is updated based on mouse movements, and the view matrix is recalculated accordingly.
Depth Texture: A depth texture is created to handle 3D rendering correctly.
Rendering Loop:
Compute Pass: The compute pipeline runs to update the Game of Life grid each frame.
Render Pass: The rendering pipeline draws all live cells as cubes. The camera's view is updated based on user input.
Buffer Swapping: After each compute pass, the currentGridBuffer and nextGridBuffer are swapped to prepare for the next iteration.
Utility Functions:
createCube: Generates the vertex positions, colors, and indices for a cube at a given position.
Notes and Improvements
Performance: Rendering a large number of cubes can be performance-intensive. Consider using instancing or more optimized rendering techniques.
Interactivity: Extend camera controls to include zoom and pan. Implement UI controls to pause/resume the simulation or reset the grid.
Visualization Enhancements: Add lighting, shading, or different color schemes to enhance the visual appearance.
Compute Shader Optimization: Optimize the compute shader to handle larger grids efficiently, possibly using shared memory or better memory access patterns.
Final Thoughts
This example provides a foundational implementation of a 3D Game of Life using WebGPU and TypeScript. WebGPU is a powerful and low-level API, offering significant control over GPU operations, which is essential for compute-heavy tasks like simulations. As WebGPU continues to evolve, further optimizations and features will become available, enabling even more complex and efficient GPU-accelerated applications.