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

Thursday, 11 February 2010

MPeano Fractal (Traveling Salesman Problem)

Uses my grammar library see the Cesàro fractal, here I included it in the mpeano.rb file, which is why it didn't need to be separately loaded (omitted for brevity).

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

class MPeano_Test < Processing::App
  attr_reader :mpeano, :points, :production

  def setup
    size(600, 600)
    @mpeano = MPeano.new(width/2, height*0.95)
    @production = mpeano.create_grammar(7)
    @points = mpeano.translate_rules(production)
    no_loop()
  end

  def draw()
    background(0)
    stroke(255)
    points.each do |tmp|
      line(*tmp)
    end
  end
end

####################################################
# The MPeano fractal has been used to study the
# Euclidean travelling salesman problem
####################################################
class MPeano

  attr_reader :draw_length, :xpos, :ypos, :theta, :axiom, :grammar, :delta

  def initialize xpos, ypos
    @axiom = "XFF--AFF--XFF--AFF"
    @delta = Math::PI/4 # 45 degrees
    @theta  = delta * 2
    @grammar = Grammar.new(axiom)
    grammar.add_rule("X", "+!X!FF-BQFI-!X!FF+")
    grammar.add_rule("F", "")
    grammar.add_rule("Y", "FFY")
    grammar.add_rule("A", "BQFI")
    grammar.add_rule("B", "AFF")
    @draw_length = 8
    @xpos = xpos
    @ypos = ypos
  end

  def create_grammar(gen)  
    grammar.generate(gen)
  end

  def translate_rules(prod)
    points = [] # An empty array to store lines as an array of points
    prod.scan(/./) do |ch|
      case(ch)
      when "F"
        temp = [xpos, ypos, (@xpos -= draw_length * Math.cos(theta)), (@ypos -= draw_length * Math.sin(theta))]
        points.push(temp)    
      when "+"
        @theta += delta    
      when "-"
        @theta -= delta  
      when "!"
        @delta = -delta
      when "I"
              @draw_length *= 1/Math.sqrt(2)    
      when "Q"
              @draw_length *= Math.sqrt(2)    
      when "X", "A", "B"    
      else
        puts("character '#{ch}' not in grammar")
      end
   end
   return points
  end
end


 

No comments:

Post a Comment

Followers

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