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

Wednesday 6 January 2010

Another control panel example with odd turtle turns


##
# A Spiro fractal implemented using a
# Lindenmayer System in ruby-processing by Martin Prout
###
require 'spiro'

class Spiro_Test < Processing::App
  load_libraries :grammar, :control_panel

  attr_reader :spiro, :repeat, :xpos, :ypos

  def setup
    size 600, 800
    setup_panel
    @xpos = width/3
    @ypos = height/4
    @repeat = 5
    redraw
  end

  def setup_panel
    control_panel do |c|
      c.title = "Control:"
      c.menu(:generation, ['5', '6', '7', '8'], '5') {|m| load_menu_item(m) }
      c.slider(:xpos, 0..600, 200)
      c.slider(:ypos, 0..800, 200)
      c.button(:redraw)
    end
  end

  def redraw
    @spiro = Spiro.new(xpos, ypos)
    spiro.create_grammar(repeat)
  end

  def load_menu_item(item)
    @repeat = item.to_i
    case repeat
    when 7
      @xpos = width/2
      @ypos = height/2
    when 5, 6
      @xpos = width/3
      @ypos = height/4
    else
      @xpos = width/2
      @ypos = height/2
    end
  end

  def draw
    background 0
    spiro.render
  end
end

############################
# spiro.rb
###########################
class Spiro
  include Processing::Proxy

  attr_accessor :axiom, :grammar, :start_length, :theta, :production, :draw_length, :xpos, :ypos
  DELTA = (Math::PI/180) * 251                 # convert degrees to radians
  GAMMA = (Math::PI/180) * 252                 # convert degrees to radians

  def initialize(xpos, ypos)
    @axiom = "F"
    @grammar = Grammar.new axiom
    grammar.add_rule "F", "F-F+F+F-F"                  # replace F rule see grammar library
    @start_length = 100
    @theta = 0.0
    @xpos = xpos
    @ypos = ypos
    stroke 255
    @production = axiom
    @draw_length = start_length
  end

  def render                       # NB using affine transforms here
    translate(xpos, ypos)        
    production.each_char do |element|
      case element
      when 'F'                    
        line(0, 0, draw_length, 0)
        translate(draw_length, 0)
      when '+'
        rotate(DELTA)   # rotate by +DELTA
      when '-'
        rotate(-GAMMA)   # rotate by - GAMMA
      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
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