summaryrefslogtreecommitdiff
path: root/anim/tools
diff options
context:
space:
mode:
Diffstat (limited to 'anim/tools')
-rw-r--r--anim/tools/__pycache__/chart.cpython-314.pycbin0 -> 2973 bytes
-rw-r--r--anim/tools/bench.zig91
-rw-r--r--anim/tools/chart.py42
-rw-r--r--anim/tools/fib.c12
-rw-r--r--anim/tools/hello.c11
-rw-r--r--anim/tools/list.c44
-rw-r--r--anim/tools/motion.py210
-rw-r--r--anim/tools/note1
-rw-r--r--anim/tools/sort.c22
9 files changed, 433 insertions, 0 deletions
diff --git a/anim/tools/__pycache__/chart.cpython-314.pyc b/anim/tools/__pycache__/chart.cpython-314.pyc
new file mode 100644
index 0000000..2d61f61
--- /dev/null
+++ b/anim/tools/__pycache__/chart.cpython-314.pyc
Binary files differ
diff --git a/anim/tools/bench.zig b/anim/tools/bench.zig
new file mode 100644
index 0000000..ad6fe4b
--- /dev/null
+++ b/anim/tools/bench.zig
@@ -0,0 +1,91 @@
+//! What a recording costs a frame: `zig build bench` opens each recording
+//! (which indexes it) and times the queries components make of a moment,
+//! walking forward a moment at a time as a playing scene does, and jumping
+//! about as a seek does. Always built ReleaseFast.
+//! `zig build bench -- NAME BY [FUNCTION]` lists a recording's steps instead.
+const std = @import("std");
+const canim = @import("canim");
+const recordings = @import("recordings");
+
+fn now() u64 {
+ var ts: std.os.linux.timespec = undefined;
+ _ = std.os.linux.clock_gettime(.MONOTONIC, &ts);
+ return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec));
+}
+
+/// `bench NAME BY [FUNCTION]`: every stop of kind BY (moment, line, over) in
+/// recording NAME (from FUNCTION's first call on), with what the step to it changed. What a scene's author needs to
+/// know to pace it.
+fn steps(rec: *canim.Recording, by: canim.Recording.Stop, function: ?[]const u8) void {
+ var at: u64 = if (function) |name| rec.call(name, 0).enter else 0;
+ var n: usize = 0;
+ while (at < rec.end()) : (n += 1) {
+ const to = rec.next(by, at);
+ var bytes: u64 = 0;
+ for (rec.written(at, to)) |w| bytes += w.len;
+ std.debug.print("{d:>4} moment {d:>5} line {d:>3} depth {d} wrote {d:>3} bytes in {d} read {d} regs", .{ n, to, rec.own[to], rec.depths[to], bytes, rec.written(at, to).len, rec.read(at, to).len });
+ const mask = rec.registersChanged(at, to);
+ for (@import("ztrace").Regs.names, 0..) |reg, i| if (mask >> @intCast(i) & 1 != 0) std.debug.print(" {s}", .{reg});
+ for (rec.syscalls) |call| if (call.enter > at and call.enter <= to) std.debug.print(" syscall {d}", .{call.nr});
+ std.debug.print("\n", .{});
+ at = to;
+ }
+}
+
+pub fn main(init: std.process.Init) !void {
+ const gpa = init.gpa;
+ const args = try init.minimal.args.toSlice(init.arena.allocator());
+ if (args.len >= 3) {
+ inline for (@typeInfo(recordings).@"struct".decl_names) |name| {
+ if (@TypeOf(@field(recordings, name)) == recordings.Program and std.mem.eql(u8, name, args[1]))
+ return steps(canim.open(@field(recordings, name)), std.meta.stringToEnum(canim.Recording.Stop, args[2]) orelse return error.NoSuchStop, if (args.len > 3) args[3] else null);
+ }
+ return error.NoSuchRecording;
+ }
+ std.debug.print("{s:<8} {s:>7} {s:>9} {s:>8} | ns a query, moments in order: {s:>6} {s:>6} {s:>6} {s:>6} {s:>6} {s:>6} | {s:>9}\n", .{ "", "moments", "bytes", "open ms", "regs", "read64", "vars", "heap", "stack", "reach", "seek us" });
+ inline for (@typeInfo(recordings).@"struct".decl_names) |name| {
+ if (@TypeOf(@field(recordings, name)) != recordings.Program) continue;
+ const program = @field(recordings, name);
+ const start = now();
+ const rec = canim.open(program);
+ const opened = now() - start;
+ // Somewhere memory was written, to read back.
+ const addr: u64 = if (rec.write_spans.all.len > 0) rec.write_spans.all[rec.write_spans.all.len / 2].addr else 0;
+ var took: [6]u64 = @splat(0);
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const rounds = @max(1, 20_000 / rec.len());
+ for (0..rounds) |_| for (0..rec.len()) |i| {
+ _ = arena.reset(.retain_capacity);
+ const m = rec.moment(i);
+ var t = now();
+ _ = try m.regs(rec.tid);
+ took[0] += now() - t;
+ t = now();
+ var buf: [64]u8 = undefined;
+ var known: [64]bool = undefined;
+ try m.read(addr, &buf, &known);
+ took[1] += now() - t;
+ t = now();
+ _ = try m.variables(arena.allocator());
+ took[2] += now() - t;
+ t = now();
+ _ = try m.heap(arena.allocator());
+ took[3] += now() - t;
+ t = now();
+ _ = rec.stack(arena.allocator(), i);
+ took[4] += now() - t;
+ t = now();
+ _ = canim.objects.reach(arena.allocator(), rec, m, null);
+ took[5] += now() - t;
+ };
+ // A seek: moments far apart, each replayed from its keyframe.
+ var rng: std.Random.DefaultPrng = .init(1);
+ const seeks = 200;
+ const seek_start = now();
+ for (0..seeks) |_| _ = try rec.moment(rng.random().uintLessThan(u64, rec.len())).regs(rec.tid);
+ const seek = (now() - seek_start) / seeks;
+ const n = rounds * rec.len();
+ std.debug.print("{s:<8} {d:>7} {d:>9} {d:>8.2} | {s:>29} {d:>6} {d:>6} {d:>6} {d:>6} {d:>6} {d:>6} | {d:>9.1}\n", .{ name, rec.len(), program.trace.len, @as(f64, @floatFromInt(opened)) / 1e6, "", took[0] / n, took[1] / n, took[2] / n, took[3] / n, took[4] / n, took[5] / n, @as(f64, @floatFromInt(seek)) / 1e3 });
+ }
+}
diff --git a/anim/tools/chart.py b/anim/tools/chart.py
new file mode 100644
index 0000000..ca783dc
--- /dev/null
+++ b/anim/tools/chart.py
@@ -0,0 +1,42 @@
+#!/usr/bin/env python3
+"""The designer's motion instrument (design/motion/motion.py: timing chart,
+five rule checks, contact sheets), told where canim's panels are now.
+
+ chart.py chart|auto|sheet|onion|track VIDEO ... as motion.py takes them
+
+The video's file name (fib-1080.mp4 -> fib) picks its regions.
+"""
+import os, sys
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "design", "motion"))
+import motion
+
+W = motion.W
+# theme.layout (design revision 2): the state column is the same in every scene; the program
+# column is shared by the scene's split (lens, source, disassembly). The clock is over the caption.
+def panel(rows):
+ return 36 + 24 * rows
+
+def split(lens, source, disasm):
+ y = 48 + (lens + 12 if lens else 0)
+ out = {"lens": (64, 48, 880, lens)} if lens else {}
+ out["source"] = (64, y, 880, panel(source))
+ out["disasm"] = (64, y + panel(source) + 12, 880, panel(disasm))
+ return out
+
+# The clock is under the name the instrument gives to words that are not panels ("head"):
+# its progress line moves with every step and must not count as a panel starting.
+state = {"head": (0, 888, W, 46), "registers": (976, 48, 880, panel(18)), "stack": (976, 528, 880, panel(8)), "backtrace": (976, 768, 880, panel(3))}
+CAPTION = (0, 934, W, 146)
+beside, subject, none = split(312, 8, 10), split(432, 5, 8), split(0, 14, 17)
+motion.REGIONS.update({
+ "fib": {**beside, **state, "caption": CAPTION},
+ "sort": {**beside, **state, "caption": CAPTION},
+ "syscalls": {**beside, **state, "caption": CAPTION},
+ "list": {**subject, **state, "caption": CAPTION},
+ "zoom": {**none, **state, "caption": CAPTION},
+})
+_regions_for = motion.regions_for
+motion.regions_for = lambda video, name: _regions_for(video, name or os.path.basename(video).split("-")[0].split(".")[0])
+
+if __name__ == "__main__":
+ motion.main() if hasattr(motion, "main") else sys.exit("design/motion/motion.py has no main()")
diff --git a/anim/tools/fib.c b/anim/tools/fib.c
new file mode 100644
index 0000000..975f1a6
--- /dev/null
+++ b/anim/tools/fib.c
@@ -0,0 +1,12 @@
+#include <stdio.h>
+
+long fib(long n) {
+ if (n < 2)
+ return n;
+ return fib(n-1) + fib(n-2);
+}
+
+int main(void) {
+ printf("%ld\n", fib(5));
+ return 0;
+}
diff --git a/anim/tools/hello.c b/anim/tools/hello.c
new file mode 100644
index 0000000..8f3bb7d
--- /dev/null
+++ b/anim/tools/hello.c
@@ -0,0 +1,11 @@
+#include <fcntl.h>
+#include <unistd.h>
+
+int main(void) {
+ char buf[32];
+ int f = open("note", 0);
+ int n = read(f, buf, 32);
+ close(f);
+ write(1, buf, n);
+ return 0;
+}
diff --git a/anim/tools/list.c b/anim/tools/list.c
new file mode 100644
index 0000000..99836c5
--- /dev/null
+++ b/anim/tools/list.c
@@ -0,0 +1,44 @@
+#include <stdlib.h>
+
+typedef struct node {
+ long value;
+ struct node *next;
+} node;
+
+node *head;
+
+void push(long value) {
+ node *n = malloc(sizeof *n);
+ n->value = value;
+ n->next = head;
+ head = n;
+}
+
+void reverse(void) {
+ node *prev = NULL;
+ node *cur = head;
+ while (cur) {
+ node *next = cur->next;
+ cur->next = prev;
+ prev = cur;
+ cur = next;
+ }
+ head = prev;
+}
+
+void clear(void) {
+ while (head) {
+ node *n = head;
+ head = n->next;
+ free(n);
+ }
+}
+
+int main(void) {
+ push(7);
+ push(12);
+ push(9);
+ reverse();
+ clear();
+ return 0;
+}
diff --git a/anim/tools/motion.py b/anim/tools/motion.py
new file mode 100644
index 0000000..9bf0a39
--- /dev/null
+++ b/anim/tools/motion.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python3
+"""Motion, made visible: a scene judged by how it moves, not by its stills.
+
+ motion.py SCENE_EXE OUT_DIR [--size 960x540] [--fps 60]
+
+Exports the scene twice (it is deterministic) and writes into OUT_DIR:
+
+ change.png how much of the picture changes from each frame to the
+ next: the whole frame on top (log scale), then a lane for
+ each panel, the head and the caption. Holds are gaps,
+ a metronome is evenly spaced spikes, overlapping action
+ is lanes that light one after another.
+ change-NN.png the same, ten seconds a picture, a frame about two pixels.
+ sheet-NN.png contact sheets: a row for each transition (a run of
+ frames in which something changes), six frames of it
+ side by side, cropped to where the change is, with its
+ length and the hold after it.
+ transitions.txt every transition: when, how long, how much, which panels
+ in what order, and the hold that follows.
+
+and prints the summary: how many transitions, how long the holds are, how
+regular the beat is.
+"""
+import os, subprocess, sys
+import numpy as np
+from PIL import Image, ImageDraw
+import matplotlib
+matplotlib.use("Agg")
+import matplotlib.pyplot as plt
+
+args = [a for a in sys.argv[1:] if not a.startswith("--")]
+opts = dict(zip(sys.argv[1:], sys.argv[2:]))
+exe, out = args[0], args[1]
+W, H = (int(v) for v in opts.get("--size", "960x540").split("x"))
+FPS = int(opts.get("--fps", "60"))
+os.makedirs(out, exist_ok=True)
+for old in os.listdir(out):
+ if old.startswith(("sheet-", "change")) or old == "transitions.txt":
+ os.remove(os.path.join(out, old))
+
+# A pixel has changed when any channel moved by more than this: above what
+# antialiasing does to a still edge, below the faintest ember.
+THRESHOLD = 10
+# A frame is moving when this share of it changed; transitions closer than
+# GAP frames are one (a strike, then its cooling).
+ACTIVE = 0.0002
+GAP = 4
+
+
+def frames(want=None):
+ """The scene's frames in order, as H x W x 3 arrays; with `want` (a set of indices), those alone."""
+ env = dict(os.environ, CANIM_PANELS="1")
+ # The scene says where its panels are, a line a panel a frame: kept aside, read once.
+ log = open(os.path.join(out, "panels.log"), "w+")
+ p = subprocess.Popen([exe, "--state", os.path.join(out, "motion.state"), "--export", "-", "--size", f"{W}x{H}", "--fps", str(FPS)],
+ stdout=subprocess.PIPE, stderr=log, env=env)
+ size, i = W * H * 4, 0
+ while True:
+ raw = p.stdout.read(size)
+ if len(raw) < size:
+ break
+ if want is None or i in want:
+ yield i, np.frombuffer(raw, np.uint8).reshape(H, W, 4)[:, :, :3]
+ i += 1
+ p.wait()
+ log.seek(0)
+ frames.stderr = log.read()
+ log.close()
+ os.remove(os.path.join(out, "panels.log"))
+
+
+# Pass one: what changes, frame by frame, in the whole picture and in each region.
+regions = {"head": (0, 0, W, int(H * 112 / 1080)), "caption": (0, int(H * 896 / 1080), W, H)}
+# The scene says where its panels are on frame 45, so each frame's change
+# is kept small (a 96 x 54 map of where) and cut into lanes afterwards.
+whole, maps, boxes, prev, n = [], [], [], None, 0
+for i, frame in frames():
+ n = i + 1
+ # Every second pixel each way is enough to see what moves, four times sooner.
+ now = frame[::2, ::2].copy()
+ changed = np.zeros(now.shape[:2], bool) if prev is None else ((np.maximum(now, prev) - np.minimum(now, prev)).max(axis=2) > THRESHOLD)
+ prev = now
+ whole.append(float(changed.mean()))
+ maps.append(changed.reshape(54, changed.shape[0] // 54, 96, changed.shape[1] // 96).mean(axis=(1, 3)).astype(np.float32))
+ ys, xs = np.nonzero(changed)
+ boxes.append((2 * xs.min(), 2 * ys.min(), 2 * xs.max() + 2, 2 * ys.max() + 2) if len(xs) else None)
+whole = np.array(whole)
+
+# Where each panel is when it first shows (before any camera move).
+for line in frames.stderr.splitlines():
+ if line.startswith("canim-panel "):
+ x0, y0, x1, y1, name = line.split(" ", 5)[1:]
+ if name not in regions:
+ regions[name] = (max(0, int(float(x0) * W)), max(0, int(float(y0) * H)), min(W, int(float(x1) * W)), min(H, int(float(y1) * H)))
+lanes = {}
+for name, (x0, y0, x1, y1) in regions.items():
+ cx0, cy0, cx1, cy1 = x0 * 96 // W, y0 * 54 // H, max(x1 * 96 // W, x0 * 96 // W + 1), max(y1 * 54 // H, y0 * 54 // H + 1)
+ lanes[name] = np.array([m[cy0:cy1, cx0:cx1].mean() for m in maps])
+
+# Transitions: runs of moving frames, bridged over short gaps.
+moving = whole > ACTIVE
+runs, i = [], 0
+while i < n:
+ if not moving[i]:
+ i += 1
+ continue
+ j = i
+ while j + 1 < n and (moving[j + 1] or moving[j + 1:j + 1 + GAP].any()):
+ j += 1
+ runs.append((i, j))
+ i = j + 1
+
+def order(a, b):
+ """The panels that move in frames a..b, each with the frame it starts at after a."""
+ firsts = []
+ for name, lane in lanes.items():
+ hit = np.nonzero(lane[a:b + 1] > ACTIVE * 4)[0]
+ if len(hit):
+ firsts.append((int(hit[0]), name))
+ return sorted(firsts)
+
+with open(os.path.join(out, "transitions.txt"), "w") as f:
+ f.write(f"{exe}: {n} frames, {n / FPS:.2f} s at {FPS} fps; {len(runs)} transitions\n")
+ f.write(" # start frames length peak hold after panels, in the order they start (frames after the first)\n")
+ for k, (a, b) in enumerate(runs):
+ hold = (runs[k + 1][0] if k + 1 < len(runs) else n) - b - 1
+ who = " ".join(f"{name}+{d}" for d, name in order(a, b))
+ f.write(f"{k:3d} {a / FPS:7.2f}s {a:5d}-{b:<5d} {(b - a + 1) / FPS:6.2f}s {whole[a:b + 1].max() * 100:5.1f}% {hold / FPS:6.2f}s {who}\n")
+
+# The plot: the whole frame, then a lane each.
+names = list(regions)
+def plot(path, a, b):
+ t = np.arange(a, b) / FPS
+ fig, axes = plt.subplots(2, 1, figsize=(min(20, max(8, (b - a) / FPS * 1.8)), 2.4 + 0.32 * len(names)), sharex=True,
+ gridspec_kw={"height_ratios": [2.2, 0.32 * len(names) + 0.4]})
+ ax = axes[0]
+ ax.fill_between(t, np.maximum(whole[a:b] * 100, 0.005), 0.005, color="#ff6a4a", step="mid", linewidth=0)
+ ax.set_yscale("log"); ax.set_ylim(0.005, 100); ax.set_ylabel("% of frame changed")
+ for (s, e) in runs:
+ if e >= a and s < b:
+ ax.axvspan(s / FPS, (e + 1) / FPS, color="#e8c46a", alpha=0.18, linewidth=0)
+ ax.grid(True, which="major", axis="both", alpha=0.25)
+ grid = np.array([lanes[name][a:b] for name in names])
+ axes[1].imshow(np.sqrt(grid), aspect="auto", cmap="magma", vmin=0, vmax=0.5, extent=(a / FPS, b / FPS, len(names), 0), interpolation="nearest")
+ axes[1].set_yticks(np.arange(len(names)) + 0.5); axes[1].set_yticklabels(names)
+ axes[1].set_xlabel("seconds")
+ fig.tight_layout(); fig.savefig(path, dpi=110); plt.close(fig)
+
+plot(os.path.join(out, "change.png"), 0, n)
+for k, a in enumerate(range(0, n, 10 * FPS)):
+ plot(os.path.join(out, f"change-{k:02d}.png"), a, min(n, a + 10 * FPS))
+
+# Contact sheets: six frames of each transition, cropped to where it happens.
+TILE, COLS, ROWS = (320, 180), 6, 5
+picks = {}
+for k, (a, b) in enumerate(runs):
+ # From two frames before to where it has settled, evenly.
+ span = np.linspace(max(a - 2, 0), min(b + 3, n - 1), COLS).round().astype(int)
+ picks[k] = list(span)
+want = {int(i) for span in picks.values() for i in span}
+kept = {i: frame.copy() for i, frame in frames(want)}
+
+def crop(a, b):
+ """The box the change of frames a..b happens in, grown to the tile's shape, at least a quarter of the frame."""
+ found = [bx for bx in boxes[a:b + 1] if bx is not None]
+ if not found:
+ return (0, 0, W, H)
+ x0, y0 = min(bx[0] for bx in found), min(bx[1] for bx in found)
+ x1, y1 = max(bx[2] for bx in found), max(bx[3] for bx in found)
+ w = max(x1 - x0 + 40, W // 4, int((y1 - y0 + 40) * 16 / 9))
+ w = min(W, w); h = min(H, int(w * 9 / 16))
+ cx, cy = (x0 + x1) // 2, (y0 + y1) // 2
+ left = min(max(cx - w // 2, 0), W - w); top = min(max(cy - h // 2, 0), H - h)
+ return (left, top, left + w, top + h)
+
+for s in range(0, len(runs), ROWS):
+ sheet = Image.new("RGB", (COLS * TILE[0], min(ROWS, len(runs) - s) * (TILE[1] + 22)), "#000000")
+ draw = ImageDraw.Draw(sheet)
+ for r, k in enumerate(range(s, min(s + ROWS, len(runs)))):
+ a, b = runs[k]
+ box = crop(a, b)
+ hold = (runs[k + 1][0] if k + 1 < len(runs) else n) - b - 1
+ y = r * (TILE[1] + 22)
+ draw.text((6, y + 4), f"#{k} {a / FPS:.2f}s frames {a}-{b} {(b - a + 1) / FPS:.2f}s long, then still {hold / FPS:.2f}s " + " ".join(f"{name}+{d}" for d, name in order(a, b)), fill="#eee6d2")
+ for c, i in enumerate(picks[k]):
+ tile = Image.fromarray(kept[int(i)]).crop(box).resize(TILE, Image.LANCZOS)
+ sheet.paste(tile, (c * TILE[0], y + 22))
+ draw.text((c * TILE[0] + 6, y + 26), f"{int(i)}", fill="#e8c46a")
+ sheet.save(os.path.join(out, f"sheet-{s // ROWS:02d}.png"))
+
+# The summary: the beat, and whether it is a metronome.
+starts = np.array([a for a, _ in runs]) / FPS
+lengths = np.array([b - a + 1 for a, b in runs]) / FPS
+holds = np.array([(runs[k + 1][0] if k + 1 < len(runs) else n) - runs[k][1] - 1 for k in range(len(runs))]) / FPS
+gaps = np.diff(starts)
+print(f"{os.path.basename(exe)}: {n / FPS:.1f} s, {len(runs)} transitions; moving {moving.mean() * 100:.0f}% of the time")
+if len(runs) > 2:
+ print(f" transitions last {np.median(lengths):.2f} s (median), {lengths.min():.2f} to {lengths.max():.2f}")
+ print(f" holds: median {np.median(holds):.2f} s, shortest {holds.min():.2f} s; {int((holds < 0.25).sum())} under 0.25 s")
+ same = np.abs(gaps[1:] - gaps[:-1]) < 0.02
+ longest, cur = 0, 0
+ for v in same:
+ cur = cur + 1 if v else 0
+ longest = max(longest, cur)
+ print(f" beat: {len(set(np.round(gaps, 2)))} different intervals between starts; longest run of equal ones: {longest + 1}")
+print(f" sheets and plots in {out}")
+try:
+ os.remove(os.path.join(out, "motion.state"))
+except OSError:
+ pass
diff --git a/anim/tools/note b/anim/tools/note
new file mode 100644
index 0000000..de75b8f
--- /dev/null
+++ b/anim/tools/note
@@ -0,0 +1 @@
+Hello, kernel!
diff --git a/anim/tools/sort.c b/anim/tools/sort.c
new file mode 100644
index 0000000..5816390
--- /dev/null
+++ b/anim/tools/sort.c
@@ -0,0 +1,22 @@
+int a[8] = {4, 9, 17, 31, 12, 26, 5, 20};
+
+void swap(int *x, int *y) {
+ int t = *x;
+ *x = *y;
+ *y = t;
+}
+
+void sort(int n) {
+ for (int i = 1; i < n; i++) {
+ int j = i;
+ while (j > 0 && a[j - 1] > a[j]) {
+ swap(&a[j - 1], &a[j]);
+ j--;
+ }
+ }
+}
+
+int main(void) {
+ sort(8);
+ return 0;
+}