electronstudio / jaylib

Java JNI bindings for Raylib
Other
121 stars 23 forks source link

[Proposal] Use the Project Panama FFI #20

Open electronstudio opened 3 years ago

electronstudio commented 3 years ago

As we all know, FFI in Java is a mess. From Sun you have JNI which requires you to write C code, you have JNA which doesn't require C but is slower and still needs a generator program (long since abandoned) to avoid writing it by hand. Then there are third party solutions, like JavaCPP which we are currently using. It's the best I have found so far but still not easy to configure.

The latest attempt from Oracle to fix this is Project Panama, which is available now in Early Access and may perhaps be in Java 17 or 18. https://jdk.java.net/panama/

So should we switch to this?

I've tried the EA and it works, but the generator currently doesn't seem to generate anything to automate access to data structures. For example, to print the mouse coordinates you would do this:

         MemorySegment vector2 = GetMousePosition(newImplicitScope());
         System.out.println(Vector2.x$get(vector2)+" "+Vector2.y$get(vector2));

To clear the screen with a colour:

        BeginDrawing();
        MemorySegment color = MemorySegment.allocateNative(Color.$LAYOUT(),newImplicitScope());
        Color.r$set(color, (byte) 255);
        Color.g$set(color, (byte) 255);
        Color.b$set(color, (byte) 255);
        Color.a$set(color, (byte) 255);
        ClearBackground(color);
        EndDrawing();

I have not read every page of the docs, so I don't know if they have implemented or are planning to implement automatic generator of helpers to do all this. If you know the answer please comment. But my feeling at the moment is we would have to write so much wrapper code to make an API that is easy to use we may as well use JNI.

electronstudio commented 7 months ago

Since this has now been released in Java 22, I did a Bunnymark benchmark using it. It got 83%, which is a bit slower than Raylib C (100%), a bit faster than Jaylib (65%), and about the same as Raylib-J (which is a re-implementation of Raylib in Java.) So I suspect that 83% represents the upper limit on what Java can get.

I think 65% for Jaylib is pretty respectable. A simple FFI binding would be easy to create and a bit faster but the generated API is so nasty that I don't think anyone would use it over Jaylib. It would need a wrapper to make it nice to use and that's going to be quite a bit of work.

electronstudio commented 5 months ago

I made the wrapper https://github.com/electronstudio/jaylib-ffm