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

Monday 28 December 2009

Peano curve fractal using Lindenmayer Systems

Peano curve using my custom library

######################################################
# peano_test.rb
#
# Lindenmayer System in ruby-processing by Martin Prout
######################################################
require 'grammar'
require 'peano'

class Peano_Test < Processing::App
  attr_reader :peano
  def setup
    size 1000, 1000
    @peano = Peano.new
    peano.create_grammar 4
    no_loop
  end
  def draw
    background 0
    peano.render
  end
end

############################
# peano.rb
#
# Peano Fractal
###########################
class Peano
  include Processing::Proxy

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

  def initialize
    @axiom = "XF"
    @grammar = Grammar.new axiom
    grammar.add_rule 'X', "X+YF++YF-FX--FXFX-YF+"    ## replace X with this string see grammar library
    grammar.add_rule 'Y', "-FX+YFYF++YF+FX--FX-Y"   ## replace Y with this string see grammar library
    @start_length = 120.0
    @theta = 0.0
    @xpos = width/3
    @ypos = height/10
    @production = axiom
    @draw_length = start_length
  end

  def render()
    @production.each_char do |element|
      case element
      when 'F'
        line(@xpos, @ypos, (@xpos -= (draw_length * Math.cos(theta))), (@ypos += (draw_length * Math.sin(theta))))
      when '+'
        @theta += DELTA
      when '-'
        @theta -= DELTA
      when 'X','Y'     ## do nothing except recognize the grammar
      else puts "Grammar not recognized"
      end
    end
  end

  def create_grammar(gen)
    stroke 255
    @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