Personal JRubyArt blog
Monkstone
Ruby-Processing group blog
Ruby Processing Group
Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0
class JWishy < Processing::App # bare sketch code endBare 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

Live coding in ruby-processing now using pry
Bounce.rb code used in video
Using refined includes in ruby-processing, don't over pollute your classes: http://t.co/WQ9OmnvgcV
— monkstone (@monkstoneT) June 26, 2015
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
Prototyping Java-Processing in Ruby-Processing | Viget: http://t.co/IktN1UvQbW, and just brilliant for shader sketches .
— monkstone (@monkstoneT) June 6, 2015
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 }
:wAnd the sketch reloads with new EDGE_FUNCTION brilliant....
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); }
require 'rpextras' class Processing::App include Java::ProcessingCore::VideoInterface endNow if those processing guys had only created some decent interfaces in the first place this would have been a bit easier.
# # 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
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
# 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 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 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
// 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);
# 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
# 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 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
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
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 endHere 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
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
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
# 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