Jake Zohdi Developer
thumbnail

WebGPU Conway’s

Source:

https://github.com/jzohdi/portfolio/blob/main/src/lib/utils/experiments/gpu/conways-2d.ts

WebGPU is a modern graphics and compute API that provides low-level access to GPU resources. It allows efficient computation for tasks like Conway's Game of Life by leveraging parallelism. Unlike CPU-bound simulations, GPU-based approaches handle grid updates in parallel for better performance, especially on large grids.

Canvas and Grid Setup

The grid is defined as a 2D array (gridState), where each cell is either alive (1 for black) or dead (0 for white). The SQUARE_SIZE_PIXELS determines the size of each cell, while GRID_ROWS and GRID_COLS are calculated based on the canvas dimensions. The CELL_SIZE is normalized to device coordinates for rendering.

TYPESCRIPT

2. Rendering Pipeline

Vertex Shader

The vertex shader calculates the final position of each cell based on its position, scale, and a normalized square geometry. It also forwards the color to the fragment shader.

TYPESCRIPT

Fragment Shader

The fragment shader determines the pixel color for each cell.

TYPESCRIPT

Pipeline Configuration

The render pipeline connects the shaders and specifies vertex attributes (position, scale, and color).

TYPESCRIPT

Animation Loop

The render function is responsible for rendering the updated grid state and executing the animation loop using requestAnimationFrame.

  1. Grid Update: Every frame, the updateGrid function recalculates the grid state based on Conway's rules.
  2. Render Pass: A command encoder and render pass are used to draw the updated grid.
TYPESCRIPT