//Java Binding for the OpenCL API

I am currently working on Java Binding for the OpenCL API using GlueGen (as used in JOGL, JOAL). The project started as part of my bachelor of CS thesis short after the release of the first OpenCL specification draft and is now fully feature complete with OpenCL 1.1. JOCL is currently in the stabilization phase, a beta release shouldn't be far away.

Overview - How does it work?

JOCL enables applications running on the JVM to use OpenCL for massively parallel, high performance computing tasks, executed on heterogeneous hardware (GPUs, CPUs, FPGAs etc) in a platform independent manner. JOCL consists of two parts, the low level and the high level binding.

The low level bindings (LLB) are automatically generated using the official OpenCL headers as input and provide a high performance, JNI based, 1:1 mapping to the C functions.

This has the following advantages:

  • reduces maintenance overhead and ensures spec conformance
  • compiletime JNI bindings are the fastest way to access native libs from the JVM
  • makes translating OpenCL C code into Java + JOCL very easy (e.g. from books or tutorials)
  • flexibility and stability: OpenCL libs are loaded dynamically and accessed via function pointers

The hand written high level bindings (HLB) is build on top of LLB and hides most boilerplate code (like object IDs, pointers and resource management) behind easy to use java objects. HLB use direct NIO buffers internally for fast memory transfers between the JVM and the OpenCL implementation and is very GC friendly. Most of the API is designed for method chaining but of course you don't have to use it this way if you don't want to. JOCL also seamlessly integrates with JOGL 2 (both are built and tested together). Just pass the JOGL context as parameter to the JOCL context factory and you will receive a shared context. If you already know OpenCL and Java, HLB should be very intuitive for you.

The project is available on jogamp.org. Please use the mailinglist / forum for feedback or questions and the bugtracker if you experience any issues. The JOCL root repository is located on github, you may also want to take a look at the jocl-demos project. (If the demos are not enough you might also want to take a look at the junit tests)

Screenshots (sourcecode in jocl-demos project):

JOCL Julia Set high precision

More regarding OpenGL interoperability and other features in upcoming blog entries.

The following sample shows basic setup, computation and cleanup using the high level APIs.

Hello World or parallel a+b=c

/**
 * Hello Java OpenCL example. Adds all elements of buffer A to buffer B
 * and stores the result in buffer C.
 * Sample was inspired by the Nvidia VectorAdd example written in C/C++
 * which is bundled in the Nvidia OpenCL SDK.
 * @author Michael Bien
 */
public class HelloJOCL {

    public static void main(String[] args) throws IOException {
        // Length of arrays to process (arbitrary number)
        int elementCount = 11444777;
        // Local work size dimensions
        int localWorkSize = 256;
        // rounded up to the nearest multiple of the localWorkSize
        int globalWorkSize = roundUp(localWorkSize, elementCount);

        // setup
        CLContext context = CLContext.create();

        CLProgram program = context.createProgram(
                       HelloJOCL.class.getResourceAsStream("VectorAdd.cl")
                                 ).build();

        CLBuffer<FloatBuffer> clBufferA =
                       context.createFloatBuffer(globalWorkSize, READ_ONLY);
        CLBuffer<FloatBuffer> clBufferB =
                       context.createFloatBuffer(globalWorkSize, READ_ONLY);
        CLBuffer<FloatBuffer> clBufferC =
                       context.createFloatBuffer(globalWorkSize, WRITE_ONLY);

        out.println("used device memory: "
            + (clBufferA.getSize()+clBufferB.getSize()+clBufferC.getSize())/1000000 +"MB");

        // fill read buffers with random numbers (just to have test data).
        fillBuffer(clBufferA.getBuffer(), 12345);
        fillBuffer(clBufferB.getBuffer(), 67890);

        // get a reference to the kernel functon with the name 'VectorAdd'
        // and map the buffers to its input parameters.
        CLKernel kernel = program.createCLKernel("VectorAdd");
        kernel.putArgs(clBufferA, clBufferB, clBufferC).putArg(elementCount);

        // create command queue on fastest device.
        CLCommandQueue queue = context.getMaxFlopsDevice().createCommandQueue();

        // asynchronous write to GPU device,
        // blocking read later to get the computed results back.
        long time = nanoTime();
        queue.putWriteBuffer(clBufferA, false)
             .putWriteBuffer(clBufferB, false)
             .put1DRangeKernel(kernel, 0, globalWorkSize, localWorkSize)
             .putReadBuffer(clBufferC, true);
        time = nanoTime() - time;

        // cleanup all resources associated with this context.
        context.release();

        // print first few elements of the resulting buffer to the console.
        out.println("a+b=c results snapshot: ");
        for(int i = 0; i < 10; i++)
            out.print(clBufferC.getBuffer().get() + ", ");
        out.println("...; " + clBufferC.getBuffer().remaining() + " more");

        out.println("computation took: "+(time/1000000)+"ms");

    }

    private static final void fillBuffer(FloatBuffer buffer, int seed) {
        Random rnd = new Random(seed);
        while(buffer.remaining() != 0)
            buffer.put(rnd.nextFloat()*100);
        buffer.rewind();
    }

    private static final int roundUp(int groupSize, int globalSize) {
        int r = globalSize % groupSize;
        if (r == 0) {
            return globalSize;
        } else {
            return globalSize + groupSize - r;
        }
    }

}

VectorAdd.cl

    // OpenCL Kernel Function for element by element vector addition
    kernel void VectorAdd(global const float* a,
                          global const float* b,
                          global float* c, int numElements) {

        // get index into global data array
        int iGID = get_global_id(0);

        // bound check (equivalent to the limit on a 'for' loop)
        if (iGID >= numElements)  {
            return;
        }

        // add the vector elements
        c[iGID] = a[iGID] + b[iGID];
    }

//New Getting Started with JOGL 2 tutorials

Thanks to Justin Stoecker, computer science graduate student at the University of Miami, JOGL gets a new set of getting started tutorials:

JOGL, or Java Bindings for OpenGL, allows Java programs to access the OpenGL API for graphics programming. The graphics code in JOGL programs will look almost identical to that found in C or C++ OpenGL programs, as the API is automatically generated from C header files. This is one of the greatest strengths of JOGL, as it is quite easy to port OpenGL programs written in C or C++ to JOGL; learning JOGL is essentially learning OpenGL[...]

Tutorials:

Thanks Justin!

//JOGL 2 - Composeable Pipline

JOGL provides a feature called 'composeable pipeline' which can be quite useful in some situations. It enables you to put additional delegating layers between your java application and the OpenGL driver. A few usecases could be:
  • performance metrics
  • logging, debugging or diagnostics
  • to ignore specific function calls
It is very easy to set up. Just put this line into your code and the DebugGL layer will throw a GLException as soon an error occurs (you want this usually when you are developing the software).
    public void init(GLAutoDrawable drawable) {
        // wrap composeable pipeline in a Debug utility, all OpenGL error codes are automatically
        // converted to GLExceptions as soon as they appear
        drawable.setGL(new DebugGL3(drawable.getGL().getGL3()));
        //..
    }
Another predefined layer is TraceGL which intercepts all OpenGL calls and prints them to an output stream.
        drawable.setGL(new TraceGL3(drawable.getGL().getGL3(), System.out));
see also GL Profiles

//NetBeans GIT support

If you are using GIT as SCM and NetBeans as IDE you should probably check out NBGit. The plugin integrates GIT in NetBeans in the same way as the out of the box Mercurial support does it. In fact both modules have the same origin since nbgit is a fork of the mercurial integration project and incrementally adds features to catch up.

NBGit Version 0.3 is already fairly stable and provides the basic set of features you would expect from distributed versioning system IDE integration.

Features

  • Graph visualization of parallel branches (Browser similar to giggle)
  • Versioning History (git log)
  • Show changes (git status)
  • update/commit/reset
  • clone/clone other/git init
  • custom actions (custom git commands)
  • diff
  • in-editor annotation of code changes
  • ignore files (parsing '.gitignore' files)
  • git properties (username, email etc via options)

The project is developed by volunteers outside Sun, if you like to see GIT integration as out-of-the-box feature in a future version of NetBeans please vote for this RFE.

I use the plugin for most of my open source projects and haven't experience any serious issues so far. I would say its already safe to use since you can't do anything wrong if you do a 'git status' -> 'git push' via command line as last step anyway.

Screenshots

showcase shot

clone shot editor shot


//JOGL 2 - OpenGL Profiles explained

June 16 2010, updated blogpost: OpenGL 4

JOGL 2 supports several OpenGL Profiles. In this blog entry I try to explain what profiles are and why they are needed.

History

SGI released the first OpenGL specification 1992. Since this point OpenGL 1.x constantly evolved (under the ARB and later Khronos Group) by adding new functions to the core API. This went well until programmable graphics hardware became mainstream and shaders became suddenly more flexible and efficient as the generic fixed function pipeline.

OpenGL 2.x was the last version in which you could freely mix the fixed function pipeline with the programmable pipeline (as a core feature).

With the release of OpenGL 3.0 the whole fixed function pipeline has been deprecated but you could still use it if you haven't requested a forward compatible context.

OpenGL 3.1 and 3.2 removed most deprecated functionality from core specification, however some implementations (e.g. Nvidia drivers) still allow to get them back via an optional compatibility extension. Since 3.1 was the first release which broke compatibility, it is often seen as major OpenGL 3 release.

JOGL 2 (JSR 231)

JOGL 1.1.1 lived in the timeframe up to OpenGL 3.0 which made it easy to stay in sync with the spec. To be able to solve the issue with the deprecation of functionality, JOGL 2 (JSR maintenance release) introduces an abstraction of the original OpenGL versioning called Profile. Profiles allow Java applications to be written in a way which allows compatibility with multiple OpenGL versions at the same time. Since OpenGL ES (GL for embedded systems) has overlapping functionality with OpenGL itself it opened the opportunity to add even Profiles which bridge desktop and embedded implementations. The class diagram below shows the dependencies between all available Profiles.

Before you start writing a JOGL application you will have to decide first which GLProfile you want to use. The code snippet below lists all currently supported profiles (extracted from GLProfile).


Current list of supported profiles and their mapping to the implementation versions

    /** The desktop OpenGL compatibility profile 4.x, with x >= 0, ie GL2 plus GL4.
bc stands for backward compatibility. */ public static final String GL4bc = "GL4bc"; /** The desktop OpenGL core profile 4.x, with x >= 0 */ public static final String GL4 = "GL4"; /** The desktop OpenGL compatibility profile 3.x, with x >= 1, ie GL2 plus GL3.
bc stands for backward compatibility. */ public static final String GL3bc = "GL3bc"; /** The desktop OpenGL core profile 3.x, with x >= 1 */ public static final String GL3 = "GL3"; /** The desktop OpenGL profile 1.x up to 3.0 */ public static final String GL2 = "GL2"; /** The embedded OpenGL profile ES 1.x, with x >= 0 */ public static final String GLES1 = "GLES1"; /** The embedded OpenGL profile ES 2.x, with x >= 0 */ public static final String GLES2 = "GLES2"; /** The intersection of the desktop GL2 and embedded ES1 profile */ public static final String GL2ES1 = "GL2ES1"; /** The intersection of the desktop GL3, GL2 and embedded ES2 profile */ public static final String GL2ES2 = "GL2ES2"; /** The intersection of the desktop GL3 and GL2 profile */ public static final String GL2GL3 = "GL2GL3";

Note: GL2 Profile supports OpenGL up to version 3.0 (included) - this is not a bug: OpenGL 3.1 was the big game changer

The next two code snippets show the basic steps how to set up OpenGL with JOGL 2.

Context creation

        //create a profile, in this case OpenGL 3.1 or later
        GLProfile profile = GLProfile.get(GLProfile.GL3);
        
        //configure context
        GLCapabilities capabilities = new GLCapabilities(profile);
        capabilities.setNumSamples(2); // enable anti aliasing - just as a example
        capabilities.setSampleBuffers(true);
        
        //initialize a GLDrawable of your choice
        GLCanvas canvas = new GLCanvas(capabilities);

        //register GLEventListener
        canvas.addGLEventListener(...);
        //... (start rendering thread -> start rendering...)

Rendering

    public void display(GLAutoDrawable drawable) {
        GL3 gl = drawable.getGL().getGL3();
        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
        //.. render something
    }

Summary

Profiles make JOGL 2 very flexible and allow it to build modular and portable applications. For instance part A of an application can be written against the GL2ES2 interface and part B (which is more hardware specific) against the GL3 interface. This would in theory allow to reuse A in an embedded application and B could e.g. disable itself on old desktop hardware which runs only OpenGL 2.x or fall back to a GL2 implementation.

More information can be found on JogAmp.org (direct link to javadoc)

The next release of the OpenGL Pack for NetBeans will fully support JOGL 2. Beta builds can be found here (builds contain JOGL2 beta5):


//XPath plugin now available via NetBeans plugin portal

The XPath Utility I submitted to the NetBeans Plugin Portal over two months ago has been recently verified against NetBeans 6.7. This makes the plugin now directly available from within the IDE over the Plugin manager (Tools -> Plugins).

NB Plugin Manager

One .nbm less to carry with me ;)


//Object Pooling - Determinism vs. Throughput

Object pooling in java is often seen as an anti pattern and/or wasted effort - but there are still valid reasons to think about pooling for certain kind of applications.

The JVM allocates objects much faster from managed heap (young generation; contiguous and defragmented) as you could ever recycle objects from a self written pool running on top of a VM. A good configured garbage collector is also able to delete unused objects fast. GCs in fact don't delete objects explicitly, they rather evacuate all surviving objects and sweep whole memory regions in a very efficient manner and only when its necessary to reduce runtime overhead.

Object allocation (of small objects) on modern JVMs is even so fast that making a copy of immutable objects sometimes outperforms modification of mutable (and often old) objects. JVM languages like scala or clojure make heavy use of this observation. One of the reasons for that anomaly is that generational JVMs are designed to be able to deal with loads of short living objects which makes them inexpensive compared to long living objects in old generations.

Performance does not always mean Throughput

Rendering a game with 60fps might be optimal throughput for a renderer but the performance might be still unacceptable when all frames are rendered in the first half of the second with the second half spent on GC ;). Even if Object Pools may not increase system throughput they can still increase determinism of your application. Here are some observations and tips which might help:

When should I consider Object Pools?

  • GC tuning did not help - you want to try something else
  • The application creates a lot of objects which die in the old generation
  • Your Objects are expansive to create but easy to recycle
  • Determinism, e.g response time (soft real time requirements) is more important for you than throughput

Pro Pooling:

  • pools reduce GC activity in peak times (worst case scenarios)
  • are easy to implement and test (its basically an array ;))
  • are easy to disable (inject a fake pool which returns only new Objects)

Con Pooling:

  • more (old) objects are referenced when a GC kicks in (increases gc overhead)
  • memory leaks (don't forget to reclaim your objects!)
  • cause additional problems in a multi-threaded scenario (new Object() is thread safe!)
  • may decrease throughput
  • cumbersome, repetitive client code

When you decided to use pools you have to make sure to reclaim all objects as soon they are no longer used. One way of doing this is by applying the static factory method pattern for object allocation and a per object dispose method for deallocation.

/**not Thread safe!**/
public class Vector3f {
    
    private static final ObjectPool<Vector3f> pool;
    public float x, y, z;
    private boolean disposed;
    
    static{
        pool = new <Vector3f>ObjectPool(1024);
        for(int i = 0; i  < 1024; i++) {
            pool.reclaim(new Vector3f());
        }
    }

    private Vector3f() {}

    public static Vector3f create(float x, float y, float z) {
        Vector v = pool.isEmpty() ? new Vector() : pool.get();
        v.x = x;
        v.y = y;
        v.z = z;
        v.disposed = false;
        return v;
    }
    
    public void dispose() {
        if(!disposed) {
            disposed = true;
            pool.reclaim(this);
        }
    }
}

To demonstrate the perceived performance difference I captured two flyovers of my old 3d engine. The second flyover was captured with disabled object pools. The terrain engine triangulates the ground dependent on the position and view direction of the observer which makes object allocation hard to predict. The triangulation runs in parallel to the rendering thread which made the pool implementations a bit more complex as the example above.

Every vertex, normal, triangle and quad-tree node is a pooled object (wireframe on mouse over)

on the left: flyover with pre allocated object pools; right: dynamic object allocation (new Object())

Notice the pauses at 7, 17 and 26s on the flyover with disabled pools (right video).

Note on the videos: The quality is very bad since the tool I used created 700MB large files for the 30s videos a lot of frames got skipped. I even sampled them down from 1600x1200 to 1024x768 and limited the fps to 30 but the bottleneck was still the hard disk. This is the main reason why even the left video does not look smooth. (I even had to boot windows the first time in 2 years to use the tool!). I'll try to capture better vids next time.

Conclusion

Using pools requires discipline, is error prone, not good for system throughput and does not play very well with threads. However there are some attempts to make them more usable in case you think you need them. The physics engine JBullet for example uses JStackAlloc to prevent repetitive and cumbersome code by using automatic bytecode instrumentation in the build process. Type Annotations (JSR 308 targeted for OpenJDK 7) in combination with project lombok and/or the automatic resource management proposal might provide further possibilities for simplifying the usage of object pools in java and reduce the risk for memory leaks.


//NetBeans OpenGL Pack 0.5.5 released

NetBeans OpenGL Pack logo The NetBeans 6.7 compatible OpenGL Pack has been updated to version 0.5.5 and is now available on the plugin portal also. The current release is feature compatible with 0.5.4 (release notes) only JOGL and project webstart extensions have been updated to JOGL 1.1.1a security update.

//Using Applets as fallback mode for video on pre html5 browsers

The upcoming html5 standard will make it very easy to embed media of not proprietary formats in webpages. For example video can be embedded in the same way you would probably do it with an image. But what happens when your browser does not support html5 yet?

Firstly: don't panic! Secondly: you could consider using for example the 256kb large cortado applet as fallback mode, since pre html5 browsers will ignore unknown tags like the video tag they will still read the object tag. Using an applet as cross platform fallback mode for playing e.g. theora encoded hd movies is therefore fairly easy - you even don't have to convert the video to an other format.

Read More


//Java EE 6 - The Salvation

My Brother Adam Bien released his new book Real World Java EE Patterns - Rethinking Best Practices yesterday. It is available as download or softcover. I am sure you will like it. (all in english)

You can testread the first two chapters here, more infos are on his blog.

He will check in all samples of his book to this projekt on kenai.com - so make sure you bookmark it or do a mercurial refresh in your favourite IDE when you are interested.


//OpenGL Pack 0.5.4 now ready for NetBeans 6.7

NetBeans OpenGL Pack logoNetBeans OpenGL Pack 0.5.4 is now ready to be used in the upcoming NetBeans 6.7 release, currently as rc2 available.

It wasn't sure if we would be able to ship the GLSL editor in this release since NetBeans 6.7 changed the editor APIs once again. But fortunately the P1 bug was fixed in time and we (and apparently many others, thanks for voting!) can keep using the Generic Language Framework (GLF aka Schlieman) - at least for now since GLF it is now a deprecated/unsupported module.

Build 0.5.4 will break compatibility with NB 6.5. The latest and also all other releases can be downloaded on the project page. I will wait with the upload to the plugin portal until NetBeans 6.7 final is released.

Features/Enhancements:

Anyway. Not much changed since the last release. The most important point is probably that the GLWorker used internally for tasks like shader compilation or capabilities viewer is now more stable on systems which do software rendering (e.g Mesa GL).

I added also an experimental feature which lets you define GLSL shader dependencies similar to java imports.

It is very common in GLSL to reuse code by simple concatenation of files. For example a set of independent shaders can reuse a code fragment defining some generic mathematical functions if the fragment has been concatenated to the top of all shaders which make use of the functions. Editing those kind of shaders would produce compilation errors without a way to inform the editor about those dependencies.

For example the following shader uses the function light() of PerPixelLight.frag by inserting the file ./PerPixelLight.frag at the position of the //import statement.

PerPixelLight.frag


vec4 light(void) {
    // insert fancy light calculation here
}

PlanetShader.frag

//import PerPixelLight.frag

uniform samplerCube cubemap;
varying vec3 vertex;

void main (void) {
    //Cubemap
    gl_FragColor = vec4(textureCube(cubemap, vertex)) * light();
}

When you compile a shader with dependencies you should see something like that in the output window:


All dependencies are listed in the compiler log and even the line numbers of the compiler warnings are translated back to the code fragments, which lets you jump via hyperlink directly to the annotated files.

Just a warning: Please don't define cyclic dependencies, however double imports should work in theory (have I mentioned it is experimental? ;))

Happy coding!


//JavaOne 09 keynote replays and technical session slides available

For those who haven't watched to the keynotes live or per live stream can now watch the replays of all general sessions (on your favourite screen of your live - sorry couldn't resist ;)).

The good thing about that is: you can hit the fast forward button as soon as the marketing guys start talking ;).

The slides of most presentations are also available [updated link] for download.

Especially recommended are James Gosling's toy show (last session), the first two keynotes and of course the pdfs of the technical sessions.


//XPath NetBeans plugin

I built some time ago a NetBeans plugin which simplifies browsing through large xml documents a bit. Just start typing a XPath expression in the text field of the TopComponent and the result of the (last) xml editor in focus are computed and printed in the textarea below. (You can open the XPath window either by using the context menu on xml files or directly via the window menu)

It uses the JDK's javax.xml.xpath package which means XPath 1.0 support.

xpath query results

it also supports basic auto completion:

xpath completion for expressions

localized error messages (in other words: XPathExpressionException.getCause().getLocalizedMessage()):

error messages 

I uploaded the module to the plugin portal. Feel free to use it ;)


//NetBeans OpenGL Pack #2 in most popular plugins ranking

NetBeans OpenGL Pack logoSince I haven't bloged for a long time about the OpenGL Pack, here are some notes for the last two update releases.

Beside updates and fixes the only new feature I added is the OpenGL Quicksearch. It uses the NetBeans 6.5 Quicksearch functionality (similar to ctrl + 3 in eclipse) and searches through several OpenGL resources.



currently are five resources available for search:

power users can restrict the search to a category with the following prefixes ([prefix  space] searchstring  (space searchstring)*):
gl for GL SDK, ext for GL extensions, nv for Nvidia extensions, ati for ATI/AMD Extensions.


JOGL component in NetBeans Formdesigner OpenGL quicksearch GLSL editor

Pictures featuring: Form Designer sample project, GL Quicksearch, updated GLSL 1.3 editor

Changes in 0.5.3:

  • Java Applet and Webstart support
  • OpenGL Quicksearch
  • GLSL editor updated to support GLSL 1.3 (OpenGL 3.0 spec)
  • two new NetBeans Form Designer sample JOGL projects
  • NetBeans 6.5 and JDK6 are the new minimum requirements

Changes in 0.5.2 since last release:

  • JOGL distribution has been updated to version 1.1.1
  • GLSL linker now does not stop linking shaders on compiler warnings
  • the pack should now correctly deploy JOGL and GlueGen's native libraries on all supported platforms (64bit bug)

To download the pack, please visit the plugin portal.

As always, please use the user mailing list for feedback and the issue tracker for bug reports on the project page.

- - - - -

BTW the pack recenty reached the 36k downloads milestone which makes it to the #2 in the most popular plugins category of the plugin portal ;)


//Enabling the new java browser plugin on ubuntu

When you are using Ubuntu and upgraded from older releases to intrepid or jaunty you might have run into a setup bug which causes the browser to keep using the old java plugin despite having latest Java SE and plugin packages installed (e.g 1.6 update 13 from multiverse repository).

To fix this you will have to update some symlinks and let them point to the correct location.

one easy way of doing this is by using the update-alternatives command:

 sudo update-alternatives --all

this will iterate through all symlinks in /etc/alternatives which have more than one alternative and ask you which one to use. Simple update all links which point to:

.../libjavaplugin_oji.so

to the location of the new plugin (e.g for i386):

/usr/lib/jvm/java-6-sun/jre/lib/i386/libnpjp2.so

For all other links just hit Return.

This is a little bit of a brute force approach but there shouldn't be many of them and it is the only way to make sure you don't overlook one of them since they are all called differently ;)

Next time you restart your browser the new plugin should be loaded and applets which use e.g jnlp for deployment (or out of process functionality) should work.