summaryrefslogtreecommitdiff
path: root/src/vector/morph.zig
blob: f285c7e2a70d6dd77eba6c9525c0668c5a4a89a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
//! Drawings in between two drawings, as manim transforms them: shapes pair up
//! in order; each pair's subpaths, then each subpath's cubics, are made equal
//! in number by splitting the longest curves; then every control point and
//! color is interpolated. A shape without a partner collapses to (or grows
//! from) the other drawing's center.
const std = @import("std");
const geom = @import("math");
const Drawing = @import("Drawing.zig");
const Vec = geom.Vec;
const Cubic = geom.Cubic;

/// The drawing `t` of the way from `a` (placed by `ma`) to `b` (placed by
/// `mb`), in the space both transforms map to. Allocated in `arena`.
pub fn between(arena: std.mem.Allocator, a: Drawing, ma: geom.Affine, b: Drawing, mb: geom.Affine, t: f32) !Drawing {
    var out: Drawing.Builder = .init(arena);
    const ca = center(a, ma);
    const cb = center(b, mb);
    const n = @max(a.shapes.len, b.shapes.len);
    for (0..n) |i| {
        const sa: ?Drawing.Shape = if (i < a.shapes.len) a.shapes[i] else null;
        const sb: ?Drawing.Shape = if (i < b.shapes.len) b.shapes[i] else null;
        // The missing side is the other side, shrunk to a point.
        const pa = try placed(arena, a, sa, ma, sb, b, mb, cb);
        const pb = try placed(arena, b, sb, mb, sa, a, ma, ca);
        const count = @max(pa.len, pb.len);
        for (0..count) |k| {
            const from = try pad(arena, pa, k, if (pa.len > 0) lastPoint(pa) else ca);
            const to = try pad(arena, pb, k, if (pb.len > 0) lastPoint(pb) else cb);
            const aligned = try align2(arena, from.cubics, to.cubics);
            for (aligned[0], aligned[1]) |x, y| {
                var c: Cubic = undefined;
                for (&c, x, y) |*p, u, v| p.* = geom.mix(u, v, t);
                try out.cubic(c);
            }
            try out.closeSubpath(from.closed or to.closed);
        }
        const style_a = if (sa) |s| s.style else fade(sb.?.style);
        const style_b = if (sb) |s| s.style else fade(sa.?.style);
        try out.endShape(.identity, mixStyle(a, style_a, b, style_b, t));
    }
    return out.finish(a.view, a.width, a.height);
}

const Path = struct { cubics: []const Cubic, closed: bool };

/// The subpaths of `shape` in the shared space; for a missing shape, its
/// partner's subpaths collapsed onto `point`.
fn placed(arena: std.mem.Allocator, d: Drawing, shape: ?Drawing.Shape, m: geom.Affine, partner: ?Drawing.Shape, pd: Drawing, pm: geom.Affine, point: Vec) ![]Path {
    const s = shape orelse {
        const p = partner.?;
        const subpaths = pd.subpathsOf(p);
        const out = try arena.alloc(Path, subpaths.len);
        for (out, subpaths) |*o, sp| {
            const cubics = try arena.alloc(Cubic, pd.cubicsOf(sp).len);
            @memset(cubics, .{ point, point, point, point });
            o.* = .{ .cubics = cubics, .closed = sp.closed };
        }
        _ = pm;
        return out;
    };
    const subpaths = d.subpathsOf(s);
    const full = m.mul(s.transform);
    const out = try arena.alloc(Path, subpaths.len);
    for (out, subpaths) |*o, sp| {
        const src = d.cubicsOf(sp);
        const cubics = try arena.alloc(Cubic, src.len);
        for (cubics, src) |*dst, c| dst.* = .{ full.apply(c[0]), full.apply(c[1]), full.apply(c[2]), full.apply(c[3]) };
        o.* = .{ .cubics = cubics, .closed = sp.closed };
    }
    return out;
}

/// Subpath `k`, or a point-sized one where the list is shorter.
fn pad(arena: std.mem.Allocator, paths: []const Path, k: usize, point: Vec) !Path {
    if (k < paths.len) return paths[k];
    const one = try arena.alloc(Cubic, 1);
    one[0] = .{ point, point, point, point };
    return .{ .cubics = one, .closed = false };
}

fn lastPoint(paths: []const Path) Vec {
    const last = paths[paths.len - 1].cubics;
    return last[last.len - 1][3];
}

/// Both lists with the same number of cubics: the shorter one's longest
/// curves are split in half until they match.
fn align2(arena: std.mem.Allocator, a: []const Cubic, b: []const Cubic) ![2][]const Cubic {
    if (a.len == b.len) return .{ a, b };
    if (a.len < b.len) return .{ try refine(arena, a, b.len), b };
    return .{ a, try refine(arena, b, a.len) };
}

fn refine(arena: std.mem.Allocator, cubics: []const Cubic, n: usize) ![]const Cubic {
    var list: std.ArrayList(Cubic) = try .initCapacity(arena, n);
    list.appendSliceAssumeCapacity(cubics);
    while (list.items.len < n) {
        var longest: usize = 0;
        var best: f32 = -1;
        for (list.items, 0..) |c, i| {
            const len = geom.roughLength(c);
            if (len > best) {
                best = len;
                longest = i;
            }
        }
        const halves = geom.split(list.items[longest], 0.5);
        list.items[longest] = halves[0];
        list.insertAssumeCapacity(longest + 1, halves[1]);
    }
    return list.items;
}

fn center(d: Drawing, m: geom.Affine) Vec {
    const b = d.bounds();
    return m.apply(if (b.empty()) d.view.center() else b.rect().center());
}

/// A style that draws nothing, for shapes appearing from or vanishing into
/// a point.
fn fade(s: Drawing.Style) Drawing.Style {
    var out = s;
    out.opacity = 0;
    return out;
}

/// Styles in between: numbers blend; solid colors blend; anything else
/// switches halfway.
fn mixStyle(a: Drawing, sa: Drawing.Style, b: Drawing, sb: Drawing.Style, t: f32) Drawing.Style {
    var s = if (t < 0.5) sa else sb;
    s.fill = mixPaint(a, sa.fill, b, sb.fill, t);
    s.stroke = mixPaint(a, sa.stroke, b, sb.stroke, t);
    s.stroke_width = std.math.lerp(sa.stroke_width, sb.stroke_width, t);
    s.opacity = std.math.lerp(sa.opacity, sb.opacity, t);
    s.fill_opacity = std.math.lerp(sa.fill_opacity, sb.fill_opacity, t);
    s.stroke_opacity = std.math.lerp(sa.stroke_opacity, sb.stroke_opacity, t);
    return s;
}

fn mixPaint(a: Drawing, pa: Drawing.Paint, b: Drawing, pb: Drawing.Paint, t: f32) Drawing.Paint {
    _ = a;
    _ = b;
    const ca = switch (pa) {
        .color => |c| c,
        .none => if (pb == .color) pb.color * Drawing.Color{ 1, 1, 1, 0 } else return pb,
        .gradient => return if (t < 0.5) pa else pb,
    };
    const cb = switch (pb) {
        .color => |c| c,
        .none => ca * Drawing.Color{ 1, 1, 1, 0 },
        .gradient => return if (t < 0.5) pa else pb,
    };
    return .{ .color = ca + (cb - ca) * @as(Drawing.Color, @splat(t)) };
}

test "a square becomes a circle through aligned cubics" {
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    var ba: Drawing.Builder = .init(arena.allocator());
    try ba.rect(.{ .x = -10, .y = -10, .w = 20, .h = 20 }, 0);
    try ba.endShape(.identity, .{ .fill = .{ .color = .{ 1, 0, 0, 1 } } });
    const square = try ba.finish(.{}, 0, 0);
    var bb: Drawing.Builder = .init(arena.allocator());
    try bb.ellipse(.{ 0, 0 }, 10, 10);
    try bb.ellipse(.{ 30, 0 }, 5, 5);
    try bb.endShape(.identity, .{ .fill = .{ .color = .{ 0, 0, 1, 1 } } });
    const circles = try bb.finish(.{}, 0, 0);

    const start = try between(arena.allocator(), square, .identity, circles, .identity, 0);
    const end = try between(arena.allocator(), square, .identity, circles, .identity, 1);
    const mid = try between(arena.allocator(), square, .identity, circles, .identity, 0.5);
    try std.testing.expectEqual(@as(usize, 2), mid.subpaths.len);
    try std.testing.expectEqual(mid.subpaths[0].count, mid.subpaths[1].count);
    // The ends are the originals.
    try std.testing.expectEqual(square.cubics[0][0], start.cubics[0][0]);
    try std.testing.expectEqual(geom.vec(10, 0), end.cubics[0][0]);
    try std.testing.expectEqual(Drawing.Color{ 0.5, 0, 0.5, 1 }, mid.shapes[0].style.fill.color);
}