본문 바로가기

Game/Graphics

OpenGL-Tutorial 13 : Normal Mapping

link : http://www.opengl-tutorial.org/kr/intermediate-tutorials/tutorial-13-normal-mapping/


이번 튜토리얼은 사진이 많다. 그만큼 어려운 부분도 많겠지만 열심히 시작해보자!


튜토리얼 8 : Basic shading 이후로 삼각형 법서을 사용해 적절한 쉐이딩을 얻는 방법을 알고 있다.


한 가지 주의해야할 점은 지금까지는 정점당 하나의 법선만 있었다.

: 각 삼각형 내부에는 텍스처와 샘플링되는 색상의 반대쪽에서 부드럽게 변한다


정규 맵핑의 기본 개념은 법선을 유사하게 만드는 것이다.




Normal textures


"normal texture"는 다음과 같이 생겼다.



각 RGB texel에는 XYZ 벡터가 인코딩된다. 각 색상 구성 요소는 0과 1사이에 있고,


각 벡터 구성 요소는 -1과 1사이에 있으므로 이 간단한 매핑은 텍셀에서 일반으로 이동한다.

normal = (2*color)-1 // on each component

Texture는 일반적으로 블루톤을 지니는데 그 이유는 전체적으로 표면이 "표면 바깥"을 향하고 있기 때문이다.


평소처럼 X는 텍스처의 평면에서 오른쪽이고, Y는 위로, 따라서 오른손 법칙 Z가 텍스처면의 "외부"를 가리킨다.


이 텍스처는 확산된 텍스처처럼 매핑된다. 큰 문제는 모형 공간에서 각 개별 삼각형을 공간에서


표현하는 법선을 변환하는 방법이다.




Tangent and Bitangent


이제 우리는 공간을 정의하기 위해 3개의 벡터가 필요하다는 것을 알고 있다. 우리는 이미 up 벡터를 가지고 있다.
: 블렌더에 의해 주어지거나 삼각형으로부터 단순 교차 곱으로 계산된 것은 정상이다.

  이것은 노멀 맵의 전체 색상과 마찬가지로 파란색으로 표시된다.


다음으로 우리는 접선이 필요하다. T : 표면에 평행한 벡터 (많은 벡터들이 존재한다)



어느 것을 선택해야할까? 이론적으로 어떤것이든 우리는 못생긴 가장자리를 피하기 위해 이웃과 일치해야한다.


표준 방법은 텍스처의 좌표와 같은 방향으로 탄젠트 방향을 지정하는 것이다.



기초를 정의하기 위해 3개의 벡터가 필요하기 때문에, bitangent B를 계산해야한다.



알고리즘은 다음과 같다. deltaPos1과 deltaPos2 삼각형의 두 가장자리와 deltaUV1과 deltaUV2에


UV의 해당 차이점을 기록한 경우 다음 방정식으로 문제를 나타낼 수 있다.

deltaPos1 = deltaUV1.x * T + deltaUV1.y * B
deltaPos2 = deltaUV2.x * T + deltaUV2.y * B

T와 B에 대해서만 시스템을 풀면 벡터가 생긴다.


우리가 T,B,N 벡터를 가지게 되면 Tangent Space에서 Model Space로 갈 수 있게 해주는 멋진 매트릭스를 갖게된다.



이 TBN 행렬을 사용해 법선을 모형 공간으로 변활 할 수 있다. 그러나, 일반적으로 다른 방법으로 수행된다.


모델 공간에서 탄젠트 공간으로 모든 것을 변환하고 그대로 추출 된 상태로 유지한다.


모든 계산은 Tangent Space에서 수행된다. Tangent Space는 아무것도 변경하지 않는다.


이 역변환을 사용하면 간단히 역행렬을 취해야한다.

invTBN = transpose(TBN)




Preparing our VBO


Computing the tangents and bitangents


우리의 법선 위에 접선과 비트가 필요하기 때문에 전체 메쉬에 대해 계산해야한다. 별도의 함수로 이 작업을 수행한다.

void computeTangentBasis(
    // inputs
    std::vector<glm::vec3> & vertices,
    std::vector<glm::vec2> & uvs,
    std::vector<glm::vec3> & normals,
    // outputs
    std::vector<glm::vec3> & tangents,
    std::vector<glm::vec3> & bitangents
){

각 삼각형에 대해 우리는 edge와 deltaUV를 계산해야한다.

    for ( int i=0; i<vertices.size(); i+=3){

        // Shortcuts for vertices
        glm::vec3 & v0 = vertices[i+0];
        glm::vec3 & v1 = vertices[i+1];
        glm::vec3 & v2 = vertices[i+2];

        // Shortcuts for UVs
        glm::vec2 & uv0 = uvs[i+0];
        glm::vec2 & uv1 = uvs[i+1];
        glm::vec2 & uv2 = uvs[i+2];

        // Edges of the triangle : postion delta
        glm::vec3 deltaPos1 = v1-v0;
        glm::vec3 deltaPos2 = v2-v0;

        // UV delta
        glm::vec2 deltaUV1 = uv1-uv0;
        glm::vec2 deltaUV2 = uv2-uv0;

 이제 공식을 사용해 탄젠트와 비트를 계산할 수 있다.

        float r = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x);
        glm::vec3 tangent = (deltaPos1 * deltaUV2.y   - deltaPos2 * deltaUV1.y)*r;
        glm::vec3 bitangent = (deltaPos2 * deltaUV1.x   - deltaPos1 * deltaUV2.x)*r;

 마지막으로 tangents와 bitangents 버퍼를 채운다. 이러한 버퍼는 아직 인덱싱되지 않으므로 꼭지점에는 자체 복사본이 있다.

        // Set the same tangent for all three vertices of the triangle.
        // They will be merged later, in vboindexer.cpp
        tangents.push_back(tangent);
        tangents.push_back(tangent);
        tangents.push_back(tangent);

        // Same thing for binormals
        bitangents.push_back(bitangent);
        bitangents.push_back(bitangent);
        bitangents.push_back(bitangent);

    }



Indexing


VBO를 인덱싱하는 것은 이전과 매우 유사하지만 미묘한 차이가 있다.


유사한 꼭지점 (같은 위치, 동일 법선, 동일 텍스처 좌표)을 찾으면 우리는 tangent와 binormal을 사용하고 싶지 않다.


이제 이전 코드를 조금 수정해보자.

        // Try to find a similar vertex in out_XXXX
        unsigned int index;
        bool found = getSimilarVertexIndex(in_vertices[i], in_uvs[i], in_normals[i],     out_vertices, out_uvs, out_normals, index);

        if ( found ){ // A similar vertex is already in the VBO, use it instead !
            out_indices.push_back( index );

            // Average the tangents and the bitangents
            out_tangents[index] += in_tangents[i];
            out_bitangents[index] += in_bitangents[i];
        }else{ // If not, it needs to be added in the output data.
            // Do as usual
            [...]
        }

우리는 여기서 어떤 것도 정규화하지 않는다는 것을 유의해라. 이 방법은 더 작은 탄젠트 및 비트탄젠트 벡터를 갖는


작은 삼각형(최종 모양에 더 많은 기여를 하는)보다 최종 벡터에 약한 효과를 갖기 때문에 실제로는 편리하다.





The shader


Additional Buffers & uniforms


우리는 두 개의 새로운 버퍼가 필요하다. : 하나는 접선을 위한 것이고, 다른 하나는 bitangents를 위한 것이다.

    GLuint tangentbuffer;
    glGenBuffers(1, &tangentbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, tangentbuffer);
    glBufferData(GL_ARRAY_BUFFER, indexed_tangents.size() * sizeof(glm::vec3), &indexed_tangents[0], GL_STATIC_DRAW);

    GLuint bitangentbuffer;
    glGenBuffers(1, &bitangentbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, bitangentbuffer);
    glBufferData(GL_ARRAY_BUFFER, indexed_bitangents.size() * sizeof(glm::vec3), &indexed_bitangents[0], GL_STATIC_DRAW);

 우리는 또한 새로운 normal texture를 위한 새로운 uniform이 필요하다.

    [...]
    GLuint NormalTexture = loadTGA_glfw("normal.tga");
    [...]
    GLuint NormalTextureID  = glGetUniformLocation(programID, "NormalTextureSampler");

하나는 3x3 ModelView matrix용이다. 이것은 엄격히 말하자면 필수는 아니지만 쉽다.
우리는 방향을 배가 할 것이기 때문에 3x3의 왼쪽 위 부분만 필요하기 때문에 변역 부분을 삭제할 수 있다.

    GLuint ModelView3x3MatrixID = glGetUniformLocation(programID, "MV3x3");

So the full drawing code becomes :

        // Clear the screen
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Use our shader
        glUseProgram(programID);

        // Compute the MVP matrix from keyboard and mouse input
        computeMatricesFromInputs();
        glm::mat4 ProjectionMatrix = getProjectionMatrix();
        glm::mat4 ViewMatrix = getViewMatrix();
        glm::mat4 ModelMatrix = glm::mat4(1.0);
        glm::mat4 ModelViewMatrix = ViewMatrix * ModelMatrix;
        glm::mat3 ModelView3x3Matrix = glm::mat3(ModelViewMatrix); // Take the upper-left part of ModelViewMatrix
        glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;

        // Send our transformation to the currently bound shader,
        // in the "MVP" uniform
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
        glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]);
        glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);
        glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);
        glUniformMatrix3fv(ModelView3x3MatrixID, 1, GL_FALSE, &ModelView3x3Matrix[0][0]);

        glm::vec3 lightPos = glm::vec3(0,0,4);
        glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z);

        // Bind our diffuse texture in Texture Unit 0
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, DiffuseTexture);
        // Set our "DiffuseTextureSampler" sampler to user Texture Unit 0
        glUniform1i(DiffuseTextureID, 0);

        // Bind our normal texture in Texture Unit 1
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, NormalTexture);
        // Set our "Normal    TextureSampler" sampler to user Texture Unit 0
        glUniform1i(NormalTextureID, 1);

        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(
            0,                  // attribute
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
        );

        // 2nd attribute buffer : UVs
        glEnableVertexAttribArray(1);
        glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
        glVertexAttribPointer(
            1,                                // attribute
            2,                                // size
            GL_FLOAT,                         // type
            GL_FALSE,                         // normalized?
            0,                                // stride
            (void*)0                          // array buffer offset
        );

        // 3rd attribute buffer : normals
        glEnableVertexAttribArray(2);
        glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
        glVertexAttribPointer(
            2,                                // attribute
            3,                                // size
            GL_FLOAT,                         // type
            GL_FALSE,                         // normalized?
            0,                                // stride
            (void*)0                          // array buffer offset
        );

        // 4th attribute buffer : tangents
        glEnableVertexAttribArray(3);
        glBindBuffer(GL_ARRAY_BUFFER, tangentbuffer);
        glVertexAttribPointer(
            3,                                // attribute
            3,                                // size
            GL_FLOAT,                         // type
            GL_FALSE,                         // normalized?
            0,                                // stride
            (void*)0                          // array buffer offset
        );

        // 5th attribute buffer : bitangents
        glEnableVertexAttribArray(4);
        glBindBuffer(GL_ARRAY_BUFFER, bitangentbuffer);
        glVertexAttribPointer(
            4,                                // attribute
            3,                                // size
            GL_FLOAT,                         // type
            GL_FALSE,                         // normalized?
            0,                                // stride
            (void*)0                          // array buffer offset
        );

        // Index buffer
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);

        // Draw the triangles !
        glDrawElements(
            GL_TRIANGLES,      // mode
            indices.size(),    // count
            GL_UNSIGNED_INT,   // type
            (void*)0           // element array buffer offset
        );

        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
        glDisableVertexAttribArray(2);
        glDisableVertexAttribArray(3);
        glDisableVertexAttribArray(4);

        // Swap buffers
        glfwSwapBuffers();




Vertex shader


전에 말했듯이 우리는 카메라 공간 내부에서 모든것을 처리한다, 그 이유는 이 공간에서 fragment의 위치를 얻는 것이


더 간단하기 때문이다. 이것이 우리가 T,B,N 벡터에 ModelView 행렬을 곱하는 이유이다. .xml 왼쪽 위 부분은


방향을 곱하기 때문에 번역부분을 삭제할 수 있다.

    vertexNormal_cameraspace = MV3x3 * normalize(vertexNormal_modelspace);
    vertexTangent_cameraspace = MV3x3 * normalize(vertexTangent_modelspace);
    vertexBitangent_cameraspace = MV3x3 * normalize(vertexBitangent_modelspace);

이 세가지 벡터는 다음과 같이 구성된 TBN 행렬을 정의한다.


    mat3 TBN = transpose(mat3(
        vertexTangent_cameraspace,
        vertexBitangent_cameraspace,
        vertexNormal_cameraspace
    )); // You can use dot products instead of building this matrix and transposing it. See References for details.

이 행렬은 카메라 공간에서 접선 공간으로 이동한다. 우리는 이것을 사용해 접선 공간에서 빛의 방향과 눈의 방향을 계산할 수 있다.


    LightDirection_tangentspace = TBN * LightDirection_cameraspace;
    EyeDirection_tangentspace =  TBN * EyeDirection_cameraspace;


Fragment shader


tangent 공간에서 우리의 normal은 얻기 쉽다.

    // Local normal, in tangent space
    vec3 TextureNormal_tangentspace = normalize(texture( NormalTextureSampler, UV ).rgb*2.0 - 1.0);

이제 우리는 필요한 모든 것을 갖추고 있다. 확산 조명은 클램프 (점 (n,l), 0,1)를 사용하며 n과 l은 접선 공간으로 표현된다.

(점과 십자가를 만드는 공간은 중요하지 않다. 중요한 점은 n과 l이다. 둘 다 같은 공간에서 표현된다)


반사 조명은 E와 R이 접선 공간으로 표현된채로 클램프 (점 (E,R), 0,1)를 사용한다.






Result


우리의 결과이다. 다음 사항을 확인할 수 있다.


1) 법선에 많은 변형이 있기 때문에 벽돌이 울퉁불퉁해보인다.

2) 일반 질감이 균일하게 파란색이므로 시멘트가 평평하게 보인다.






Going further


Orthogonalization


우리의 버텍스 쉐이더에서는 반전 대신 transpose를 사용했다. 그러나 행렬이 나타내는 공간이 직각인 경우에만 작동한다.


다행히도 이것은 매우 쉽게 해결할 수 있다 : computeTangentBasis()의 끝에서 접선을 법선에 수직으로 만들어야한다.

t = glm::normalize(t - n * glm::dot(n, t));

이 수식은 파악하기 어려울 수 있으므로 스키마가 도움이 될 수 있다.



n과 t는 거의 수직이므로, 우리는 점의 점 (n,t)에 의해 -n의 방향으로 t를 "밀어 넣는다"




Handedness


거의 걱정할 필요가 없지만 대칭 모델을 사용하면 UV가 잘못된 방향으로 향하고 T의 방향이 잘못된다.


반전되어야하는지 여부를 확인하기 위한 검사는 간단하다.


TBN은 오른 손잡이 좌표계를 형성해야한다. 즉, cross(n,t)는 b와 동일한 방향을 가져야한다.


수학에서 "벡터 A는 벡터 B와 동일한 방향을 가집니다"는 점 (A,B) > 0으로 변환되므로


dot(cross(n,t,b) > 0인지 확인해야한다.




Specular texture


그냥 재미로 코드에 반사 텍스처를 추가했다. 다음과 같이 보인다.



우리가 반사 색상으로 사용한 간단한 "vec3(0.3,0.3,0.3)" 회색 대신에 사용된다.



이젠 시멘트는 항상 검은색이다. 텍스처에 반사 요소가 없다고 말한다.






Debugging with the immediate mode


이 웹 사이트의 진정한 목적은 여러 측면에서 더 이상 사용되지 않으며, 문제가 되는 직접 모드를 사용하지 않는 것이다.


그러나 이것은 디버깅할 때도 매우 편리하다.



여기에서는 직선 모드로 그린 선으로 접선 공간을 시각화한다.


이를 위해서는 3.3 core profile을 포기해야한다.

glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);

우리의 행렬을 OpenGL의 구식 파이프 라인에 제공해라.

glMatrixMode(GL_PROJECTION);
glLoadMatrixf((const GLfloat*)&ProjectionMatrix[0]);
glMatrixMode(GL_MODELVIEW);
glm::mat4 MV = ViewMatrix * ModelMatrix;
glLoadMatrixf((const GLfloat*)&MV[0]);

Disable shaders :

glUseProgram(0);

And draw your lines (in this case, normals, normalized and multiplied by 0.1, and applied at the correct vertex) :

glColor3f(0,0,1);
glBegin(GL_LINES);
for (int i=0; i<indices.size(); i++){
    glm::vec3 p = indexed_vertices[indices[i]];
    glVertex3fv(&p.x);
    glm::vec3 o = glm::normalize(indexed_normals[indices[i]]);
    p+=o*0.1f;
    glVertex3fv(&p.x);
}
glEnd();

기억해라 : 실제 모드에서는 immediate 모드를 사용하지 마라. 디버깅을 위해서만 사용하고 나중에 다시 핵심 프로필을 사용하도록


설정하는 것을 잊지말아라! 그렇지 않으면 해당 작업을 수행하지 않아도 된다.





Debugging with colors


디버깅 할 때 벡터의 값을 시각화하는 것이 유용할 수 있다. 이를 수행하기 가장 쉬운 방법은 실제 색상 대신 프레임 버퍼를 쓰는 것이다.


예를 들어 LightDirection_tangentspace를 시각화해보겠다.

color.xyz = LightDirection_tangentspace;

이것은 다음을 말한다 :
1) 원통의 오른쪽 부분에서 빛 (작은 흰색 선)이 up(접선 공간에서)이다. 즉, 빛은 삼각형의 법선 방향이다.
2) 원통의 중간 부분에서 빛은 접선 방향 (+X 방향)으로 향하게 된다.

몇 가지 팁 :
1) 시각화하려는 대상에 따라 표준화를 원할 수 있다.
    보고 있는 내용을 이해할 수 없으며 녹색과 파란색을 0으로 설정해 모든 구성 요소를 개별적으로 시각화해라.
2) 알파를 사용해 모든 것을 피해라, 이것은 너무 복잡하다
3) 음수 값을 시각화하려면 일반 텍스처에서 사용하는 것과 동일한 트릭을 사용할 수 있다.
   즉, 시각화 (v+1.0)/2.0 대신 검정색은 -1을 의미하고 전체 색상은 +1을 의미한다.




Debugging with variable names


이미 언급했듯이, 벡터가 어느 공간에 있는지 정확히 아는 것이 중요하다. 카메라 공간의 벡터와 모델 공간의 벡터의 내적을 가져가지 말아라.


그들의 이름에 각 벡터의 공간을 추가하면 수학 버그를 엄청나게 수정하는데 도움이 된다.




How to create a normal map





1) NormalMapping.fragmentshader


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#version 330 core
 
// Interpolated values from the vertex shaders
in vec2 UV;
in vec3 Position_worldspace;
in vec3 EyeDirection_cameraspace;
in vec3 LightDirection_cameraspace;
 
in vec3 LightDirection_tangentspace;
in vec3 EyeDirection_tangentspace;
 
// Ouput data
out vec3 color;
 
// Values that stay constant for the whole mesh.
uniform sampler2D DiffuseTextureSampler;
uniform sampler2D NormalTextureSampler;
uniform sampler2D SpecularTextureSampler;
uniform mat4 V;
uniform mat4 M;
uniform mat3 MV3x3;
uniform vec3 LightPosition_worldspace;
 
void main(){
 
    // Light emission properties
    // You probably want to put them as uniforms
    vec3 LightColor = vec3(1,1,1);
    float LightPower = 40.0;
    
    // Material properties
    vec3 MaterialDiffuseColor = texture( DiffuseTextureSampler, UV ).rgb;
    vec3 MaterialAmbientColor = vec3(0.1,0.1,0.1) * MaterialDiffuseColor;
    vec3 MaterialSpecularColor = texture( SpecularTextureSampler, UV ).rgb * 0.3;
 
    // Local normal, in tangent space. V tex coordinate is inverted because normal map is in TGA (not in DDS) for better quality
    vec3 TextureNormal_tangentspace = normalize(texture( NormalTextureSampler, vec2(UV.x,-UV.y) ).rgb*2.0 - 1.0);
    
    // Distance to the light
    float distance = length( LightPosition_worldspace - Position_worldspace );
 
    // Normal of the computed fragment, in camera space
    vec3 n = TextureNormal_tangentspace;
    // Direction of the light (from the fragment to the light)
    vec3 l = normalize(LightDirection_tangentspace);
    // Cosine of the angle between the normal and the light direction, 
    // clamped above 0
    //  - light is at the vertical of the triangle -> 1
    //  - light is perpendicular to the triangle -> 0
    //  - light is behind the triangle -> 0
    float cosTheta = clamp( dot( n,l ), 0,1 );
 
    // Eye vector (towards the camera)
    vec3 E = normalize(EyeDirection_tangentspace);
    // Direction in which the triangle reflects the light
    vec3 R = reflect(-l,n);
    // Cosine of the angle between the Eye vector and the Reflect vector,
    // clamped to 0
    //  - Looking into the reflection -> 1
    //  - Looking elsewhere -> < 1
    float cosAlpha = clamp( dot( E,R ), 0,1 );
    
    color = 
        // Ambient : simulates indirect lighting
        MaterialAmbientColor +
        // Diffuse : "color" of the object
        MaterialDiffuseColor * LightColor * LightPower * cosTheta / (distance*distance) +
        // Specular : reflective highlight, like a mirror
        MaterialSpecularColor * LightColor * LightPower * pow(cosAlpha,5) / (distance*distance);
 
}
cs


2) NormalMapping.vertexshader


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#version 330 core
 
layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec2 vertexUV;
layout(location = 2) in vec3 vertexNormal_modelspace;
layout(location = 3) in vec3 vertexTangent_modelspace;
layout(location = 4) in vec3 vertexBitangent_modelspace;
 
out vec2 UV;
out vec3 Position_worldspace;
out vec3 EyeDirection_cameraspace;
out vec3 LightDirection_cameraspace;
 
out vec3 LightDirection_tangentspace;
out vec3 EyeDirection_tangentspace;
 
uniform mat4 MVP;
uniform mat4 V;
uniform mat4 M;
uniform mat3 MV3x3;
uniform vec3 LightPosition_worldspace;
 
void main(){
 
    // Output position of the vertex, in clip space : MVP * position
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);
    
    // Position of the vertex, in worldspace : M * position
    Position_worldspace = (M * vec4(vertexPosition_modelspace,1)).xyz;
    
    // Vector that goes from the vertex to the camera, in camera space.
    // In camera space, the camera is at the origin (0,0,0).
    vec3 vertexPosition_cameraspace = ( V * M * vec4(vertexPosition_modelspace,1)).xyz;
    EyeDirection_cameraspace = vec3(0,0,0) - vertexPosition_cameraspace;
 
    // Vector that goes from the vertex to the light, in camera space. M is ommited because it's identity.
    vec3 LightPosition_cameraspace = ( V * vec4(LightPosition_worldspace,1)).xyz;
    LightDirection_cameraspace = LightPosition_cameraspace + EyeDirection_cameraspace;
    
    // UV of the vertex. No special space for this one.
    UV = vertexUV;
    
    // model to camera = ModelView
    vec3 vertexTangent_cameraspace = MV3x3 * vertexTangent_modelspace;
    vec3 vertexBitangent_cameraspace = MV3x3 * vertexBitangent_modelspace;
    vec3 vertexNormal_cameraspace = MV3x3 * vertexNormal_modelspace;
    
    mat3 TBN = transpose(mat3(
        vertexTangent_cameraspace,
        vertexBitangent_cameraspace,
        vertexNormal_cameraspace    
    )); // You can use dot products instead of building this matrix and transposing it. See References for details.
 
    LightDirection_tangentspace = TBN * LightDirection_cameraspace;
    EyeDirection_tangentspace =  TBN * EyeDirection_cameraspace;
    
    
}
 
 
cs


3) source.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <GL/glew.h>
#include <glfw3.h>
#include <GL/glew.h>
GLFWwindow* window;
 
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
using namespace glm;
 
#define FOURCC_DXT1 0x31545844 // Equivalent to "DXT1" in ASCII
#define FOURCC_DXT3 0x33545844 // Equivalent to "DXT3" in ASCII
#define FOURCC_DXT5 0x35545844 // Equivalent to "DXT5" in ASCII
 
GLuint LoadShaders(const char *const char *);
GLuint loadBMP_custom(const char *);
GLuint loadDDS(const char *);
bool loadOBJ(
    const char *,
    std::vector<glm::vec3> &,
    std::vector<glm::vec2> &,
    std::vector<glm::vec3> &);
 
void indexVBO(
    std::vector<glm::vec3> & ,
    std::vector<glm::vec2> & ,
    std::vector<glm::vec3> & ,
 
    std::vector<unsigned short> & ,
    std::vector<glm::vec3> & ,
    std::vector<glm::vec2> & ,
    std::vector<glm::vec3> & 
);
void indexVBO_TBN(
    std::vector<glm::vec3> &,
    std::vector<glm::vec2> &,
    std::vector<glm::vec3> &,
    std::vector<glm::vec3> &,
    std::vector<glm::vec3> &,
 
    std::vector<unsigned short> &,
    std::vector<glm::vec3> &,
    std::vector<glm::vec2> &,
    std::vector<glm::vec3> &,
    std::vector<glm::vec3> &,
    std::vector<glm::vec3> &
);
 
 
//mouse-keyboard input
void computeMatricesFromInputs();
glm::mat4 getViewMatrix();
glm::mat4 getProjectionMatrix();
 
glm::mat4 ViewMatrix;
glm::mat4 ProjectionMatrix;
 
glm::mat4 getViewMatrix() {
    return ViewMatrix;
}
glm::mat4 getProjectionMatrix() {
    return ProjectionMatrix;
}
 
struct PackedVertex {
    glm::vec3 position;
    glm::vec2 uv;
    glm::vec3 normal;
    bool operator<(const PackedVertex that) const {
        return memcmp((void*)this, (void*)&that, sizeof(PackedVertex))>0;
    };
};
 
bool is_near(float v1, float v2) {
    return fabs(v1 - v2) < 0.01f;
}
 
bool getSimilarVertexIndex_fast(
    PackedVertex & packed,
    std::map<PackedVertex, unsigned short> & VertexToOutIndex,
    unsigned short & result
) {
    std::map<PackedVertex, unsigned short>::iterator it = VertexToOutIndex.find(packed);
    if (it == VertexToOutIndex.end()) {
        return false;
    }
    else {
        result = it->second;
        return true;
    }
}
 
bool getSimilarVertexIndex(
    glm::vec3 & in_vertex,
    glm::vec2 & in_uv,
    glm::vec3 & in_normal,
    std::vector<glm::vec3> & out_vertices,
    std::vector<glm::vec2> & out_uvs,
    std::vector<glm::vec3> & out_normals,
    unsigned short & result
) {
    // Lame linear search
    for (unsigned int i = 0; i<out_vertices.size(); i++) {
        if (
            is_near(in_vertex.x, out_vertices[i].x) &&
            is_near(in_vertex.y, out_vertices[i].y) &&
            is_near(in_vertex.z, out_vertices[i].z) &&
            is_near(in_uv.x, out_uvs[i].x) &&
            is_near(in_uv.y, out_uvs[i].y) &&
            is_near(in_normal.x, out_normals[i].x) &&
            is_near(in_normal.y, out_normals[i].y) &&
            is_near(in_normal.z, out_normals[i].z)
            ) {
            result = i;
            return true;
        }
    }
    // No other vertex could be used instead.
    // Looks like we'll have to add it to the VBO.
    return false;
}
 
 
void computeTangentBasis(
    //inputs
    std::vector<glm::vec3> &,
    std::vector<glm::vec2> &,
    std::vector<glm::vec3> &,
    //outputs
    std::vector<glm::vec3> &,
    std::vector<glm::vec3> &
);
 
//text2D
unsigned int Text2DTextureID;
unsigned int Text2DVertexBufferID;
unsigned int Text2DUVBufferID;
unsigned int Text2DShaderID;
unsigned int Text2DUniformID;
 
void initText2D(const char *);
void printText2D(const char *intintint);
void cleanupText2D();
 
 
//포지션 초기화
glm::vec3 position = glm::vec3(005);
float horizontalAngle = 3.14f;
float verticalAngle = 0.0f;
float initialFoV = 45.0f;
 
float speed = 3.0f;
float mouseSpeed = 0.005f;
 
void APIENTRY DebugOutputCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) {
 
    printf("OpenGL Debug Output message : ");
 
    if (source == GL_DEBUG_SOURCE_API_ARB) printf("Source : API; ");
    else if (source == GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB)    printf("Source : WINDOW_SYSTEM; ");
    else if (source == GL_DEBUG_SOURCE_SHADER_COMPILER_ARB)    printf("Source : SHADER_COMPILER; ");
    else if (source == GL_DEBUG_SOURCE_THIRD_PARTY_ARB)        printf("Source : THIRD_PARTY; ");
    else if (source == GL_DEBUG_SOURCE_APPLICATION_ARB)        printf("Source : APPLICATION; ");
    else if (source == GL_DEBUG_SOURCE_OTHER_ARB)            printf("Source : OTHER; ");
 
    if (type == GL_DEBUG_TYPE_ERROR_ARB)                        printf("Type : ERROR; ");
    else if (type == GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB)    printf("Type : DEPRECATED_BEHAVIOR; ");
    else if (type == GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB)    printf("Type : UNDEFINED_BEHAVIOR; ");
    else if (type == GL_DEBUG_TYPE_PORTABILITY_ARB)            printf("Type : PORTABILITY; ");
    else if (type == GL_DEBUG_TYPE_PERFORMANCE_ARB)            printf("Type : PERFORMANCE; ");
    else if (type == GL_DEBUG_TYPE_OTHER_ARB)                printf("Type : OTHER; ");
 
    if (severity == GL_DEBUG_SEVERITY_HIGH_ARB)                printf("Severity : HIGH; ");
    else if (severity == GL_DEBUG_SEVERITY_MEDIUM_ARB)        printf("Severity : MEDIUM; ");
    else if (severity == GL_DEBUG_SEVERITY_LOW_ARB)            printf("Severity : LOW; ");
 
    //break point를 여기에 설정해라, 당신의 디버거는 프로그램을 멈출 것이다
    //callstack은 바로 너에게 offending call을 보여줄 것이다
    printf("Mesage : %s\n", message);
}
 
int main() {
 
    // Initialise GLFW
    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        getchar();
        return -1;
    }
 
    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
 
    // Open a window and create its OpenGL context
    window = glfwCreateWindow(1024768"QBOT_opengl"NULLNULL);
    if (window == NULL) {
        fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
        getchar();
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
 
    // Initialize GLEW
    glewExperimental = true;
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        getchar();
        glfwTerminate();
        return -1;
    }
 
    // Example 1:
    /*if (GLEW_AMD_seamless_cubemap_per_texture) {
        printf("The GL_AMD_seamless_cubemap_per_texture is present, (but we're not goint to use it)\n");
        //이제 glTexParameterf를 TEXTURE_CUBE_MAP_SEAMLESS_ARB 매개 변수와 함께 호출하는 것이 합법적이다
        //분명히 이 코드는 AMD가 아닌 하드웨어에서는 실표할 것이기 때문에 테스트해야한다
    }
    // Example 2:
    if (GLEW_ARB_debug_output) {
        printf("The OpenGL implementation provides debug output. Let's use it!\n");
        glDebugMessageCallbackARB(&DebugOutputCallback, NULL);
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
    }
    else {
        printf("ARB_debug_output unavailable. You have to use glGetError() and/or gDebugger to catch mistakes.\n");
    }*/
 
    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
 
    // Set the mouse at the center of the screen
    glfwPollEvents();
    glfwSetCursorPos(window, 1024 / 2768 / 2);
 
    // Dark blue background
    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
 
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_CULL_FACE);
 
    GLuint VertexArrayID;
    glGenVertexArrays(1&VertexArrayID);
    glBindVertexArray(VertexArrayID);
 
    //Shader를 불러온다.
    GLuint programID = LoadShaders("NormalMapping.vertexshader""NormalMapping.fragmentshader");
 
    //매트릭스ID 추가
    GLuint MatrixID = glGetUniformLocation(programID, "MVP");
    GLuint ViewMatrixID = glGetUniformLocation(programID, "V");
    GLuint ModelMatrixID = glGetUniformLocation(programID, "M");
    GLuint ModelView3x3MatrixID = glGetUniformLocation(programID, "MV3x3");
 
    //어떠한 두 가지의 함수를 사용해서 텍스처를 불러온다
    //GLuint Texture = loadBMP_custom("uvtemplate.bmp");
    //GLuint Texture = loadDDS("uvmap.DDS");
    GLuint DiffuseTexture = loadDDS("diffuse.DDS");
    GLuint NormalTexture = loadBMP_custom("normal.bmp");
    GLuint SpecularTexture = loadDDS("specular.DDS");
 
    //GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler");
    GLuint DiffuseTextureID = glGetUniformLocation(programID, "DiffuseTextureSampler");
    GLuint NormalTextureID = glGetUniformLocation(programID, "NormalTextureSampler");
    GLuint SpecularTextureID = glGetUniformLocation(programID, "SpecularTextureSampler");
 
    //우리의 .obj file을 읽는다
    std::vector<glm::vec3> vertices;
    std::vector<glm::vec2> uvs;
    std::vector<glm::vec3> normals;
    bool res = loadOBJ("cylinder.obj", vertices, uvs, normals);
    
    std::vector<glm::vec3> tangents;
    std::vector<glm::vec3> bitangents;
    computeTangentBasis(
        vertices, uvs, normals, // input
        tangents, bitangents    // output
    );
 
    std::vector<unsigned short> indices;
    std::vector<glm::vec3> indexed_vertices;
    std::vector<glm::vec2> indexed_uvs;
    std::vector<glm::vec3> indexed_normals;
    std::vector<glm::vec3> indexed_tangents;
    std::vector<glm::vec3> indexed_bitangents;
    indexVBO_TBN(
        vertices, uvs, normals, tangents, bitangents,
        indices, indexed_vertices, indexed_uvs, indexed_normals, indexed_tangents, indexed_bitangents
    );
    
    GLuint vertexbuffer;
    glGenBuffers(1&vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(glm::vec3), &indexed_vertices[0], GL_STATIC_DRAW);
 
    GLuint uvbuffer;
    glGenBuffers(1&uvbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
    glBufferData(GL_ARRAY_BUFFER, indexed_uvs.size() * sizeof(glm::vec2), &indexed_uvs[0], GL_STATIC_DRAW);
 
    GLuint normalbuffer;
    glGenBuffers(1&normalbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
    glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(glm::vec3), &indexed_normals[0], GL_STATIC_DRAW);
 
    GLuint tangentbuffer;
    glGenBuffers(1&tangentbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, tangentbuffer);
    glBufferData(GL_ARRAY_BUFFER, indexed_tangents.size() * sizeof(glm::vec3), &indexed_tangents[0], GL_STATIC_DRAW);
 
    GLuint bitangentbuffer;
    glGenBuffers(1&bitangentbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, bitangentbuffer);
    glBufferData(GL_ARRAY_BUFFER, indexed_bitangents.size() * sizeof(glm::vec3), &indexed_bitangents[0], GL_STATIC_DRAW);
 
 
    // Generate a buffer for the indices as well
    GLuint elementbuffer;
    glGenBuffers(1&elementbuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW);
 
    glUseProgram(programID);
    GLuint LightID = glGetUniformLocation(programID, "LightPosition_worldspace");
 
    //little text library를 초기화
    //initText2D("Holstein.DDS");
 
    //speed computation
    double lastTime = glfwGetTime();
    int nbFrames = 0;
 
    //enable blending
    //glEnable(GL_BLEND);
    //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);    
 
    do {
        //속도 측정
        double currentTime = glfwGetTime();
        nbFrames++;
        if (currentTime - lastTime >= 1.0) {
            printf("%f ms/frame\n"1000.0 / double(nbFrames));
            nbFrames = 0;
            lastTime += 1.0;
        }
 
        // Clear the screen. It's not mentioned before Tutorial 02, but it can cause flickering, so it's there nonetheless.
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 
        glUseProgram(programID);
 
        //키보드와 마우스 인풋으로부터의 MVP 매트릭스를 계산한다
        computeMatricesFromInputs();
        glm::mat4 ProjectionMatrix = getProjectionMatrix();
        glm::mat4 ViewMatrix = getViewMatrix();
        glm::mat4 ModelMatrix = glm::mat4(1.0);
        glm::mat4 ModelViewMatrix = ViewMatrix * ModelMatrix;
        glm::mat3 ModelView3x3Matrix = glm::mat3(ModelViewMatrix);
        glm::mat4 MVP = ProjectionMatrix*ViewMatrix*ModelMatrix;
 
        //transformation을 현재 쉐이더에 보냄
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
        glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]);
        glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);
        //glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);
        glUniformMatrix3fv(ModelView3x3MatrixID, 1, GL_FALSE, &ModelView3x3Matrix[0][0]);
 
        glm::vec3 lightPos = glm::vec3(004);
        glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z);
 
        //텍스처 유닛0에 있는 텍스처를 바인딩한다.
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, DiffuseTexture);
        glUniform1i(DiffuseTextureID, 0);
 
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, NormalTexture);
        glUniform1i(NormalTextureID, 1);
        
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, SpecularTexture);
        glUniform1i(SpecularTextureID, 2);
 
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(
            0,            //0번째 속성. 0이 될 특별한 이유는 없지만 쉐이더의 레이아웃과 반드시 맞춰야함
            3,            //크기(size)
            GL_FLOAT,    //타입(type)
            GL_FALSE,    //정규화(normalized)?
            0,            //다음 요소까지의 간격(stride)
            (void*)0    //배열 버퍼의 오프셋(offset)
        );
 
        //2nd 속성 버퍼 : UVs
        glEnableVertexAttribArray(1);
        glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
        glVertexAttribPointer(
            1,
            2,
            GL_FLOAT,
            GL_FALSE,
            0,
            (void*)0
        );
 
        //3rd 속성 버퍼 : normals
        glEnableVertexAttribArray(2);
        glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
        glVertexAttribPointer(
            2,            
            3,            
            GL_FLOAT,
            GL_FALSE,
            0,
            (void*)0
        );
 
        // 4th attribute buffer : tangents
        glEnableVertexAttribArray(3);
        glBindBuffer(GL_ARRAY_BUFFER, tangentbuffer);
        glVertexAttribPointer(
            3,                                // attribute
            3,                                // size
            GL_FLOAT,                         // type
            GL_FALSE,                         // normalized?
            0,                                // stride
            (void*)0                          // array buffer offset
        );
 
        // 5th attribute buffer : bitangents
        glEnableVertexAttribArray(4);
        glBindBuffer(GL_ARRAY_BUFFER, bitangentbuffer);
        glVertexAttribPointer(
            4,                                // attribute
            3,                                // size
            GL_FLOAT,                         // type
            GL_FALSE,                         // normalized?
            0,                                // stride
            (void*)0                          // array buffer offset
        );
 
        // Index 버퍼
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
 
        // 삼각형 그리기
        glDrawElements(
            GL_TRIANGLES,        //mode
            indices.size(),        //count
            GL_UNSIGNED_SHORT,    //type
            (void*)0            //element array buffer offset
        );
 
        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
        glDisableVertexAttribArray(2);
        glDisableVertexAttribArray(3);
        glDisableVertexAttribArray(4);
 
        //char text[256];
        //sprintf(text, "%.2f sec", glfwGetTime());
        //printText2D(text, 10, 500, 60);
        
        ////////////////////////////////////////////////////////
        // DEBUG ONLY !!!
        // Don't use this in real code !!
        ////////////////////////////////////////////////////////
        
        glMatrixMode(GL_PROJECTION);
        glLoadMatrixf((const GLfloat*)&ProjectionMatrix[0]);
        glMatrixMode(GL_MODELVIEW);
        glm::mat4 MV = ViewMatrix * ModelMatrix;
        glLoadMatrixf((const GLfloat*)&MV[0]);
        
        glUseProgram(0);
 
        // normals
        glColor3f(001);
        glBegin(GL_LINES);
        for (unsigned int i = 0; i<indices.size(); i++) {
            glm::vec3 p = indexed_vertices[indices[i]];
            glVertex3fv(&p.x);
            glm::vec3 o = glm::normalize(indexed_normals[indices[i]]);
            p += o*0.1f;
            glVertex3fv(&p.x);
        }
        glEnd();
        // tangents
        glColor3f(100);
        glBegin(GL_LINES);
        for (unsigned int i = 0; i<indices.size(); i++) {
            glm::vec3 p = indexed_vertices[indices[i]];
            glVertex3fv(&p.x);
            glm::vec3 o = glm::normalize(indexed_tangents[indices[i]]);
            p += o*0.1f;
            glVertex3fv(&p.x);
        }
        glEnd();
        // bitangents
        glColor3f(010);
        glBegin(GL_LINES);
        for (unsigned int i = 0; i<indices.size(); i++) {
            glm::vec3 p = indexed_vertices[indices[i]];
            glVertex3fv(&p.x);
            glm::vec3 o = glm::normalize(indexed_bitangents[indices[i]]);
            p += o*0.1f;
            glVertex3fv(&p.x);
        }
        glEnd();
        // light pos
        glColor3f(111);
        glBegin(GL_LINES);
        glVertex3fv(&lightPos.x);
        lightPos += glm::vec3(100)*0.1f;
        glVertex3fv(&lightPos.x);
        lightPos -= glm::vec3(100)*0.1f;
        glVertex3fv(&lightPos.x);
        lightPos += glm::vec3(010)*0.1f;
        glVertex3fv(&lightPos.x);
        glEnd();
 
        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();
 
    } // Check if the ESC key was pressed or the window was closed
    while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
        glfwWindowShouldClose(window) == 0);
 
    // Cleanup VBO and shader
    glDeleteBuffers(1&vertexbuffer);
    glDeleteBuffers(1&uvbuffer);
    glDeleteBuffers(1&normalbuffer);
    glDeleteBuffers(1&tangentbuffer);
    glDeleteBuffers(1&bitangentbuffer);
    glDeleteBuffers(1&elementbuffer);
    glDeleteProgram(programID);
    glDeleteTextures(1&DiffuseTexture);
    glDeleteTextures(1&NormalTexture);
    glDeleteTextures(1&SpecularTexture);
    glDeleteVertexArrays(1&VertexArrayID);
 
    // Close OpenGL window and terminate GLFW
    glfwTerminate();
 
    return 0;
}
 
GLuint LoadShaders(const char * vertex_file_path, const char * fragment_file_path) {
 
    //쉐이더 생성
    GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
    GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
 
    //버텍스 쉐이더 코드를 파일에서 읽기
    std::string VertexShaderCode;
    std::ifstream VertexShaderStream(vertex_file_path, std::ios::in);
    if (VertexShaderStream.is_open()) {
        std::stringstream sstr;
        sstr << VertexShaderStream.rdbuf();
        VertexShaderCode = sstr.str();
        VertexShaderStream.close();
    }
    else {
        printf("파일 %s를 읽을 수 없음. 정확한 디렉토리를 사용 중입니까?\n", vertex_file_path);
        getchar();
        return 0;
    }
 
    //프래그먼트 쉐이더 코드를 파일에서 읽기
    std::string FragmentShaderCode;
    std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in);
    if (FragmentShaderStream.is_open()) {
        std::stringstream sstr;
        sstr << FragmentShaderStream.rdbuf();
        FragmentShaderCode = sstr.str();
        FragmentShaderStream.close();
    }
 
    GLint Result = GL_FALSE;
    int InfoLogLength;
 
    //버텍스 쉐이더를 컴파일
    printf("Compiling shader : %s\n", vertex_file_path);
    char const * VertexSourcePointer = VertexShaderCode.c_str();
    glShaderSource(VertexShaderID, 1&VertexSourcePointer, NULL);
    glCompileShader(VertexShaderID);
 
    //버텍스 쉐이더를 검사
    glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
    glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
    if (InfoLogLength > 0) {
        std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1);
        glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL&VertexShaderErrorMessage[0]);
        printf("%s\n"&VertexShaderErrorMessage[0]);
    }
 
    //프래그먼트 쉐이더를 컴파일
    printf("Compiling shader : %s", fragment_file_path);
    char const * FragmentSourcePointer = FragmentShaderCode.c_str();
    glShaderSource(FragmentShaderID, 1&FragmentSourcePointer, NULL);
    glCompileShader(FragmentShaderID);
 
    //프래그먼트 쉐이더를 검사
    glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
    glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
    if (InfoLogLength > 0) {
        std::vector<char> FragmentShaderErrorMessage(InfoLogLength + 1);
        glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL&FragmentShaderErrorMessage[0]);
        printf("%s\n"&FragmentShaderErrorMessage[0]);
    }
 
    //프로그램에 링크
    printf("Linking program\n");
    GLuint ProgramID = glCreateProgram();
    glAttachShader(ProgramID, VertexShaderID);
    glAttachShader(ProgramID, FragmentShaderID);
    glLinkProgram(ProgramID);
 
    //프로그램 검사
    glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
    glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
    if (InfoLogLength > 0) {
        std::vector<char> ProgramErrorMessage(InfoLogLength + 1);
        glGetProgramInfoLog(ProgramID, InfoLogLength, NULL&ProgramErrorMessage[0]);
        printf("%s\n"&ProgramErrorMessage[0]);
    }
 
    glDetachShader(ProgramID, VertexShaderID);
    glDetachShader(ProgramID, FragmentShaderID);
 
    glDeleteShader(VertexShaderID);
    glDeleteShader(FragmentShaderID);
 
    return ProgramID;
}
 
GLuint loadBMP_custom(const char * imagepath) {
 
    printf("Reading image %s\n", imagepath);
 
    //BMP파일의 헤더에서 데이터를 읽는다
    unsigned char header[54];
    unsigned int dataPos;
    unsigned int imageSize;
    unsigned int width, height;
    //실제 RGB 데이터
    unsigned char * data;
 
    //파일을 연다
    FILE * file = fopen(imagepath, "rb");
    if (!file) {
        printf("%s는 열수 없다. 경로가 맞는지 확인해라.\n", imagepath);
        getchar();
        return 0;
    }
 
    //헤더를 읽는다, i.e. the 54 first bytes
 
    //만약 54 bytes보다 적게 읽혔으면 문제 발생
    if (fread(header, 154, file) != 54) {
        printf("BMP 파일이 아니다\n");
        return 0;
    }
    //A BMP 파일은 항상 "BM"으로 시작한다.
    if (header[0!= 'B' || header[1!= 'M') {
        printf("BMP 파일이 아니다\n");
        return 0;
    }
    //24pp file임을 확인한다.
    if (*(int*)&(header[0x1e]) != 0 || *(int*)&(header[0x1C]) != 24) {
        printf("BMP 파일이 아니다\n");
        return 0;
    }
 
    //이미지에 대한 정보를 읽는다.
    dataPos = *(int*)&(header[0x0A]);
    imageSize = *(int*)&(header[0x22]);
    width = *(int*)&(header[0x12]);
    height = *(int*)&(header[0x16]);
 
    //몇몇 BMP 파일들은 포맷이 놓쳐졌다, 놓쳐진 정보를 추측해라
    if (imageSize == 0) imageSize = width*height * 3// 3 : one byte for each Red-Green-Blue component
    if (dataPos == 0) dataPos = 54//BMP 헤더는 항상 이 형식
 
    //버퍼를 생성한다
    data = new unsigned char[imageSize];
 
    //파일의 버퍼에 있는 실제 데이터를 읽는다
    fread(data, 1, imageSize, file);
 
    //모든 것은 현재 메모리에 있다, 파일을 닫는다
    fclose(file);
 
    //openGL 텍스처를 만든다
    GLuint textureID;
    glGenTextures(1&textureID);
 
    //새로이 만들어진 텍스처를 바인딩한다.
    glBindTexture(GL_TEXTURE_2D, textureID);
 
    //이미지를 OpenGL에게 넘긴다
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
 
    delete[] data;
 
    // trilinear(삼선형) 필터링
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glGenerateMipmap(GL_TEXTURE_2D);
 
    return textureID;
}
 
GLuint loadDDS(const char * imagepath) {
 
    unsigned char header[124];
 
    FILE *fp;
 
    //파일을 연다
    fp = fopen(imagepath, "rb");
    if (fp == NULL) {
        printf("%s는 열 수 없다. 경로를 확인해라\n", imagepath);
        getchar();
        return 0;
    }
 
    //파일의 타입을 확인한다
    char filecode[4];
    fread(filecode, 14, fp);
    if (strncmp(filecode, "DDS "4!= 0) {
        fclose(fp);
        return 0;
    }
 
    //surface desc를 얻는다
    fread(&header, 1241, fp);
 
    unsigned int height = *(unsigned int*)&(header[8]);
    unsigned int width = *(unsigned int*)&(header[12]);
    unsigned int linearSize = *(unsigned int*)&(header[16]);
    unsigned int mipMapCount = *(unsigned int*)&(header[24]);
    unsigned int fourCC = *(unsigned int*)&(header[80]);
 
    unsigned char * buffer;
    unsigned int bufsize;
 
    bufsize = mipMapCount > 1 ? linearSize * 2 : linearSize;
    buffer = (unsigned char*)malloc(bufsize * sizeof(unsigned char));
    fread(buffer, 1, bufsize, fp);
    fclose(fp);
 
    unsigned int components = (fourCC == FOURCC_DXT1) ? 3 : 4;
    unsigned int format;
    switch (fourCC)
    {
    case FOURCC_DXT1:
        format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
        break;
    case FOURCC_DXT3:
        format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
        break;
    case FOURCC_DXT5:
        format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
        break;
    default:
        free(buffer);
        return 0;
    }
 
    //하나의 OpenGL 텍스처를 생성한다
    GLuint textureID;
    glGenTextures(1&textureID);
 
    //새로이 만들어진 텍스처를 바인딩한다
    glBindTexture(GL_TEXTURE_2D, textureID);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 
    unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;
    unsigned int offset = 0;
 
    //밉맵을 불러온다
    for (unsigned int level = 0; level < mipMapCount && (width || height); ++level)
    {
        unsigned int size = ((width + 3/ 4)*((height + 3/ 4)*blockSize;
        glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height,
            0size, buffer + offset);
 
        offset += size;
        width /= 2;
        height /= 2;
 
        //Non-Power-Of-Two 텍스처를 사용합니다.
        //이 코드는 혼란을 줄이기 위해 웹 페이지에는 포함되어 있지 않습니다.
        if (width < 1)width = 1;
        if (height < 1) height = 1;
    }
 
    free(buffer);
 
    return textureID;
}
 
bool loadOBJ(
    const char * path,
    std::vector<glm::vec3> & out_vertices,
    std::vector<glm::vec2> & out_uvs,
    std::vector<glm::vec3> & out_normals
) {
    printf("OBJ 파일 로딩중 %s...\n", path);
 
    std::vector<unsigned int> vertexIndices, uvIndices, normalIndices;
    std::vector<glm::vec3> temp_vertices;
    std::vector <glm::vec2> temp_uvs;
    std::vector<glm::vec3> temp_normals;
 
    FILE * file = fopen(path, "r");
    if (file == NULL) {
        printf("파일 경로를 확인하세요!\n");
        getchar();
        return false;
    }
 
    while (1) {
        
        char lineHeader[128];
 
        //첫번째 라인의 첫번째 단어를 읽는다
        int res = fscanf(file, "%s", lineHeader);
        if (res == EOF)
            break;
 
        //else : 라인의 헤더를 parse
        if (strcmp(lineHeader, "v"== 0) {
            glm::vec3 vertex;
            fscanf(file, "%f %f %f\n"&vertex.x, &vertex.y, &vertex.z);
            temp_vertices.push_back(vertex);
        }
        else if (strcmp(lineHeader, "vt"== 0) {
            glm::vec2 uv;
            fscanf(file, "%f %f\n"&uv.x, &uv.y);
            uv.y = -uv.y; //우리가 DDS texture만을 이용할 것이므로 V의 좌표를 반대로 바꾸어준다. 만약 TGA or BMP 로더를 사용하면 이 것을 제거해라.
            temp_uvs.push_back(uv);
        }
        else if (strcmp(lineHeader, "vn"== 0) {
            glm::vec3 normal;
            fscanf(file, "%f %f %f\n"&normal.x, &normal.y, &normal.z);
            temp_normals.push_back(normal);
        }
        else if (strcmp(lineHeader, "f"== 0) {
            std::string vertex1, vertex2, vertex3;
            unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
            int matches = fscanf(file,"%d/%d/%d %d/%d/%d %d/%d/%d\n"&vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);
            if (matches != 9) {
                printf("파일을 읽을수없다.");
                return false;
            }
            vertexIndices.push_back(vertexIndex[0]);
            vertexIndices.push_back(vertexIndex[1]);
            vertexIndices.push_back(vertexIndex[2]);
            uvIndices.push_back(uvIndex[0]);
            uvIndices.push_back(uvIndex[1]);
            uvIndices.push_back(uvIndex[2]);
            normalIndices.push_back(normalIndex[0]);
            normalIndices.push_back(normalIndex[1]);
            normalIndices.push_back(normalIndex[2]);
        }
        else {
            //나머지 라인을 먹는다.
            char stupidBuffer[1000];
            fgets(stupidBuffer, 1000, file);
        }
    }
 
    //각 삼각형의 각 꼭지점
    for (unsigned int i = 0; i < vertexIndices.size(); i++) {
        
        //속성의 인덱스를 가져온다
        unsigned int vertexIndex = vertexIndices[i];
        unsigned int uvIndex = uvIndices[i];
        unsigned int normalIndex = normalIndices[i];
 
        //인덱스에서 속성을 가져온다
        glm::vec3 vertex = temp_vertices[vertexIndex - 1];
        glm::vec2 uv = temp_uvs[uvIndex - 1];
        glm::vec3 normal = temp_normals[normalIndex - 1];
 
        //버퍼에 속성을 넣는다
        out_vertices.push_back(vertex);
        out_uvs.push_back(uv);
        out_normals.push_back(normal);
 
    }
 
    return true;
 
}
 
void indexVBO(
    std::vector<glm::vec3> & in_vertices,
    std::vector<glm::vec2> & in_uvs,
    std::vector<glm::vec3> & in_normals,
 
    std::vector<unsigned short> & out_indices,
    std::vector<glm::vec3> & out_vertices,
    std::vector<glm::vec2> & out_uvs,
    std::vector<glm::vec3> & out_normals
) {
    std::map<PackedVertex, unsigned short> VertexToOutIndex;
 
    //각 input vertex를 위해
    for (unsigned int i = 0; i < in_vertices.size(); i++) {
        PackedVertex packed = { in_vertices[i], in_uvs[i], in_normals[i] };
 
        //out_XXXX에서 비슷한 vertex를 찾는다
        unsigned short index;
        bool found = getSimilarVertexIndex_fast(packed, VertexToOutIndex, index);
 
        if (found) { //비슷한 vertex가 VBO에 이미 있다면 대신 사용한다
            out_indices.push_back(index);
        }
        else {         //아니라면 이것은 아웃풋 데이터 추가가 필요하다
            out_vertices.push_back(in_vertices[i]);
            out_uvs.push_back(in_uvs[i]);
            out_normals.push_back(in_normals[i]);
            unsigned short newindex = (unsigned short)out_vertices.size() - 1;
            out_indices.push_back(newindex);
            VertexToOutIndex[packed] = newindex;
        }
 
    }
 
 
}
 
void indexVBO_TBN(
    std::vector<glm::vec3> & in_vertices,
    std::vector<glm::vec2> & in_uvs,
    std::vector<glm::vec3> & in_normals,
    std::vector<glm::vec3> & in_tangents,
    std::vector<glm::vec3> & in_bitangents,
 
    std::vector<unsigned short> & out_indices,
    std::vector<glm::vec3> & out_vertices,
    std::vector<glm::vec2> & out_uvs,
    std::vector<glm::vec3> & out_normals,
    std::vector<glm::vec3> & out_tangents,
    std::vector<glm::vec3> & out_bitangents
) {
    //각 input vertex를 위해
    for (unsigned int i = 0; i < in_vertices.size(); i++) {
 
        //out_XXXX 에서 비슷한 vertex를 찾는다
        unsigned short index;
        bool found = getSimilarVertexIndex(in_vertices[i], in_uvs[i], in_normals[i], out_vertices, out_uvs, out_normals, index);
 
        if (found) { //비슷한 vertex가 이미 VBO에 있으면, 이것을 대신 사용
            out_indices.push_back(index);
 
            //tangents와 bitangents의 평균을 한다
            out_tangents[index] += in_tangents[i];
            out_bitangents[index] += in_bitangents[i];
        }
        else { // 만약 아니라면, output data에서 추가한다
            out_vertices.push_back(in_vertices[i]);
            out_uvs.push_back(in_uvs[i]);
            out_normals.push_back(in_normals[i]);
            out_tangents.push_back(in_tangents[i]);
            out_bitangents.push_back(in_bitangents[i]);
            out_indices.push_back((unsigned short)out_vertices.size() - 1);
        }
    }
 
 
}
 
void computeMatricesFromInputs() {
 
    //glfwGetTime은 한번만 호출된다.
    static double lastTime = glfwGetTime();
 
    //현재와 마지막 프레임의 시간 차를 계산한다.
    double currentTime = glfwGetTime();
    float deltaTime = float(currentTime - lastTime);
 
    //마우스의 위치를 얻는다.
    double xpos, ypos;
    glfwGetCursorPos(window, &xpos, &ypos);
 
    //다음 프레임의 마우스 위치를 리셋한다.
    glfwSetCursorPos(window, 1024 / 2768 / 2);
 
    horizontalAngle += mouseSpeed * float(1024 / 2 - xpos);
    verticalAngle += mouseSpeed * float(768 / 2 - ypos);
 
    //Direction : Spherical 좌표 to Cartesian 좌표 변환
    glm::vec3 direction(
        cos(verticalAngle)*sin(horizontalAngle),
        sin(verticalAngle),
        cos(verticalAngle)*cos(horizontalAngle)
    );
 
    //Right vector
    glm::vec3 right = glm::vec3(
        sin(horizontalAngle - 3.14f / 2.0f),
        0,
        cos(horizontalAngle - 3.14f / 2.0f)
    );
 
    //Up vector
    glm::vec3 up = glm::cross(right, direction);
 
    //앞으로 이동
    if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) {
        position += direction*deltaTime*speed;
    }
    //뒤로 이동
    if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) {
        position -= direction*deltaTime*speed;
    }
    //오른쪽로 Strafe
    if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
        position += right*deltaTime*speed;
    }
    //왼쪽으로 Strafe
    if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
        position -= right*deltaTime*speed;
    }
 
    float FoV = initialFoV;
 
    ProjectionMatrix = glm::perspective(FoV, 4.0f / 3.0f, 0.1f, 100.0f);
 
    ViewMatrix = glm::lookAt(
        position,                //camera here
        position + direction,        //and looks here
        up                        // Head is up
    );
 
    //다음 프레임을 위해
    lastTime = currentTime;
}
 
void computeTangentBasis(
    //inputs
    std::vector<glm::vec3> & vertices,
    std::vector<glm::vec2> & uvs,
    std::vector<glm::vec3> & normals,
    //outputs
    std::vector<glm::vec3> & tangents,
    std::vector<glm::vec3> & bitangents
) {
    for (unsigned int i = 0; i < vertices.size(); i += 3) {
        
        //shortcuts for vertices
        glm::vec3 & v0 = vertices[i + 0];
        glm::vec3 & v1 = vertices[i + 1];
        glm::vec3 & v2 = vertices[i + 2];
 
        //shortcuts for UVs
        glm::vec2 & uv0 = uvs[i + 0];
        glm::vec2 & uv1 = uvs[i + 1];
        glm::vec2 & uv2 = uvs[i + 2];
 
        //edges of the triangle : position delta
        glm::vec3 deltaPos1 = v1 - v0;
        glm::vec3 deltaPos2 = v2 - v0;
 
        //UV delta
        glm::vec2 deltaUV1 = uv1 - uv0;
        glm::vec2 deltaUV2 = uv2 - uv0;
 
        float r = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x);
        glm::vec3 tangent = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y)*r;
        glm::vec3 bitangent = (deltaPos2 * deltaUV1.x - deltaPos1*deltaUV2.x)*r;
 
        //삼각형의 모든 세개의 정점을 위해 같은 tangent를 세팅한다.
        //그것들은 곧 병합될겉이다
        tangents.push_back(tangent);
        tangents.push_back(tangent);
        tangents.push_back(tangent);
 
        //binormals를 위한 같은 것
        bitangents.push_back(bitangent);
        bitangents.push_back(bitangent);
        bitangents.push_back(bitangent);
        
    }
 
    // "Going Further" 봐라
    for (unsigned int i = 0; i < vertices.size(); i += 1) {
        glm::vec3 & n = normals[i];
        glm::vec3 & t = tangents[i];
        glm::vec3 & b = bitangents[i];
 
        //Gram-Schmidt orthogonalize
        t = glm::normalize(t - n*glm::dot(n, t));
 
        //handedness 계산
        if (glm::dot(glm::cross(n, t), b) < 0.0f) {
            t = t*-1.0f;
        }
    }
}
 
void initText2D(const char * texturePath) {
 
    //텍스쳐 초기화
    Text2DTextureID = loadDDS(texturePath);
 
    //VBO 초기화
    glGenBuffers(1&Text2DVertexBufferID);
    glGenBuffers(1&Text2DUVBufferID);
 
    //Shader 초기화
    Text2DShaderID = LoadShaders("TextVertexShader.vertexshader""TextVertexShader.fragmentshader");
 
    //uniforms' IDs 초기화
    Text2DUniformID = glGetUniformLocation(Text2DShaderID, "myTextureSampler");
 
}
void printText2D(const char * text, int x, int y, int size) {
 
    unsigned int length = strlen(text);
 
    //buffer 채우기
    std::vector<glm::vec2> vertices;
    std::vector<glm::vec2> UVs;
    for (unsigned int i = 0; i < length; i++) {
        glm::vec2 vertex_up_left = glm::vec2(x + i*size, y + size);
        glm::vec2 vertex_up_right = glm::vec2(x + i*size+size, y + size);
        glm::vec2 vertex_down_right = glm::vec2(x + i*size+size, y);
        glm::vec2 vertex_down_left = glm::vec2(x + i*size, y);
 
        vertices.push_back(vertex_up_left);
        vertices.push_back(vertex_down_left);
        vertices.push_back(vertex_up_right);
 
        vertices.push_back(vertex_down_right);
        vertices.push_back(vertex_up_right);
        vertices.push_back(vertex_down_left);
 
        char character = text[i];
        float uv_x = (character % 16/ 16.0f;
        float uv_y = (character / 16/ 16.0f;
 
        glm::vec2 uv_up_left = glm::vec2(uv_x, uv_y);
        glm::vec2 uv_up_right = glm::vec2(uv_x + 1.0f / 16.0f, uv_y);
        glm::vec2 uv_down_right = glm::vec2(uv_x+1.0f/16.0f, (uv_y+1.0f/16.0f));
        glm::vec2 uv_down_left = glm::vec2(uv_x, (uv_y+1.0f/16.0f));
        UVs.push_back(uv_up_left);
        UVs.push_back(uv_down_left);
        UVs.push_back(uv_up_right);
 
        UVs.push_back(uv_down_right);
        UVs.push_back(uv_up_right);
        UVs.push_back(uv_down_left);
 
        glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID);
        glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_STATIC_DRAW);
        glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID);
        glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW);
 
        // Bind shader
        glUseProgram(Text2DShaderID);
 
        // Bind texture
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, Text2DTextureID);
        // Set our "myTextureSampler" sampler to user Texture Unit 0
        glUniform1i(Text2DUniformID, 0);
 
        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID);
        glVertexAttribPointer(02, GL_FLOAT, GL_FALSE, 0, (void*)0);
 
        // 2nd attribute buffer : UVs
        glEnableVertexAttribArray(1);
        glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID);
        glVertexAttribPointer(12, GL_FLOAT, GL_FALSE, 0, (void*)0);
 
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 
        // Draw call
        glDrawArrays(GL_TRIANGLES, 0, vertices.size());
 
        glDisable(GL_BLEND);
 
        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
    }
 
}
void cleanupText2D() {
 
    // Delete buffers
    glDeleteBuffers(1&Text2DVertexBufferID);
    glDeleteBuffers(1&Text2DUVBufferID);
 
    // Delete texture
    glDeleteTextures(1&Text2DTextureID);
 
    // Delete shader
    glDeleteProgram(Text2DShaderID);
}
cs


'Game > Graphics' 카테고리의 다른 글

OpenGL-Tutorial 15 : Lightmaps  (0) 2018.07.02
OpenGL-Tutorial 14 : Render To Texture  (0) 2018.07.01
OpenGL-Tutorial 12 : OpenGL Extensions  (6) 2018.06.29
OpenGL-Tutorial 11 : 2D Text  (0) 2018.06.28
OpenGL-Tutorial 10 : Transparency  (0) 2018.06.28