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

Monday 7 April 2014

Funked up drawolver

Now draw multiple shapes, use 'c' key to clear.
# Composite Drawolver: draw 2D & revolve 3D

# Example to show how to use the VecMath library.
# Also features the use each_cons, possibly a rare 
# use for this ruby Enumerable method?
# From an original by fjenett (funked up by monkstone)
# now uses 'zip' and 'each', in place of a custom Array object
# with a 'one_of_each' method

load_library :vecmath

attr_reader :drawing_mode, :points, :rot_x, :rot_y, :vertices

def setup
  size 1024, 768, P3D
  frame_rate 30
  reset_scene
end

def draw
  background 0
  if (!drawing_mode)
    translate(width/2, height/2)
    rotate_x rot_x
    rotate_y rot_y
    @rot_x += 0.01
    @rot_y += 0.02
    translate(-width/2, -height/2)
  end
  no_fill
  stroke 255
  points.each_cons(2) { |ps, pe| line ps.x, ps.y, pe.x, pe.y}

  if (!drawing_mode)
    stroke 125
    fill 120
    lights
    ambient_light 120, 120, 120
    vertices.each_cons(2) do |r1, r2|
      begin_shape(TRIANGLE_STRIP)
      r1.zip(r2).each do |v1, v2|
        vertex v1.x, v1.y, v1.z
        vertex v2.x, v2.y, v2.z
      end
      end_shape
    end
  end
end

def reset_scene
  @drawing_mode = true
  @points = []
  @rot_x = 0.0
  @rot_y = 0.0
end

def mouse_pressed
  reset_scene
  points << Vec3D.new(mouse_x, mouse_y)
end

def mouse_dragged
  points << Vec3D.new(mouse_x, mouse_y)
end

def mouse_released
  points << Vec3D.new(mouse_x, mouse_y)
  recalculate_shape
end

def key_pressed
  case key
  when 'c'
    @vertices.clear
    reset_scene
  end
end

def recalculate_shape
  @vertices ||= []
  points.each_cons(2) do |ps, pe|
    b = points.last - points.first
    b.normalize!
    a = ps - points.first
    dot = a.dot b
    b = b * dot
    normal = points.first + b
    c = ps - normal
    vertices << []
    ecos = ->(n, c, a){n +c * cos(a)}
    esin = ->(c, a){c.mag * sin(a)}
    (0..TAU).step(PI/15) do |ang|
      e = ecos.call(normal, c, ang)
      e.z = esin.call(c, ang)
      vertices.last << e
    end
  end
  @drawing_mode = false
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