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

Wednesday 25 November 2009

Snake Kolam Ruby Processing


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

require 'snake_kolam'

class Kolam_Test < Processing::App
  load_libraries 'grammar'
  
  attr_reader :snake
  
  def setup
    size 900, 900
    @snake = SnakeKolam.new
    snake.create_grammar 4
    no_loop
  end
  
  def draw
    background 0
    stroke(255)
    snake.render
  end
end

############################  
# snake_kolam.rb using l-systems
############################

class SnakeKolam
  include Processing::Proxy
  
  attr_accessor :axiom, :start_length, :xpos, :ypos, :grammar, :production, :draw_length
  XPOS = 0
  YPOS = 1
  ANGLE = 2
  DELTA = (Math::PI/180) * 90.0 # convert degrees to radians
  
  def initialize
    setup_grammar
    @start_length = 160.0
    @theta = (Math::PI/180) * 90.0 # convert degrees to radians
    @draw_length = start_length
    @draw_length = start_length
    @xpos = width/8
    @ypos = height*0.8
  end

  def setup_grammar
    @axiom = "FX+F+FX+F"
    @grammar = Grammar.new(axiom)
    grammar.add_rule("X", "X-F-F+FX+F+FX-F-F+FX")
    @production = axiom
  end
  
  def render                       # NB not using affine transforms here
    turtle = [xpos, ypos, 0.0]
    production.scan(/./).each do |element|
      case element
      when 'F'                    
        turtle = draw_line(turtle, draw_length)
      when '+'
        turtle[ANGLE] += DELTA   # rotate by + theta if going the affine transform route
      when '-'
        turtle[ANGLE] -= DELTA   # rotate by - theta if going the affine transform route
      when 'X'                     # do nothing except recognize 'X' as a word in the L-system grammar
      else 
              puts "Character '#{element}' is not in grammar" 
      end
    end
  end
  
  ##############################
  # create grammar from axiom and
  # rules (adjust scale)
  ##############################
  
  def create_grammar(gen)
    @draw_length *=  0.6**gen
    @production = @grammar.generate gen
  end
  
  private
  ######################################################
  # draws line using current turtle and length parameters
  # returns a turtle corresponding to the new position
  ######################################################

  def draw_line(turtle, length)
    new_xpos = turtle[XPOS] + length * Math.cos(turtle[ANGLE])
    new_ypos = turtle[YPOS] + length * Math.sin(turtle[ANGLE])
    line(turtle[XPOS], turtle[YPOS], new_xpos, new_ypos)
    turtle = [new_xpos, new_ypos, turtle[ANGLE]]
  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