在Matlab中使用OpenGL与Java?

twe*_*ter 6 java opengl matlab

在Matlab我有

import javax.media.opengl.GL;
Run Code Online (Sandbox Code Playgroud)

我现在如何使用OpenGL?任何人都可以提供非常小的样品吗?

请注意:如果这不是在Matlab中,那么这将很容易.但问题特别涉及在Matlab中使用它.

Amr*_*mro 8

MATLAB在其静态类路径中提供了JOGL 1.x库,因此需要编译源代码(使用类路径上的那些JAR文件),然后在MATLAB中运行程序.

下面是Java中的"hello world"OpenGL示例.我将展示如何直接从MATLAB内部编译和运行它:

HelloWorld.java

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCanvas;
import javax.media.opengl.GLEventListener;

public class HelloWorld implements GLEventListener {

    public static void main(String[] args) {
        Frame frame = new Frame("JOGL HelloWorld");
        GLCanvas canvas = new GLCanvas();
        canvas.addGLEventListener(new HelloWorld());
        frame.add(canvas);
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public void display(GLAutoDrawable drawable) {
        GL gl = drawable.getGL();
        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        gl.glClear(GL.GL_COLOR_BUFFER_BIT);
        gl.glColor3f(1.0f, 1.0f, 1.0f);
        gl.glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

        gl.glBegin(GL.GL_POLYGON);
        gl.glVertex2f(-0.5f, -0.5f);
        gl.glVertex2f(-0.5f, 0.5f);
        gl.glVertex2f(0.5f, 0.5f);
        gl.glVertex2f(0.5f, -0.5f);
        gl.glEnd();

        gl.glFlush();
    }

    public void init(GLAutoDrawable drawable) {
    }
    public void reshape(GLAutoDrawable drawable, 
        int x, int y, int width, int height) {
    }
    public void displayChanged(GLAutoDrawable drawable, 
        boolean modeChanged, boolean deviceChanged) {
    }
}
Run Code Online (Sandbox Code Playgroud)

HelloWorld_compile_run.m

%# compile the Java code
jPath = fullfile(matlabroot,'java','jarext',computer('arch'));
cp = [fullfile(jPath,'jogl.jar') pathsep fullfile(jPath,'gluegen-rt.jar')];
cmd = ['javac -cp "' cp '" HelloWorld.java'];
system(cmd,'-echo')
javaaddpath(pwd)

%# run it
javaMethodEDT('main','HelloWorld','')
Run Code Online (Sandbox Code Playgroud)

截图

您可以尝试直接在MATLAB中调用Java命令(如@DarkByte所示),但在某些时候,您必须通过实现GLEventListener接口方法来处理OpenGL事件:init,display,reshape等.因为您无法定义Java类直接在MATLAB中,您也可以像我一样用Java编写全部内容.