카테고리 없음

안드로이드 OpenGL ES 예제, 다각형 그리기

Soul-Learner 2012. 5. 13. 13:44

원문출처 http://blog.jayway.com/2009/12/04/opengl-es-tutorial-for-android-%E2%80%93-part-ii-building-a-polygon/

OpenGL ES에서 배경색상을 청색으로 설정하고 그 위에 적색 사각형을 출력하는 예

적용실습: 사각형이 점차 멀어져서 한 점으로 되었다가 다시 가까워지기를 반복하도록 코드를 작성해보세요.


Activity

package gl.test2;


import android.app.Activity;

import android.opengl.GLSurfaceView;

import android.os.Bundle;

import android.view.Window;

import android.view.WindowManager;


public class TutorialPartII extends Activity {

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

   

    this.requestWindowFeature(Window.FEATURE_NO_TITLE); 

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

            WindowManager.LayoutParams.FLAG_FULLSCREEN);

        

  GLSurfaceView view = new GLSurfaceView(this);

    view.setRenderer(new OpenGLRenderer());

    setContentView(view);

    }

}


Renderer

package gl.test2;


import javax.microedition.khronos.egl.EGLConfig;

import javax.microedition.khronos.opengles.GL10;


import android.opengl.GLU;

import android.opengl.GLSurfaceView.Renderer;


public class OpenGLRenderer implements Renderer {

private Square square; // 화면에 그릴 사각형에 대한 정보

        private int zvalue, delta;

public OpenGLRenderer() {

square = new Square();

                zvalue = -4;

delta = -1;

}

public void onSurfaceCreated(GL10 gl, EGLConfig config) {

// Set the background color to blue ( rgba ).

gl.glClearColor(0.0f, 0.0f, 1.0f, 0.5f); // 청색 배경

// Enable Smooth Shading, default not really needed.

gl.glShadeModel(GL10.GL_SMOOTH);

// Depth buffer setup.

gl.glClearDepthf(1.0f);

// Enables depth testing.

gl.glEnable(GL10.GL_DEPTH_TEST);

// The type of depth testing to do.

gl.glDepthFunc(GL10.GL_LEQUAL);

// Really nice perspective calculations.

gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);

}


public void onDrawFrame(GL10 gl) {

// Clears the screen and depth buffer.

gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); //앞서 설정한 클리어 색상 적용

// Replace the current matrix with the identity matrix

gl.glLoadIdentity(); // 매 프레임마다 단위행렬을 설정하는 이유는 기존 변환을 이번 프레임에 적용하지 않기 위함

                zvalue += delta; 

             gl.glTranslatef(0, 0, zvalue); 

             if(zvalue<-100 || zvalue>-4) delta *= -1;

                // Translates 4 units into the screen.

//gl.glTranslatef(0, 0, -4); //이동변환을 적용하지 않으면 0,0,0 에 그리므로 카메라와 너무 근접하여 안 그려질 수도 있음

// Draw our square.

square.draw(gl); 

}


public void onSurfaceChanged(GL10 gl, int width, int height) {

// Sets the current view port to the new size.

gl.glViewport(0, 0, width, height);

// Select the projection matrix

gl.glMatrixMode(GL10.GL_PROJECTION);

// Reset the projection matrix

gl.glLoadIdentity();

// Calculate the aspect ratio of the window

GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f, 100.0f);

// Select the modelview matrix

gl.glMatrixMode(GL10.GL_MODELVIEW);

// Reset the modelview matrix

gl.glLoadIdentity();

}

}


Square.java

package gl.test2;


import java.nio.ByteBuffer;

import java.nio.ByteOrder;

import java.nio.FloatBuffer;

import java.nio.ShortBuffer;


import javax.microedition.khronos.opengles.GL10;


public class Square {

private float vertices[] = {

     -1.0f,  1.0f, 0.0f,  // 0, Top Left

     -1.0f, -1.0f, 0.0f,  // 1, Bottom Left

      1.0f, -1.0f, 0.0f,  // 2, Bottom Right

      1.0f,  1.0f, 0.0f,  // 3, Top Right

};

// The order we like to connect them.

private short[] indices = { 0, 1, 2, 0, 2, 3 };

// Our vertex buffer.

private FloatBuffer vertexBuffer;


// Our index buffer.

private ShortBuffer indexBuffer;

public Square() {

// a float is 4 bytes, therefore we multiply the number if 

// vertices with 4.

ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);

vbb.order(ByteOrder.nativeOrder());

vertexBuffer = vbb.asFloatBuffer();

vertexBuffer.put(vertices);

vertexBuffer.position(0);

// short is 2 bytes, therefore we multiply the number if 

// vertices with 2.

ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);

ibb.order(ByteOrder.nativeOrder());

indexBuffer = ibb.asShortBuffer();

indexBuffer.put(indices);

indexBuffer.position(0);

}

public void draw(GL10 gl) {

// Counter-clockwise winding.

gl.glFrontFace(GL10.GL_CCW);

// Enable face culling.

gl.glEnable(GL10.GL_CULL_FACE);

// What faces to remove with the face culling.

gl.glCullFace(GL10.GL_BACK); // 뒷면은 그리지 않도록 설정

// Enabled the vertices buffer for writing and to be used during 

// rendering.

gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

// Specifies the location and data format of an array of vertex

// coordinates to use when rendering.

gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);// 레퍼런스 보기

gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, 

GL10.GL_UNSIGNED_SHORT, indexBuffer);

// Disable the vertices buffer.

gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);

// Disable face culling.

gl.glDisable(GL10.GL_CULL_FACE);

}

}