본문 바로가기

실시간 운영체제

[실시간 운영체제] Open GL clones animation

Open GL의 기본적인 코드는

https://developer.android.com/develop/ui/views/graphics/opengl

위 사이트에 공개된 코드를 사용하였다.


 

animation clones.webm
2.06MB

 

 

MainActivity.java

package com.example.clones;

import androidx.appcompat.app.AppCompatActivity;

import android.opengl.GLSurfaceView;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private GLSurfaceView gLView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Create a GLSurfaceView instance and set it
        // as the ContentView for this Activity.
        gLView = new MyGLSurfaceView(this);
        setContentView(gLView);
    }
}

 

 

 

 

 

MyGLSurfaceView.java

package com.example.clones;

import android.content.Context;
import android.opengl.GLSurfaceView;

class MyGLSurfaceView extends GLSurfaceView {

    private final MyGLRenderer renderer;

    public MyGLSurfaceView(Context context){
        super(context);

        // Create an OpenGL ES 2.0 context
        setEGLContextClientVersion(2);

        renderer = new MyGLRenderer();

        // Set the Renderer for drawing on the GLSurfaceView
        setRenderer(renderer);
    }
}

 

 

 

 

 

MyGLRenderer.java

package com.example.clones;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class MyGLRenderer implements GLSurfaceView.Renderer {

    private clones_animation mClones_animation;

    // vPMatrix is an abbreviation for "Model View Projection Matrix"
    private final float[] vPMatrix = new float[16];
    private final float[] projectionMatrix = new float[16];
    private final float[] viewMatrix = new float[16];

    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
        // Set the background frame color
        GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

        mClones_animation = new clones_animation();

    }

    public void onDrawFrame(GL10 unused) {
        // Redraw background color
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

        // Set the camera position (View matrix)
        Matrix.setLookAtM(viewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

        // Calculate the projection and view transformation
        Matrix.multiplyMM(vPMatrix, 0, projectionMatrix, 0, viewMatrix, 0);

        // call it 25 times per second
        mClones_animation.draw(vPMatrix);
    }

    public void onSurfaceChanged(GL10 unused, int width, int height) {
        GLES20.glViewport(0, 0, width, height);

        float ratio = (float) width / height;

        // this projection matrix is applied to object coordinates
        // in the onDrawFrame() method
        Matrix.frustumM(projectionMatrix, 0, ratio, -ratio, -1, 1, 3, 7);
    }

    public static int loadShader(int type, String shaderCode){

        // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
        // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
        int shader = GLES20.glCreateShader(type);

        // add the source code to the shader and compile it
        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);

        return shader;
    }
}

 

 

 

 

 

clones_animation.java

package com.example.clones;

import android.opengl.GLES20;
import android.opengl.Matrix;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

public class clones_animation {

    private final String vertexShaderCode =
            // This matrix member variable provides a hook to manipulate
            // the coordinates of the objects that use this vertex shader
            "uniform mat4 uMVPMatrix;" +
                    "attribute vec4 vPosition;" +
                    "void main() {" +
                    // the matrix must be included as a modifier of gl_Position
                    // Note that the uMVPMatrix factor *must be first* in order
                    // for the matrix multiplication product to be correct.
                    "  gl_Position = uMVPMatrix * vPosition;" +
                    '}';

    // Use to access and set the view transformation
    private int vPMatrixHandle;

    private final float[] mTranslationMatrix = new float[16];
    private final float[] result_mvpMatrix_translation = new float[16];

    private final float[] mRotationMatrix = new float[16];
    private final float[] result_mvpMatrix_rotation = new float[16];

    private final float[] result_mvpMatrix_translation_rotation = new float[16];

    private final float[] mRotationMatrix90 = new float[16];

    private final float[] result_mvpMatrix_translation_rotation90 = new float[16];


    private FloatBuffer vertexBuffer,house_vertexBuffer;

    private final int mProgram;

    private int positionHandle;
    private int colorHandle;

    private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex
    // number of coordinates per vertex in this array
    static final int COORDS_PER_VERTEX = 3;

    static int vertex_number = 1000;
    static float vertexes_coordinates[]  = new float[vertex_number * 3];

    float color_matrix[] = new float[4];

    ///색의 RGB 값을 넣어준 2차원 배열 생성
    float colors[][] = {{0.6f,0.6f,  0.6f, 1.0f},   ///// gray color : color [0][]
            {0.0f,0.0f,  1.0f, 1.0f},   ///// blue color : color [1][]
            {0.0f,1.0f,  0.0f, 1.0f},   ///// green color : color [2][]
            {1.0f,0.0f,  0.0f, 1.0f},   ///// red color : color [3][]
            {0.0f,0.0f,  0.0f, 1.0f},   ///// black color : color [4][]
            {1.0f,1.0f,  0.0f, 1.0f}};   ///// yellow color : color [5][]

    //원하는 색 배열로 지정해줌
    int object_color[][] = {{3,3,3,3},   ///// ellipse 1: (red + red + red + red)
            {1,3,1,3},   ////ellipse 2: (blue +red)
            {1,1,3,3},   ////ellipse 3: (blue + blue + red + red)
            {5,4,2,0},   ////ellipse 4: (yellow + black + green + gray)
    };


    //0이 큰원, 13이 작은 원
    int object_shape[][] = {{0,0,13,13},   ///// ellipse 1: (gray + green)
            {13,0,13,0},   ////ellipse 2: (blue +red)
            {0,0,0,0},   ////ellipse 3: (black +yellow)
            {13,13,13,13},   ////ellipse 4: (blue +black)
    };


    //// Animation setup ///

    //// make clones ////
    ////   x   ,  y
    ///원 4개의 좌표 설정해주는거임 (겹치면 큰거는 보이는데 똑같은 사이즈이면 마지막에 실행한게 최종적으로 뜸)
//    float object_centers[][] = {{0.3f, 0.3f},    ///// object 1
//            {0.3f, -0.3f},   ///// object 2
//            {-0.3f,0.3f},   ///// object 3
//            {-0.3f,-0.3f}};  ///// object 4

    //원 4개의 좌표 설정(원 3, 4 겹치게 설정)
    float object_centers[][] = {{0.3f, 0.3f},    ///// object 1
            {0.3f, -0.3f},   ///// object 2
            {-0.3f,0.0f},   ///// object 3
            {-0.3f,-0.0f}};  ///// object 4

    //원 위치 조절하는거 (두개 동일한 값 넣어주면 같이 움직임)
    float object_d_xy[][] = {   {0.0f, 0.0f},    ///// object 1
            {0.0f, 0.0f},   ///// object 2
            {0.0f,0.001f},   ///// object 3
            {0.0f,0.001f}};  ///// object 4

    float Angles[] = {0.0f, 0.0f, 0.0f,0.0f};

    //제자리에서 회전
    float d_Angles[] = {1.0f, -3.0f, -2.0f,0.5f};

    //1/4원짜리 회전하는 각도
    float Quard[] = {0.0f,90.0f,180.0f,270.0f};

    static float house_vertex_coor[] = {   // in counterclockwise order:

            0.6f,  0.3f, 0.0f, // 지붕 v0
            -0.6f, 0.3f, 0.0f, // v1
            0.0f, 0.6f, 0.0f,  // v2
            0.45f, 0.3f, 0.0f, //벽면 v3
            0.45f, -0.3f, 0.0f, //v4
            -0.45f, 0.3f, 0.0f, //v6 => v5 (strip 사용하면서 사각형만드려면 점 위치 바꿔줘야함)
            -0.45f, -0.3f, 0.0f, //v5 => v6

            0.0f, 0.2f, 0.0f, // 창틀 v7
            -0.35f, 0.2f, 0.0f, //v8
            0.0f, -0.05f, 0.0f, //v9
            -0.35f, -0.05f, 0.0f, //v10

            -0.02f, 0.18f, 0.0f, // 창문 v11
            -0.33f, 0.18f, 0.0f, //v12
            -0.02f, -0.03f, 0.0f, //v13
            -0.33f, -0.03f, 0.0f, //v14

            -0.16f, 0.18f, 0.0f, // 창문 중간선 v15
            -0.18f, 0.18f, 0.0f, //v16
            -0.16f, -0.03f, 0.0f, //v17
            -0.18f, -0.03f, 0.0f, //v18

            0.35f, 0.2f, 0.0f, // 문 v19
            0.15f, 0.2f, 0.0f, //v20
            0.35f, -0.2f, 0.0f, //v21
            0.15f, -0.2f, 0.0f, //v22

            0.33f, 0.18f, 0.0f, // 창문 v23
            0.17f, 0.18f, 0.0f, //v24
            0.33f, 0.05f, 0.0f, //v25
            0.17f, 0.05f, 0.0f, //v26

    }; //집 만들기

    // Set color with red, green, blue and alpha (opacity) values
    //float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };

    //지붕 색 정하기 (rgb값/255.0f)
    float roof_color[] = {160/255.0f, 160/255.0f, 160/255.0f, 1.0f };

    float wall_color[] = {224/255.0f, 224/255.0f, 224/255.0f, 1.0f };

    float wood_color[] = {105/255.0f, 51/255.0f, 0/255.0f, 1.0f };

    float window_color[] = {204/255.0f, 229/255.0f, 255/255.0f, 1.0f };


    public clones_animation() {

        int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
                vertexShaderCode);
        int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
                fragmentShaderCode);

        // create empty OpenGL ES Program
        mProgram = GLES20.glCreateProgram();

        // add the vertex shader to program
        GLES20.glAttachShader(mProgram, vertexShader);

        // add the fragment shader to program
        GLES20.glAttachShader(mProgram, fragmentShader);

        // creates OpenGL ES program executables
        GLES20.glLinkProgram(mProgram);


        float d_angle = (float) Math.PI/20;





        //// Circle 1
        float R_circle_1 = 0.2f;
        int index = 0;

        vertexes_coordinates[index] = 0.0f; //// p44
        vertexes_coordinates[index+1] = 0.0f; //// p0
        vertexes_coordinates[index+2] = 0.0f;            //// p0

        index = index + 3;
        //// setup vertexes p1 - pn
        for (float angle = 0.0f; angle<=Math.PI/2 +  d_angle; angle = angle + d_angle)
        {

            vertexes_coordinates[index] =  R_circle_1*(float)Math.cos(angle);
            vertexes_coordinates[index+1] =  R_circle_1*(float)Math.sin(angle);
            vertexes_coordinates[index+2] = 0.0f;

            index = index + 3;  //// index = 9
        }

        //// Circle 2
        float R_circle_2 = 0.15f;


        vertexes_coordinates[index] = 0.0f; //// p44
        vertexes_coordinates[index+1] = 0.0f; //// p0
        vertexes_coordinates[index+2] = 0.0f;            //// p0
        index = index + 3;
        //// setup vertexes p1 - pn
        for (float angle = 0.0f; angle<=Math.PI/2 +  d_angle; angle = angle + d_angle)
        {

            vertexes_coordinates[index] =  R_circle_2*(float)Math.cos(angle);
            vertexes_coordinates[index+1] =  R_circle_2*(float)Math.sin(angle);
            vertexes_coordinates[index+2] = 0.0f;

            index = index + 3;  //// index = 9
        }


        ///// Add circle 1 vertexes to vertexBuffer_circle_1

        // initialize vertex byte buffer for shape coordinates
        ByteBuffer bb1 = ByteBuffer.allocateDirect(
                // (number of coordinate values * 4 bytes per float)
                vertexes_coordinates.length * 4);
        // use the device hardware's native byte order
        bb1.order(ByteOrder.nativeOrder());

        // create a floating point buffer from the ByteBuffer
        vertexBuffer = bb1.asFloatBuffer();
        // add the coordinates to the FloatBuffer
        vertexBuffer.put(vertexes_coordinates);
        // set the buffer to read the first coordinate
        vertexBuffer.position(0);




        ByteBuffer bb2 = ByteBuffer.allocateDirect(
                // (number of coordinate values * 4 bytes per float)
                house_vertex_coor.length * 4);
        // use the device hardware's native byte order
        bb2.order(ByteOrder.nativeOrder());

        // create a floating point buffer from the ByteBuffer
        house_vertexBuffer = bb2.asFloatBuffer();
        // add the coordinates to the FloatBuffer
        house_vertexBuffer.put(house_vertex_coor);
        // set the buffer to read the first coordinate
        house_vertexBuffer.position(0);

    }

    public void draw(float[] mvpMatrix) {


        // Add program to OpenGL ES environment
        GLES20.glUseProgram(mProgram);

        // get handle to vertex shader's vPosition member
        positionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");

        // Enable a handle to the triangle vertices
        GLES20.glEnableVertexAttribArray(positionHandle);


        // get handle to fragment shader's vColor member
        colorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");





        //display a house(백그라운드에 집 추가해줌)
        //load vertexas
        GLES20.glVertexAttribPointer(positionHandle, COORDS_PER_VERTEX,
                GLES20.GL_FLOAT, false,
                vertexStride, house_vertexBuffer);

        //// Implement the effect of rotation and projection (집이 같이 움직이 않도록 mvpMatrix로 바꿔줘야 안 움직이고 백그라운드에 위치할 수 있게함)
        GLES20.glUniformMatrix4fv(vPMatrixHandle, 1, false, mvpMatrix, 0);


        // Set color for drawing the triangle (지붕 만드는 삼각형, 바꾼 색 넣어줌)
        GLES20.glUniform4fv(colorHandle, 1, roof_color, 0);
        // Draw the roof (지붕 그리기)
        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);

        // Draw the wall (벽면 그리기)
        GLES20.glUniform4fv(colorHandle, 1, wall_color, 0); //여기서 색 안바꿔주면 앞에서 지정한 색으로 만들어짐
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 3, 4); //삼각형 두개 합쳐줌
        //3 4 5 하나, 3 5 6 하나 만들어짐 -> GL_TRIANGLE_FAN

        // Draw the wood (창틀 그리기)
        GLES20.glUniform4fv(colorHandle, 1, wood_color, 0);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 7, 4); //삼각형 두개 합쳐줌

        // Draw the windom (창문 그리기)
        GLES20.glUniform4fv(colorHandle, 1, window_color, 0);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 11, 4); //삼각형 두개 합쳐줌

        // Draw the wood (중간 창틀 그리기)
        GLES20.glUniform4fv(colorHandle, 1, wood_color, 0);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 15, 4); //삼각형 두개 합쳐줌

        // Draw the door (문 그리기)
        GLES20.glUniform4fv(colorHandle, 1, wood_color, 0);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 19, 4); //삼각형 두개 합쳐줌

        // Draw the window for door (문에 있는 창문 그리기)
        GLES20.glUniform4fv(colorHandle, 1, window_color, 0);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 23, 4); //삼각형 두개 합쳐줌






        // get handle to shape's transformation matrix
        vPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");

        //// Load vertexes ////

        GLES20.glVertexAttribPointer(positionHandle, COORDS_PER_VERTEX,
                GLES20.GL_FLOAT, false,
                vertexStride, vertexBuffer);


        for (int object_ID = 0; object_ID<4;object_ID++) //// object_ID = 0,1,2,3
        {

            //// Move the center of the screen using glTranslation
            Matrix.setIdentityM(mTranslationMatrix, 0);
            Matrix.setIdentityM(mRotationMatrix, 0);
            Matrix.rotateM(mRotationMatrix, 0, Angles[object_ID], 0, 0, -1.0f);

            ////  float Angles[] = {0.0f, 45.0f, 90.0f,10.0f};

            //미리 설정해둔 object_centers좌표로 설정되도록 해줌
            Matrix.translateM(mTranslationMatrix, 0, object_centers[object_ID][0], object_centers[object_ID][1], 0.0f); /// x and y are the variables of time


            Matrix.multiplyMM(result_mvpMatrix_translation, 0, mvpMatrix, 0, mTranslationMatrix, 0);
            Matrix.multiplyMM(result_mvpMatrix_translation_rotation, 0, result_mvpMatrix_translation, 0, mRotationMatrix, 0);

            //// Implement the effect of translation and projection
            GLES20.glUniformMatrix4fv(vPMatrixHandle, 1, false, result_mvpMatrix_translation_rotation, 0);

            int color_ID_for_current_part;
            for (int parts_ID = 0; parts_ID < 4; parts_ID++) {
                color_ID_for_current_part = object_color[object_ID][parts_ID];


                for (int color_ID = 0; color_ID < 4; color_ID++) ///   color_ID = 0,1,2,3
                {
                    ///                 0,1,2,3                        0                 0,1,2,3
                    color_matrix[color_ID] = colors[color_ID_for_current_part][color_ID];
                }

                //// Draw the part parts_ID

                // Set color for drawing the part 1
                GLES20.glUniform4fv(colorHandle, 1, color_matrix, 0);

                //// Rotate n * 90 degree ///// (90도씩 회전하면서 색이 변화함)
                Matrix.setIdentityM(mRotationMatrix, 0);
                Matrix.rotateM(mRotationMatrix, 0, Quard[parts_ID], 0, 0, -1.0f);

                Matrix.multiplyMM(result_mvpMatrix_translation_rotation90, 0, result_mvpMatrix_translation_rotation, 0, mRotationMatrix, 0);

                //// Implement the effect of rotation and projection
                GLES20.glUniformMatrix4fv(vPMatrixHandle, 1, false, result_mvpMatrix_translation_rotation90, 0);

                // Draw using vertexes  part 2
                GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, object_shape[object_ID][parts_ID], 12);



                ///// Animation updates

                Angles[object_ID] = Angles[object_ID] + d_Angles[object_ID];

                //  float d_Angles[] = {1.0f, 0.5f, 5.0f,10.0f};
                /////               0     x
                object_centers[object_ID][0] = object_centers[object_ID][0] + object_d_xy[object_ID][0];  //// x = x + d_x
                ///     0.31                           0.3                            0.01

                object_centers[object_ID][1] = object_centers[object_ID][1] + object_d_xy[object_ID][1];   ///// y = y + dy


                if ((object_centers[object_ID][0] > 0.5) || (object_centers[object_ID][0] < -0.5)) {
                    object_d_xy[object_ID][0] = -object_d_xy[object_ID][0]; /// dx = 0.01f -> dx = -0.01f
                }

                if ((object_centers[object_ID][1] > 0.8) || (object_centers[object_ID][1] < -0.8)) {
                    object_d_xy[object_ID][1] = -object_d_xy[object_ID][1]; /// dy = 0.01f -> dy = -0.01f
                }


                //   float object_centers[][] = {{0.3f, 0.3f},    ///// object 1
                //                             {0.3f, -0.3f},   ///// object 2
                //                              {-0.3f,0.3f},   ///// object 3
                //                             {-0.3f,-0.3f}};  ///// object 4

            }
        }



        // Disable vertex array
        GLES20.glDisableVertexAttribArray(positionHandle);
    }



    private final String fragmentShaderCode =
            "precision mediump float;" +
                    "uniform vec4 vColor;" +
                    "void main() {" +
                    "  gl_FragColor = vColor;" +
                    "}";

}