diff options
Diffstat (limited to 'examples/noc/src/recursive_tree.zig')
| -rw-r--r-- | examples/noc/src/recursive_tree.zig | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/examples/noc/src/recursive_tree.zig b/examples/noc/src/recursive_tree.zig new file mode 100644 index 0000000..a71f7f9 --- /dev/null +++ b/examples/noc/src/recursive_tree.zig @@ -0,0 +1,35 @@ +//! Example 8.6: Recursive Tree. Each branch draws itself, then two +//! branches two thirds as long, turned by the angle the pointer's x sets +//! (0 at the left edge, a right angle at the right). Push/pop is +//! `pen.transformed`: each call gets its own pen. +const std = @import("std"); +const sk = @import("sketch"); + +pub const name = "recursive_tree"; +pub const width = 640; +pub const height = 360; + +pub const State = struct { + angle: f32 = 0, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + s.angle = std.math.lerp(0, std.math.pi / 2.0, in.mouse_x / width); +} + +const trunk: sk.draw.Pen = .{ .stroke = .black, .width = 2, .xf = .translate(width / 2, height) }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(.white); + branch(f, trunk, 100, s.angle); +} + +fn branch(f: *sk.Frame, pen: sk.draw.Pen, len: f32, angle: f32) void { + sk.draw.line(f, .{ 0, 0 }, .{ 0, -len }, pen); + const tip = pen.transformed(.translate(0, -len)); + const next = len * 0.67; + if (next > 2) { + branch(f, tip.transformed(.rotate(angle)), next, angle); + branch(f, tip.transformed(.rotate(-angle)), next, angle); + } +} |
