Thursday, October 22, 2009

groovyとJOGLで凹んだポリゴンを描画する

groovyとJOGLで凹んだポリゴンを描画するには、以下のコードを実行します。


import static javax.media.opengl.GL.*;
import java.io.*;
import javax.media.opengl.glu.*;
import javax.media.opengl.*;
import com.sun.opengl.util.*;


class TessCB extends GLUtessellatorCallbackAdapter
{
def gl = null
def glu = null

TessCB(GL gla, GLU glua)
{
gl = gla
glu = glua
}
void begin(int type)
{
gl.glBegin(type)
}

void end()
{
gl.glEnd()
}

void vertex(Object vertexData)
{
if( vertexData instanceof double[] ){
gl.glVertex3dv(vertexData, 0);
}
}

void error(int errnum)
{
println(glu.gluErrorString(errnum))
System.exit(0)
}
}


// 出力画像サイズ
width = 300
height = 300

GLDrawableFactory gldf =
GLDrawableFactory.getFactory()
GLCapabilities glc = new GLCapabilities()
glc.setDoubleBuffered(false)
GLPbuffer buf = gldf.createGLPbuffer(
glc, null, width, height, null)
GL gl = buf.getGL()

buf.addGLEventListener(
[ init: {
// 背景色
gl.glClearColor(
0xf0/0xff as Float,
0xf0/0xff as Float,
0xf0/0xff as Float,
1f)
},

display: {
GLU glu = new GLU()
gl.glViewport(0, 0, width, height)

// 透視投影
gl.glMatrixMode(GL_PROJECTION)
gl.glLoadIdentity()
float ratio = height/width as Float
gl.glFrustum(-1.0f, 1.0f, -ratio, ratio,
5.0f, 40.0f)

gl.glMatrixMode(GL_MODELVIEW)
gl.glLoadIdentity()
gl.glTranslatef(0.0f, 0.0f, -7.0f)

gl.glEnable(GL_LIGHTING)
gl.glEnable(GL_LIGHT0)
gl.glEnable(GL_COLOR_MATERIAL)
gl.glEnable(GL_NORMALIZE)
gl.glEnable(GL_DEPTH_TEST)

gl.glClear(GL_COLOR_BUFFER_BIT
| GL_DEPTH_BUFFER_BIT )

gl.glPushMatrix()

// 面の色を設定
gl.glColor3f(
0x77/0xff as float,
0x99/0xff as float,
0xff/0xff as float
)

GLUtessellator tess = glu.gluNewTess()

tcb = new TessCB(gl, glu)
glu.gluTessCallback(tess, GLU.GLU_TESS_VERTEX, tcb)
glu.gluTessCallback(tess, GLU.GLU_TESS_BEGIN, tcb)
glu.gluTessCallback(tess, GLU.GLU_TESS_END, tcb)
glu.gluTessCallback(tess, GLU.GLU_TESS_ERROR, tcb)

va = [
[1.0, -1.0, 0.0],
[1.0, 1.0, 0.0],
[-1.0, 1.0, 0.0],
[-1.0, -1.0, 0.0],
[0.0, -0.5, 0.0]
]

glu.gluTessBeginPolygon(tess, null);
glu.gluTessBeginContour(tess);
for(al in 0..va.size-1){
glu.gluTessVertex(tess, va[al] as double[], 0,
va[al] as double[])
}
glu.gluTessEndContour(tess);
glu.gluTessEndPolygon(tess);

gl.glPopMatrix()
},

reshape: {},
displayChanged: {}
] as GLEventListener
)
GLContext context =
buf.createContext(null)
context.makeCurrent()
buf.display()
Screenshot.writeToFile(
new File("sample1316a.png"),
width, height, true)
context.release()
context.destroy()


出力画像(sample1316a.png)
groovyとJOGLで描画したへこんだポリゴン

動作環境
JDK1.6 Update14, Groovy 1.6.3, JOGL 1.1.1a

関連情報
groovyとJOGLのまとめ

No comments:

Post a Comment