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

Showing posts with label ruby-processing. Show all posts
Showing posts with label ruby-processing. Show all posts

Monday, 12 October 2015

Bye Bye Blogger Hello Github

It was nice to be gothic but I've moved onto github.io for blogging about JRubyArt:-

Personal JRubyArt blog



Monkstone

Ruby-Processing group blog



Ruby Processing Group

Thursday, 30 July 2015

Ruby-Processing now using pry for live coding mode

The latest release of ruby-processing uses pry for live coding, and this is genuinely exciting. Here is a live mode for a class wrapped jwishy.rb sketch, which I have listed in the pry console using '$' command (NB: click on images to see full size):-

This is all the class wrapping needed

class JWishy < Processing::App
  # bare sketch code
end
Bare sketches instead get listed as the super class, but to be honest listing of the code in the pry console is not that exciting see embedded video, the exciting bit is to be able to futz with sketch code from the console and watch it affect the running console (but why not try it for yourself). In the "Wishy Worm" example we change the background of the sketch by changing the @back_color variable, and change the bluish accessor method to a custom method that returns bluish as function of the y_wiggle variable

But you can do so much more, including 'ls' available methods, and remember pry has a built in help...


live from monkstone on Vimeo.

Live coding in ruby-processing now using pry

Bounce.rb code used in video
You should also checkout the pry 'edit' function, which allows you to use your favourite editor to edit a method say 'JWishy#draw'

Friday, 3 July 2015

JRubyArt-0.3.0 vs ruby-processing-2.6.12

Previously I posted a comparison between a different version of JRubyArt and ruby-processing where both were running using processing-2.2.1 and the the same version, but they had different designs. The current JRubyArt candidate is more similar to ruby-processing, but is targetting processing-3.0 (currently 3.0a10) and jruby-9.0.0.0 (currently jruby-9.0.0.0.rc1). I see ruby-processing as sticking with processing-2.2.1, but remaining compatible with stable releases of jruby, whereas JRubyArt will only be compatible with processing-3.0a10+.

External Dependencies

  • ruby-processing requires an installed version of processing-2.2.1
  • ruby-processing requires an installed version of processing-3.0a10+

Core processing libraries (sound, video etc)

  • ruby-processing has builtin support 
  • jruby_art has the same built in support but sound, video libraries are now external (since processing-3.0)

Contributed processing libraries

  • ruby-processing has builtin support for libraries installed by processing ide 
  • jruby_art has the same builtin support for libraries installed by processing

Vec2D, Vec3D, Arcball and DEGLUT

  • ruby-processing requires load_library 
  • jruby_art these libraries automatically loaded into jruby runtime

Processing::Proxy module

  • in ruby-processing Proxy can be used to mimic processings inner classes, probably v. bad juju convenience isn't everything 
  • in jruby_art a different Proxy can also be used to mimic processings inner classes but has a simpler implementation

Friday, 26 June 2015

When to use Processing::Proxy

Just in case it has passed you by, processing uses java inner classes to give your own classes access to the PApplet methods/variables. For ruby-processing you can include the Processing::Proxy module to give you a similar level of access, note the width and height variables are not available (you can use $app.width and $app.height to get round that). This all very non OO so you should use it only when you need it:-

Sunday, 14 June 2015

FX2D works better than JAVA2D on ruby-processing-3.0

Interesting pre-processing of pde sketches to move "size" from "setup" to "settings" does not seem to be implemented for FX2D sketches see sketch:-
FX2D sketch run from processing ide



















Possibly because of a Ben Fry kludge JAVA2D isn't playing well in ruby-processing-3.0 (but then I tried FX2D) and happiness ensued shame about the opengl sketches jumping around
def setup
  sketch_title 'FX2D'
end

def draw
  background 0
  fill 200, 0, 0
  ellipse width / 2, height / 2, 300, 200
end

def settings
  size 400, 300, FX2D
end


Sketch run from ruby-processing-3.0

Saturday, 6 June 2015

Prototyping glsl shader sketches in ruby-processing

Well actually there's an argument for sticking with ruby-processing since there is not much of a performance improvement to be gained by using vanilla processing. I have now included some modififications to ruby-processing that give it the "winning edge" for developing shader sketches in the since ruby-processing-2.6.11 the watch mode has been extended to monitor changes to the glsl shader code (in addition to the ruby code).
                                                        
rp5 watch edge_detect_capture.rb                                                                                                                                               

                                                        
vim data/edge.glsl                                                                                                                                               


// Original shader by Ken Slade
// https://www.shadertoy.com/view/ldsSWr

// Ported to Processing by Raphaël de Courville <twitter: @sableRaph>

#ifdef GL_ES
precision highp float;
#endif

uniform sampler2D texture; // iChannel0 in Shadertoy
uniform vec2 sketchSize; // iResolution in Shadertoy

//options are edge, colorEdge, or trueColorEdge
#define EDGE_FUNC edge


//options are KAYYALI_NESW, KAYYALI_SENW, PREWITT, ROBERTSCROSS, SCHARR, or SOBEL
#define SOBEL

// Use these parameters to fiddle with settings
#ifdef SCHARR
#define STEP 0.15
#else
#define STEP 1.0
#endif


#ifdef KAYYALI_NESW
const mat3 kayyali_NESW = mat3(-6.0, 0.0, 6.0,
                               0.0, 0.0, 0.0,
                               6.0, 0.0, -6.0);
#endif
#ifdef KAYYALI_SENW
const mat3 kayyali_SENW = mat3(6.0, 0.0, -6.0,
                               0.0, 0.0, 0.0,
                               -6.0, 0.0, 6.0);
#endif
#ifdef PREWITT
// Prewitt masks (see http://en.wikipedia.org/wiki/Prewitt_operator)
const mat3 prewittKernelX = mat3(-1.0, 0.0, 1.0,
                                 -1.0, 0.0, 1.0,
                                 -1.0, 0.0, 1.0);

const mat3 prewittKernelY = mat3(1.0, 1.0, 1.0,
                                 0.0, 0.0, 0.0,
                                 -1.0, -1.0, -1.0);
#endif
#ifdef ROBERTSCROSS
// Roberts Cross masks (see http://en.wikipedia.org/wiki/Roberts_cross)
const mat3 robertsCrossKernelX = mat3(1.0, 0.0, 0.0,
                                      0.0, -1.0, 0.0,
                                      0.0, 0.0, 0.0);
const mat3 robertsCrossKernelY = mat3(0.0, 1.0, 0.0,
                                      -1.0, 0.0, 0.0,
                                      0.0, 0.0, 0.0);
#endif
#ifdef SCHARR
// Scharr masks (see http://en.wikipedia.org/wiki/Sobel_operator#Alternative_operators)
const mat3 scharrKernelX = mat3(3.0, 10.0, 3.0,
                                0.0, 0.0, 0.0,
                                -3.0, -10.0, -3.0);

const mat3 scharrKernelY = mat3(3.0, 0.0, -3.0,
                                10.0, 0.0, -10.0,
                                3.0, 0.0, -3.0);
#endif
#ifdef SOBEL
// Sobel masks (see http://en.wikipedia.org/wiki/Sobel_operator)
const mat3 sobelKernelX = mat3(1.0, 0.0, -1.0,
                               2.0, 0.0, -2.0,
                               1.0, 0.0, -1.0);

const mat3 sobelKernelY = mat3(-1.0, -2.0, -1.0,
                               0.0, 0.0, 0.0,
                               1.0, 2.0, 1.0);
#endif

//performs a convolution on an image with the given kernel
float convolve(mat3 kernel, mat3 image) {
    float result = 0.0;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            result += kernel[i][j]*image[i][j];
        }
    }
    return result;
}

//helper function for colorEdge()
float convolveComponent(mat3 kernelX, mat3 kernelY, mat3 image) {
    vec2 result;
    result.x = convolve(kernelX, image);
    result.y = convolve(kernelY, image);
    return clamp(length(result), 0.0, 255.0);
}

//returns color edges using the separated color components for the measure of intensity
//for each color component instead of using the same intensity for all three.  This results
//in false color edges when transitioning from one color to another, but true colors when
//the transition is from black to color (or color to black).
vec4 colorEdge(float stepx, float stepy, vec2 center, mat3 kernelX, mat3 kernelY) {
    //get samples around pixel
    vec4 colors[9];
    colors[0] = texture2D(texture,center + vec2(-stepx,stepy));
    colors[1] = texture2D(texture,center + vec2(0,stepy));
    colors[2] = texture2D(texture,center + vec2(stepx,stepy));
    colors[3] = texture2D(texture,center + vec2(-stepx,0));
    colors[4] = texture2D(texture,center);
    colors[5] = texture2D(texture,center + vec2(stepx,0));
    colors[6] = texture2D(texture,center + vec2(-stepx,-stepy));
    colors[7] = texture2D(texture,center + vec2(0,-stepy));
    colors[8] = texture2D(texture,center + vec2(stepx,-stepy));

    mat3 imageR, imageG, imageB, imageA;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            imageR[i][j] = colors[i*3+j].r;
            imageG[i][j] = colors[i*3+j].g;
            imageB[i][j] = colors[i*3+j].b;
            imageA[i][j] = colors[i*3+j].a;
        }
    }

    vec4 color;
    color.r = convolveComponent(kernelX, kernelY, imageR);
    color.g = convolveComponent(kernelX, kernelY, imageG);
    color.b = convolveComponent(kernelX, kernelY, imageB);
    color.a = convolveComponent(kernelX, kernelY, imageA);

    return color;
}

//finds edges where fragment intensity changes from a higher value to a lower one (or
//vice versa).
vec4 edge(float stepx, float stepy, vec2 center, mat3 kernelX, mat3 kernelY){
    // get samples around pixel
    mat3 image = mat3(length(texture2D(texture,center + vec2(-stepx,stepy)).rgb),
                      length(texture2D(texture,center + vec2(0,stepy)).rgb),
                      length(texture2D(texture,center + vec2(stepx,stepy)).rgb),
                      length(texture2D(texture,center + vec2(-stepx,0)).rgb),
                      length(texture2D(texture,center).rgb),
                      length(texture2D(texture,center + vec2(stepx,0)).rgb),
                      length(texture2D(texture,center + vec2(-stepx,-stepy)).rgb),
                      length(texture2D(texture,center + vec2(0,-stepy)).rgb),
                      length(texture2D(texture,center + vec2(stepx,-stepy)).rgb));
    vec2 result;
    result.x = convolve(kernelX, image);
    result.y = convolve(kernelY, image);

    float color = clamp(length(result), 0.0, 255.0);
    return vec4(color);
}

//Colors edges using the actual color for the fragment at this location
vec4 trueColorEdge(float stepx, float stepy, vec2 center, mat3 kernelX, mat3 kernelY) {
    vec4 edgeVal = edge(stepx, stepy, center, kernelX, kernelY);
    return edgeVal * texture2D(texture,center);
}

void main( void ){
    vec2 uv = gl_FragCoord.xy / sketchSize.xy;
    vec4 color = texture2D(texture, uv.xy);
#ifdef KAYYALI_NESW
    gl_FragColor = EDGE_FUNC(STEP/sketchSize[0], STEP/sketchSize[1],
                            uv,
                            kayyali_NESW, kayyali_NESW);
#endif
#ifdef KAYYALI_SENW
    gl_FragColor = EDGE_FUNC(STEP/sketchSize[0], STEP/sketchSize[1],
                            uv,
                            kayyali_SENW, kayyali_SENW);
#endif
#ifdef PREWITT
    gl_FragColor = EDGE_FUNC(STEP/sketchSize[0], STEP/sketchSize[1],
                            uv,
                            prewittKernelX, prewittKernelY);
#endif
#ifdef ROBERTSCROSS
    gl_FragColor = EDGE_FUNC(STEP/sketchSize[0], STEP/sketchSize[1],
                            uv,
                            robertsCrossKernelX, robertsCrossKernelY);
#endif
#ifdef SOBEL
    gl_FragColor = EDGE_FUNC(STEP/sketchSize[0], STEP/sketchSize[1],
                            uv,
                            sobelKernelX, sobelKernelY);
#endif
#ifdef SCHARR
    gl_FragColor = EDGE_FUNC(STEP/sketchSize[0], STEP/sketchSize[1],
                            uv,
                            scharrKernelX, scharrKernelY);
#endif
}

Edit the above code to change say "#define EDGE_FUNCTION edge" to edgeTrueColor say... save the changes
                                                        
:w                                                                                                                                               
And the sketch reloads with new EDGE_FUNCTION brilliant....
To get you started checkout my fork of Filters4Processing (by Raphaël de Courville) and Andrés Colubri blog. See also processing tutorial. Find shaders from shadertoy (that Raphaël has shown we can translate for processing) check this link. See also glsl syntax highlighting in vim other versions available, other editors too.

Monday, 1 June 2015

More Experiments with Java Reflection in Ruby-Processing

I think I may have cracked it this time!!! Recently I have created a ruby-processing fork of Filters4Processing, whose examples include running movie sketches. Now in vanilla processing there are these convenience methods void movieEvent(Movie movie) and void captureEvent(Capture capture)that are used to read the movie/capture (presumably a frame at a time prior to draw loop). These are/were not available via ruby-processing, however I have found a way to make it work by creating a java interface (and compiling into my rpextras.jar). Then I reopen the Processing::App class to include the interface and it just works!!!

The Interface

package processing.core;

/**
 * This interface makes it easier/possible to use the reflection methods
 * void captureEvent(Capture capture); and
 * void movieEvent(Movie movie); from ruby-processing
 * @author Martin Prout
 */
public interface VideoInterface {
    void movieEvent(processing.video.Movie movie);
    void captureEvent(processing.video.Capture capture);
}

The video_event video library script

require 'rpextras'

class Processing::App
  include Java::ProcessingCore::VideoInterface
end
Now if those processing guys had only created some decent interfaces in the first place this would have been a bit easier.

Method in Use

#
# Speed. 
#
# Use the Movie.speed method to change
# the playback speed. The video_event library is
# required to use "movieEvent" java reflection method
#

load_libraries :video, :video_event
include_package 'processing.video'

attr_reader :mov

def setup
  size(640, 360)
  background(0)
  @mov = Movie.new(self, "transit.mov")
  mov.loop
end

def draw
  image(mov, 0, 0)
  new_speed = map(mouse_x, 0, width, 0.1, 2)
  mov.speed(new_speed)
  fill(255)
  text("%.2f" % new_speed << "X", 10, 30)
end

# The java reflection method  
def movieEvent(mov)
  mov.read
end

A capture example
load_library :video, :video_event
include_package 'processing.video'
attr_reader :cam, :my_shader

def setup
  size(640, 480, P2D)
  cameras = Capture.list
  @my_shader = load_shader('edge_detect.glsl')
  my_shader.set('sketchSize', width.to_f, height.to_f)
  start_capture(width, height)
end

def start_capture(w, h)
  @cam = Capture.new(self, w, h)
  cam.start
end

def draw
  image(cam, 0, 0)
  return if mouse_pressed?
  filter(my_shader)
end

# The java reflection method  
def captureEvent(cam)
  cam.read
end

Main problem is an introduction of a compile time dependency on processing video.jar, and also seems to be safer to keep camel case for reflection method, paradoxically that may improve in latest processing where the video library becomes an external library.

Wednesday, 13 May 2015

Some observations and reflections

It now seem very likely that vanilla processing changes will be very significant (this is a good thing) and such changes will likely take some time to solidify. For that reason there is not much point in ruby-processing (or JRubyArt) trying to keep up. Everything seemed to be pointing toward a LWJGL3 (Andrés Colubri) future (but now it's changed back to jogl update 16 May 2015), and possible javafx integration (Ben Fry). Seems the LWJGL3 project is too unstable?  So near term efforts will concentrate on jruby-9.0.0.0 and ruby-2.2 syntax changes/opportunities using the existing processing-2.2.1 release.  Possible opportunity for jruby games...?

Sunday, 3 May 2015

Adding structure to processing examples (in ruby-processing)

Thinking about ruby-2.0 and structure got me thinking about processing color, but then I though about Struct and OStruct, as easy way to add structure to these processing sketches, see how this gives meaning to fill for example:-
Hue
# Hue is the color reflected from or transmitted through an object
# and is typically referred to as the name of the color (red, blue, yellow,
# etc.). Move the cursor vertically over each bar to alter its hue.
require 'ostruct'

attr_reader :bar_width, :color_array

def setup
  size 640, 360
  color_mode HSB, 360
  no_stroke
  @bar_width = 20
  @color_array = (0..width / bar_width).map do
    OpenStruct.new(hue: height, saturation: height, brightness: height)
  end
end

def draw
  color_array.each_with_index do |col, i|
    n = i * bar_width
    range = (n..n + bar_width)
    color_array[i].hue = mouse_y if range.include?(mouse_x)
    fill col.hue, col.saturation, col.brightness
    rect n, 0, bar_width, height
  end
end

Saturation
# Saturation is the strength or purity of the color and represents the
# amount of gray in proportion to the hue. A "saturated" color is pure
# and an "unsaturated" color has a large percentage of gray.
# Move the cursor vertically over each bar to alter its saturation.
require 'ostruct'

attr_reader :bar_width, :color_array

def setup
  size 640, 360
  color_mode HSB, 360
  no_stroke
  @bar_width = 20
  @color_array = (0..width / bar_width).map do |n|
    OpenStruct.new(hue: n * bar_width, saturation: height, brightness: height / 1.5)
  end
end

def draw
  color_array.each_with_index do |col, i|
    n = i * bar_width
    range = (n..n + bar_width)
    color_array[i].saturation = mouse_y if range.include? mouse_x
    fill col.hue, col.saturation, col.brightness
    rect n, 0, bar_width, height
  end
end

Brightness
# Brightness is the relative lightness or darkness of a color.
# Move the cursor vertically over each bar to alter its brightness.
require 'ostruct'

attr_reader :bar_width, :color_array

def setup
  size 640, 360
  no_stroke
  color_mode HSB, width, 100, height
  @bar_width = 20
  @color_array = (0..width / bar_width).map do |n|
    OpenStruct.new(hue: n * bar_width, saturation: 100, brightness: height)
  end
end

def draw
  color_array.each_with_index do |col, i|
    n = i * bar_width
    range = (n..n + bar_width)
    color_array[i].brightness = mouse_y if range.include? mouse_x
    fill col.hue, col.saturation, col.brightness
    rect n, 0, bar_width, height
  end
end

First class keyword arguments in ruby-processing?

In vanilla processing there are many multi parameter arguments (sometimes overloaded, usual java stuff) that can cause offence to the average rubyist, take camera for example:-
// java/processing 9 float arguments
void camera(
     float eyeX,
     float eyeY,
     float eyeZ,
     float centerX,
     float centerY,
     float centerZ,
     float upX,
     float upY,
     float upZ){...}

// default values
camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / 180.0), width/2.0, height/2.0, 0, 0, 1, 0);

Since we can now use ruby-2.0 syntax (with jruby-9.0.0.0) there is scope for improvement, by using keyword arguments and Vector object (need not be Vec3D a Struct would do):-
# ruby 3 named parameters (order would be unimportant)
def camera_vec(
               eye: Vec3D.new(width / 2.0, height / 2.0, (height / 2.0) / tan(PI * 30.0 / 180.0)),
               center: Vec3D.new(width / 2.0, height / 2.0, 0),
               up: Vec3D.new(0, 1.0, 0))
  camera(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z)
end

Saturday, 18 April 2015

Sandi Metz suspicion of nil (pbox2d example)

Late last year Sandi Metz blogged about Suspicions of nil, more recently she presented Nothing is Something at Bath ruby, and I just watched the video at confreaks. The timing could not be much better I had just translated Dan Shiffmans MouseJoint sketch to run with ruby-processing, and the Spring class which has all these egregious checks for null (or nil in initial ruby version). I found that by using ruby duck-typing I could create a DummySpring class, that got rid of all those suspicious null checks!!!
The DummySpring class
# dummy_spring.rb by Martin Prout
# using duck-typing so class can stand in for Spring

# Using this class avoids test for nil
class DummySpring
  def initialize; end

  # If it exists we set its target to the mouse location
  def update(_x, _y); end

  def display; end

  # This is the key function where
  # we attach the spring to an x,y location
  # and the Box object's location
  def bind(x, y, box)
    spring = Spring.new
    spring.bind(x, y, box)
    spring
  end

  def destroy; end
end

The only slightly tricky thing was the sketch needs to know that DummyString bind returns an instance of Spring, but otherwise it all looks pretty cool. Would make a good example except that pbox2d confounds things (we have two worlds a jbox2d physics world and a processing sketch world, and we track both).

Monday, 6 April 2015

Using Forwardable in place of Processing::Proxy to mimic java inner class

In the following example we are using the pbox2d gem (in place of Dan Shiffmans Box2D-for-Processing to provide jbox2d. Here is the translated sketch:-
# The Nature of Code
# PBox2D example translated to use pbox2d gem by Martin Prout, and to use
# forwardable instead of Processing::Proxy to mimic java inner class access
# An uneven surface

require 'pbox2d'
load_library :surface

attr_reader :surface, :box2d, :particles

def setup
  size(500, 300)
  smooth 4
  # Initialize box2d physics and create the world
  @box2d = Box2D.new(self)
  box2d.init_options(gravity: [0, -20])
  box2d.create_world
  # to later set a custom gravity
  # box2d.gravity([0, -20])
  # Create the empty list
  @particles = []
  # Create the surface
  @surface = Surface.new(self)
end

def draw
  # If the mouse is pressed, we make new particles
  # We must always step through time!
  background(138, 66, 54)
  # Draw the surface
  surface.display
  # NB ? reqd to call mouse_pressed value, else method gets called.
  particles << Particle.new(self, mouse_x, mouse_y, rand(2.0..6)) if mouse_pressed?
  # Draw all particles
  particles.each(&:display)
  # Particles that leave the screen, we delete them
  # (note they have to be deleted from both the box2d world and our list
  particles.reject!(&:done)
  # Just drawing the framerate to see how many particles it can handle
  fill(0)
  text(format('framerate: %d', frame_rate.to_i), 12, 16)
end

Here is the associated library that uses Forwardable in place of Processing::Proxy. Place surface.rb in "library/surface" folder, or modify the sketch to use require_relative:-
require 'forwardable'

# The Nature of Code
# PBox2D example
# An uneven surface boundary
class Surface
  extend Forwardable
  # We'll keep track of all of the surface points
  def_delegators(:@app, :box2d, :width, :height, :begin_shape,
                 :end_shape, :fill, :stroke, :stroke_weight,
                 :vertex, :map1d, :noise)
  attr_reader :surface, :body, :y

  def initialize(app)
    @app = app
    @surface = []
    # This is what box2d uses to put the surface in its world
    chain = ChainShape.new
    # Perlin noise argument
    xoff = 0.0
    # This has to go backwards so that the objects  bounce off the top of the
    # surface. This "edgechain" will only work in one direction!
    (width + 10).step(-10, -5) do |x|
      # Doing some stuff with perlin noise to calculate a surface that points
      # down on one side and up on the other
      if x > width / 2
        @y = 100 + (width - x) * 1.1 + map1d(noise(xoff), (0..1.0), (-80..80))
      else
        @y = 100 + x * 1.1 + map1d(noise(xoff), (0..1.0), (-80..80))
      end
      # Store the vertex in screen coordinates
      surface << Vec2.new(x, y)
      # Move through perlin noise
      xoff += 0.1
    end
    # Build an array of vertices in Box2D coordinates
    # from the ArrayList we made
    vertices = []
    surface.each do |surf|
      vertices << box2d.processing_to_world(surf)
    end
    # Create the chain!
    chain.createChain(vertices, vertices.length)
    # The edge chain is now attached to a body via a fixture
    bd = BodyDef.new
    bd.position.set(0.0, 0.0)
    @body = box2d.createBody(bd)
    # Shortcut, we could define a fixture if we
    # want to specify frictions, restitution, etc.
    body.createFixture(chain, 1)
  end

  # A simple function to just draw the edge chain as a series of vertex points
  def display
    stroke_weight(2)
    stroke(0)
    fill(135, 206, 250)
    begin_shape
    vertex(width, 0)          # extra vertices so we can fill sky
    surface.map { |v| vertex(v.x, v.y) }     # the mountain range
    vertex(0, 0)              # extra vertices so we can fill sky
    end_shape
  end
end

# Using forwardable again
class Particle
  extend Forwardable
  def_delegators(:@app, :box2d, :push_matrix, :pop_matrix, :rotate,
                 :translate, :fill, :stroke, :stroke_weight, :noise,
                 :map1d, :ellipse, :line)
  # We need to keep track of a Body

  attr_reader :body, :x, :y, :r

  # Constructor
  def initialize(app, x, y, r)
    @app, @x, @y, @r = app, x, y, r
    # This function puts the particle in the Box2d world
    make_body(x, y, r)
  end

  # This function removes the particle from the box2d world
  def kill_body
    box2d.destroy_body(body)
  end

  # Is the particle ready for deletion?
  def done
    pos = box2d.body_coord(body)
    # Is it off the bottom of the screen?
    return false unless pos.y > box2d.height + r * 2
    kill_body
    true
  end

  def display
    # We look at each body and get its screen position
    pos = box2d.body_coord(body)
    # Get its angle of rotation
    a = body.get_angle
    push_matrix
    translate(pos.x,  pos.y)
    rotate(-a)
    fill(175)
    stroke(0)
    stroke_weight(1)
    ellipse(0, 0, r * 2, r * 2)
    # Let's add a line so we can see the rotation
    line(0, 0, r, 0)
    pop_matrix
  end

  # This function adds the particle to the box2d world
  def make_body(x, y, r)
    # Define and create the body
    bd = BodyDef.new
    bd.position = box2d.processing_to_world(x, y)
    bd.type = BodyType::DYNAMIC
    @body = box2d.create_body(bd)
    # Make the body's shape a circle
    cs = CircleShape.new
    cs.m_radius = box2d.scale_to_world(r)
    fd = FixtureDef.new
    fd.shape = cs
    # Parameters that affect physics
    fd.density = 1
    fd.friction = 0.01
    fd.restitution = 0.3
    # Attach fixture to body
    body.create_fixture(fd)
    # Give it a random initial velocity (and angular velocity)
    body.set_linear_velocity(Vec2.new(rand(-10..10), rand(5..10)))
    body.set_angular_velocity(rand(-10..10))
  end
end

Sunday, 5 April 2015

Replacing Processing::Proxy in ruby-processing

I have often thought that Processing::Proxy in ruby-processing is a bit of hack (further it doesn't always do what you need to mimic vanilla processings "inner" class access to methods/variables), here is a more respectable alternative using forwardable. As a bonus shows the neat Vec3D :to_vertex method in action:-
require 'forwardable'
load_libraries :icosahedron, :vecmath

def setup
  size 640, 360, P3D
  @ico1 = Icosahedron.new self, 75.0
  @ico2 = Icosahedron.new self, 75.0
  @ico3 = Icosahedron.new self, 75.0
end

def draw
  background 0
  lights
  translate(width / 2, height / 2)
  push_matrix
  translate(-width / 3.5, 0)
  rotate_x frame_count * PI / 185
  rotate_y frame_count * PI / -200
  stroke 170, 0, 0
  no_fill
  @ico1.draw
  pop_matrix
  push_matrix
  rotate_x frame_count * PI / 200
  rotate_y frame_count * PI / 300
  stroke 170, 0, 180
  fill 170, 170, 0
  @ico2.draw
  pop_matrix
  push_matrix
  translate(width / 3.5, 0)
  rotate_x frame_count * PI / -200
  rotate_y frame_count * PI / 200
  no_stroke
  fill 0, 0, 185
  @ico3.draw
  pop_matrix
end
Here is the library class that uses forwardable:-
# Example of replacing Processing::Proxy with extend Forwardable
# And using Vec3D :to_vertex function
class Icosahedron
  extend Forwardable   # replacing Processing::Proxy mixin
  def_delegators(:@app, :begin_shape, :end_shape)
  attr_reader :r, :app, :renderer

  def initialize(app, radius)
    @r = radius
    @app = app
    @renderer = AppRender.new(app)
  end

  ##
  # Draw an icosahedron defined by a radius r.
  #
  def draw
    # Calculate vertex data for an icosahedron inscribed by a sphere radius 'r'.
    # Use 4 Golden Ratio rectangles as the basis.
    phi = (1.0 + Math.sqrt(5.0)) / 2.0
    h = r / Math.sqrt(1.0 + phi * phi)
    v =
    [
      Vec3D.new(0, -h, h * phi), Vec3D.new(0, -h, -h * phi),
      Vec3D.new(0, h, -h * phi), Vec3D.new(0, h, h * phi),
      Vec3D.new(h, -h * phi, 0), Vec3D.new(h, h * phi, 0),
      Vec3D.new(-h, h * phi, 0), Vec3D.new(-h, -h * phi, 0),
      Vec3D.new(-h * phi, 0, h), Vec3D.new(-h * phi, 0, -h),
      Vec3D.new(h * phi, 0, -h), Vec3D.new(h * phi, 0, h)
    ]

    begin_shape(Java::ProcessingCore::PConstants::TRIANGLES)
    draw_triangle(v[0], v[7], v[4])
    draw_triangle(v[0], v[4], v[11])
    draw_triangle(v[0], v[11], v[3])
    draw_triangle(v[0], v[3], v[8])
    draw_triangle(v[0], v[8], v[7])
    draw_triangle(v[1], v[4], v[7])
    draw_triangle(v[1], v[10], v[4])
    draw_triangle(v[10], v[11], v[4])
    draw_triangle(v[11], v[5], v[10])
    draw_triangle(v[5], v[3], v[11])
    draw_triangle(v[3], v[6], v[5])
    draw_triangle(v[6], v[8], v[3])
    draw_triangle(v[8], v[9], v[6])
    draw_triangle(v[9], v[7], v[8])
    draw_triangle(v[7], v[1], v[9])
    draw_triangle(v[2], v[1], v[9])
    draw_triangle(v[2], v[10], v[1])
    draw_triangle(v[2], v[5], v[10])
    draw_triangle(v[2], v[6], v[5])
    draw_triangle(v[2], v[9], v[6])
    end_shape
  end

  def draw_triangle(p1, p2, p3)
    p1.to_vertex(renderer)
    p2.to_vertex(renderer)
    p3.to_vertex(renderer)
  end
end

Thursday, 2 April 2015

Using delegators in JRubyArt (where vanilla processing uses inner classes)

Using delegators in JRubyArt (where vanilla processing uses inner classes) and ruby-processing uses 'include Processing::Proxy' to mimic the same behaviour. See node.rb, where we selectively expose PApplets fill, stroke, stroke_weight and ellipse methods in the Node class.


force_directed_graph.rb
require 'jruby_art'
require 'toxiclibs'
require_relative 'cluster'
require_relative 'node'

#
# Copyright (c) 2010 Daniel Shiffman
#
# This demo & library is free software you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation either
# version 2.1 of the License, or (at your option) any later version.
#
# http://creativecommons.org/licenses/LGPL/2.1/
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
class ForceDirectedGraph < Processing::App
  attr_reader :physics, :clusters, :show_physics, :show_particles, :f

  def setup
    size(640, 360)
    @f = create_font('Georgia', 12, true)
    @show_physics = true
    @show_particles = true
    # Initialize the physics
    @physics = Physics::VerletPhysics2D.new
    physics.set_world_bounds(Toxi::Rect.new(10, 10, width - 20, height - 20))
    # Spawn a new random graph
    new_graph
  end

  # Spawn a new random graph
  def new_graph
    # Clear physics
    physics.clear
    center = TVec2D.new(width / 2, height / 2)
    @clusters = (0..8).map { Cluster.new(physics, rand(3..8), rand(20..100), center) }
    # All clusters connect to all clusters
    clusters.each_with_index do |ci, i|
      clusters[i + 1..clusters.size - 1].each do |cj|
        ci.connect(cj)
      end
    end
  end

  def draw
    # Update the physics world
    physics.update
    background(255)
    # Display all points
    clusters.each(&:display) if show_particles
    # If we want to see the physics
    if show_physics
      clusters.each_with_index do |ci, i|
        ci.internal_connections self
        # Cluster connections to other clusters
        clusters[1 + i..clusters.size - 1].each do |cj|
          ci.show_connections(self, cj)
        end
      end
    end
    # Instructions
    fill(0)
    text_font(f)
    text("'p' to display or hide particles\n'c' to display or hide connections\n'n' for new graph", 10, 20)
  end

  # Key press commands
  def key_pressed
    case key
    when 'c'
      @show_physics = !show_physics
      @show_particles = true unless show_physics
    when 'p'
      @show_particles = !show_particles
      @show_physics = true unless show_particles
    when 'n'
      new_graph
    end
  end
end

ForceDirectedGraph.new(title: 'Force directed graphs')

cluster.rb
#
# Copyright (c) 2010 Daniel Shiffman
#
# This demo & library is free software you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation either
# version 2.1 of the License, or (at your option) any later version.
#
# http://creativecommons.org/licenses/LGPL/2.1/
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
class Cluster
  attr_reader :nodes, :diameter, :physics

  # We initialize a with a number of nodes, a diameter, and centerpoint
  def initialize(physics, n, d, center)
    @physics = physics
    @diameter = d
    @nodes = (0..n).map { Node.new(center.add(TVec2D.random_vector)) }
    # Connect all the nodes with a Spring
    nodes[1..nodes.size - 1].each_with_index do |pi, i|
      nodes[0..i].each do |pj|
        physics.add_spring(Physics::VerletSpring2D.new(pi, pj, diameter, 0.01))
      end
    end
  end

  def display
    nodes.each(&:display)
  end
  # This functons connects one cluster to another
  # Each point of one cluster connects to each point of the other cluster
  # The connection is a "VerletMinDistanceSpring"
  # A VerletMinDistanceSpring is a spring which only enforces its rest length if the
  # current distance is less than its rest length. This is handy if you just want to
  # ensure objects are at least a certain distance from each other, but don't
  # care if it's bigger than the enforced minimum.

  def connect(other)
    other_nodes = other.nodes
    nodes.each do |pi|
      other_nodes.each do |pj|
        physics.add_spring(Physics::VerletMinDistanceSpring2D.new(pi, pj, (diameter + other.diameter) * 0.5, 0.05))
      end
    end
  end

  # Draw all the internal connections
  def internal_connections(app)
    app.stroke(200, 0, 0, 80)
    nodes[0..nodes.size - 1].each_with_index do |pi, i|
      nodes[i + 1..nodes.size - 1].each do |pj|
        app.line(pi.x, pi.y, pj.x, pj.y)
      end
    end
  end

  # Draw all the connections between this and another Cluster
  def show_connections(app, other)
    app.stroke(200, 200, 0, 20)
    app.stroke_weight(2)
    other_nodes = other.nodes
    nodes.each do |pi|
      other_nodes[0..other_nodes.size - 1].each do |pj|
        app.line(pi.x, pi.y, pj.x, pj.y)
      end
    end
  end
end

node.rb
require 'forwardable'

# The Nature of Code
# Daniel Shiffman
# http://natureofcode.com
# Force directed graph
# Heavily based on: http://code.google.com/p/fidgen/
# Notice how we are using inheritance here!
# We could have just stored a reference to a VerletParticle object
# inside the Node class, but inheritance is a nice alternative
class Node < Physics::VerletParticle2D
  extend Forwardable
  def_delegators(:@app, :fill, :stroke, :stroke_weight, :ellipse)
  def initialize(pos)
    super(pos)
    @app = $app
  end

  # All we're doing really is adding a display function to a VerletParticle
  def display
    fill(50, 200, 200, 150)
    stroke(50, 200, 200)
    stroke_weight(2)
    ellipse(x, y, 16, 16)
  end
end

Tuesday, 24 March 2015

Toxiclibs gem released

I've just released a toxiclibs gem that can be used with JRubyArt or ruby-processing (examples uses gem version 0.3.0.pre))
# A ruby processing sketch (needs re-factoring for jruby_art)
#
#
# This example implements a custom VolumetricSpace using an implicit function
# to calculate each voxel. This is slower than the default array or HashMap
# based implementations, but also has much less memory requirements and so might
# be an interesting and more viable approach for very highres voxel spaces
# (e.g. >32 million voxels). This implementation here also demonstrates how to
# achieve an upper boundary on the iso value (in addition to the one given and
# acting as lower threshold when computing the iso surface)
#
# Usage:
# drag mouse to rotate camera
# w: toggle wireframe on/off
# mouse wheel to zoom in/out
# l: apply laplacian mesh smooth
#
#

#
# Copyright (c) 2010 Karsten Schmidt & ruby-processing version Martin Prout 2012
# This sketch relies on a custom toxiclibscore library for PovRAY export
#
# This library is free software you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation either
# version 2.1 of the License, or (at your option) any later version.
#
# http://creativecommons.org/licenses/LGPL/2.1/
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

require 'toxiclibs'
load_library 'vecmath' # uncomment this line for ruby-processing
RES = 64
ISO = 0.2
MAX_ISO = 0.66
attr_reader :mesh, :gfx, :curr_zoom, :is_wire_frame

def setup
  size(720, 720, P3D)
  ArcBall.init(self)
  @gfx = Gfx::ToxiclibsSupport.new(self)
  vol = EvaluatingVolume.new(Toxi::Vec3D.new(400, 400, 400), RES, RES, RES, MAX_ISO)
  surface = Volume::HashIsoSurface.new(vol)
  @mesh = Toxi::WETriangleMesh.new
  surface.compute_surface_mesh(mesh, ISO)
  @is_wire_frame = false
end

def draw
  background(0)
  if is_wire_frame
    no_fill
    stroke(255)
  else
    fill(255)
    no_stroke
    define_lights
    lights
  end
  @gfx.mesh(mesh, true)
end

def key_pressed
  case key
  when 'w', 'W'
    @is_wire_frame = !is_wire_frame
  when 'l', 'L'
    Toxi::LaplacianSmooth.new.filter(mesh, 1)
  when 's', 'S'
    save_frame('implicit.png')
  end
end

def define_lights
  ambient_light(50, 50, 50)
  point_light(30, 30, 30, 200, -150, 0)
  directional_light(0, 30, 50, 1, 0, 0)
  spot_light(30, 30, 30, 0, 40, 200, 0, -0.5, -0.5, PI / 2, 2)
end

# Creating a volumetric space class
#
class EvaluatingVolume < Volume::VolumetricSpace
  include Processing::Proxy
  attr_reader :upper_bound
  FREQ = PI * 3.8

  def initialize(scal_vec, resX, resY, resZ, upper_limit)
    super(scal_vec, resX, resY, resZ)
    @upper_bound = upper_limit
  end

  def clear
    # nothing to do here
  end

  def getVoxelAt(i)
    getVoxel(i % resX, (i % sliceRes) / resX, i / sliceRes)
  end

  def getVoxel(x, y, z)  # can't overload so we renamed
    val = 0
    if x > 0 && x < resX1 && y > 0 && y < resY1 && z > 0 && z < resZ1
      xx = x * 1.0 / resX - 0.5  # NB: careful about integer division !!!
      yy = y * 1.0 / resY - 0.5
      zz = z * 1.0 / resZ - 0.5
      val = cos(xx * FREQ) * sin(yy * FREQ) + cos(yy * FREQ) * sin(zz* FREQ) + cos(zz * FREQ) * sin(xx * FREQ)
      # val = sin(xx * FREQ) + cos(yy * FREQ) + sin(zz * FREQ)
      # val = sin(xx * FREQ) * (xx * FREQ) + sin(yy * FREQ) * (yy * FREQ) + sin(zz * FREQ) * (zz * FREQ)
      val = 0 if val > upper_bound
    end
    val
  end
end

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