JOGL是JAVA通過JNI的方式調用OpenGL的封裝。
給出一個簡單Demo(所需依賴,不是最小依賴,有多餘的jar和DLL)
1、環境配置
依賴jar包:
指定native庫
工程配置和javacv配置過程類似:指定依賴的jar包、dll庫。
2、使用JOGL顯示三角形
公共類:OneTriangle,進行OpenGL的初始化、繪圖。
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.glu.GLU;
public class OneTriangle {
//初始化
protected static void setup( GL2 gl2, int width, int height ) {
gl2.glMatrixMode( GL2.GL_PROJECTION );
gl2.glLoadIdentity();
// coordinate system origin at lower left with width and height same as the window
GLU glu = new GLU();
glu.gluOrtho2D( 0.0f, width, 0.0f, height );
gl2.glMatrixMode( GL2.GL_MODELVIEW );
gl2.glLoadIdentity();
gl2.glViewport( 0, 0, width, height );
}
//渲染
protected static void render( GL2 gl2, int width, int height ) {
gl2.glClear( GL.GL_COLOR_BUFFER_BIT );
// draw a triangle filling the window
gl2.glLoadIdentity();
//繪製圖元:三角形
gl2.glBegin( GL.GL_TRIANGLES );
//第一個點以及顏色
gl2.glColor3f( 1, 0, 0 );
gl2.glVertex2f( 0, 0 );
//第二個點以及顏色
gl2.glColor3f( 0, 1, 0 );
gl2.glVertex2f( width, 0 );
//第三個點以及顏色
gl2.glColor3f( 0, 0, 1 );
gl2.glVertex2f( width / 2, height );
gl2.glEnd();
}
}
OneTriangleSwingGLCanvas:顯示三角形
package com.test;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.awt.GLCanvas;
public class OneTriangleSwingGLCanvas {
public static void main( String [] args ) {
GLProfile glprofile = GLProfile.getDefault();
GLCapabilities glcapabilities = new GLCapabilities( glprofile );
final GLCanvas glcanvas = new GLCanvas( glcapabilities );
//添加監聽
glcanvas.addGLEventListener( new GLEventListener() {
@Override
public void reshape( GLAutoDrawable glautodrawable, int x, int y, int width, int height ) {
OneTriangle.setup( glautodrawable.getGL().getGL2(), width, height );
}
@Override
public void init( GLAutoDrawable glautodrawable ) {
}
@Override
public void dispose( GLAutoDrawable glautodrawable ) {
}
@Override
public void display( GLAutoDrawable glautodrawable ) {
//調用渲染方法,進行渲染
OneTriangle.render( glautodrawable.getGL().getGL2(), glautodrawable.getSurfaceWidth(), glautodrawable.getSurfaceHeight() );
}
});
//創建繪圖窗口
final JFrame jframe = new JFrame( "JAVA下的OpenGL實現" );
jframe.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent windowevent ) {
jframe.dispose();
System.exit( 0 );
}
});
//將GL渲染的圖,顯示到窗口中
jframe.getContentPane().add( glcanvas, BorderLayout.CENTER );
jframe.setSize( 640, 480 );
jframe.setVisible( true );
}
}
結果展示: