summaryrefslogtreecommitdiff
path: root/src/sketch
diff options
context:
space:
mode:
Diffstat (limited to 'src/sketch')
-rw-r--r--src/sketch/clock.zig2
-rw-r--r--src/sketch/request.zig2
-rw-r--r--src/sketch/root.zig175
-rw-r--r--src/sketch/sfxr.zig267
-rw-r--r--src/sketch/text.zig319
-rw-r--r--src/sketch/web.zig80
6 files changed, 797 insertions, 48 deletions
diff --git a/src/sketch/clock.zig b/src/sketch/clock.zig
index e64e2a8..2d63e12 100644
--- a/src/sketch/clock.zig
+++ b/src/sketch/clock.zig
@@ -85,7 +85,7 @@ test "N updates of one tick each step exactly as one update of N ticks" {
var sum: u32 = 0;
for (per) |n| sum += n;
try std.testing.expectEqual(sum, total);
- try std.testing.expectEqual(std.mem.toBytes(one), std.mem.toBytes(all));
+ try std.testing.expectEqualDeep(one, all);
try std.testing.expectEqual(@as(u32, Clock.max_steps), per[300]);
try std.testing.expectEqual(@as(u64, total), all.count);
}
diff --git a/src/sketch/request.zig b/src/sketch/request.zig
index 0b8b400..4a8e414 100644
--- a/src/sketch/request.zig
+++ b/src/sketch/request.zig
@@ -1,5 +1,5 @@
//! Requests from `update` that `draw` carries out once. `update` sees only
-//! State and input, so when a key should do something to Session or Store
+//! State and input, so when a key should do something to Session
//! (start the microphone, open a dialog, seek a stream), State holds the
//! request and Session remembers which ones it has handled:
//!
diff --git a/src/sketch/root.zig b/src/sketch/root.zig
index 52f05b2..490b2f9 100644
--- a/src/sketch/root.zig
+++ b/src/sketch/root.zig
@@ -7,18 +7,18 @@
//! pub const height = 600;
//! pub const State = struct { ... }; // saved, snapshotted, replayed: no pointers
//! pub const Session = struct { ... }; // this process: survives reloads
-//! pub const Store = struct { ... }; // on disk: survives restarts too
//! pub const commands = .{"hello"}; // console completions
//! pub fn init(state: *State, host: sk.Host) void
+//! pub fn setup(session: *Session, init: *sk.Init) !void
//! pub fn update(state: *State, in: *const sk.Input) void
-//! pub fn draw(state: *const State, session: *Session, store: *Store, f: *sk.Frame) void
-//! pub fn command(state: *State, store: *Store, c: *sk.Console, line: []const u8) !bool
+//! pub fn draw(state: *const State, session: *Session, f: *sk.Frame) void
+//! pub fn command(state: *State, session: *Session, c: *sk.Console, line: []const u8) !bool
//!
//! Functions take the parameters they name, by type, in any order: `draw`
-//! may ask for `*Session`, `*Store`, both or neither. `update` must be
+//! may ask for `*Session` or not. `update` must be
//! deterministic, so it gets `State` and `Input` only: the host replays
//! recorded input through it. `draw` presents state as pictures and sound,
-//! and changes only Session and Store. Geometry and colors are duck-typed:
+//! and changes only Session. Geometry and colors are duck-typed:
//! see `shape`.
const std = @import("std");
pub const abi = @import("abi");
@@ -40,7 +40,13 @@ pub const List = @import("list.zig").List;
/// Data computed in draw from a few State fields, kept in Session and rebuilt when they change (or after a reload).
pub const Derived = @import("derived.zig").Derived;
pub const web = @import("web.zig");
+/// Text measured and laid out anywhere (`update` too): `size`, `layout`,
+/// `font`, and the `Paragraph` `Frame.paragraph` draws.
+pub const text = @import("text.zig");
+/// sfxr's sound effects, rendered to samples for `host.newSound`.
+pub const sfxr = @import("sfxr.zig");
const request = @import("request.zig");
+const text_module = text;
pub const Request = request.Request;
pub const Handled = request.Handled;
@@ -59,6 +65,13 @@ pub const Voice = abi.Voice;
pub const BlendMode = abi.BlendMode;
pub const Face = abi.Face;
+/// Resource initialization, once per fresh Session (also when State is restored).
+/// No State, Input, scratch allocator, or drawing commands are available here.
+pub const Init = struct {
+ host: Host,
+ session: std.mem.Allocator,
+};
+
/// What `draw` receives: input, host services, memory by lifetime and the
/// command list. Commands may be built from anything: the methods copy what
/// they keep (text, GPU descriptions) into `scratch`, except bulk data
@@ -71,14 +84,12 @@ pub const Frame = struct {
scratch: std.mem.Allocator,
/// For Session: this process.
session: std.mem.Allocator,
- /// For Store: on disk, across restarts.
- store: std.mem.Allocator,
/// A library's own state for this frame (canim's table of places), in
/// `scratch`: null at each frame's start.
user: ?*anyopaque = null,
pub fn init(ctx: *const abi.Context) Frame {
- return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session, .store = ctx.store };
+ return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session };
}
pub fn emit(f: *Frame, command: abi.Command) void {
@@ -150,13 +161,23 @@ pub const Frame = struct {
pub fn blend(f: *Frame, mode: BlendMode) void {
f.emit(.{ .blend = mode });
}
+ /// Text from its top left corner, scale 1 a 13 px face; a `\n` starts
+ /// a line. `sk.text.size(.mono, scale, bytes)` is what it covers.
pub fn text(f: *Frame, x: f32, y: f32, scale: f32, bytes: []const u8, color: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes) } });
+ f.textIn(.mono, x, y, scale, bytes, color);
}
- /// `text` in another face of the built-in family: bold or italic mono,
- /// or the sans (`host.textSizeIn` measures it).
+ /// `text` in another face: bold or italic mono, the sans, JetBrains
+ /// Mono NL, or a sketch's own (`sk.text.font`).
pub fn textIn(f: *Frame, face: Face, x: f32, y: f32, scale: f32, bytes: []const u8, color: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face } });
+ if (std.mem.indexOfScalar(u8, bytes, '\n') != null) {
+ _ = f.paragraph(x, y, bytes, .{ .face = face, .scale = scale, .color = paint(color) });
+ } else f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face } });
+ }
+ /// A paragraph from its top left corner (`sk.text.Paragraph`: a width
+ /// to wrap at, alignment, spans, the glyphs revealed, a caret), drawn;
+ /// its `Layout` returned, as `sk.text.layout` gives it, from `x`, `y`.
+ pub fn paragraph(f: *Frame, x: f32, y: f32, bytes: []const u8, p: text_module.Paragraph) text_module.Layout {
+ return text_module.lay(f.keep(u8, bytes), p, x, y, f, &.{});
}
/// `textIn` laid out and rasterized at `raster` and drawn at `scale`,
/// its position not snapped to a pixel: for text under a moving
@@ -167,7 +188,7 @@ pub const Frame = struct {
f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face, .raster = raster } });
}
pub fn print(f: *Frame, x: f32, y: f32, scale: f32, color: anytype, comptime fmt: []const u8, args: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.format(fmt, args) } });
+ f.textIn(.mono, x, y, scale, f.format(fmt, args), color);
}
/// Formats into scratch memory.
pub fn format(f: *Frame, comptime fmt: []const u8, args: anytype) []const u8 {
@@ -201,9 +222,20 @@ pub const Frame = struct {
pub fn voice(f: *Frame, v: Voice) void {
f.emit(.{ .voice = v });
}
+ /// Scales every voice of `group` this frame (1 when not declared).
+ pub fn gain(f: *Frame, group: u3, value: f32) void {
+ f.emit(.{ .gain = .{ .group = group, .gain = value } });
+ }
pub fn audio(f: *Frame, key: u32, samples: []const f32, options: struct { clear: bool = false }) void {
f.emit(.{ .audio = .{ .key = key, .samples = samples, .clear = options.clear } });
}
+ /// Streams `count` samples a compute shader wrote to `buffer` (f32 from
+ /// `offset`) on stream `key`, as `audio` streams samples: a GPU synth's
+ /// output, heard without a readback of the sketch's own. Make
+ /// `in.lead -| in.stream(key).queued` of them a frame.
+ pub fn audioBuffer(f: *Frame, key: u32, buffer: abi.Buffer, options: struct { offset: u32 = 0, count: u32 }) void {
+ f.emit(.{ .audio_buffer = .{ .key = key, .buffer = buffer, .offset = options.offset, .count = options.count } });
+ }
pub fn pixels(f: *Frame, img: Image, w: u32, h: u32, rgba: []const u8, options: struct { premultiplied: bool = false }) void {
f.emit(.{ .pixels = .{ .image = img, .w = w, .h = h, .rgba = rgba, .premultiplied = options.premultiplied } });
}
@@ -223,6 +255,12 @@ pub const Frame = struct {
kept.draws = draws;
f.emit(.{ .gpu = kept });
}
+ /// Samples the source color and optionally depth into a distinct image.
+ pub fn postProcess(f: *Frame, source: Image, destination: Image, post: abi.gpu.PostProcess) void {
+ var kept = post;
+ kept.fragment_uniforms = f.keep(u8, post.fragment_uniforms);
+ f.emit(.{ .post_process = .{ .source = source, .target = destination, .effect = kept } });
+ }
/// `bytes` into a buffer made by `Host.newBuffer`.
pub fn upload(f: *Frame, buffer: abi.Buffer, offset: u32, bytes: []const u8) void {
f.emit(.{ .upload = .{ .buffer = buffer, .offset = offset, .bytes = bytes } });
@@ -270,12 +308,11 @@ fn paint(value: anytype) Color {
}
/// What `command` receives: somewhere to answer, the current input, and the
-/// allocators for Session and Store.
+/// allocator for Session.
pub const Console = struct {
host: Host,
in: *const Input,
session: std.mem.Allocator,
- store: std.mem.Allocator,
pub fn log(c: *Console, message: []const u8) void {
c.host.log(message);
@@ -285,29 +322,41 @@ pub const Console = struct {
}
};
+/// What the build knows of a sketch and passes to `sketch` and
+/// `exportSketch` (build.zig's generated roots fill it in).
+pub const Build = struct {
+ /// The repository revision the sketch was built from, "" when unknown.
+ source: []const u8 = "",
+ /// Keep history in the save (`abi.Info.record`).
+ record: bool = false,
+};
+
/// The entry points of `App`, for a host that links it statically.
-pub fn sketch(comptime App: type) abi.Sketch {
- const G = Glue(App);
- return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .update = G.update, .draw = G.draw, .command = G.command };
+pub fn sketch(comptime App: type, comptime made: Build) abi.Sketch {
+ const G = Glue(App, made);
+ return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .setup = G.setup, .update = G.update, .draw = G.draw, .command = G.command };
}
/// Exports `App` under `abi.Sketch.symbols`, for a hot-reloaded library.
-pub fn exportSketch(comptime App: type) void {
- const G = Glue(App);
+pub fn exportSketch(comptime App: type, comptime made: Build) void {
+ const G = Glue(App, made);
const names = abi.Sketch.symbols;
@export(&G.info, .{ .name = names.info });
@export(&G.defaults, .{ .name = names.defaults });
@export(&G.init, .{ .name = names.init });
+ @export(&G.setup, .{ .name = names.setup });
@export(&G.update, .{ .name = names.update });
@export(&G.draw, .{ .name = names.draw });
@export(&G.command, .{ .name = names.command });
+ @export(&G.build, .{ .name = "sketch_build" });
}
-pub fn Glue(comptime App: type) type {
+pub fn Glue(comptime App: type, comptime made: Build) type {
return struct {
pub const State = if (@hasDecl(App, "State")) App.State else struct {};
pub const Session = if (@hasDecl(App, "Session")) App.Session else struct {};
- pub const Store = if (@hasDecl(App, "Store")) App.Store else struct {};
+
+ const build: [abi.build.len:0]u8 = abi.build.*;
pub const description: abi.Info = .{
.abi = abi.hash,
@@ -316,8 +365,10 @@ pub fn Glue(comptime App: type) type {
.height = if (@hasDecl(App, "height")) App.height else 600,
.state = abi.layout.of(State, .state),
.session = abi.layout.of(Session, .session),
- .store = abi.layout.of(Store, .store),
.commands = if (@hasDecl(App, "commands")) &App.commands else &.{},
+ .source = made.source ++ " " ++ abi.build,
+ .record = made.record,
+ .audio_pull = if (@hasDecl(App, "audio_pull")) App.audio_pull else 0,
};
/// What a call can offer, by type.
@@ -325,12 +376,14 @@ pub fn Glue(comptime App: type) type {
ctx: *const abi.Context,
state: [*]u8,
frame: ?*Frame = null,
+ resource_init: ?*Init = null,
console: ?*Console = null,
line: []const u8 = "",
};
/// Calls `func` with the arguments its parameter types ask for.
fn call(comptime func: anytype, comptime name: []const u8, offer: Offer) @typeInfo(@TypeOf(func)).@"fn".return_type.? {
+ text_module.host = offer.ctx.host;
const F = @TypeOf(func);
var args: std.meta.ArgsTuple(F) = undefined;
inline for (@typeInfo(F).@"fn".param_types, 0..) |P, i| {
@@ -340,8 +393,11 @@ pub fn Glue(comptime App: type) type {
return std.mem.eql(u8, name, n);
}
};
- if (comptime is.named("update") and (T == *Session or T == *Store))
+ if (comptime is.named("update") and T == *Session)
@compileError("update must be deterministic: it gets State and Input only, so a replay reproduces it");
+ if (comptime is.named("setup") and (T == *State or T == *const State or T == *const Input))
+ @compileError("setup initializes resources: it gets Session, Init and Host only");
+ if (comptime (T == *Init or T == *const Init) and !is.named("setup")) @compileError(name ++ " gets no Init: only setup does");
if (comptime is.named("draw") and T == *State) @compileError("draw only reads State: take *const State");
if (comptime T == *Frame and !is.named("draw")) @compileError(name ++ " gets no Frame: only draw does");
if (comptime T == *Console and !is.named("command")) @compileError(name ++ " gets no Console: only command does");
@@ -349,12 +405,12 @@ pub fn Glue(comptime App: type) type {
@ptrCast(@alignCast(offer.state))
else if (T == *Session or T == *const Session)
@ptrCast(@alignCast(offer.ctx.session_root))
- else if (T == *Store or T == *const Store)
- @ptrCast(@alignCast(offer.ctx.store_root))
else if (T == *const Input)
offer.ctx.input
else if (T == Host)
offer.ctx.host
+ else if (T == *Init or T == *const Init)
+ offer.resource_init.?
else if (T == *Frame)
offer.frame.?
else if (T == *Console)
@@ -374,12 +430,21 @@ pub fn Glue(comptime App: type) type {
switch (which) {
.state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{},
.session => @as(*Session, @ptrCast(@alignCast(ptr))).* = .{},
- .store => @as(*Store, @ptrCast(@alignCast(ptr))).* = .{},
}
}
pub fn init(ctx: *const abi.Context, s: [*]u8) callconv(.c) void {
if (@hasDecl(App, "init")) call(App.init, "init", .{ .ctx = ctx, .state = s });
}
+ pub fn setup(ctx: *const abi.Context) callconv(.c) bool {
+ if (!@hasDecl(App, "setup")) return true;
+ var resource_init: Init = .{ .host = ctx.host, .session = ctx.session };
+ const result = call(App.setup, "setup", .{ .ctx = ctx, .state = undefined, .resource_init = &resource_init });
+ if (@typeInfo(@TypeOf(result)) == .error_union) result catch |err| {
+ ctx.host.print("session setup failed: {t}", .{err});
+ return false;
+ };
+ return true;
+ }
pub fn update(ctx: *const abi.Context, s: [*]u8) callconv(.c) void {
if (@hasDecl(App, "update")) call(App.update, "update", .{ .ctx = ctx, .state = s });
}
@@ -390,7 +455,7 @@ pub fn Glue(comptime App: type) type {
}
pub fn command(ctx: *const abi.Context, s: [*]u8, line: *const []const u8) callconv(.c) abi.Outcome {
if (!@hasDecl(App, "command")) return .unknown;
- var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session, .store = ctx.store };
+ var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session };
const taken = call(App.command, "command", .{ .ctx = ctx, .state = s, .console = &c, .line = line.* }) catch |err| {
c.print("{t}. Type help for usage.", .{err});
return .failed;
@@ -410,4 +475,58 @@ test {
_ = @import("clock.zig");
_ = @import("list.zig");
_ = @import("derived.zig");
+ _ = sfxr;
+ _ = text;
+}
+
+test "setup receives session resources without a Frame and reports errors" {
+ const App = struct {
+ pub const Session = struct { bytes: []u8 = &.{}, calls: u32 = 0 };
+ pub fn setup(session: *Session, resources: *Init) !void {
+ session.calls += 1;
+ session.bytes = try resources.session.dupe(u8, "ready");
+ return error.TestSetupFailure;
+ }
+ };
+ const Log = struct {
+ fn log(ctx: *anyopaque, message: []const u8) void {
+ const seen: *bool = @ptrCast(@alignCast(ctx));
+ seen.* = std.mem.eql(u8, message, "session setup failed: TestSetupFailure");
+ }
+ };
+ var seen = false;
+ var vtable: abi.Host.VTable = undefined;
+ vtable.log = Log.log;
+ var session: App.Session = .{};
+ var ctx: abi.Context = undefined;
+ ctx.host = .{ .ctx = &seen, .vtable = &vtable };
+ ctx.session_root = std.mem.asBytes(&session);
+ ctx.session = std.testing.allocator;
+ const app = sketch(App, .{});
+ try std.testing.expect(!app.setup(&ctx));
+ defer std.testing.allocator.free(session.bytes);
+ try std.testing.expectEqualStrings("ready", session.bytes);
+ try std.testing.expectEqual(@as(u32, 1), session.calls);
+ try std.testing.expect(seen);
+}
+
+test "postprocess preserves image handles and copies transient uniforms" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ var commands: std.ArrayList(abi.Command) = .empty;
+ var ctx: abi.Context = undefined;
+ ctx.commands = &commands;
+ var frame: Frame = undefined;
+ frame.ctx = &ctx;
+ frame.scratch = arena.allocator();
+ var uniforms = [_]u8{ 1, 2, 3, 4 };
+ const source: Image = @fromBackingInt(@intCast(1));
+ const target: Image = @fromBackingInt(@intCast(2));
+ frame.postProcess(source, target, .{ .vertex = .{ .code = "vertex" }, .fragment = .{ .code = "fragment" }, .sample_depth = true, .fragment_uniforms = &uniforms });
+ uniforms[0] = 9;
+ const post = commands.items[0].post_process;
+ try std.testing.expectEqual(source, post.source);
+ try std.testing.expectEqual(target, post.target);
+ try std.testing.expect(post.effect.sample_depth);
+ try std.testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4 }, post.effect.fragment_uniforms);
}
diff --git a/src/sketch/sfxr.zig b/src/sketch/sfxr.zig
new file mode 100644
index 0000000..01657b5
--- /dev/null
+++ b/src/sketch/sfxr.zig
@@ -0,0 +1,267 @@
+//! sfxr, DrPetter's sound-effect generator (blips, coins, lasers,
+//! explosions): one waveform through an envelope, pitch slides, vibrato,
+//! arpeggio, duty sweep, a phaser and two filters, 8× oversampled. Pure and
+//! deterministic: the same `Params` and rate give the same samples, so a
+//! sketch renders its sounds whenever it likes and plays them as voices:
+//!
+//! const n = sk.sfxr.render(.{ .freq = 0.5, .decay = 0.2 }, f.in.sample_rate, &buf);
+//! ss.blip = f.host.newSound(buf[0..n]);
+//!
+//! Ported from 02-dont-rat-me-out's synth.zig. sfxr's knobs count in
+//! samples at 44.1 kHz; at another rate every length, step and filter
+//! coefficient is scaled to keep the same durations, pitches and cutoffs
+//! (to first order for the slides and filters), and at 44.1 kHz the
+//! samples are the original's to the bit.
+const std = @import("std");
+
+/// The rate sfxr's knobs were tuned at.
+pub const reference_rate = 44_100;
+
+pub const Wave = enum(u8) { square, sawtooth, sine, noise };
+
+/// All sfxr knobs. Most are 0..1, a few -1..1.
+pub const Params = struct {
+ wave: Wave = .square,
+ // envelope
+ attack: f32 = 0.0,
+ sustain: f32 = 0.3,
+ punch: f32 = 0.0,
+ decay: f32 = 0.4,
+ // frequency
+ freq: f32 = 0.3,
+ freq_limit: f32 = 0.0,
+ freq_ramp: f32 = 0.0,
+ freq_dramp: f32 = 0.0,
+ // vibrato
+ vibrato_depth: f32 = 0.0,
+ vibrato_speed: f32 = 0.0,
+ // arpeggio
+ arp_mod: f32 = 0.0,
+ arp_speed: f32 = 0.0,
+ // square duty
+ duty: f32 = 0.0,
+ duty_ramp: f32 = 0.0,
+ // phaser
+ phaser_offset: f32 = 0.0,
+ phaser_ramp: f32 = 0.0,
+ // filters
+ lpf_freq: f32 = 1.0,
+ lpf_ramp: f32 = 0.0,
+ lpf_resonance: f32 = 0.0,
+ hpf_freq: f32 = 0.0,
+ hpf_ramp: f32 = 0.0,
+ // repeat
+ repeat_speed: f32 = 0.0,
+ // output
+ volume: f32 = 0.5,
+};
+
+inline fn sq(x: f32) f32 {
+ return x * x;
+}
+inline fn cube(x: f32) f32 {
+ return x * x * x;
+}
+inline fn xs(s: *u32) u32 {
+ s.* ^= s.* << 13;
+ s.* ^= s.* >> 17;
+ s.* ^= s.* << 5;
+ return s.*;
+}
+fn frnd(s: *u32, range: f32) f32 {
+ return @as(f32, @floatFromInt(xs(s))) / 4294967295.0 * range;
+}
+
+/// Synthesizes `p` at `rate` samples a second into `out` (mono, -1..1).
+/// Returns the number of samples written: the envelope's length, or less
+/// when `out` is shorter or the pitch falls to `freq_limit`.
+pub fn render(p: Params, rate: u32, out: []f32) usize {
+ // Samples at `rate` per sample at 44.1 kHz: lengths grow by it, steps
+ // per sample shrink by it.
+ const k: f64 = @as(f64, @floatFromInt(rate)) / reference_rate;
+ const kf: f32 = @floatCast(k);
+ var rng: u32 = 0x52ad4326;
+
+ var fperiod: f64 = 100.0 / (@as(f64, p.freq) * p.freq + 0.001) * k;
+ var period: i32 = @intFromFloat(fperiod);
+ const fmaxperiod: f64 = 100.0 / (@as(f64, p.freq_limit) * p.freq_limit + 0.001) * k;
+ var fslide: f64 = 1.0 - @as(f64, cube(p.freq_ramp)) * 0.01 / k;
+ const fdslide: f64 = -@as(f64, cube(p.freq_dramp)) * 0.000001 / (k * k);
+
+ var square_duty: f32 = 0.5 - p.duty * 0.5;
+ const square_slide: f32 = -p.duty_ramp * 0.00005 / kf;
+
+ const arp_mod: f64 = if (p.arp_mod >= 0) 1.0 - @as(f64, sq(p.arp_mod)) * 0.9 else 1.0 + @as(f64, sq(p.arp_mod)) * 10.0;
+ var arp_time: i32 = 0;
+ var arp_limit: i32 = @intFromFloat((sq(p.arp_speed) * 20000 + 32) * kf);
+ if (p.arp_speed == 1.0) arp_limit = 0;
+
+ var env_vol: f32 = 0;
+ var env_stage: usize = 0;
+ var env_time: i32 = 0;
+ const env_length = [3]i32{
+ @intFromFloat(p.attack * p.attack * 100000 * kf),
+ @intFromFloat(p.sustain * p.sustain * 100000 * kf),
+ @intFromFloat(p.decay * p.decay * 100000 * kf),
+ };
+
+ var fphase: f32 = sq(p.phaser_offset) * 1020 * kf;
+ if (p.phaser_offset < 0) fphase = -fphase;
+ var fdphase: f32 = sq(p.phaser_ramp) * 1.0;
+ if (p.phaser_ramp < 0) fdphase = -fdphase;
+ var iphase: i32 = @intFromFloat(@min(@abs(fphase), 1023));
+ var ipp: i32 = 0;
+ var phaser_buffer: [1024]f32 = @splat(0);
+
+ var noise_buffer: [32]f32 = undefined;
+ for (&noise_buffer) |*nb| nb.* = frnd(&rng, 2) - 1;
+
+ var fltp: f32 = 0;
+ var fltdp: f32 = 0;
+ var fltw: f32 = cube(p.lpf_freq) * 0.1 / kf;
+ const fltw_d: f32 = 1.0 + p.lpf_ramp * 0.0001 / kf;
+ var fltdmp: f32 = 5.0 / (1.0 + sq(p.lpf_resonance) * 20) * (0.01 + fltw);
+ if (fltdmp > 0.8) fltdmp = 0.8;
+ var fltphp: f32 = 0;
+ var flthp: f32 = sq(p.hpf_freq) * 0.1 / kf;
+ const flthp_d: f32 = 1.0 + p.hpf_ramp * 0.0003 / kf;
+
+ var vib_phase: f32 = 0;
+ const vib_speed: f32 = sq(p.vibrato_speed) * 0.01 / kf;
+ const vib_amp: f32 = p.vibrato_depth * 0.5;
+
+ var rep_time: i32 = 0;
+ var rep_limit: i32 = @intFromFloat((sq(1 - p.repeat_speed) * 20000 + 32) * kf);
+ if (p.repeat_speed == 0) rep_limit = 0;
+
+ var phase: i32 = 0;
+ var n: usize = 0;
+ var finished = false;
+ while (!finished and n < out.len) : (n += 1) {
+ rep_time += 1;
+ if (rep_limit != 0 and rep_time >= rep_limit) {
+ rep_time = 0;
+ fperiod = 100.0 / (@as(f64, p.freq) * p.freq + 0.001) * k;
+ period = @intFromFloat(fperiod);
+ fslide = 1.0 - @as(f64, cube(p.freq_ramp)) * 0.01 / k;
+ arp_time = 0;
+ arp_limit = @intFromFloat((sq(p.arp_speed) * 20000 + 32) * kf);
+ if (p.arp_speed == 1.0) arp_limit = 0;
+ }
+
+ arp_time += 1;
+ if (arp_limit != 0 and arp_time >= arp_limit) {
+ arp_limit = 0;
+ fperiod *= arp_mod;
+ }
+
+ fslide += fdslide;
+ fperiod *= fslide;
+ if (fperiod > fmaxperiod) {
+ fperiod = fmaxperiod;
+ if (p.freq_limit > 0) finished = true;
+ }
+
+ var rfperiod: f32 = @floatCast(fperiod);
+ if (vib_amp > 0) {
+ vib_phase += vib_speed;
+ rfperiod = @floatCast(fperiod * (1.0 + @as(f64, @sin(vib_phase) * vib_amp)));
+ }
+ period = @intFromFloat(rfperiod);
+ if (period < 8) period = 8;
+
+ square_duty += square_slide;
+ square_duty = std.math.clamp(square_duty, 0, 0.5);
+
+ env_time += 1;
+ if (env_time > env_length[env_stage]) {
+ env_time = 0;
+ env_stage += 1;
+ if (env_stage == 3) finished = true;
+ }
+ env_vol = switch (env_stage) {
+ 0 => @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[0]))),
+ 1 => 1.0 + (1.0 - @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[1])))) * 2.0 * p.punch,
+ else => 1.0 - @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[2]))),
+ };
+
+ fphase += fdphase;
+ iphase = @intFromFloat(@min(@abs(fphase), 1023));
+
+ flthp *= flthp_d;
+ flthp = std.math.clamp(flthp, 0.00001, 0.1);
+
+ var ssample: f32 = 0;
+ var oi: u32 = 0;
+ while (oi < 8) : (oi += 1) {
+ var sample: f32 = 0;
+ phase += 1;
+ if (phase >= period) {
+ phase = @mod(phase, period);
+ if (p.wave == .noise) for (&noise_buffer) |*nb| {
+ nb.* = frnd(&rng, 2) - 1;
+ };
+ }
+ const fp: f32 = @as(f32, @floatFromInt(phase)) / @as(f32, @floatFromInt(period));
+ sample = switch (p.wave) {
+ .square => if (fp < square_duty) 0.5 else -0.5,
+ .sawtooth => 1.0 - fp * 2,
+ .sine => @sin(fp * 2.0 * std.math.pi),
+ .noise => noise_buffer[@intCast(@as(i32, @intFromFloat(fp * 32)) & 31)],
+ };
+
+ const pp = fltp;
+ fltw *= fltw_d;
+ fltw = std.math.clamp(fltw, 0, 0.1);
+ if (p.lpf_freq != 1.0) {
+ fltdp += (sample - fltp) * fltw;
+ fltdp -= fltdp * fltdmp;
+ } else {
+ fltp = sample;
+ fltdp = 0;
+ }
+ fltp += fltdp;
+ fltphp += fltp - pp;
+ fltphp -= fltphp * flthp;
+ sample = fltphp;
+ phaser_buffer[@intCast(ipp & 1023)] = sample;
+ sample += phaser_buffer[@intCast((ipp - iphase + 1024) & 1023)];
+ ipp = (ipp + 1) & 1023;
+
+ ssample += sample * env_vol;
+ }
+ ssample = ssample / 8.0 * p.volume * 2.0;
+ out[n] = std.math.clamp(ssample, -1, 1);
+ }
+ return n;
+}
+
+/// One parameter set per wave, between them every knob: a coin with punch,
+/// arpeggio and a duty sweep; an explosion through both filters; a laser
+/// with vibrato, phaser, repeat and a pitch limit; a rising sine.
+const sets = [_]Params{
+ .{ .wave = .square, .sustain = 0.1, .punch = 0.5, .decay = 0.3, .freq = 0.45, .freq_ramp = -0.2, .arp_mod = 0.4, .arp_speed = 0.6, .duty = 0.3, .duty_ramp = 0.2 },
+ .{ .wave = .noise, .sustain = 0.2, .decay = 0.4, .freq = 0.2, .freq_ramp = -0.1, .lpf_freq = 0.6, .lpf_ramp = -0.1, .lpf_resonance = 0.4, .hpf_freq = 0.1, .hpf_ramp = 0.05 },
+ .{ .wave = .sawtooth, .sustain = 0.25, .decay = 0.2, .freq = 0.5, .freq_limit = 0.1, .freq_dramp = 0.1, .vibrato_depth = 0.3, .vibrato_speed = 0.5, .phaser_offset = 0.3, .phaser_ramp = -0.1, .repeat_speed = 0.5 },
+ .{ .wave = .sine, .attack = 0.2, .sustain = 0.2, .decay = 0.2, .freq = 0.3, .freq_ramp = 0.1, .freq_limit = 0.2, .volume = 0.8 },
+};
+
+test "sfxr renders the original's samples at 44.1 kHz, and as long a sound at 48 kHz" {
+ // Length and Wyhash of the samples the original (02-dont-rat-me-out
+ // synth.zig) rendered for each set at 44.1 kHz.
+ const original = [_]struct { usize, u64 }{
+ .{ 10003, 0xb969b441e8bd800 },
+ .{ 20003, 0x5fc62aaf3122de5a },
+ .{ 10253, 0x8d81ee15b98f33ac },
+ .{ 12003, 0xe656fadd21b7dedb },
+ };
+ const out = try std.testing.allocator.alloc(f32, 2 * 48_000);
+ defer std.testing.allocator.free(out);
+ for (sets, original) |p, want| {
+ const n = render(p, reference_rate, out);
+ try std.testing.expectEqual(want[0], n);
+ try std.testing.expectEqual(want[1], std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(out[0..n])));
+ const at48 = render(p, 48_000, out);
+ try std.testing.expectApproxEqRel(@as(f64, @floatFromInt(n)) * 48_000 / reference_rate, @as(f64, @floatFromInt(at48)), 0.01);
+ }
+}
diff --git a/src/sketch/text.zig b/src/sketch/text.zig
new file mode 100644
index 0000000..636258f
--- /dev/null
+++ b/src/sketch/text.zig
@@ -0,0 +1,319 @@
+//! Text as a sketch measures and lays it out, anywhere: `update` (pure: the
+//! same bytes give the same numbers), `draw` and tests. One host entry,
+//! `textRun` (a run in one face at one scale: its advance, its line box,
+//! each byte's x), and the rest here, in plain Zig, the same on every host:
+//! lines at `\n`, wrapping at spaces to a width, alignment, spans of
+//! another colour, face or scale, the first N glyphs revealed, a caret.
+//! A glyph, for `reveal` and `Layout.glyphs`, is a codepoint.
+//!
+//! The glue sets `host` before each call into the sketch. A test binary has
+//! no host: it calls vendor/text.c, which `App.addTest` links (the static
+//! library the native host is built with), so a test measures as the host.
+const std = @import("std");
+const builtin = @import("builtin");
+const abi = @import("abi");
+const Face = abi.Face;
+const Color = abi.Color;
+
+/// Who measures: set by the glue before each call into the sketch.
+pub var host: ?abi.Host = null;
+
+extern fn sk_text_run(face: c_int, px: f32, utf8: [*]const u8, len: usize, xs: ?[*]f32, ascent: *i32, height: *i32) i32;
+extern fn sk_text_font(bytes: [*]const u8, len: usize) c_int;
+
+/// From its `start` byte to the next span's: another colour, face or
+/// scale (null: the paragraph's). Spans are in order of `start`.
+pub const Span = struct { start: u32, color: ?Color = null, face: ?Face = null, scale: ?f32 = null };
+pub const Align = enum { left, center, right };
+
+pub const Paragraph = struct {
+ face: Face = .mono,
+ /// 1 is a 13 px face.
+ scale: f32 = 1,
+ color: Color = .white,
+ /// Lines wrap at spaces to this width; 0: lines end only at `\n`.
+ width: f32 = 0,
+ /// Within `width`, or within the widest line when it is 0.
+ @"align": Align = .left,
+ spans: []const Span = &.{},
+ /// Draw only the first `reveal` glyphs; the layout is the whole text's.
+ reveal: u32 = std.math.maxInt(u32),
+ /// A byte index whose place `Layout.caret` gives (`bytes.len`: the end).
+ caret: ?u32 = null,
+};
+
+/// A paragraph's extent and lines, its glyph count, and where `caret`
+/// sits: the left of its glyph, the top of its line and that line's height.
+/// Positions are the paragraph's (from its `x`, `y`; `layout` lays it out
+/// at 0, 0).
+pub const Layout = struct { w: f32 = 0, h: f32 = 0, lines: u32 = 0, glyphs: u32 = 0, caret: Caret = .{} };
+pub const Caret = struct { x: f32 = 0, y: f32 = 0, h: f32 = 0 };
+
+/// One run measured: its advance and line box, each byte's x into `xs`
+/// (empty, or one a byte).
+pub fn run(face: Face, scale: f32, bytes: []const u8, xs: []f32) abi.TextRun {
+ if (builtin.is_test) {
+ var ascent: i32 = 0;
+ var height: i32 = 0;
+ const advance = sk_text_run(@backingInt(face), 13 * scale, bytes.ptr, bytes.len, if (xs.len == 0) null else xs.ptr, &ascent, &height);
+ return .{ .width = @floatFromInt(advance), .ascent = @floatFromInt(ascent), .height = @floatFromInt(height) };
+ }
+ const h = host.?;
+ return h.vtable.textRun(h.ctx, face, scale, bytes, xs);
+}
+
+/// A face for a sketch's own TTF or OTF bytes (copied; the same bytes give
+/// the same face). Null when they are not a font. Its missing glyphs come
+/// from JetBrains Mono NL.
+pub fn font(bytes: []const u8) ?Face {
+ if (builtin.is_test) {
+ const face = sk_text_font(bytes.ptr, bytes.len);
+ return if (face < 0) null else @enumFromInt(face);
+ }
+ const h = host.?;
+ return h.vtable.font(h.ctx, bytes);
+}
+
+/// The width and height `bytes` covers in `face` at `scale`: its widest
+/// line and its lines' heights.
+pub fn size(face: Face, scale: f32, bytes: []const u8) [2]f32 {
+ const l = layout(bytes, .{ .face = face, .scale = scale });
+ return .{ l.w, l.h };
+}
+
+/// `p`'s layout of `bytes`, nothing drawn.
+pub fn layout(bytes: []const u8, p: Paragraph) Layout {
+ return lay(bytes, p, 0, 0, null, &.{});
+}
+
+/// `p`'s layout of `bytes`, and in `out` the place of every byte: where a
+/// caret before it sits (`layout` with `.caret = i`), `out[bytes.len]` the
+/// end's. An editor draws ranges and hit-tests with it: the byte at a point
+/// is the last whose line holds the point's y and whose x is at or left of
+/// it. `out` has a place a byte and one more.
+pub fn places(bytes: []const u8, p: Paragraph, out: []Caret) Layout {
+ std.debug.assert(out.len > bytes.len);
+ return lay(bytes, p, 0, 0, null, out);
+}
+
+/// The longest run measured at once; longer stretches are measured in
+/// pieces, at codepoint boundaries.
+const piece = 256;
+
+const Style = struct { face: Face, scale: f32, color: Color };
+
+/// The style at byte `i`, and the byte its span ends at.
+fn styleAt(bytes: []const u8, p: Paragraph, i: usize) struct { Style, usize } {
+ var s: Style = .{ .face = p.face, .scale = p.scale, .color = p.color };
+ var end = bytes.len;
+ for (p.spans) |span| {
+ if (span.start > i) {
+ end = @min(end, span.start);
+ break;
+ }
+ s = .{ .face = span.face orelse p.face, .scale = span.scale orelse p.scale, .color = span.color orelse p.color };
+ }
+ return .{ s, end };
+}
+
+/// Where the piece of one style from `at` ends: its span's end, a `\n`,
+/// `limit`, or `piece` bytes on (backed off to a codepoint's start).
+fn pieceEnd(bytes: []const u8, span_end: usize, at: usize, limit: usize) usize {
+ var end = @min(span_end, limit, at + piece);
+ if (std.mem.indexOfScalarPos(u8, bytes[0..end], at, '\n')) |nl| end = nl;
+ if (end < @min(span_end, limit) and end > at + 4) while (end > at and bytes[end] & 0xc0 == 0x80) {
+ end -= 1;
+ };
+ return end;
+}
+
+/// A line: bytes `[start, end)` drawn, the next line from `next`; its
+/// width and line box.
+const Line = struct { end: usize, next: usize, w: f32, ascent: f32, height: f32 };
+
+/// The line from `start`: to its `\n` or the end, or wrapped at the last
+/// space before the first glyph past `width`. A word wider than `width`
+/// stays whole. Spaces where it wraps are not part of its width.
+fn fit(bytes: []const u8, p: Paragraph, start: usize) Line {
+ var xs: [piece]f32 = undefined;
+ var at = start;
+ var w: f32 = 0;
+ var ascent: f32 = 0;
+ var descent: f32 = 0;
+ var wrap: ?Line = null;
+ // The first of the spaces before a break: the line's end if it wraps there.
+ var spaces: ?struct { at: usize, x: f32 } = null;
+ while (true) {
+ const style, const span_end = styleAt(bytes, p, at);
+ const end = pieceEnd(bytes, span_end, at, bytes.len);
+ const r = run(style.face, style.scale, bytes[at..end], xs[0 .. end - at]);
+ // A line wrapped where this piece starts has the line box before it.
+ const before: [2]f32 = .{ ascent, descent };
+ ascent = @max(ascent, r.ascent);
+ descent = @max(descent, r.height - r.ascent);
+ for (at..end) |i| {
+ const x = w + xs[i - at];
+ if (bytes[i] == ' ') {
+ if (spaces == null and i > start and bytes[i - 1] != ' ') spaces = .{ .at = i, .x = x };
+ continue;
+ }
+ if (spaces) |s| {
+ const box: [2]f32 = if (i == at) before else .{ ascent, descent };
+ wrap = .{ .end = s.at, .next = i, .w = s.x, .ascent = box[0], .height = box[0] + box[1] };
+ spaces = null;
+ }
+ const right = w + (if (i + 1 < end) xs[i + 1 - at] else r.width);
+ if (p.width > 0 and right > p.width) if (wrap) |l| return l;
+ }
+ w += r.width;
+ at = end;
+ // An empty line has its style's line box: an empty run's.
+ if (at == bytes.len or bytes[at] == '\n') return .{ .end = at, .next = @min(at + 1, bytes.len), .w = w, .ascent = ascent, .height = ascent + descent };
+ }
+}
+
+/// Lays `bytes` out from `x`, `y`, and with a frame, draws it: a
+/// `Command.text` a piece; with `out`, each byte's place (`places`).
+pub fn lay(bytes: []const u8, p: Paragraph, x: f32, y: f32, frame: anytype, out_places: []Caret) Layout {
+ const box = if (p.width > 0) p.width else if (p.@"align" != .left) blk: {
+ var left = p;
+ left.@"align" = .left;
+ left.caret = null;
+ break :blk layout(bytes, left).w;
+ } else 0;
+ var out: Layout = .{};
+ var xs: [piece]f32 = undefined;
+ var top = y;
+ var start: usize = 0;
+ var shown: u32 = 0;
+ while (true) {
+ const line = fit(bytes, p, start);
+ const offset: f32 = switch (p.@"align") {
+ .left => 0,
+ .center => @round((box - line.w) / 2),
+ .right => box - line.w,
+ };
+ var at = start;
+ var pen = x + offset;
+ if (p.caret) |caret| if (caret >= start and (caret < line.next or line.next == bytes.len)) {
+ out.caret = .{ .x = if (caret >= line.end) pen + line.w else pen, .y = top, .h = line.height };
+ };
+ while (at < line.end) {
+ const style, const span_end = styleAt(bytes, p, at);
+ const end = pieceEnd(bytes, span_end, at, line.end);
+ const r = run(style.face, style.scale, bytes[at..end], xs[0 .. end - at]);
+ if (p.caret) |caret| if (caret >= at and caret <= end and caret <= line.end) {
+ out.caret.x = pen + (if (caret < end) xs[caret - at] else r.width);
+ };
+ if (out_places.len > 0) for (at..end) |i| {
+ out_places[i] = .{ .x = pen + xs[i - at], .y = top, .h = line.height };
+ };
+ const count: u32 = @intCast(std.unicode.utf8CountCodepoints(bytes[at..end]) catch end - at);
+ if (@TypeOf(frame) != @TypeOf(null) and shown < p.reveal) {
+ var cut = end;
+ if (shown + count > p.reveal) {
+ var left = p.reveal - shown;
+ cut = at;
+ while (left > 0 and cut < end) : (left -= 1) cut += std.unicode.utf8ByteSequenceLength(bytes[cut]) catch 1;
+ }
+ frame.emit(.{ .text = .{ .x = pen, .y = top + line.ascent - r.ascent, .scale = style.scale, .color = style.color, .bytes = bytes[at..cut], .face = style.face } });
+ }
+ shown += count;
+ pen += r.width;
+ at = end;
+ }
+ // A `\n` or the spaces a line wraps at, and the end, sit at its end.
+ const after = if (line.next == bytes.len) line.next + 1 else line.next;
+ if (out_places.len > 0) for (line.end..after) |i| {
+ out_places[i] = .{ .x = pen, .y = top, .h = line.height };
+ };
+ out.w = @max(out.w, line.w);
+ out.lines += 1;
+ top += line.height;
+ // Spaces where a line wraps count too, so reveal walks the text; a
+ // `\n` is no glyph. After a last `\n` comes an empty line.
+ const newline = line.end < bytes.len and bytes[line.end] == '\n';
+ if (!newline) shown += @intCast(std.unicode.utf8CountCodepoints(bytes[line.end..line.next]) catch 0);
+ if (line.next == bytes.len and !newline) break;
+ start = line.next;
+ }
+ out.h = top - y;
+ out.glyphs = shown;
+ return out;
+}
+
+test "a paragraph wraps at spaces, aligns, reveals and finds its caret" {
+ const t = std.testing;
+ // Go Mono at 13 px: 8 px a glyph, a 16 px line (vendor/text.c).
+ const one = run(.mono, 1, "0123456789", &.{});
+ try t.expectEqual(@as(f32, 80), one.width);
+ try t.expectEqual(@as(f32, 16), one.height);
+ try t.expectEqual([2]f32{ 80, 16 }, size(.mono, 1, "0123456789"));
+ try t.expectEqual([2]f32{ 80, 32 }, size(.mono, 1, "01234\n0123456789"));
+ // 10 glyphs wide: "aaaa bbbb" fits, "cccc" wraps; the space is not width.
+ const l = layout("aaaa bbbb cccc", .{ .width = 80 });
+ try t.expectEqual(@as(u32, 2), l.lines);
+ try t.expectEqual(@as(f32, 72), l.w);
+ try t.expectEqual(@as(f32, 32), l.h);
+ try t.expectEqual(@as(u32, 14), l.glyphs);
+ // The caret before "cccc" is at the second line's start; at the end, after it.
+ try t.expectEqual(Caret{ .x = 0, .y = 16, .h = 16 }, layout("aaaa bbbb cccc", .{ .width = 80, .caret = 10 }).caret);
+ try t.expectEqual(Caret{ .x = 32, .y = 16, .h = 16 }, layout("aaaa bbbb cccc", .{ .width = 80, .caret = 14 }).caret);
+ try t.expectEqual(Caret{ .x = 16, .y = 0, .h = 16 }, layout("ab\ncd", .{ .caret = 2 }).caret);
+ try t.expectEqual(Caret{ .x = 8, .y = 16, .h = 16 }, layout("ab\ncd", .{ .caret = 4 }).caret);
+ // Centred in 100: a line of 4 starts at 34.
+ try t.expectEqual(Caret{ .x = 34, .y = 0, .h = 16 }, layout("abcd", .{ .width = 100, .@"align" = .center, .caret = 0 }).caret);
+ try t.expectEqual(Caret{ .x = 68, .y = 0, .h = 16 }, layout("abcd", .{ .width = 100, .@"align" = .right, .caret = 0 }).caret);
+ // A span twice the size makes its line taller, and wider.
+ const big = layout("ab cd", .{ .spans = &.{.{ .start = 3, .scale = 2 }} });
+ try t.expectEqual(@as(f32, 24 + 2 * 8 * 2), big.w);
+ try t.expect(big.h >= 31);
+ // A word wider than the width stays whole on its own line.
+ try t.expectEqual(@as(u32, 2), layout("abcdefghijkl x", .{ .width = 40 }).lines);
+ // An empty text is one empty line.
+ try t.expectEqual(Layout{ .w = 0, .h = 16, .lines = 1 }, layout("", .{}));
+}
+
+test "reveal draws the first glyphs of the same layout" {
+ const t = std.testing;
+ const Frame = struct {
+ drawn: [8][]const u8 = undefined,
+ n: usize = 0,
+ fn emit(f: *@This(), c: abi.Command) void {
+ f.drawn[f.n] = c.text.bytes;
+ f.n += 1;
+ }
+ };
+ var f: Frame = .{};
+ const whole = lay("ab cd\nef", .{ .width = 32 }, 0, 0, &f, &.{});
+ try t.expectEqual(@as(usize, 3), f.n);
+ try t.expectEqualStrings("ab", f.drawn[0]);
+ try t.expectEqualStrings("cd", f.drawn[1]);
+ try t.expectEqualStrings("ef", f.drawn[2]);
+ f = .{};
+ const part = lay("ab cd\nef", .{ .width = 32, .reveal = 4 }, 0, 0, &f, &.{});
+ try t.expectEqual(whole, part);
+ try t.expectEqual(@as(u32, 7), whole.glyphs);
+ try t.expectEqual(@as(usize, 2), f.n);
+ try t.expectEqualStrings("c", f.drawn[1]);
+}
+
+test "a paragraph's places are where its caret sits, byte by byte" {
+ const t = std.testing;
+ // Wrapped at a space, a `\n`, a span twice the size on the first line,
+ // a two-byte codepoint and a last empty line.
+ const text = "ab cd efgh\nij é\n";
+ const p: Paragraph = .{ .width = 80, .spans = &.{ .{ .start = 3, .scale = 2 }, .{ .start = 5, .scale = 1 } } };
+ var out: [text.len + 1]Caret = undefined;
+ try t.expectEqual(layout(text, p), places(text, p, &out));
+ for (0..text.len + 1) |i| {
+ var at = p;
+ at.caret = @intCast(i);
+ try t.expectEqual(layout(text, at).caret, out[i]);
+ }
+ // The big span's line is taller; the byte after its line, on the next.
+ try t.expect(out[0].h > 16);
+ try t.expectEqual(@as(f32, 3 * 8 + 2 * 8 * 2), out[5].x);
+ try t.expectEqual(out[6].y, out[7].y);
+ try t.expect(out[6].y > out[5].y);
+}
diff --git a/src/sketch/web.zig b/src/sketch/web.zig
index 3e102ad..e12acb3 100644
--- a/src/sketch/web.zig
+++ b/src/sketch/web.zig
@@ -2,7 +2,7 @@
//! the imports below: drawing on a 2D canvas, GPU work on WebGPU, sound and
//! the microphone on Web Audio, files through the page. State, `update` and
//! `draw` are the same Zig as on native. There is no timeline, and nothing
-//! persists: Store lasts as long as the page.
+//! persists.
const std = @import("std");
const abi = @import("abi");
const root = @import("root.zig");
@@ -15,6 +15,11 @@ const js = struct {
extern "host" fn newImage(w: u32, h: u32) u32;
extern "host" fn freeImage(image: u32) void;
extern "host" fn clock() f64;
+ /// canvas measureText: the run's width, ascent and height into `out`,
+ /// and with `xs_len` (the run's length) each byte's x.
+ extern "host" fn textRun(face: u32, scale: f32, ptr: [*]const u8, len: usize, xs: [*]f32, xs_len: usize, out: *[3]f32) void;
+ /// A FontFace from the bytes: its face, or -1.
+ extern "host" fn font(ptr: [*]const u8, len: usize) i32;
extern "host" fn openFile(command: [*]const u8, command_len: usize, pattern: [*]const u8, pattern_len: usize) void;
extern "canvas" fn clear(r: u32, g: u32, b: u32, a: u32) void;
extern "canvas" fn fill(x: f32, y: f32, w: f32, h: f32, r: u32, g: u32, b: u32, a: u32) void;
@@ -30,7 +35,7 @@ const js = struct {
extern "canvas" fn target(id: u32) void;
/// `abi.BlendMode` by value.
extern "canvas" fn blend(mode: u32) void;
- extern "canvas" fn text(x: f32, y: f32, scale: f32, ptr: [*]const u8, len: usize, r: u32, g: u32, b: u32, a: u32) void;
+ extern "canvas" fn text(x: f32, y: f32, scale: f32, face: u32, ptr: [*]const u8, len: usize, r: u32, g: u32, b: u32, a: u32) void;
extern "canvas" fn clip(enabled: u32, x: f32, y: f32, w: f32, h: f32) void;
extern "canvas" fn canvas(w: u32, h: u32) void;
extern "canvas" fn cursor(kind: u32) void;
@@ -39,14 +44,17 @@ const js = struct {
extern "gpu" fn available() u32;
extern "gpu" fn newBuffer(size: u32) u32;
extern "gpu" fn freeBuffer(id: u32) void;
- extern "gpu" fn write(id: u32, offset: u32, ptr: [*]const u8, len: usize) void;
+ extern "gpu" fn write(id: u32, offset: u32, ptr: [*]const u8, len: usize) u32;
/// A `Dispatch` or a `Pass`, described in JSON (see `describe`).
extern "gpu" fn compute(ptr: [*]const u8, len: usize) void;
extern "gpu" fn pass(ptr: [*]const u8, len: usize) void;
+ extern "gpu" fn postProcess(ptr: [*]const u8, len: usize) void;
/// Answers through `sk_download`.
extern "gpu" fn download(id: u32, offset: u32, size: u32, key: u32) void;
extern "audio" fn rate() u32;
extern "audio" fn push(key: u32, ptr: [*]const f32, len: usize, clear: u32) void;
+ /// `count` samples from a GPU buffer, queued on arrival.
+ extern "audio" fn buffer(key: u32, id: u32, offset: u32, count: u32) void;
extern "audio" fn queued(key: u32) u32;
/// Keeps the microphone open; it answers through `sk_microphone`.
extern "audio" fn listen() void;
@@ -75,13 +83,12 @@ pub fn exportWeb(comptime App: type) void {
}
fn Driver(comptime App: type) type {
- const G = root.Glue(App);
+ const G = root.Glue(App, .{});
const gpa = std.heap.wasm_allocator;
return struct {
+ var ready = false;
var state: G.State = undefined;
var session: G.Session = undefined;
- // No disk on the web: the store lasts as long as the page.
- var store: G.Store = undefined;
var events: [1024]abi.Event = undefined;
var event_count: usize = 0;
var input: abi.Input = .{};
@@ -103,9 +110,7 @@ fn Driver(comptime App: type) type {
.input = &input,
.scratch = scratch.allocator(),
.session = gpa,
- .store = gpa,
.session_root = std.mem.asBytes(&session),
- .store_root = std.mem.asBytes(&store),
.commands = &commands,
};
}
@@ -113,7 +118,6 @@ fn Driver(comptime App: type) type {
fn init() callconv(.c) void {
G.defaults(.state, std.mem.asBytes(&state));
G.defaults(.session, std.mem.asBytes(&session));
- G.defaults(.store, std.mem.asBytes(&store));
input.width = G.description.width;
input.height = G.description.height;
if (input.window_width == 0) {
@@ -124,6 +128,7 @@ fn Driver(comptime App: type) type {
js.canvas(G.description.width, G.description.height);
const ctx = context();
G.init(&ctx, std.mem.asBytes(&state));
+ ready = G.setup(&ctx);
}
/// The page's room for the canvas, in CSS pixels.
@@ -144,6 +149,10 @@ fn Driver(comptime App: type) type {
}
fn frame(ms: f64) callconv(.c) void {
+ if (!ready) {
+ event_count = 0;
+ return;
+ }
const now: u64 = @intFromFloat(@max(0, ms) * std.time.ns_per_ms);
const dt = if (last == 0) 0 else now -| last;
last = now;
@@ -203,7 +212,7 @@ fn Driver(comptime App: type) type {
.shape => |v| js.shape(v.points.ptr, v.points.len, v.ends.ptr, v.ends.len, v.colors.ptr, v.colors.len, v.color.r, v.color.g, v.color.b, v.color.a),
.target => |v| js.target(@backingInt(v)),
.blend => |v| js.blend(@backingInt(v)),
- .text => |v| js.text(v.x, v.y, v.scale, v.bytes.ptr, v.bytes.len, v.color.r, v.color.g, v.color.b, v.color.a),
+ .text => |v| js.text(v.x, v.y, v.scale, @backingInt(v.face), v.bytes.ptr, v.bytes.len, v.color.r, v.color.g, v.color.b, v.color.a),
.clip => |v| if (v) |r| js.clip(1, r.x, r.y, r.w, r.h) else js.clip(0, 0, 0, 0, 0),
.canvas => |v| {
input.width = @floatFromInt(v.w);
@@ -218,8 +227,12 @@ fn Driver(comptime App: type) type {
s.pushed += v.samples.len;
js.push(v.key, v.samples.ptr, v.samples.len, @intFromBool(v.clear));
},
+ .audio_buffer => |v| {
+ stream(v.key).pushed += v.count;
+ js.buffer(v.key, @backingInt(v.buffer), v.offset, v.count);
+ },
.microphone => js.listen(),
- .upload => |v| js.write(@backingInt(v.buffer), v.offset, v.bytes.ptr, v.bytes.len),
+ .upload => |v| _ = js.write(@backingInt(v.buffer), v.offset, v.bytes.ptr, v.bytes.len),
.compute => |v| {
const json = describe(v);
js.compute(json.ptr, json.len);
@@ -228,11 +241,15 @@ fn Driver(comptime App: type) type {
const json = describe(v);
js.pass(json.ptr, json.len);
},
+ .post_process => |v| {
+ const json = describe(v);
+ js.postProcess(json.ptr, json.len);
+ },
.download => |v| js.download(@backingInt(v.buffer), v.offset, v.size, v.key),
.open_file => |v| js.openFile(v.command.ptr, v.command.len, v.pattern.ptr, v.pattern.len),
- // Synthesised voices are not on the web yet; quitting a page
+ // Voices (and so their groups) are not on the web yet; quitting a page
// means nothing; `run` lines go after the frame.
- .voice, .quit, .run, .backdrop => {},
+ .voice, .gain, .quit, .run, .backdrop => {},
}
}
@@ -243,6 +260,7 @@ fn Driver(comptime App: type) type {
}
fn run(line: []const u8) void {
+ if (!ready) return;
const ctx = context();
if (G.command(&ctx, std.mem.asBytes(&state), &line) == .unknown) {
var buf: [160]u8 = undefined;
@@ -394,12 +412,16 @@ fn Driver(comptime App: type) type {
.gpu = gpu,
.newBuffer = newBuffer,
.freeBuffer = freeBuffer,
+ .writeBuffer = writeBuffer,
.imageSize = imageSize,
- .textSize = textSize,
+ .textRun = textRun,
+ .font = font,
.loadSound = loadSound,
.decodeSound = unsupportedSound,
+ .newSound = newSound,
.samples = samples,
.readFile = readFile,
+ .appendFile = appendFile,
.env = env,
.clock = clock,
};
@@ -424,16 +446,24 @@ fn Driver(comptime App: type) type {
fn newBuffer(_: *anyopaque, size: u32) abi.Buffer {
return @fromBackingInt(js.newBuffer(size));
}
+ fn writeBuffer(_: *anyopaque, b: abi.Buffer, offset: u32, bytes: []const u8) !void {
+ if (js.write(@backingInt(b), offset, bytes.ptr, bytes.len) == 0) return error.BufferUploadFailed;
+ }
fn freeBuffer(_: *anyopaque, b: abi.Buffer) void {
js.freeBuffer(@backingInt(b));
}
fn imageSize(_: *anyopaque, img: abi.Image) [2]u32 {
return .{ js.imageWidth(@backingInt(img)), js.imageHeight(@backingInt(img)) };
}
- /// As host.js draws text: 8 px a character and a 16 px line at scale 1.
- fn textSize(_: *anyopaque, scale: f32, bytes: []const u8, _: abi.Face) [2]f32 {
- const count = std.unicode.utf8CountCodepoints(bytes) catch bytes.len;
- return .{ @as(f32, @floatFromInt(count)) * 8 * scale, 16 * scale };
+ /// As host.js draws text: canvas measureText, in the page's fonts.
+ fn textRun(_: *anyopaque, face: abi.Face, scale: f32, bytes: []const u8, xs: []f32) abi.TextRun {
+ var out: [3]f32 = .{ 0, 0, 0 };
+ js.textRun(@backingInt(face), scale, bytes.ptr, bytes.len, xs.ptr, xs.len, &out);
+ return .{ .width = out[0], .ascent = out[1], .height = out[2] };
+ }
+ fn font(_: *anyopaque, bytes: []const u8) ?abi.Face {
+ const face = js.font(bytes.ptr, bytes.len);
+ return if (face < 0) null else @enumFromInt(face);
}
/// Only sounds the page has decoded (opened or dropped files): the
/// browser decodes asynchronously, so there is no reading on demand.
@@ -444,6 +474,16 @@ fn Driver(comptime App: type) type {
fn unsupportedSound(_: *anyopaque, _: []const u8) abi.Audio {
return .none;
}
+ /// Kept, unnamed, for `samples` (voices are silent on the web).
+ fn newSound(_: *anyopaque, ptr: [*]const f32, len: usize) callconv(.c) abi.Audio {
+ for (ptr[0..len]) |v| if (!std.math.isFinite(v)) return .none;
+ const copy = gpa.dupe(f32, ptr[0..len]) catch return .none;
+ sounds.append(gpa, .{ .name = "", .samples = copy }) catch {
+ gpa.free(copy);
+ return .none;
+ };
+ return @fromBackingInt(@intCast(sounds.items.len));
+ }
fn samples(_: *anyopaque, a: abi.Audio) []const f32 {
const i = @backingInt(a);
return if (i == 0 or i > sounds.items.len) &.{} else sounds.items[i - 1].samples;
@@ -451,6 +491,10 @@ fn Driver(comptime App: type) type {
fn readFile(_: *anyopaque, _: []const u8) []const u8 {
return &.{};
}
+ /// No files on the web: nothing is written, and the path is "".
+ fn appendFile(_: *anyopaque, _: [*]const u8, _: usize, _: [*]const u8, _: usize, _: bool) callconv(.c) [*:0]const u8 {
+ return "";
+ }
fn env(_: *anyopaque, _: []const u8) ?[]const u8 {
return null;
}