Wednesday, August 12, 2009

JOGLでポリゴンに繰り返しテクスチャを貼り付ける

JOGLでポリゴンに繰り返しテクスチャを貼り付けるには、以下のコードを実行します。


import java.io.*;
import javax.media.opengl.*;
import com.sun.opengl.util.*;
import com.sun.opengl.util.texture.*;

public class JoglSample48
{
// 出力画像サイズ
private static int width = 300;
private static int height = 300;

public static void main(String args[])
throws IOException
{
GLDrawableFactory gldf =
GLDrawableFactory.getFactory();
GLCapabilities glc = new GLCapabilities();
glc.setDoubleBuffered(false);
GLPbuffer buf = gldf.createGLPbuffer(
glc, null, width, height, null);

buf.addGLEventListener(
new GLEventListener(){
// 初期化
public void init(GLAutoDrawable dr)
{
GL gl = dr.getGL();
// 背景色
gl.glClearColor(
(float)0xf0/(float)0xff,
(float)0xf0/(float)0xff,
(float)0xf0/(float)0xff,
1f);

try
{
Texture texture = TextureIO.newTexture(
new File("sf_r.jpg"), true);
texture.enable();
texture.bind();
}
catch(IOException ioex){}

}

public void display(GLAutoDrawable dr)
{
GL gl = dr.getGL();
GLUT glut = new GLUT();
gl.glViewport(0, 0, width, height);

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

gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0.0f, 0.0f, -15.0f);

gl.glEnable(GL.GL_LIGHTING);
gl.glEnable(GL.GL_LIGHT0);
gl.glEnable(gl.GL_COLOR_MATERIAL);
gl.glEnable(GL.GL_NORMALIZE);
gl.glEnable(GL.GL_DEPTH_TEST);
gl.glEnable(GL.GL_CULL_FACE);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glEnable(GL.GL_TEXTURE_GEN_S);
gl.glEnable(GL.GL_TEXTURE_GEN_T);
gl.glClear(GL.GL_COLOR_BUFFER_BIT
|GL.GL_DEPTH_BUFFER_BIT );

gl.glPushMatrix();

gl.glTexParameteri(GL.GL_TEXTURE_2D,
GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT);
gl.glTexParameteri(GL.GL_TEXTURE_2D,
GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT);

// Y軸回転
gl.glRotatef(30.0f, 0.0f, 1.0f, 0.0f);

// テクスチャが張られたポリゴンを描画
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(0.0f, 1.0f);
gl.glVertex3f(-2f, -2f, 0.0f);
gl.glTexCoord2f(1.0f, 1.0f);
gl.glVertex3f(2f, -2f, 0.0f);
gl.glTexCoord2f(1.0f, 0.0f);
gl.glVertex3f(2f, 2f, 0.0f);
gl.glTexCoord2f(0.0f, 0.0f);
gl.glVertex3f(-2f, 2f, 0.0f);
gl.glEnd();

gl.glPopMatrix();
}

public void reshape(
GLAutoDrawable dr,
int x, int y,
int width, int height){}

public void displayChanged(
GLAutoDrawable dr,
boolean modeChanged,
boolean deviceChanged){}
}
);

GLContext context = buf.createContext(null);
context.makeCurrent();
buf.display();
Screenshot.writeToFile(
new File("sample1206a.png"), width, height, true);
context.release();
context.destroy();
}
}


テクスチャ画像(sf_r.jpg)


出力画像(sample1206a.png)
繰り返しテクスチャを貼り付けたポリゴン


動作環境
JDK6 Upadate13, JOGL 1.1.1

No comments:

Post a Comment