Skip to content

How to use the library

Martin Prout edited this page Jul 28, 2013 · 22 revisions

The first thing do to is to run the included samples, it will give you an idea of what can be done. It might also be interesting to look at the huge range of examples at contextfreeart.org for inspiration. However there are some limitations on what can be achieved, I have not yet implemented a depth sampling function so contextfreeart sketches that use the z parameter cannot be translated. But interestingly some sketches like my 'y' sketch are not possible using the c++ program, nor is a gui for adjusting the running sketch (control-panel ruby-processing). The following example demonstrates the DSL features.

# city.rb after city.cfdg

require 'cf3'  # NB: requires ruby 1.9 for rand range

def setup_the_city
  @city = ContextFree.define do
    
    shape :neighborhood do
      split do
        block x: -0.25, y: -0.25
        rewind
        block x: 0.25, y: -0.25
        rewind
        block x: 0.25, y: 0.25
        rewind
        block x: -0.25, y: 0.25
      end
    end
    
    shape :block do
      buildings size: 0.85
    end
    
    shape :block, 5 do
      neighborhood size: 0.5, rotation: rand(-PI..PI), hue: rand(2), brightness: rand(0.75..1.75)
    end
    
    shape :block, 0.1 do
      # Do nothing
    end
    
    shape :buildings do
      square
    end
    
  end
end

def setup
  size 600, 600
  smooth
  setup_the_city
  @background = color 255, 255, 255
  draw_it
end

def draw
  # Do nothing
end

def draw_it
  background @background
  @city.render :neighborhood, 
               start_x: width/2, start_y: height/2, 
               size: height/2.5, color: [0.1, 0.1, 0.1]
end

def mouse_clicked
  draw_it
end

Since contextfreeart version 3.0 the basic rule, is now called a shape. There may more than one of these shape rules included in the grammar:-

See :block above where there are three, each given a different weighting or probability, no number given equates to a weighting factor of 1.0 (in this case we have weighting of 5.0, 1,0 and 0.1 = sum 6.1). The actual probability of the first :block rule being run is 5.0 / 6.1 and the others follow. So for example we look at the :neighbourhood shape rule we call :block 4 times, and the actual :block shape rules get run according to their probabilities. So what does rewind do, well with out rewind the shape would get drawn according the current position size etc rewind restores the position size etc to where it would have been if the immediately preceding shape rule had not been run. So what actually gets drawn, well on terminal shapes get rendered in this case represented by the :building shape rule where a square gets drawn (a processing rect under the hood). The three basic terminals are square, triangle and circle (ellipse under the hood), but user defined shapes may also be declared.

Clone this wiki locally