09 Drawing in several passes
Feedback: one frame feeds the next
Game of Life: every cell reads its 8 neighbours from the last frame to decide whether it lives. Press and drag on the canvas to draw new cells.
04
0.050.7
Exercise
Drag the underlined numbers left and rightDrag numbers, or edit the code
// simulation shader: read the last frame, tPrevfloat n = 0.0;for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) if (x != 0 || y != 0) n += texture2D(tPrev, vUv + vec2(x, y) * texel).r;float alive = texture2D(tPrev, vUv).r;float next = (n == 3.0 || (alive > 0.5 && n == 2.0)) ? 1.0 : 0.0;// JS: swap the two textures each step (x steps/frame)[read, write] = [write, read];
ping-pongRead A, write B; next frame read B, write A. A texture cannot be read and written at the same time.JS side
A fragment shader cannot read pixels it is writing. Write the last frame into a texture and read it in the next — two textures swapping back and forth (ping-pong).
Try it
- Press and drag on the canvas to draw new cells
- Set the speed to 0 to pause the simulation
- Raise the initial density and look at the pattern once it settles