//! The drawing layer's low levels, mixed with today's Frame methods: many //! triangles tessellated into two `sk.draw.Tessellation`s (L1) and emitted //! as two `Command.shape`s (L0), between an `f.fill` and an `f.print`. //! Batching like this is the sketch's own choice, and changes nothing in //! the picture: both hosts draw the shapes of a batch one after another. const std = @import("std"); const sk = @import("sketch"); const vec = sk.math; pub const name = "flock"; pub const width = 640; pub const height = 360; const Boid = struct { position: vec.Vec = .{ 0, 0 }, velocity: vec.Vec = .{ 1, 0 }, }; pub const State = struct { rng: std.Random.Xoshiro256 = .init(7), boids: sk.List(Boid, 512) = .{}, clock: sk.Clock = .{}, }; pub fn update(s: *State, in: *const sk.Input) void { // Dragging adds boids, where the pointer was at each move. if (in.buttons & 1 != 0) for (in.events) |e| if (e.kind == .mouse_move) { const r = s.rng.random(); s.boids.appendBounded(.{ .position = .{ e.x, e.y }, .velocity = vec.unit(r.float(f32) * 2 * std.math.pi) }) catch {}; }; for (0..s.clock.steps(in)) |_| for (s.boids.slice()) |*b| { // Steer toward the centre, gently; wrap at the edges. const centre: vec.Vec = .{ width / 2, height / 2 }; b.velocity = vec.withLength(b.velocity + vec.withLength(centre - b.position, 0.03), 2); b.position += b.velocity; b.position = @mod(b.position + vec.Vec{ width, height }, vec.Vec{ width, height }); }; } const shape = [_]vec.Vec{ .{ 8, 0 }, .{ -8, -4 }, .{ -8, 4 } }; pub fn draw(s: *const State, f: *sk.Frame) void { f.clear(0xffffff); f.fill(.{ .x = 0, .y = height - 40, .w = width, .h = 40 }, 0xdcdcdc); // L0: a Frame method var bodies: sk.draw.Tessellation = .empty; // L1: our own triangles var edges: sk.draw.Tessellation = .empty; for (s.boids.constSlice()) |b| { const xf: vec.Affine = .place(b.position, vec.angle(b.velocity)); bodies.fillPolygon(f.scratch, &shape, xf) catch return; edges.strokePolygon(f.scratch, &shape, 1, xf) catch return; } f.shape(&bodies, .gray(127)); // L0 itself: the command, built by hand from the same data. f.emit(.{ .shape = .{ .color = .black, .points = edges.points.items, .ends = edges.ends.items, .indices = edges.indices.items } }); f.print(8, height - 30, 2, 0x000000, "{d} boids, drag to add", .{s.boids.len}); }