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

Tuesday 14 July 2015

A more refined (ruby-2.2) interface for java classes with mixed arguments

Since ruby-2.0 it has been possible to use keywords as first class arguments, and ruby-2.1 introduced the required keyword argument (these are available to JRubyArt and potentially ruby-processing since jruby-9.0.0.0). So I thought it would be sensible to make use of them to make say the parameters of an ArcBall library more descriptive:-
# experimental ArcBall class
class ArcBall
  attr_reader :applet, :x, :y, :r
  def initialize(app:, center_x: nil, center_y: nil, radius: nil)
    @applet = app
    @x = (center_x.nil?) ? app.width * 0.5 : center_x
    @y = (center_y.nil?) ? app.height * 0.5 : center_y
    @r = (radius.nil?) ? app.width * 0.8 : radius
  end

  def to_s
    format('ArcBall.new(applet: %s, centre_x: %d, centre_y: %d, radius: %d)',
           applet, x, y, r)
  end
end

Applet = Struct.new(:width, :height) do
  def to_s
    'MyApplet'
  end
end

applet = Applet.new(800, 600)
puts ArcBall.new(app: applet).to_s
puts ArcBall.new(app: applet, center_x: 300, center_y: 200, radius: 800).to_s

Output:
ArcBall.new(applet: MyApplet, centre_x: 400, centre_y: 300, radius: 640)
ArcBall.new(applet: MyApplet, centre_x: 300, centre_y: 200, radius: 800)

Testing whether concept works in practice for JRubyArt (using a local ArcBall library in sketchbook for test purposes);-
load_library :arcball

def setup
  sketch_title 'Arcball Box'
  ArcBall.new(app: self)
  fill 180
end

def draw
  background 50
  box 300, 300, 300
end

def settings
  size 600, 600, P3D
  smooth 8
end

# experimental ArcBall class
class ArcBall
  include_package 'arcball'
  attr_reader :applet, :x, :y, :r
  def initialize(app:, center_x: nil, center_y: nil, radius: nil)
    @applet = app
    @x = (center_x.nil?) ? app.width * 0.5 : center_x
    @y = (center_y.nil?) ? app.height * 0.5 : center_y
    @r = (radius.nil?) ? app.width * 0.8 : radius
    app = JarcBall.new applet.to_java, x.to_java(:float), y.to_java(:float), r.to_java(:float)
    app.set_active true
  end

  def to_s
    format('ArcBall.new(applet: %s, centre_x: %d, centre_y: %d, radius: %d)',
           applet, x, y, r)
  end
end

And indeed it does work if you supply suitable java types to the "hidden" java ArcBall class.

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