Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0

Saturday 21 November 2009

Koch Island Using Lindemayer System in Ruby Processing


##
# Lindenmayer System in ruby-processing by Martin Prout
###

require 'koch'

class Koch < Processing::App
  attr_reader :koch
  def setup
    size 500, 500
    @koch = KochLSystem.new
    koch.simulate 4
  end
 
  def draw
    background 0
    koch.render
    save_frame "/home/tux/koch.png"
  end
end

#####################################################################################
## Koch island using an L-System
#####################################################################################


class KochLSystem
  include Processing::Proxy
  @@steps = 0
  attr_accessor :axiom, :rule, :start_length, :theta, :production, :generations, :draw_length
  def initialize
    @axiom = "F-F-F-F"
    @rule = "F-FF--F-F"
    @start_length = 60.0
    @theta = (Math::PI/180) * 90.0 # convert degrees to radians
    reset
  end

  def reset # initialize or reset variables
    @production = axiom
    @draw_length = start_length
    @generations = 0
  end
 
  def iterate(prod_, rule_)
    @draw_length *=  0.6
    @generations += 1
    new_production = prod_         
    new_production.gsub!('F', rule_)
  end
 
  def render()
    translate(width/2, height/3)
    @@steps += 4        
    @@steps = production.length if @@steps > production.length
    prod = production.split(//)  ### for ruby 1.9 use each_char
    @@steps.times do |i|
      case prod[i]
      when 'F'
        no_fill
        stroke 255
        line(0, 0, 0, -draw_length)       
        translate(0, -draw_length)
      when 'f'               #unused
        translate(0, -draw_length)     
      when '+'
        rotate(theta)
      when '-'
        rotate(-theta)
      when '['               # unused
        push_matrix()
      when ']'               # unused
        pop_matrix()
      else puts "Unrecognised grammar" 
      end
    end
  end
  def simulate(gen)
    while (generations < gen)
      @production = iterate(@production, @rule)
    end
  end
end





 

No comments:

Post a Comment

Followers

Blog Archive

About Me

My photo
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2