|
| 1 | +require 'forwardable' |
| 2 | + |
| 3 | +# Here we use our own Vec2D class, until we create a path as an array of TVec2D |
| 4 | +# toxis Vec2D. Required to use the ToxicLibsSupport lineStrip2D method. |
| 5 | +# further we can and should use power of ruby to make Branch enumerable and |
| 6 | +# Forwardable to define which enumerable methods we want to use |
| 7 | +class Branch |
| 8 | + include Enumerable |
| 9 | + extend Forwardable |
| 10 | + def_delegators(:@children, :<<, :each, :length) |
| 11 | + # variance angle for growth direction per time step |
| 12 | + THETA = Math::PI / 6 |
| 13 | + # max segments per branch |
| 14 | + MAX_LEN = 100 |
| 15 | + # max recursion limit |
| 16 | + MAX_GEN = 3 |
| 17 | + # branch chance per time step |
| 18 | + BRANCH_CHANCE = 0.05 |
| 19 | + # branch angle variance |
| 20 | + BRANCH_THETA = Math::PI / 3 |
| 21 | + attr_reader :position, :dir, :path, :children, :xbound, :speed, :ybound, :app |
| 22 | + |
| 23 | + def initialize(app, pos, dir, speed) |
| 24 | + @app = app |
| 25 | + @position = pos |
| 26 | + @dir = dir |
| 27 | + @speed = speed |
| 28 | + @path = [] |
| 29 | + @children = [] |
| 30 | + @xbound = Boundary.new(0, app.width) |
| 31 | + @ybound = Boundary.new(0, app.height) |
| 32 | + path << TVec2D.new(pos.x, pos.y) |
| 33 | + end |
| 34 | + |
| 35 | + def run |
| 36 | + grow |
| 37 | + display |
| 38 | + end |
| 39 | + |
| 40 | + private |
| 41 | + |
| 42 | + # Note use of both rotate! (changes original) rotate (returns a copy) of Vec2D |
| 43 | + def grow |
| 44 | + check_bounds(position + (dir * speed)) if path.length < MAX_LEN |
| 45 | + @position += (dir * speed) |
| 46 | + dir.rotate!(rand(-0.5..0.5) * THETA) |
| 47 | + path << TVec2D.new(position.x, position.y) |
| 48 | + if (length < MAX_GEN) && (rand < BRANCH_CHANCE) |
| 49 | + branch_dir = dir.rotate(rand(-0.5..0.5) * BRANCH_THETA) |
| 50 | + self << Branch.new(app, position.copy, branch_dir, speed * 0.99) |
| 51 | + end |
| 52 | + each(&:grow) |
| 53 | + end |
| 54 | + |
| 55 | + def display |
| 56 | + app.gfx.lineStrip2D(path) |
| 57 | + each(&:display) |
| 58 | + end |
| 59 | + |
| 60 | + def check_bounds(pos) |
| 61 | + dir.x *= -1 if xbound.exclude? pos.x |
| 62 | + dir.y *= -1 if ybound.exclude? pos.y |
| 63 | + end |
| 64 | +end |
| 65 | + |
| 66 | +# we are looking for excluded values |
| 67 | +Boundary = Struct.new(:lower, :upper) do |
| 68 | + def exclude?(val) |
| 69 | + true unless (lower...upper).cover? val |
| 70 | + end |
| 71 | +end |
0 commit comments