summaryrefslogtreecommitdiff
path: root/examples/spheres/src/main.zig
diff options
context:
space:
mode:
Diffstat (limited to 'examples/spheres/src/main.zig')
-rw-r--r--examples/spheres/src/main.zig1134
1 files changed, 1134 insertions, 0 deletions
diff --git a/examples/spheres/src/main.zig b/examples/spheres/src/main.zig
new file mode 100644
index 0000000..60b498f
--- /dev/null
+++ b/examples/spheres/src/main.zig
@@ -0,0 +1,1134 @@
+//! spheres: the three-body problem, heard. Three bodies attract each other;
+//! the GPU integrates thousands of copies of them at once, each a hair
+//! apart, and draws them as a cloud around the one it follows in full, so
+//! chaos shows as the cloud spreading (and a stable orbit as it staying a
+//! thin line). Each body is also a voice, synthesised on the GPU from its
+//! motion: speed is pitch, the balance of its two distances is the
+//! modulator's ratio, and the nearness of its closest neighbour is the
+//! modulation depth, as sine, additive, AM, ring, FM or PM synthesis. The
+//! scope shows the result: an oscilloscope, the spectrum with each voice's
+//! predicted partials marked, and a spectrogram.
+//!
+//! Memory by lifetime: State is the preset, the transport and the
+//! synthesis settings, changed by `update` and replayable. Session holds the
+//! GPU objects, the sound on its way to the speakers and the scope. No
+//! Store: a run is not worth keeping.
+const std = @import("std");
+const sk = @import("sketch");
+const gpu = sk.abi.gpu;
+const scope = @import("scope");
+const layouts = @import("layouts");
+const shaders = @import("shaders");
+const chords = @import("chords.zig");
+
+pub const name = "spheres";
+pub const width = 1280;
+pub const height = 800;
+
+/// The audio stream's key.
+const stream = 1;
+/// How much sound is kept queued ahead: synthesised, read back, queued.
+const lead_seconds = 0.1;
+/// Systems integrated: system 0 and its cloud.
+const systems = layouts.max_systems;
+/// How far apart the copies start.
+const spread = 2e-4;
+const background = 0x05070d;
+/// Body colours; match the shaders' palette.
+const palette = [3]u24{ 0x66d9ff, 0xff73d1, 0xffcc59 };
+
+pub const Preset = enum {
+ figure_eight,
+ butterfly,
+ pythagorean,
+ lagrange,
+ random,
+
+ fn label(p: Preset) []const u8 {
+ return switch (p) {
+ .figure_eight => "figure eight",
+ .butterfly => "butterfly",
+ .pythagorean => "Pythagorean",
+ .lagrange => "Lagrange triangle",
+ .random => "random",
+ };
+ }
+};
+pub const Mode = layouts.Mode;
+pub const Scale = layouts.Scale;
+
+pub const State = struct {
+ preset: Preset = .figure_eight,
+ /// Starts the preset over, its copies spread with this seed.
+ reset: sk.Request(u32) = .{},
+ running: bool = true,
+ backward: bool = false,
+ /// Simulated time per second: a little under real time, so the
+ /// look-ahead's share of each frame keeps it well ahead.
+ speed: f32 = 0.7,
+ mode: Mode = .additive,
+ /// Where pitches snap: the more notes, the more chords.
+ scale: Scale = .diatonic,
+ muted: bool = false,
+ /// The voice whose partials the spectrum marks in full.
+ focus: u8 = 0,
+ /// Played as an instrument: chord pads, each sending the sky to the
+ /// nearest time its chord plays and holding the chord. Off, it runs on
+ /// by itself.
+ instrument: bool = false,
+ /// A chord to play, as its pitch classes (a grid button's).
+ chord: sk.Request(u16) = .{},
+};
+
+/// On the way to a pad's chord: where to, and how fast (simulated seconds
+/// a second).
+const Travel = struct { to: chords.Pick, speed: f64 };
+
+pub const Session = struct {
+ reset: sk.Handled = .{},
+ started: bool = false,
+ /// Synthesised samples not back from the GPU yet.
+ in_flight: usize = 0,
+ /// System 0 as last read back, and whether it has been.
+ lead: layouts.Lead = std.mem.zeroes(layouts.Lead),
+ have_lead: bool = false,
+ masses: [3]f32 = .{ 1, 1, 1 },
+ softening: f32 = 0.01,
+ /// The trail's newest slot, how many are filled, and the steps since its
+ /// last point.
+ trail_head: u32 = 0,
+ trail_filled: u32 = 0,
+ trail_carry: u32 = 0,
+ /// The camera: world point at the sky's centre, and the half-extent it
+ /// shows, smoothed.
+ center: [2]f32 = .{ 0, 0 },
+ extent: f32 = 1.5,
+ scope: scope.Scope = .{},
+ /// Simulated time since the preset started.
+ time: f64 = 0,
+ chord: sk.Handled = .{},
+ ahead: chords.Ahead = .{},
+ /// The scale the look-ahead's chords were found with.
+ scale: Scale = .diatonic,
+ travel: ?Travel = null,
+ /// The snapshot whose chord is held.
+ held: ?chords.Pick = null,
+ /// Samples still to come back from before a chord was chosen, dropped.
+ discard: usize = 0,
+ gpu: Gpu = .{},
+};
+
+const Gpu = struct {
+ ahead_state: sk.Buffer = .none,
+ snapshots: sk.Buffer = .none,
+ ahead_chords: sk.Buffer = .none,
+ ready: bool = false,
+ bodies: sk.Buffer = .none,
+ trail: sk.Buffer = .none,
+ voices: sk.Buffer = .none,
+ phases: sk.Buffer = .none,
+ lead: sk.Buffer = .none,
+ block: sk.Buffer = .none,
+ sky: sk.Image = .none,
+ overlay: sk.Image = .none,
+ size: [2]u32 = .{ 0, 0 },
+ clear_sky: bool = true,
+};
+
+/// Readback keys; from `chords_from`, look-ahead chords from that sample.
+const Readback = enum(u32) { audio = 1, lead = 2, _ };
+const chords_from = 0x10000;
+
+// ---------------------------------------------------------------------------
+// Layout.
+
+const Layout = struct {
+ w: f32,
+ h: f32,
+ narrow: bool,
+ sky: sk.Rect,
+ voices: sk.Rect,
+ oscilloscope: sk.Rect,
+ spectrum: sk.Rect,
+ spectrogram: sk.Rect,
+ /// As an instrument: the look-ahead's chords along time, and the grid.
+ strip: sk.Rect = .{},
+ grid: sk.Rect = .{},
+
+ const header = 36;
+ const Grid = chords.Grid;
+ /// The grid's columns on a phone: B flat to B, round C.
+ const narrow_columns = 8;
+ const narrow_first = 4;
+ /// Two rows of buttons, on a phone.
+ const toolbar = 104;
+ const per_row = buttons.len / 2;
+
+ /// Wide: the sky on the left, the sound on the right, buttons on top.
+ /// Narrow (a phone): the sky, then the sound, buttons along the bottom.
+ fn of(w: f32, h: f32, instrument: bool) Layout {
+ const narrow = w < 900;
+ if (narrow) {
+ const sky_h = @round(@min(w, h * if (instrument) @as(f32, 0.27) else 0.42));
+ const sky: sk.Rect = .{ .x = 0, .y = header, .w = w, .h = sky_h };
+ var y = sky.y + sky.h;
+ var strip: sk.Rect = .{};
+ var grid: sk.Rect = .{};
+ if (instrument) {
+ strip = .{ .x = 8, .y = y + 6, .w = w - 16, .h = 10 };
+ grid = .{ .x = 8, .y = strip.y + strip.h + 6, .w = w - 16, .h = Grid.rows * 36 - 4 };
+ y = grid.y + grid.h;
+ }
+ const voices: sk.Rect = .{ .x = 8, .y = y + 6, .w = w - 16, .h = 54 };
+ // As an instrument the grid takes the oscilloscope's room.
+ const oscilloscope: sk.Rect = if (instrument) .{ .x = 8, .y = voices.y + voices.h, .w = 0, .h = 0 } else .{ .x = 8, .y = voices.y + voices.h + 4, .w = w - 16, .h = 64 };
+ const spectrum: sk.Rect = .{ .x = 8, .y = oscilloscope.y + oscilloscope.h + 6, .w = w - 16, .h = if (instrument) 90 else 120 };
+ const rest = h - toolbar - (spectrum.y + spectrum.h + 22);
+ return .{ .w = w, .h = h, .narrow = true, .sky = sky, .voices = voices, .oscilloscope = oscilloscope, .spectrum = spectrum, .spectrogram = .{ .x = 8, .y = spectrum.y + spectrum.h + 18, .w = w - 16, .h = @max(rest, 40) }, .strip = strip, .grid = grid };
+ }
+ const sky_w = @round((w - 48) * 0.58);
+ const full: sk.Rect = .{ .x = 16, .y = header + 8, .w = sky_w, .h = h - header - 8 - 28 };
+ var sky = full;
+ var strip: sk.Rect = .{};
+ var grid: sk.Rect = .{};
+ if (instrument) {
+ const grid_h: f32 = Grid.rows * 30 - 4;
+ sky.h -= grid_h + 34;
+ strip = .{ .x = sky.x, .y = sky.y + sky.h + 8, .w = sky.w, .h = 10 };
+ grid = .{ .x = sky.x, .y = strip.y + strip.h + 8, .w = sky.w, .h = grid_h };
+ }
+ const x = sky.x + sky.w + 16;
+ const cw = w - 16 - x;
+ const voices: sk.Rect = .{ .x = x, .y = sky.y, .w = cw, .h = 66 };
+ const oscilloscope: sk.Rect = .{ .x = x, .y = voices.y + voices.h + 6, .w = cw, .h = 110 };
+ const spectrum: sk.Rect = .{ .x = x, .y = oscilloscope.y + oscilloscope.h + 10, .w = cw, .h = 210 };
+ const spectrogram_y = spectrum.y + spectrum.h + 20;
+ return .{ .w = w, .h = h, .narrow = false, .sky = sky, .voices = voices, .oscilloscope = oscilloscope, .spectrum = spectrum, .spectrogram = .{ .x = x, .y = spectrogram_y, .w = cw, .h = full.y + full.h - spectrogram_y }, .strip = strip, .grid = grid };
+ }
+
+ /// The grid's columns on screen: all twelve, or a phone's eight.
+ fn columns(l: Layout) struct { first: usize, count: usize } {
+ return if (l.narrow) .{ .first = narrow_first, .count = narrow_columns } else .{ .first = 0, .count = Grid.columns };
+ }
+
+ /// The button at `row` and grid `column`, if on screen: rows staggered
+ /// half a button right each, as on a sanfona.
+ fn key(l: Layout, row: usize, column: usize) ?sk.Rect {
+ const cols = l.columns();
+ if (column < cols.first or column >= cols.first + cols.count) return null;
+ const gap = 4;
+ const n: f32 = @floatFromInt(cols.count);
+ const w = (l.grid.w - (n - 1) * gap) / (n + @as(f32, Grid.rows - 1) * 0.5);
+ const h = (l.grid.h - (Grid.rows - 1) * gap) / Grid.rows;
+ const r: f32 = @floatFromInt(row);
+ const j: f32 = @floatFromInt(column - cols.first);
+ return .{ .x = l.grid.x + r * w * 0.5 + j * (w + gap), .y = l.grid.y + r * (h + gap), .w = w, .h = h };
+ }
+
+ fn keyAt(l: Layout, x: f32, y: f32) ?u16 {
+ for (0..Grid.rows) |row| for (0..Grid.columns) |column| {
+ if (l.key(row, column)) |r| if (r.contains(x, y)) return Grid.chord(row, column);
+ };
+ return null;
+ }
+
+ fn button(l: Layout, i: usize) sk.Rect {
+ const n: f32 = @floatFromInt(buttons.len);
+ const at: f32 = @floatFromInt(i);
+ if (l.narrow) {
+ const per: f32 = per_row;
+ const w = (l.w - 8 - (per - 1) * 4) / per;
+ const column = @mod(at, per);
+ const line = @floor(at / per);
+ return .{ .x = 4 + column * (w + 4), .y = l.h - toolbar + 6 + line * 48, .w = w, .h = 44 };
+ }
+ const w = 66;
+ return .{ .x = l.w - 16 - (n - at) * (w + 6) + 6, .y = 5, .w = w, .h = 26 };
+ }
+
+ fn buttonAt(l: Layout, x: f32, y: f32) ?Action {
+ for (buttons, 0..) |a, i| if (l.button(i).contains(x, y)) return a;
+ return null;
+ }
+};
+
+// ---------------------------------------------------------------------------
+// Update.
+
+const Action = enum { play, reverse, mode, preset, scale, mute, faster, slower, reset, focus, eight, random, instrument };
+
+const keys = [_]struct { sk.Key, Action }{
+ .{ .space, .play }, .{ .left, .reverse }, .{ .right, .reverse }, .{ .s, .mode }, .{ .p, .preset },
+ .{ .q, .scale }, .{ .m, .mute }, .{ .up, .faster }, .{ .down, .slower }, .{ .r, .reset },
+ .{ .tab, .focus }, .{ .e, .eight }, .{ .x, .random }, .{ .c, .instrument },
+};
+
+/// What touch screens reach by button; on a phone, in two rows of four.
+const buttons = [_]Action{ .play, .reverse, .mode, .mute, .eight, .random, .instrument, .scale };
+
+/// The computer keyboard as the grid: its rows are staggered like a
+/// sanfona's, so the number row plays majors, QWERTY minors, ASDF sevenths
+/// and ZXCV sus chords, column by column round the fifths.
+const grid_keys = [_][]const sk.Key{
+ &.{ .@"1", .@"2", .@"3", .@"4", .@"5", .@"6", .@"7", .@"8", .@"9", .@"0", .minus, .equals },
+ &.{ .q, .w, .e, .r, .t, .y, .u, .i, .o, .p, .left_bracket, .right_bracket },
+ &.{ .a, .s, .d, .f, .g, .h, .j, .k, .l, .semicolon, .apostrophe },
+ &.{ .z, .x, .c, .v, .b, .n, .m, .comma, .period, .slash },
+};
+
+fn isLetterOrDigit(k: sk.Key) bool {
+ const v = @intFromEnum(k);
+ return v >= @intFromEnum(sk.Key.a) and v <= @intFromEnum(sk.Key.@"0");
+}
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ // As an instrument, letters and digits play chords; Escape leaves.
+ if (s.instrument) {
+ for (grid_keys, 0..) |row, r| for (row, 0..) |k, column| {
+ if (in.pressed(k)) s.chord.send(chords.Grid.chord(r, column));
+ };
+ if (in.pressed(sk.Key.escape)) s.instrument = false;
+ }
+ for (keys) |k| if (in.pressed(k[0]) and !(s.instrument and isLetterOrDigit(k[0]))) {
+ // Left and right choose the way rather than flip it.
+ if (k[0] == .left) s.backward = true else if (k[0] == .right) s.backward = false else act(s, k[1]);
+ if (k[0] == .left or k[0] == .right) s.running = true;
+ };
+ const l = Layout.of(in.width, in.height, s.instrument);
+ for (in.events) |e| if (e.kind == .mouse_down and e.code == 1) {
+ if (l.buttonAt(e.x, e.y)) |a| act(s, a);
+ if (s.instrument) if (l.keyAt(e.x, e.y)) |chord| s.chord.send(chord);
+ };
+}
+
+fn act(s: *State, a: Action) void {
+ switch (a) {
+ .play => s.running = !s.running,
+ .reverse => {
+ s.backward = !s.backward;
+ s.running = true;
+ },
+ .mode => s.mode = @enumFromInt((@intFromEnum(s.mode) + 1) % @typeInfo(Mode).@"enum".field_names.len),
+ .preset => choose(s, @enumFromInt((@intFromEnum(s.preset) + 1) % @typeInfo(Preset).@"enum".field_names.len)),
+ .scale => s.scale = @enumFromInt((@intFromEnum(s.scale) + 1) % @typeInfo(Scale).@"enum".field_names.len),
+ .mute => s.muted = !s.muted,
+ .faster => s.speed = @min(s.speed * 1.25, 8),
+ .slower => s.speed = @max(s.speed / 1.25, 0.05),
+ .reset => s.reset.send(s.reset.value +% 1),
+ .focus => s.focus = (s.focus + 1) % 3,
+ .eight => choose(s, .figure_eight),
+ // A new seed each time: new bodies.
+ .random => choose(s, .random),
+ .instrument => s.instrument = !s.instrument,
+ }
+}
+
+fn choose(s: *State, p: Preset) void {
+ s.preset = p;
+ s.backward = false;
+ s.running = true;
+ s.reset.send(s.reset.value +% 1);
+}
+
+// ---------------------------------------------------------------------------
+// The presets.
+
+const Start = struct { masses: [3]f32, bodies: [3]layouts.Body, softening: f32 = 0.01 };
+
+fn start(p: Preset, seed: u32) Start {
+ return switch (p) {
+ // Chenciner and Montgomery's: three equal masses chasing each
+ // other round one figure of eight. Stable: the cloud stays thin.
+ .figure_eight => .{ .masses = .{ 1, 1, 1 }, .bodies = .{
+ .{ .pos = .{ 0.97000436, -0.24308753 }, .vel = .{ 0.46620368, 0.43236573 } },
+ .{ .pos = .{ -0.97000436, 0.24308753 }, .vel = .{ 0.46620368, 0.43236573 } },
+ .{ .pos = .{ 0, 0 }, .vel = .{ -0.93240737, -0.86473146 } },
+ } },
+ // Šuvakov and Dmitrašinović's butterfly I: periodic, and not stable.
+ .butterfly => .{ .masses = .{ 1, 1, 1 }, .bodies = .{
+ .{ .pos = .{ -1, 0 }, .vel = .{ 0.30689, 0.12551 } },
+ .{ .pos = .{ 1, 0 }, .vel = .{ 0.30689, 0.12551 } },
+ .{ .pos = .{ 0, 0 }, .vel = .{ -0.61378, -0.25102 } },
+ } },
+ // Burrau's: masses 3, 4 and 5 at rest on a 3-4-5 triangle. Close
+ // passes, chaos, and in the end two bodies leave as a pair.
+ .pythagorean => .{ .masses = .{ 3, 4, 5 }, .bodies = centred(.{ 3, 4, 5 }, .{
+ .{ .pos = .{ 1, 3 }, .vel = .{ 0, 0 } },
+ .{ .pos = .{ -2, -1 }, .vel = .{ 0, 0 } },
+ .{ .pos = .{ 1, -1 }, .vel = .{ 0, 0 } },
+ }) },
+ // Lagrange's equilateral solution, turning rigidly. For equal
+ // masses it is unstable: the cloud shows it coming apart.
+ .lagrange => blk: {
+ const speed: f32 = @sqrt(1.0 / @sqrt(3.0));
+ var bodies: [3]layouts.Body = undefined;
+ for (&bodies, 0..) |*b, i| {
+ const a = @as(f32, @floatFromInt(i)) * std.math.tau / 3;
+ b.* = .{ .pos = .{ @cos(a), @sin(a) }, .vel = .{ -@sin(a) * speed, @cos(a) * speed } };
+ }
+ break :blk .{ .masses = .{ 1, 1, 1 }, .bodies = bodies };
+ },
+ .random => blk: {
+ var rng: std.Random.DefaultPrng = .init(seed);
+ const r = rng.random();
+ var masses: [3]f32 = undefined;
+ var bodies: [3]layouts.Body = undefined;
+ for (&masses, &bodies) |*m, *b| {
+ m.* = 0.6 + 0.8 * r.float(f32);
+ b.* = .{ .pos = .{ 2 * r.float(f32) - 1, 2 * r.float(f32) - 1 }, .vel = .{ 0.6 * (r.float(f32) - 0.5), 0.6 * (r.float(f32) - 0.5) } };
+ }
+ break :blk .{ .masses = masses, .bodies = centred(masses, bodies) };
+ },
+ };
+}
+
+/// The bodies moved and pushed so their centre of mass sits still at 0.
+fn centred(masses: [3]f32, bodies: [3]layouts.Body) [3]layouts.Body {
+ var total: f32 = 0;
+ var p: [2]f32 = .{ 0, 0 };
+ var v: [2]f32 = .{ 0, 0 };
+ for (masses, bodies) |m, b| {
+ total += m;
+ for (0..2) |k| {
+ p[k] += m * b.pos[k];
+ v[k] += m * b.vel[k];
+ }
+ }
+ var out = bodies;
+ for (&out) |*b| for (0..2) |k| {
+ b.pos[k] -= p[k] / total;
+ b.vel[k] -= v[k] / total;
+ };
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Draw.
+
+pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
+ const in = f.in;
+ f.canvas(@intFromFloat(@max(in.window_width, 320)), @intFromFloat(@max(in.window_height, 400)));
+ f.clear(background);
+ if (!f.host.gpu()) {
+ f.text(16, 40, 2, "spheres needs a GPU: the host has none.", 0xff8080);
+ return;
+ }
+ const rate: f64 = @floatFromInt(in.sample_rate);
+ const dt: f32 = @floatCast(@min(@as(f64, @floatFromInt(in.dt)) / std.time.ns_per_s, 0.05));
+ const g = &ss.gpu;
+ setup(g, f);
+
+ // What came back: sound for the speakers and the scope, and system 0.
+ for (in.downloads) |d| switch (@as(Readback, @enumFromInt(d.key))) {
+ .audio => {
+ const samples = std.mem.bytesAsSlice(f32, d.bytes[0 .. d.bytes.len / 4 * 4]);
+ const aligned = f.scratch.alloc(f32, samples.len) catch continue;
+ for (aligned, samples) |*to, from| to.* = from;
+ ss.in_flight -|= aligned.len;
+ // Sound made before a chord was chosen is not played.
+ const dropped = @min(ss.discard, aligned.len);
+ ss.discard -= dropped;
+ f.audio(stream, aligned[dropped..], .{});
+ ss.scope.push(aligned[dropped..]);
+ },
+ .lead => if (d.bytes.len >= @sizeOf(layouts.Lead)) {
+ ss.lead = std.mem.bytesToValue(layouts.Lead, d.bytes[0..@sizeOf(layouts.Lead)]);
+ ss.have_lead = true;
+ },
+ _ => if (d.key >= chords_from) {
+ const words = f.scratch.alloc(u32, d.bytes.len / 4) catch continue;
+ @memcpy(std.mem.sliceAsBytes(words), d.bytes[0 .. words.len * 4]);
+ ss.ahead.arrived(d.key - chords_from, words);
+ },
+ };
+
+ if (!ss.started or ss.reset.take(s.reset) != null) restart(s, ss, f);
+ if (!s.instrument) {
+ ss.travel = null;
+ ss.held = null;
+ }
+ lookAhead(s, ss, f);
+
+ // A chord: the sound jumps to it now, the sky travels there.
+ if (ss.chord.take(s.chord)) |chord| if (s.instrument and ss.ahead.found[chord]) {
+ const root: u4 = if (chords.Grid.find(chord)) |at| chords.Grid.roots[at.column] else 0;
+ if (ss.ahead.nearest(chord, root, ss.time)) |pick| {
+ ss.held = pick;
+ ss.travel = .{ .to = pick, .speed = @max(@abs(pick.time() - ss.time) / 1.2, 2) };
+ f.audio(stream, &.{}, .{ .clear = true });
+ ss.discard = ss.in_flight;
+ }
+ };
+
+ // The simulation: as much simulated time as `speed` asks, either way;
+ // or, travelling to a chord, as fast as it takes to arrive in a second
+ // or so, where system 0 takes the snapshot's state. It runs every frame,
+ // still or not, so system 0 always sings: a held chord, or its motion.
+ var span: f64 = 0;
+ var adopt: u32 = 0;
+ if (ss.travel) |travel| {
+ const remaining = travel.to.time() - ss.time;
+ const step = travel.speed * dt;
+ if (@abs(remaining) <= step) {
+ adopt = travel.to.index() + 1;
+ ss.time = travel.to.time();
+ ss.travel = null;
+ } else span = std.math.sign(remaining) * step;
+ } else if (s.running and !(s.instrument and ss.held != null)) {
+ // Arrived at a chord, the sky holds still on the moment that sings it.
+ span = s.speed * dt * @as(f64, if (s.backward) -1 else 1);
+ }
+ const steps: u32 = @intFromFloat(@min(@ceil(@abs(span) / chords.base_step), 256));
+ var trail = trailPoints(ss, steps, span);
+ // Travelling back retraces system 0's own path: its trail rewinds rather
+ // than drawing over itself, as far as it reaches.
+ if (ss.travel != null and span < 0 and trail.points < ss.trail_filled) {
+ ss.trail_head = (ss.trail_head + layouts.trail - trail.points) % layouts.trail;
+ ss.trail_filled -= trail.points;
+ trail.points = 0;
+ }
+ f.compute(.{
+ .label = "sim.comp",
+ .kernel = sim_kernel,
+ .readonly = &.{g.snapshots},
+ .readwrite = &.{ g.bodies, g.trail, g.voices, g.lead },
+ .uniforms = gpu.uniform(f.scratch, layouts.SimParams{
+ .systems = systems,
+ .steps = steps,
+ .dt = if (steps > 0) @floatCast(span / @as(f64, @floatFromInt(steps))) else 0,
+ .softening = ss.softening,
+ .masses = .{ ss.masses[0], ss.masses[1], ss.masses[2], 0 },
+ .trail_head = (ss.trail_head + 1) % layouts.trail,
+ .trail_points = trail.points,
+ .trail_first = trail.first,
+ .trail_every = trail.every,
+ .quantize = @intFromEnum(s.scale),
+ .base = chords.base,
+ .speed_ref = chords.speed_ref,
+ .depth_scale = chords.depth_scale,
+ .couple_scale = chords.couple_scale,
+ .voice_source = if (ss.held) |h| h.index() + 1 else 0,
+ .adopt = adopt,
+ }),
+ .groups = .{ (systems + 63) / 64, 1, 1 },
+ });
+ ss.time += span;
+ ss.trail_head = (ss.trail_head + trail.points) % layouts.trail;
+ ss.trail_filled = @min(ss.trail_filled + trail.points, layouts.trail);
+ f.download(g.lead, .{ .size = @sizeOf(layouts.Lead), .key = @intFromEnum(Readback.lead) });
+
+ // The sound: enough to keep `lead_seconds` queued, counting what is
+ // still on its way back from the GPU.
+ const queued = in.stream(stream).queued + ss.in_flight;
+ const want: usize = @min(@as(usize, @intFromFloat(lead_seconds * rate)) -| queued, layouts.max_block);
+ if (want > 0) {
+ const params = gpu.uniform(f.scratch, layouts.SynthParams{
+ .count = @intCast(want),
+ .mode = @intFromEnum(s.mode),
+ .rate = @floatCast(rate),
+ // Loud enough for a phone's speaker; tanh rounds the peaks off.
+ .gain = if (s.muted) 0 else 1.4,
+ });
+ f.compute(.{
+ .label = "synth.comp",
+ .kernel = synth_kernel,
+ .readonly = &.{ g.voices, g.phases },
+ .readwrite = &.{g.block},
+ .uniforms = params,
+ .groups = .{ @intCast((want + 63) / 64), 1, 1 },
+ });
+ f.compute(.{ .label = "advance.comp", .kernel = advance_kernel, .readwrite = &.{ g.voices, g.phases }, .uniforms = params });
+ f.download(g.block, .{ .size = @intCast(want * @sizeOf(f32)), .key = @intFromEnum(Readback.audio) });
+ ss.in_flight += want;
+ }
+
+ const l = Layout.of(in.width, in.height, s.instrument);
+ follow(ss, dt);
+ drawSky(s, ss, f, l);
+ sound(s, ss, f, l, rate);
+ labels(s, ss, f, l, rate);
+}
+
+/// Simulated time between trail points: about a frame's at the default
+/// speed, and many points a frame when travelling.
+const trail_dt = 0.012;
+
+/// Which of this frame's `steps` leave trail points: every so many steps,
+/// carrying the remainder to the next frame, 64 at most.
+fn trailPoints(ss: *Session, steps: u32, span: f64) struct { points: u32, first: u32, every: u32 } {
+ if (steps == 0) return .{ .points = 0, .first = 1, .every = 1 };
+ const step_dt = @abs(span) / @as(f64, @floatFromInt(steps));
+ var every: u32 = @intFromFloat(@max(1, @round(trail_dt / step_dt)));
+ var first = every -| @min(ss.trail_carry, every - 1);
+ var points: u32 = if (first > steps) 0 else 1 + (steps - first) / every;
+ if (points > 64) {
+ every = (steps + 63) / 64;
+ first = every;
+ points = steps / every;
+ }
+ ss.trail_carry = if (points == 0) ss.trail_carry + steps else steps - (first + (points - 1) * every);
+ return .{ .points = points, .first = first, .every = every };
+}
+
+fn setup(g: *Gpu, f: *sk.Frame) void {
+ if (g.ready) return;
+ g.ready = true;
+ g.bodies = f.host.newBuffer(systems * layouts.bodies * @sizeOf(layouts.Body));
+ g.trail = f.host.newBuffer(layouts.bodies * layouts.trail * @sizeOf([2]f32));
+ g.voices = f.host.newBuffer(layouts.voices_len * @sizeOf([4]f32));
+ g.phases = f.host.newBuffer(3 * @sizeOf([4]f32));
+ g.lead = f.host.newBuffer(@sizeOf(layouts.Lead));
+ g.block = f.host.newBuffer(layouts.max_block * @sizeOf(f32));
+ g.ahead_state = f.host.newBuffer(layouts.alternatives * 3 * @sizeOf(layouts.Body));
+ g.snapshots = f.host.newBuffer(layouts.horizon * layouts.alternatives * 3 * @sizeOf(layouts.Body));
+ g.ahead_chords = f.host.newBuffer(layouts.horizon * layouts.alternatives * @sizeOf(u32));
+}
+
+fn lookParams(s: *const State, ss: *const Session, first: u32, count: u32) layouts.LookParams {
+ return .{
+ .alternatives = layouts.alternatives,
+ .first = first,
+ .count = count,
+ .horizon = layouts.horizon,
+ .masses = .{ ss.masses[0], ss.masses[1], ss.masses[2], 0 },
+ .softening = ss.softening,
+ .quantize = @intFromEnum(s.scale),
+ .base = chords.base,
+ .speed_ref = chords.speed_ref,
+ .depth_scale = chords.depth_scale,
+ .couple_scale = chords.couple_scale,
+ .sample_dt = chords.sample_dt,
+ };
+}
+
+/// The look-ahead: its futures a few samples further, their chords on
+/// their way back; and all the chords again when the scale changes.
+fn lookAhead(s: *const State, ss: *Session, f: *sk.Frame) void {
+ const g = &ss.gpu;
+ if (ss.scale != s.scale) {
+ ss.scale = s.scale;
+ const count = ss.ahead.asked * layouts.alternatives;
+ ss.ahead.forget();
+ if (count > 0) {
+ f.compute(.{
+ .label = "rechord.comp",
+ .kernel = rechord_kernel,
+ .readonly = &.{g.snapshots},
+ .readwrite = &.{g.ahead_chords},
+ .uniforms = gpu.uniform(f.scratch, lookParams(s, ss, 0, count)),
+ .groups = .{ (count + 63) / 64, 1, 1 },
+ });
+ f.download(g.ahead_chords, .{ .size = count * @sizeOf(u32), .key = chords_from });
+ }
+ }
+ if (ss.ahead.asked >= layouts.horizon) return;
+ const first = ss.ahead.asked;
+ const count: u32 = @min(chords.per_frame, layouts.horizon - first);
+ f.compute(.{
+ .label = "lookahead.comp",
+ .kernel = lookahead_kernel,
+ .readwrite = &.{ g.ahead_state, g.snapshots, g.ahead_chords },
+ .uniforms = gpu.uniform(f.scratch, lookParams(s, ss, first, count)),
+ });
+ f.download(g.ahead_chords, .{ .offset = first * layouts.alternatives * @sizeOf(u32), .size = count * layouts.alternatives * @sizeOf(u32), .key = chords_from + first });
+ ss.ahead.asked += count;
+}
+
+/// Puts the preset on the GPU: system 0 as given, the others each body
+/// moved by up to `spread`.
+fn restart(s: *const State, ss: *Session, f: *sk.Frame) void {
+ ss.started = true;
+ const p = start(s.preset, s.reset.value);
+ ss.masses = p.masses;
+ ss.softening = p.softening;
+ const all = f.scratch.alloc(layouts.Body, systems * layouts.bodies) catch return;
+ var rng: std.Random.DefaultPrng = .init(s.reset.value *% 0x9e3779b9 +% 1);
+ const r = rng.random();
+ for (0..systems) |i| for (0..3) |b| {
+ var body = p.bodies[b];
+ if (i > 0) for (&body.pos) |*x| {
+ x.* += spread * (2 * r.float(f32) - 1);
+ };
+ all[3 * i + b] = body;
+ };
+ f.upload(ss.gpu.bodies, 0, std.mem.sliceAsBytes(all));
+ // The voices glide from a quiet start, uncoupled; the trail starts empty.
+ const quiet = f.scratch.alloc([4]f32, layouts.voices_len) catch return;
+ for (quiet, 0..) |*v, i| v.* = if (i < layouts.coupling_previous) .{ 220, 1, 0, 0 } else .{ 0, 0, 0, 0 };
+ f.upload(ss.gpu.voices, 0, std.mem.sliceAsBytes(quiet));
+ const lead = f.scratch.create(layouts.Lead) catch return;
+ lead.* = std.mem.zeroes(layouts.Lead);
+ lead.bodies = p.bodies;
+ f.upload(ss.gpu.lead, 0, std.mem.asBytes(lead));
+ ss.lead = lead.*;
+ ss.have_lead = true;
+ ss.trail_filled = 0;
+ ss.trail_carry = 0;
+ // The look-ahead's futures: 0 as given, the rest nudged by growing
+ // amounts, so in a chaotic system they fan out.
+ const futures = f.scratch.alloc(layouts.Body, layouts.alternatives * 3) catch return;
+ for (0..layouts.alternatives) |a| for (0..3) |b| {
+ var body = p.bodies[b];
+ // Small enough that every future is recognisably this system,
+ // apart where chaos amplifies the difference.
+ const nudge = 2e-4 * @as(f32, @floatFromInt(a));
+ for (&body.pos) |*x| {
+ x.* += nudge * (2 * r.float(f32) - 1);
+ }
+ futures[3 * a + b] = body;
+ };
+ f.upload(ss.gpu.ahead_state, 0, std.mem.sliceAsBytes(futures));
+ ss.ahead.reset();
+ ss.scale = s.scale;
+ ss.time = 0;
+ ss.travel = null;
+ ss.held = null;
+ ss.gpu.clear_sky = true;
+ ss.extent = 1.5;
+}
+
+/// The camera keeps system 0's bodies in view: quick to widen, slow to
+/// close in.
+fn follow(ss: *Session, dt: f32) void {
+ var c: [2]f32 = .{ 0, 0 };
+ var total: f32 = 0;
+ for (ss.lead.bodies, ss.masses) |b, m| {
+ c[0] += m * b.pos[0];
+ c[1] += m * b.pos[1];
+ total += m;
+ }
+ c = .{ c[0] / total, c[1] / total };
+ var reach: f32 = 0;
+ for (ss.lead.bodies) |b| reach = @max(reach, @max(@abs(b.pos[0] - c[0]), @abs(b.pos[1] - c[1])));
+ const want = std.math.clamp(reach * 1.25, 1.2, 40);
+ const rate: f32 = if (want > ss.extent) 4 else 0.6;
+ ss.extent += (want - ss.extent) * (1 - @exp(-rate * dt));
+ for (&ss.center, c) |*x, to| x.* += (to - x.*) * (1 - @exp(-2 * dt));
+}
+
+const sim_kernel: gpu.Kernel = .{ .code = shaders.sim_comp, .readonly_buffers = 1, .readwrite_buffers = 4, .uniform_buffers = 1, .threads = .{ 64, 1, 1 } };
+const synth_kernel: gpu.Kernel = .{ .code = shaders.synth_comp, .readonly_buffers = 2, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 64, 1, 1 } };
+const advance_kernel: gpu.Kernel = .{ .code = shaders.advance_comp, .readwrite_buffers = 2, .uniform_buffers = 1, .threads = .{ 1, 1, 1 } };
+const lookahead_kernel: gpu.Kernel = .{ .code = shaders.lookahead_comp, .readwrite_buffers = 3, .uniform_buffers = 1, .threads = .{ 32, 1, 1 } };
+const rechord_kernel: gpu.Kernel = .{ .code = shaders.rechord_comp, .readonly_buffers = 1, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 64, 1, 1 } };
+
+const sky_pipelines = [_]gpu.Pipeline{
+ // 0: the fade, blended over what is there.
+ .{ .vertex = .{ .code = shaders.fullscreen_vert }, .fragment = .{ .code = shaders.fade_frag, .uniform_buffers = 1 }, .stride = 0, .attributes = &.{}, .blend = .premultiplied },
+ // 1: glows, added.
+ .{ .vertex = .{ .code = shaders.sprite_vert, .uniform_buffers = 1, .storage_buffers = 1 }, .fragment = .{ .code = shaders.sprite_frag }, .stride = 0, .attributes = &.{}, .blend = .additive },
+ // 2: trails, added.
+ .{ .vertex = .{ .code = shaders.trail_vert, .uniform_buffers = 1, .storage_buffers = 1 }, .fragment = .{ .code = shaders.trail_frag }, .stride = 0, .attributes = &.{}, .blend = .additive },
+ // 3: the cloud, layered: where copies crowd it takes their body's
+ // colour rather than adding up to white.
+ .{ .vertex = .{ .code = shaders.sprite_vert, .uniform_buffers = 1, .storage_buffers = 1 }, .fragment = .{ .code = shaders.sprite_frag }, .stride = 0, .attributes = &.{}, .blend = .premultiplied },
+ // 4: the coupling between the closest pair, added.
+ .{ .vertex = .{ .code = shaders.link_vert, .uniform_buffers = 1, .storage_buffers = 2 }, .fragment = .{ .code = shaders.link_frag }, .stride = 0, .attributes = &.{}, .blend = .additive },
+};
+
+/// The sky: the cloud of copies on a long exposure, and over it system 0's
+/// trails and bodies, drawn fresh each frame.
+fn drawSky(s: *const State, ss: *Session, f: *sk.Frame, l: Layout) void {
+ const g = &ss.gpu;
+ const size: [2]u32 = .{ @intFromFloat(@max(l.sky.w, 1)), @intFromFloat(@max(l.sky.h, 1)) };
+ if (g.sky == .none or g.size[0] != size[0] or g.size[1] != size[1]) {
+ if (g.sky != .none) f.host.freeImage(g.sky);
+ if (g.overlay != .none) f.host.freeImage(g.overlay);
+ g.sky = f.host.newImage(size[0], size[1]);
+ g.overlay = f.host.newImage(size[0], size[1]);
+ g.size = size;
+ g.clear_sky = true;
+ }
+ const bg = sk.Color.hex(background);
+ const bgf: [3]f32 = .{ @as(f32, @floatFromInt(bg.r)) / 255, @as(f32, @floatFromInt(bg.g)) / 255, @as(f32, @floatFromInt(bg.b)) / 255 };
+ const per_pixel = 2 * ss.extent / @as(f32, @floatFromInt(@min(size[0], size[1])));
+ const base: layouts.SkyView = .{
+ .center = ss.center,
+ .size = .{ @floatFromInt(size[0]), @floatFromInt(size[1]) },
+ .per_pixel = per_pixel,
+ .radius = 1.6,
+ .alpha = 0.06,
+ .first = 1,
+ .count = systems - 1,
+ .head = ss.trail_head,
+ .filled = ss.trail_filled,
+ .time = @floatCast(@mod(@as(f64, @floatFromInt(f.in.now)) / std.time.ns_per_s, 1000)),
+ };
+ var cloud = base;
+ cloud.radius = 2.2;
+ cloud.alpha = 0.18;
+ f.gpu(.{
+ .label = "sky cloud",
+ .image = g.sky,
+ .width = size[0],
+ .height = size[1],
+ .clear = if (g.clear_sky) .{ bgf[0], bgf[1], bgf[2], 1 } else null,
+ .pipelines = &sky_pipelines,
+ .draws = &.{
+ .{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = gpu.uniform(f.scratch, layouts.Fade{ .background = bgf, .amount = if (s.running) 0.08 else 0.02 }) },
+ .{ .pipeline = 3, .vertex_count = (systems - 1) * 3 * 6, .vertex_uniforms = gpu.uniform(f.scratch, cloud), .vertex_storage = &.{g.bodies} },
+ },
+ });
+ g.clear_sky = false;
+
+ var trails = base;
+ trails.radius = 2.2;
+ trails.alpha = 0.9;
+ // Points are 0.012 apart in time; anything this far is a jump.
+ trails.gap = @max(0.5, ss.extent * 0.25);
+ var link = base;
+ link.radius = 3;
+ link.alpha = 0.9;
+ var halo = base;
+ halo.first = 0;
+ halo.count = 1;
+ halo.radius = 34;
+ halo.alpha = 0.35;
+ var core = halo;
+ core.radius = 9;
+ core.alpha = 1;
+ f.gpu(.{
+ .label = "sky bodies",
+ .image = g.overlay,
+ .width = size[0],
+ .height = size[1],
+ .clear = .{ 0, 0, 0, 0 },
+ .pipelines = &sky_pipelines,
+ .draws = &.{
+ .{ .pipeline = 2, .vertex_count = 3 * (layouts.trail - 1) * 6, .vertex_uniforms = gpu.uniform(f.scratch, trails), .vertex_storage = &.{g.trail} },
+ .{ .pipeline = 4, .vertex_count = 6 * 6, .vertex_uniforms = gpu.uniform(f.scratch, link), .vertex_storage = &.{ g.bodies, g.voices } },
+ .{ .pipeline = 1, .vertex_count = 3 * 6, .vertex_uniforms = gpu.uniform(f.scratch, halo), .vertex_storage = &.{g.bodies} },
+ .{ .pipeline = 1, .vertex_count = 3 * 6, .vertex_uniforms = gpu.uniform(f.scratch, core), .vertex_storage = &.{g.bodies} },
+ },
+ });
+ f.image(g.sky, l.sky, .{});
+ f.image(g.overlay, l.sky, .{});
+}
+
+/// The scope: an oscilloscope steadied on the focused voice, the spectrum
+/// and the spectrogram.
+fn sound(s: *const State, ss: *Session, f: *sk.Frame, l: Layout, rate: f64) void {
+ const v = ss.lead.voices[s.focus];
+ const period: u32 = if (v.carrier > 1) @intFromFloat(@round(rate / v.carrier)) else 256;
+ ss.scope.draw(f, .{
+ .seconds = 8,
+ .spectrogram = l.spectrogram,
+ .spectrum = l.spectrum,
+ .oscilloscope = .{
+ .rect = l.oscilloscope,
+ .samples = std.math.clamp(4 * period, 256, 4096),
+ .end = @intCast(ss.scope.heard % @max(period, 1)),
+ },
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Text and marks.
+
+const dim = 0x7a8090;
+const bright = 0xe6e9ef;
+
+fn labels(s: *const State, ss: *const Session, f: *sk.Frame, l: Layout, rate: f64) void {
+ f.text(16, 10, 2, "spheres", 0xc9b6ff);
+ const room = if (l.narrow) l.w else l.button(0).x;
+ const lead = ss.lead;
+ const how = if (!s.running) " paused" else if (s.backward) " backwards" else "";
+ if (room > 420) {
+ f.print(140, 14, 1, dim, "{s} t {d:.1} energy {d:.4}{s}", .{ s.preset.label(), ss.time, lead.energy, how });
+ } else f.print(140, 14, 1, dim, "{s} t {d:.1}{s}", .{ s.preset.label(), ss.time, how });
+ for (buttons, 0..) |a, i| button(s, f, a, l.button(i));
+
+ // The voices, in their bodies' colours.
+ const v_rect = l.voices;
+ f.print(v_rect.x, v_rect.y, 1, bright, "{s} {s}", .{ modeName(s.mode), modeFormula(s.mode) });
+ for (lead.voices, 0..) |v, i| {
+ const y = v_rect.y + 16 + @as(f32, @floatFromInt(i)) * 14;
+ const mark = if (i == s.focus) ">" else " ";
+ const letter: u8 = 'A' + @as(u8, @intCast(i));
+ // Its role in the FM pair: modulating (silent), or modulated and by
+ // whom, at what index.
+ const row = lead.coupling[i];
+ var by: usize = 0;
+ for (0..3) |j| if (row[j] > row[by]) {
+ by = j;
+ };
+ const pushed = if (row[3] > 0.5)
+ f.format(" modulating", .{})
+ else if (row[by] > 0.05)
+ f.format(" FM by {c} {d:.2}", .{ @as(u8, 'A' + @as(u8, @intCast(by))), row[by] })
+ else
+ "";
+ if (l.narrow) {
+ f.print(v_rect.x, y, 1, palette[i], "{s}{c} {d:7.1} Hz r {d:4.2} d {d:5.2}{s}", .{ mark, letter, v.carrier, v.ratio, v.depth, pushed });
+ } else if (s.mode == .fm or s.mode == .pm) {
+ f.print(v_rect.x, y, 1, palette[i], "{s}{c} {d:7.1} Hz ratio {d:4.2} depth {d:5.2} index {d:5.2}{s}", .{ mark, letter, v.carrier, v.ratio, v.depth, index(s.mode, v), pushed });
+ } else f.print(v_rect.x, y, 1, palette[i], "{s}{c} {d:7.1} Hz ratio {d:4.2} depth {d:5.2}{s}", .{ mark, letter, v.carrier, v.ratio, v.depth, pushed });
+ }
+
+ // The spectrum's scale and each voice's partials where the theory puts
+ // them: the focused voice's all of them, the others' as small ticks.
+ spectrumMarks(s, ss, f, l.spectrum, rate);
+ instrumentView(s, ss, f, l);
+ f.text(l.oscilloscope.x + 4, l.oscilloscope.y + 4, 1, "oscilloscope", dim);
+ f.text(l.spectrogram.x + 4, l.spectrogram.y + 4, 1, "spectrogram, 8 s", sk.Color.white.alpha(150));
+ if (!l.narrow) f.text(16, l.h - 18, 1, if (s.instrument) "keys play the grid: 1 2 3 majors, Q W E minors, A S D sevenths, Z X C sus, by fifths ESC free SPACE pause" else "SPACE pause LEFT/RIGHT time's way UP/DOWN speed P/E/X preset C chords S synthesis Q scale M mute TAB voice R again", dim);
+}
+
+/// Grid rows' colours: majors gold, minors blue, sevenths orange, sus
+/// green, power chords violet.
+const row_colors = [chords.Grid.rows]u24{ 0xffcc59, 0x66b3ff, 0xff7a59, 0x69db7c, 0xb197fc };
+
+/// The chord sounding, over the sky; and as an instrument, the look-ahead's
+/// chords along time (system 0's own future) and the grid.
+fn instrumentView(s: *const State, ss: *const Session, f: *sk.Frame, l: Layout) void {
+ const Grid = chords.Grid;
+ var buf: [32]u8 = undefined;
+ const now = chords.chordOf(ss.lead.voices);
+ f.text(l.sky.x + 12, l.sky.y + 10, 2, f.format("{s}", .{chords.name(&buf, now)}), sk.Color.white.alpha(200));
+ if (!s.instrument) return;
+ f.print(l.sky.x + 12, l.sky.y + l.sky.h - 18, 1, sk.Color.white.alpha(120), "{d} chords found in {d} futures", .{ ss.ahead.distinct, layouts.alternatives });
+
+ const strip = l.strip;
+ const span = @as(f64, chords.horizon) * chords.sample_dt;
+ f.fill(strip, sk.Color.hex(0x10131c));
+ var t: u32 = 0;
+ while (t < ss.ahead.known) {
+ const sung = ss.ahead.sung[t][0];
+ const chord: u16 = if (sung.playable) sung.chord else 0;
+ var end = t + 1;
+ while (end < ss.ahead.known and @as(u16, if (ss.ahead.sung[end][0].playable) ss.ahead.sung[end][0].chord else 0) == chord) end += 1;
+ const x0 = strip.x + strip.w * @as(f32, @floatFromInt(t)) / chords.horizon;
+ const x1 = strip.x + strip.w * @as(f32, @floatFromInt(end)) / chords.horizon;
+ const color: sk.Color = if (Grid.find(chord)) |at| sk.Color.hex(row_colors[at.row]).alpha(170) else sk.Color.hex(0x2a2f3a);
+ f.fill(.{ .x = x0, .y = strip.y, .w = @max(x1 - x0, 1), .h = strip.h }, color);
+ t = end;
+ }
+ const at = struct {
+ fn x(r: sk.Rect, time: f64, total: f64) f32 {
+ return r.x + r.w * @as(f32, @floatCast(std.math.clamp(time / total, 0, 1)));
+ }
+ }.x;
+ if (ss.travel) |travel| f.fill(.{ .x = at(strip, travel.to.time(), span) - 1, .y = strip.y - 4, .w = 3, .h = strip.h + 8 }, sk.Color.hex(0xffd84d));
+ f.fill(.{ .x = at(strip, ss.time, span) - 1, .y = strip.y - 3, .w = 2, .h = strip.h + 6 }, sk.Color.white);
+
+ const held: ?u16 = if (ss.held) |h| ss.ahead.sung[h.sample][h.alternative].chord else null;
+ for (0..Grid.rows) |row| for (0..Grid.columns) |column| {
+ const r = l.key(row, column) orelse continue;
+ const chord = Grid.chord(row, column);
+ const found = ss.ahead.found[chord];
+ const lit = chord == now or chord == held;
+ const color = sk.Color.hex(row_colors[row]);
+ f.fill(r, if (lit) color.alpha(230) else if (found) color.alpha(70) else sk.Color.hex(0x12151d));
+ if (found) f.fill(.{ .x = r.x, .y = r.y + r.h - 2, .w = r.w, .h = 2 }, color);
+ const label = f.format("{s}{s}", .{ Grid.root_names[column], Grid.suffix(@enumFromInt(row)) });
+ const ink = if (lit) sk.Color.hex(0x05070d) else if (found) sk.Color.white else sk.Color.white.alpha(60);
+ f.text(r.x + (r.w - @as(f32, @floatFromInt(label.len * 8))) / 2, r.y + r.h / 2 - 4, 1, label, ink);
+ };
+}
+
+fn button(s: *const State, f: *sk.Frame, a: Action, r: sk.Rect) void {
+ const label: []const u8 = switch (a) {
+ .play => if (s.running) "PAUSE" else "PLAY",
+ .reverse => if (s.backward) "FWD" else "REV",
+ .mode => modeName(s.mode),
+ .preset => "NEXT",
+ .eight => "EIGHT",
+ .random => "RANDOM",
+ .instrument => if (s.instrument) "FREE" else "CHORDS",
+ .scale => switch (s.scale) {
+ .free => "UNSNAP",
+ .pentatonic => "PENTA",
+ .diatonic => "DIATON",
+ .chromatic => "CHROMA",
+ },
+ .mute => if (s.muted) "UNMUTE" else "MUTE",
+ else => "",
+ };
+ f.fill(r, sk.Color.hex(0x161a24));
+ f.fill(.{ .x = r.x, .y = r.y + r.h - 1, .w = r.w, .h = 1 }, sk.Color.hex(0x2e3440));
+ f.text(r.x + (r.w - @as(f32, @floatFromInt(label.len * 8))) / 2, r.y + r.h / 2 - 4, 1, label, bright);
+}
+
+fn modeName(m: Mode) []const u8 {
+ return switch (m) {
+ .sine => "SINE",
+ .additive => "ADD",
+ .am => "AM",
+ .ring => "RING",
+ .fm => "FM",
+ .pm => "PM",
+ };
+}
+
+fn modeFormula(m: Mode) []const u8 {
+ return switch (m) {
+ .sine => "sin c",
+ .additive => "sum r^(k-1) sin kc, r = d/(d+2)",
+ .am => "sin c (1 + a sin m)/(1 + a), a = min(d/4, 1)",
+ .ring => "sin c sin m",
+ .fm => "carrier swung d times its frequency by m: index d/ratio",
+ .pm => "sin(c + d sin m): index d",
+ };
+}
+
+/// The modulation index the theory works with: what sets the sidebands.
+fn index(m: Mode, v: layouts.Voice) f32 {
+ return switch (m) {
+ .fm => v.depth / @max(v.ratio, 1e-3),
+ .pm => v.depth,
+ else => 0,
+ };
+}
+
+/// A partial: frequency and amplitude relative to the voice's.
+const Partial = struct { hz: f64, amp: f64 };
+
+/// Where a voice's energy goes, by the textbook: FM and PM put
+/// |J_k(index)| at carrier + k modulator; AM puts a/2 at carrier ±
+/// modulator; ring modulation halves between the two; additive steps
+/// through harmonics.
+fn partials(m: Mode, v: layouts.Voice, out: []Partial) []Partial {
+ const fc: f64 = v.carrier;
+ const fm: f64 = fc * v.ratio;
+ var n: usize = 0;
+ switch (m) {
+ .sine => {
+ out[0] = .{ .hz = fc, .amp = 1 };
+ n = 1;
+ },
+ .additive => {
+ const r = v.depth / (v.depth + 2);
+ var norm: f64 = 0;
+ var w: f64 = 1;
+ for (0..16) |_| {
+ norm += w;
+ w *= r;
+ }
+ w = 1;
+ for (0..16) |k| {
+ out[n] = .{ .hz = fc * @as(f64, @floatFromInt(k + 1)), .amp = w / norm };
+ n += 1;
+ w *= r;
+ }
+ },
+ .am => {
+ const a = @min(v.depth / 4, 1);
+ out[0] = .{ .hz = fc, .amp = 1 / (1 + a) };
+ out[1] = .{ .hz = fc + fm, .amp = a / 2 / (1 + a) };
+ out[2] = .{ .hz = @abs(fc - fm), .amp = a / 2 / (1 + a) };
+ n = 3;
+ },
+ .ring => {
+ out[0] = .{ .hz = fc + fm, .amp = 0.5 };
+ out[1] = .{ .hz = @abs(fc - fm), .amp = 0.5 };
+ n = 2;
+ },
+ .fm, .pm => {
+ const beta: f64 = index(m, v);
+ var k: i32 = -12;
+ while (k <= 12) : (k += 1) {
+ out[n] = .{ .hz = @abs(fc + @as(f64, @floatFromInt(k)) * fm), .amp = @abs(bessel(@intCast(@abs(k)), beta)) };
+ n += 1;
+ }
+ },
+ }
+ return out[0..n];
+}
+
+/// A voice's partials with the FM pair's modulation on top: each of its own
+/// partials spread into sidebands |J_k(index)| at k times the modulating
+/// body's frequency (exact for sine and additive, whose harmonics all get
+/// the same push; a guide for the others).
+fn fmPair(m: Mode, v: layouts.Voice, voices: [3]layouts.Voice, row: [4]f32, own: []Partial, out: []Partial) []Partial {
+ const base = partials(m, v, own);
+ var by: usize = 0;
+ for (0..3) |j| if (row[j] > row[by]) {
+ by = j;
+ };
+ const beta: f64 = row[by];
+ if (beta < 0.05) return base;
+ const fm: f64 = voices[by].carrier;
+ var n: usize = 0;
+ for (base) |p| {
+ var k: i32 = -6;
+ while (k <= 6) : (k += 1) {
+ if (n == out.len) return out;
+ out[n] = .{ .hz = @abs(p.hz + @as(f64, @floatFromInt(k)) * fm), .amp = p.amp * @abs(bessel(@intCast(@abs(k)), beta)) };
+ n += 1;
+ }
+ }
+ return out[0..n];
+}
+
+/// J_n(x), the Bessel function of the first kind, by its series: enough
+/// terms for the indices here (x up to about 24).
+fn bessel(n: u32, x: f64) f64 {
+ const half = x / 2;
+ var term = std.math.pow(f64, half, @floatFromInt(n));
+ for (1..n + 1) |k| term /= @floatFromInt(k);
+ var sum = term;
+ for (1..80) |m| {
+ const mf: f64 = @floatFromInt(m);
+ term *= -half * half / (mf * (mf + @as(f64, @floatFromInt(n))));
+ sum += term;
+ if (@abs(term) < 1e-14 * @abs(sum) and m > 2 * @as(usize, @intFromFloat(@abs(x)))) break;
+ }
+ return sum;
+}
+
+fn spectrumMarks(s: *const State, ss: *const Session, f: *sk.Frame, r: sk.Rect, rate: f64) void {
+ for ([_]f64{ 50, 200, 1000, 5000, 20000 }) |hz| {
+ if (hz > scope.maxFreq(rate)) continue;
+ const x = r.x + scope.place(hz, rate) * r.w;
+ const label = if (hz >= 1000) f.format("{d}k", .{hz / 1000}) else f.format("{d}", .{hz});
+ f.text(@min(x + 3, r.x + r.w - 24), r.y + r.h + 4, 1, label, dim);
+ }
+ var own: [32]Partial = undefined;
+ var buf: [32 * 13]Partial = undefined;
+ for (ss.lead.voices, 0..) |v, i| {
+ const row = ss.lead.coupling[i];
+ if (row[3] > 0.5) continue;
+ const focused = i == s.focus;
+ const color = sk.Color.hex(palette[i]);
+ for (fmPair(s.mode, v, ss.lead.voices, row, &own, &buf)) |p| {
+ if (p.hz < scope.min_freq or p.hz > scope.maxFreq(rate) or p.amp < 1e-4) continue;
+ const x = @round(r.x + scope.place(p.hz, rate) * r.w);
+ // Level in dB of full scale, as the spectrum shows it.
+ const db = 20 * std.math.log10(@max(p.amp * v.amp, 1e-9));
+ const y = r.y + r.h * @as(f32, @floatCast(std.math.clamp(db / scope.floor_db, 0, 1)));
+ if (focused) {
+ f.fill(.{ .x = x, .y = y, .w = 1, .h = r.y + r.h - y }, color.alpha(70));
+ f.fill(.{ .x = x - 3, .y = y - 1, .w = 7, .h = 3 }, color.alpha(230));
+ } else f.fill(.{ .x = x - 2, .y = y, .w = 5, .h = 2 }, color.alpha(150));
+ }
+ }
+}
+
+test "the presets start with the centre of mass at rest" {
+ inline for (@typeInfo(Preset).@"enum".field_names) |field| {
+ const p = start(@field(Preset, field), 1);
+ var momentum: [2]f32 = .{ 0, 0 };
+ for (p.masses, p.bodies) |m, b| {
+ momentum[0] += m * b.vel[0];
+ momentum[1] += m * b.vel[1];
+ }
+ try std.testing.expectApproxEqAbs(@as(f32, 0), momentum[0], 1e-5);
+ try std.testing.expectApproxEqAbs(@as(f32, 0), momentum[1], 1e-5);
+ }
+}
+
+test "Bessel functions, against known values" {
+ try std.testing.expectApproxEqAbs(@as(f64, 1), bessel(0, 0), 1e-12);
+ try std.testing.expectApproxEqAbs(@as(f64, 0.7651976866), bessel(0, 1), 1e-9);
+ try std.testing.expectApproxEqAbs(@as(f64, 0.5767248078), bessel(1, 2), 1e-9);
+ // The first zero of J0: FM's carrier vanishes at index 2.405.
+ try std.testing.expectApproxEqAbs(@as(f64, 0), bessel(0, 2.404825558), 1e-8);
+ try std.testing.expectApproxEqAbs(@as(f64, -0.2459357645), bessel(0, 10), 1e-8);
+}
+
+test "PM's partials hold all the energy" {
+ var buf: [32]Partial = undefined;
+ var energy: f64 = 0;
+ for (partials(.pm, .{ .carrier = 220, .ratio = 1.5, .depth = 3, .amp = 1 }, &buf)) |p| energy += p.amp * p.amp;
+ try std.testing.expectApproxEqAbs(@as(f64, 1), energy, 1e-6);
+}