diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-16 21:28:20 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-16 21:28:20 -0300 |
| commit | 6933f99ddb2d7103515d26838496309a807bba26 (patch) | |
| tree | 991c2fe7d4a57957222876e190fa4d16a0fb889c /examples/noc/src/wolfram_ca.zig | |
| parent | 82fca5c9f29124f37f6dcd08e73e6999ce44a69d (diff) | |
| download | sketchbook-6933f99ddb2d7103515d26838496309a807bba26.tar.gz sketchbook-6933f99ddb2d7103515d26838496309a807bba26.zip | |
Move standalone sketches into sketchbook examples
Diffstat (limited to 'examples/noc/src/wolfram_ca.zig')
| -rw-r--r-- | examples/noc/src/wolfram_ca.zig | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/examples/noc/src/wolfram_ca.zig b/examples/noc/src/wolfram_ca.zig new file mode 100644 index 0000000..fd8fc63 --- /dev/null +++ b/examples/noc/src/wolfram_ca.zig @@ -0,0 +1,62 @@ +//! Nature of Code, Example 7.1: Wolfram Elementary Cellular Automaton +//! (rule 90). Processing paints one row a frame over the last frame's +//! pixels; here every frame is drawn from State, so State keeps every row. +const std = @import("std"); +const sk = @import("sketch"); + +pub const name = "wolfram_ca"; +pub const width = 640; +pub const height = 320; + +const w = 10; +const cols = width / w; +/// Processing stops once `generation * w > height`: rows 0 to 32. +const max_rows = height / w + 1; +const ruleset = [8]u1{ 0, 1, 0, 1, 1, 0, 1, 0 }; + +pub const State = struct { + rows: [max_rows][cols]u1 = initial(), + /// Rows drawn so far: Processing's `generation`. + generation: u32 = 0, + clock: sk.Clock = .{}, + + fn initial() [max_rows][cols]u1 { + var rows: [max_rows][cols]u1 = @splat(@splat(0)); + rows[0][cols / 2] = 1; + return rows; + } +}; + +fn rules(left: u1, me: u1, right: u1) u1 { + const index = @as(u3, left) << 2 | @as(u3, me) << 1 | right; + return ruleset[7 - @as(usize, index)]; +} + +pub fn update(s: *State, in: *const sk.Input) void { + for (0..s.clock.steps(in)) |_| if (s.generation < max_rows) { + // Processing draws `cells`, then computes the next generation. + if (s.generation > 0) { + const cells = s.rows[s.generation - 1]; + var next = cells; + for (1..cols - 1) |i| next[i] = rules(cells[i - 1], cells[i], cells[i + 1]); + s.rows[s.generation] = next; + } + s.generation += 1; + }; +} + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(0xffffff); + for (s.rows[0..s.generation], 0..) |cells, generation| { + for (1..cols - 1) |i| if (cells[i] == 1) { + // square(i * w, generation * w, w) with a 1px black stroke: the + // stroke adds half a pixel all round. + f.fill(sk.Rect{ + .x = @as(f32, @floatFromInt(i * w)) - 0.5, + .y = @as(f32, @floatFromInt(generation * w)) - 0.5, + .w = w + 1, + .h = w + 1, + }, 0x000000); + }; + } +} |
