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

Tuesday 29 April 2014

Implementing my ruby Vecmath library in java (as a JRuby extension)

Well finally I've done it, no compromises, no dodgy fixes, I've 100% implemented my ruby-library in java, as a jruby extension, so it behaves exactly as the original library. The last thing I implemented was the attr_accessors (well just the setters, the getters are obvious) and methods with an optional block. The setters was the easiest it was as simple as @JRubyMethod(name = "x=") instead of @JRubyMethod(name = "set_x") in the method annotation.
Here is the Vec3D version of set_mag that takes an optional block
Using the Vec3D name was a simple as Vec3D = Processing::Vec2::Vec2
/**
* Call yield if block given, do nothing if yield == false
* else set_mag to given scalar
* @param context
* @param scalar double value to set
* @param block should return a boolean (optional)
* @return
*/
@JRubyMethod(name = "set_mag")
public IRubyObject set_mag(ThreadContext context, IRubyObject scalar, Block block) {
 if (block.isGiven()) {
  if (!(boolean) block.yield(context, scalar).toJava(Boolean.class)) {
   return this;
  }
 }
 double new_mag = (Double) scalar.toJava(Double.class);
 double current = FastMath.sqrt(FastMath.pow(jx, 2) + FastMath.pow(jy, 2) + FastMath.pow(jz, 2));
 jx *= new_mag / current;
 jy *= new_mag / current;
 jz *= new_mag / current;
 return this;
}

See the full code here.

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