Skip to content

08. 3D 카메라와 쿼터니언


목차

  • 3D 카메라 만들기 (glfw설정 + 마우스로 회전 + WASDEQ로 카메라 기준 이동)
  • 쿼터니언 도입하기
  • ViewMatrix3D 재작성
  • Transform3D 재작성
  • 쿼터니언으로 큐브 회전시키기

  • 번외 : 2D 카메라 만들기

3D 카메라 만들기

여러 게임 엔진을 보면, 3차원 카메라 오브젝트를 생성하고

현재 사용할 카메라를 선택하면

그 카메라를 기준으로 보이는 화면이 출력되게 됩니다.

마찬가지로, 저희가 이전에 구현했던

ViewMatrix3DProjectionMatrix3D 를 감싸는

Camera3D 라는 새 클래스를 만들 수 있습니다.

ViewMatrix3D m_view_mat 속성에서는

  • 카메라의 위치
  • 카메라의 회전

을 담당하고,

ProjectionMatrix3D m_proj_mat 속성에서는

  • 카메라의 시야각 (FoV)
  • 절두체 크기
  • Near / Far Plane

을 담당하게 되는 것입니다.

구현은 다음과 같습니다.

그냥 두 클래스를 합쳐 놓은 것이니, 복잡한 건 없습니다.

class Camera3D {
private:
    ViewMatrix3D m_view_mat{};
    ProjectionMatrix3D m_proj_mat{};
public:
    Camera3D() = default;
    ~Camera3D() = default;
public:
    void look_up(const float& value) { m_view_mat.add_pitch(value); }
    void look_right(const float& value) { m_view_mat.add_yaw(value); }
public:
    void set_position(const glm::vec3& value) { m_view_mat.set_position(value); }
    void set_frustrum_size(const glm::uvec2& value) { m_proj_mat.set_frustrum_size(value); }
    void set_fov(const float& value) { m_proj_mat.set_fov(value); }
public:
    glm::vec3 get_front_vector() const {
        return m_view_mat.get_front_vector();
    }
    glm::vec3 get_right_vector() const {
        return m_view_mat.get_right_vector();
    }
    glm::vec3 get_up_vector() const {
        return m_view_mat.get_up_vector();
    }
public:
    const glm::vec3& get_position() const { return m_view_mat.get_position(); }
    const glm::uvec2& get_frustrum_size()const { return m_proj_mat.get_frustrum_size(); }
    const float& get_fov()const { return m_proj_mat.get_fov(); }
public:
    const ViewMatrix3D& get_view_matrix() const { return m_view_mat; }
    const ProjectionMatrix3D& get_projection_matrix() const { return m_proj_mat; }
};

그러면 이제 이 클래스를 사용해 볼까요?

먼저, 기존에 생으로 사용했던 두 클래스 인스턴스를 지우고,

Camera3D 를 전역 변수로 생성해주세요.

    //ProjectionMatrix3D proj_mat{ {1280, 720}, 0.1f, 1000.0f, glm::radians(45.0f) };
    //ViewMatrix3D view_mat{};
    //view_mat.set_position({ 0.0f, 0.0f, 100.0f });
    cam3d.set_fov(glm::radians(60.0f));
    cam3d.set_position({ 0.0f, 0.0f, 100.0f });
// 전역변수
Camera3D cam3d{};

이후 Camera3D::set_fov, Camera3D::set_position 을 통해서

카메라의 위치와 시야각을 설정해주시면 됩니다.

이제 키보드로 카메라의 움직임을 제어하기 위해서,

glfwGetKey() ... 를 통해 키보드 입력을 받는 부분을 다음과 같이 수정해주세요.

        glfwPollEvents();
        {
            // 카메라로 
            float speed = 2.0f;
            if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() - cam3d.get_right_vector() * speed);
            }
            if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() + cam3d.get_right_vector() * speed);
            }
            if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() + cam3d.get_front_vector() * speed);
            }
            if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() - cam3d.get_front_vector() * speed);
            }
            if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() + cam3d.get_up_vector() * speed);
            }
            if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() - cam3d.get_up_vector() * speed);
            }

당연히도, 유니폼 데이터를 업로드하는 부분에도

기존 변수 대신 카메라 클래스에서 가져오도록 해주세요.

            program.upload_uniform_vec3f("uSize", { 30.0f, 30.0f, 30.0f });
            // 받아오기
            program.upload_uniform_mat4f("uProj", cam3d.get_projection_matrix().get_matrix());
            program.upload_uniform_mat4f("uView", cam3d.get_view_matrix().get_matrix());
            program.upload_uniform_mat4f("uWorld", world_mat.get_matrix());

마지막으로, 마우스를 움직여서

FPS 형태의 카메라를 구현해 봅시다.

이전에 설명했듯이, GLFW에서 마우스 커서가 움직였는지를 감지하려면

해당 윈도우에 콜백 함수를 등록해주어야 합니다.

다음과 같이 커서 위치 콜백을 전역으로 만들어 주세요.

(cam3d를 선언하는 부분보다 밑에 만들어주세요.)

static void on_cursor(GLFWwindow* window, double xpos, double ypos) {
    static bool firstin = true;
    static glm::vec2 last{ 0, 0 };

    static glm::vec2 accel{};
    static glm::vec2 vel{};

    if (firstin) {
        last = { xpos, ypos };
        firstin = false;
        return;
    }

    glm::vec2 delta = { xpos - last.x, ypos - last.y };
    delta *= 0.001f;

    accel += delta;
    vel += accel;

    cam3d.look_up(-vel.y);
    cam3d.look_right(vel.x);

    vel *= 0.8f;
    accel = {};

    last = { xpos, ypos };
}

위 코드는 암시적 오일러 메서드를 사용해서

이전 프레임과 현재 프레임 사이에 얼마나 마우스를 움직였는지 누적하고,

적절한 상숫값을 곱해

Camera3d::look_upCamera3D::look_right 를 호출합니다.

이때 delta에 곱하는 상수값이 마우스 감도에 비례하게 됩니다.

또한, 최초로 이전 프레임의 마우스 위치를 얻는 경우

1회 무시해주는 것을 주목해주세요.

다음으로 콜백 등록입니다.

glfwCreateWindowglfwMakeContextCurrent 사이에

다음과 같은 코드를 붙여넣어 주세요.

    GLFWwindow* window = glfwCreateWindow(1280, 720, "Camera and Quaternion", nullptr, nullptr);

    // 3D 카메라설정!!
    glfwSetCursorPosCallback(window, on_cursor);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    if (glfwRawMouseMotionSupported()) {
        glfwSetInputMode(window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
    }

    glfwMakeContextCurrent(window);
    assert(gladLoadGL() != 0);

먼저 glfwSetCursorPosCallback 함수를 통해, 윈도우에 저희가 만든

콜백을 등록하게 됩니다.

이후에는 glfwSetInputMode를 통해서,

커서를 비활성화해줍니다.

이는 3D FPS 카메라에서

커서의 위치를 창 안쪽으로 제한하지 않게 해서

카메라가 무한히 회전할 수 있도록 하는 것입니다.

또한 같은 함수로,

만약 Raw Mouse Motion 기능이 가능하다면

해당 기능을 켜주게 됩니다.

이 기능은, 마우스를 빠르게 움직였을 때

OS 단에서 속도를 가속시키는 등의

시스템 보정값을 무시한

마우스 모션 값을 얻게 해줍니다.

(단, 이 기능은 플랫폼별로 지원하지 않을 수 있기에

한번 확인해주는 것이며, glfwSetInputMode 를 통해서

커서가 비활성화된 경우에만 작동합니다.)

이제 예제를 실행시켜 보세요.

이전에는 XZ 평면을 기준으로 이동했다면,

이제는 W A S D 키로 '카메라가 바라보는 곳' 기준

앞 / 뒤 / 왼 / 오른 쪽으로 이동할 수 있고,

E Q 키로 위 / 아래로 이동할 수 있습니다.

또한, 마우스를 움직여서 카메라를 위 / 아래 / 왼쪽 / 오른쪽으로

향하게 할 수도 있게 되었습니다.

쿼터니언 도입하기

이제 쿼터니언을 도입할 차례입니다.

쿼터니언(Quaternion, 사원수)이란,

선형대수학의 아버지라 불리는 윌리엄 로원 해밀턴이 고안한 수 체계입니다.

본래 이러한 분야에 사용되는 개념은 아니지만,

현재는 그래픽스, 물리엔진, 로보틱스 등 수많은 컴퓨터 시뮬레이션에서 쓰이는 개념입니다.

특히 3차원 물체의 회전을 표현할 때

쿼터니언이 회전 표현에 적극적으로 사용되는데, 그 이유는

매 회전마다 오일러각을 기반으로 3개의 회전 행렬을 구성하고, 이를 전부 곱하는 것보다

현재 쿼터니언에 '새로운 회전' 을 나타내는 새 쿼터니언을 곱하고-

이를 회전 행렬로 1번만 바꿔주는 방식이 훨씬 효율적이기 때문입니다.

물론 오일러 각의 짐벌락이라는 문제가 없다는 것도 크게 작용합니다.


짐벌락이 무엇이길래 심각한 문제라고 하는 것일까요?

오일러 각 시스템을 사용한다면,

  • 3개의 실수를 사용하여

  • 특정한 순서로 3개의 축을 회전

시키기 때문에,

"특정한 상황에서 2개의 축이 겹치게" 됩니다.

이런 상황이 일어나면?

한 개의 축이 아예 제 역할을 못하게 되는 것이죠.

이는 회전하는 물체의 움직임을 예측 불가능하게 만듦니다.

이해하기 위해서는, 다음 GIF를 봐주세요.

8_0.gif

(출처 : 위키피디아, 라이선스 : CC0)


쿼터니언은 (x, y, z, w) 이렇게 4개의 실수로 표현됩니다. $$ Q = (x, y, z, w) $$ 그중 3개는 (x, y, z) 로 불리는 '벡터부' 이고,

나머지 1개는 w로 불리는 '실수부' 입니다.

'쿼터니언을 사용한 회전 시스템'을 이해하려면

  • 3차원의 정규화된 벡터가 하나 있고
  • '그 벡터 방향을 축으로' 얼마나 회전하였는지

라는 걸 떠올려보시면 됩니다.

단위 쿼터니언은 다음과 같은 식으로 표현됩니다. $$ Q = cos(\theta/2) + usin(\theta/2) $$ 이는 오일러 공식에서 $$ e^{i\theta} = cos(\theta) + isin(\theta) $$ 허수 i 대신 회전 축 u를,

θ 대신 (θ / 2)를 넣은 꼴입니다.


기존의 오일러 공식에서는 $$ re^{i\theta} = r(cos(\theta) + isin(\theta)) $$ 이런 식으로 r을 곱해서 극좌표 위 점에서의 2차원 회전을 표현하죠.

그렇다면 쿼터니언에서의 3차원 회전은 어떻게 표현될까요?

먼저 로드리게스 공식을 알아봅시다.

로드리게스 공식은,

  • 특정한 회전축 u에 대해서
  • 한 3차원 벡터 v를
  • 일정 회전각 θ만큼 회전

시키는 공식입니다.

이는 다음과 같습니다. $$ Rodri(u, v, \theta) = v cos(\theta) + (u \times v) sin (\theta) + u (u \cdot v)(1 - cos(\theta)) $$ 이해를 위해

이 블로그 글을 읽어보시는 것을 추천합니다.


저희가 계속 써 왔었던

glm::rotate() 또한 위 공식으로 구현되어 있습니다.

아래 코드는, 3차원 벡터 v 없이

그냥 회전축 백터 하나를 회전각만큼 회전시켜

받은 행렬에 회전을 적용시킨 새 행렬을 반환하는 glm의 함수를 추출한 겁니다.

    template<typename T, qualifier Q>
    GLM_FUNC_QUALIFIER mat<4, 4, T, Q> rotate(mat<4, 4, T, Q> const& m, T angle, vec<3, T, Q> const& v)
    {
        T const a = angle;
        T const c = cos(a);
        T const s = sin(a);

        vec<3, T, Q> axis(normalize(v));
        vec<3, T, Q> temp((T(1) - c) * axis);

        mat<4, 4, T, Q> Rotate;
        Rotate[0][0] = c + temp[0] * axis[0];
        Rotate[0][1] = temp[0] * axis[1] + s * axis[2];
        Rotate[0][2] = temp[0] * axis[2] - s * axis[1];

        Rotate[1][0] = temp[1] * axis[0] - s * axis[2];
        Rotate[1][1] = c + temp[1] * axis[1];
        Rotate[1][2] = temp[1] * axis[2] + s * axis[0];

        Rotate[2][0] = temp[2] * axis[0] + s * axis[1];
        Rotate[2][1] = temp[2] * axis[1] - s * axis[0];
        Rotate[2][2] = c + temp[2] * axis[2];

        mat<4, 4, T, Q> Result;
        Result[0] = m[0] * Rotate[0][0] + m[1] * Rotate[0][1] + m[2] * Rotate[0][2];
        Result[1] = m[0] * Rotate[1][0] + m[1] * Rotate[1][1] + m[2] * Rotate[1][2];
        Result[2] = m[0] * Rotate[2][0] + m[1] * Rotate[2][1] + m[2] * Rotate[2][2];
        Result[3] = m[3];
        return Result;
    }

아무튼, 이 공식을 소개한 이유는

3차원 쿼터니언의 회전이 다음과 같이 일어나기 때문입니다. $$ QuatRot(v, q) = qvq^{-1} = v' $$

위 식을 전개하면, 로드리게스 회전 공식과 일치하게 됩니다. $$ v' = qvq^{-1} = v cos(\theta) + (u \times v)sin(\theta) + u(u \cdot v)(1-cos(\theta)) $$ 특히 왜 θ 대신 (θ / 2) 를 사용하는지에 대한 의문은,

위 식에서 해결됩니다.

단순하게 qv 곱으로는 회전이 깨지기에 qvq⁻¹ 를 사용하므로?

회전이 2배 들어가는 것을 방지하기 위해 (θ / 2) 를 쓰는 것입니다.


코드 내에서 쿼터니언을 사용할 때에는,

  • 해당 물체의 회전을 나타내는 쿼터니언을 하나 저장해 둔다.
  • 물체가 회전할 때마다, 그 값을 쿼터니언으로 나타내고 기존의 쿼터니언과 '합성' 한다.
  • 렌더링 시에는 해당 프레임에 마지막으로 합성된 쿼터니언을 기준으로 회전 행렬을 만들어 사용한다.

이러한 구조로 이루어지게 됩니다.

특히, 저희가 Transform3D에서

get_matrix() 를 통해

'최종적으로 합성된 행렬' 을 얻었던 것처럼,

쿼터니언을 사용해서

'짐벌락 문제 없이 회전이 누적된' 행렬을 얻는 것입니다.


또 쿼터니언을 사용할 때에는 합성하는 순서도 매우 중요합니다.

결론부터 말하자면,

두 쿼터니언의 합성은

왼쪽 쿼터니언의 좌표계 를 따릅니다.

예를 들어보죠.

다음과 같이 생성한 쿼터니언이 있다고 가정해 봅시다.

glm::quat q = glm::angleAxis(glm::radians(30.0f), glm::vec3(0, 1, 0));

(0, 1, 0) 을 축으로 해서, 30도만큼 회전시킨 쿼터니언입니다.

만약에 q를 좌항으로 두고 현재 orientation 을 합성한다면?

orientation = glm::normalize(q * orientation);

이 경우, orientation이 어떻게 회전했는지는 관계없이,

'고정된', '월드 좌표 기준' (0, 1, 0) 축 기준으로

orientation이 30도 회전하게 됩니다.

그렇다면, 반대로 q를 우항에 두어 orientation을 합성한다면?

orientation = glm::normalize(orientation * q);

이 경우에는

'현재 orientation이 어떻게 회전했는가' 에 따라서,

'현재 orientation의 로컬 좌표계 기준' 으로

로컬 좌표계의 (0, 1, 0) 축 기준으로 30도 회전하게 됩니다.

밑의 그림을 보시면 이해가 빠를 겁니다.

8_1.png


여담으로, 쿼터니언의 회전 연산에 대한 항등원은 무엇일까요?

회전을 하지 않은 상태, 즉 θ = 0 을

오일러 공식 형태의 단위 쿼터니언에 대입해 보면- $$ Q = cos(0/2) + usin(0/2) = 1 + 0 $$ 즉 실수부는 1이고 벡터부(오일러 공식에서의 허수부)는 (0, 0, 0) 인

(x=0, y=0, z=0, w=1) 이 Identity가 됩니다.


꼭 유의할 점은,

(a, b, c, d) 라는 쿼터니언이 있을 때

(a, b, c) 가 이루는 단위벡터를 축으로 d 각 만큼 회전한 것과

(-a, -b, -c) 가 이루는 단위벡터를 축으로 (-d) 각 만큼 회전한 것은

완전히 똑같은 회전이라는 것입니다.

다시말해서, $$ q \equiv -q $$ 입니다. 이러면 두 쿼터니언을 구별하지 못하게 되므로,

컴퓨터 그래픽스에서는

쿼터니언의 실수부에 다음과 같은 조건을 둡니다. $$ w = cos(\theta / 2) \geq 0 $$ 이렇게 되면 실수부가 나타내는 회전각 θ는

[0, 180] 도 사이의 범위를 가지게 됩니다.

벡터부 방향과 실수부가 부호만 다른 두 쿼터니언을

구별할 수 있게 되는 것입니다.


오일러각과 쿼터니언을 사용한 회전의 직관적인 비교를 위해,

다음 영상을 한번 봐주세요.

ViewMatrix3D 재작성

그렇다면 위의 쿼터니언을 ViewMatrix3D에 적용해 봅시다.

우선 기존의 ViewMatrix3DViewMatrix3D_EulerAngle 이란 이름으로 바꿔 주세요.

//class ViewMatrix3D final {
class ViewMatrix3D_EulerAngle final {

시작해봅시다. 먼저 멤버 변수들입니다.

class ViewMatrix3D_Quaternion final {
private:
    glm::vec3 m_position{ 0.0f, 0.0f, 0.0f };
    glm::quat m_orientation{ 1.0f, 0.0f, 0.0f, 0.0f };
private:
    glm::mat4 m_matrix{ 1.0f };

참고로, glm에서 glm::quat 형의 생성자는,

실수부 w 값을 가장 먼저, 나머지 벡터부 x, y, z 를 이어서

{w, x, y, z} 순서로 넣게 되어 있음에 유의해 주세요.

Identity로 초기화해줍니다.

다음은 생성자와 add_yaw, add_pitch 메서드입니다.

public:
    ViewMatrix3D_Quaternion() {
        this->_update_matrix();
    }
    void set_position(const glm::vec3& pos) {
        m_position = pos;
        this->_update_matrix();
    }
    void add_yaw(const float& value) {
        // 월드 up 기준 회전
        //  사원수를 '누적' 해야 함.
        glm::quat q = glm::angleAxis(-value, glm::vec3(0, 1, 0));
        m_orientation = glm::normalize(q * m_orientation);

        this->_update_matrix();
    }
    void add_pitch(const float& value) {
        glm::vec3 front = get_front_vector();
        // 단위원에서 r=1 이므로
        // sin(theta) = (y / 1) = y, 
        // theta = arcsin(y)
        float pitch = std::asin(glm::clamp(front.y, -1.0f, 1.0f));
        float newpitch = glm::clamp(pitch + value, -glm::radians(89.0f), glm::radians(89.0f));
        float delta = (newpitch - pitch);

        glm::vec3 right = get_right_vector();
        glm::quat q = glm::angleAxis(delta, right);
        m_orientation = glm::normalize(q * m_orientation);

        this->_update_matrix();
    }

add_yaw 의 경우

월드 공간 Y축을 기준으로 회전시킨 새 쿼터니언을 생성하고

이를 m_orientation 에 누적하는 식입니다.

add_pitch의 경우

단순히 X축을 기준으로 회전하는 것이 아닌,

우선 Front Vector를 기준으로 현재 pitch값을 계산하고

이를 [-89, 89] 도 범위로 제한,

이후 Right Vector를 축으로 회전량만큼 쿼터니언을 구성하여

m_orientation에 누적하는 식입니다.

마지막으로 나머지 메서드들입니다.

public:
    glm::vec3 get_front_vector() const {
        return m_orientation * glm::vec3(0.0f, 0.0f, -1.0f);
    }
    glm::vec3 get_right_vector() const {
        return m_orientation * glm::vec3(1.0f, 0.0f, 0.0f);
    }
    glm::vec3 get_up_vector() const {
        return m_orientation * glm::vec3(0.0f, 1.0f, 0.0f);
    }
public:
    const glm::vec3& get_position() const { return m_position; }
    const glm::mat4& get_matrix() const { return m_matrix; }
private:
    void _update_matrix() {
        glm::quat orien_rev = glm::conjugate(m_orientation);
        glm::mat4 rotation = glm::toMat4(orien_rev);
        // 통째로 반전해서 넣자.
        glm::mat4 translation = glm::translate( glm::mat4{ 1.0f }, -m_position );

        m_matrix = rotation * translation;
    }
};

Front / Right / Up Vector를 얻기 위해서는

쿼터니언의 우항에 축이 되는 3차원 벡터를 곱해주면 됩니다.

_update_matrix() 에서는

이전에 2차원 뷰 행렬을 만들 때와 똑같은 이유로

'월드 자체가 회전' 해야하기 때문에

glm::conjugate를 통해서 한번 뒤집어서 회전 행렬을 만드는 것에 유의하세요.

이제 다음처럼 ViewMatrix3D를 정의합시다.

//using ViewMatrix3D = ViewMatrix3D_EulerAngle;
using ViewMatrix3D = ViewMatrix3D_Quaternion;

Transform3D 재작성

이제 Transform3D 또한 쿼터니언으로 다시 작성해 봅시다.

먼저 멤버 변수와 생성자입니다.

class Transform3D final {
private:
    glm::vec3 m_position{ 0.0f, 0.0f, 0.0f };
private:
    glm::vec3 m_rotation{ 0.0f, 0.0f, 0.0f }; // 라디안입니다
private:
    glm::quat m_orientation{ 1.0f, 0.0f, 0.0f, 0.0f };
private:
    glm::vec3 m_scale{ 1.0f, 1.0f, 1.0f };
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    Transform3D() {
        this->_update_matrix();
    }
    Transform3D(const glm::vec3& pos, const glm::vec3& rot, const glm::vec3& scl)
        : m_position(pos), m_rotation(rot), m_scale(scl)
    {
        _update_matrix();
    }
    ~Transform3D() = default;

우선 멤버 변수에 glm::quat m_orientation을 추가하기만 해주세요.

다음은 setter입니다.

public:
    void set_position(const glm::vec3& value) { m_position = value; _update_matrix(); }
    void set_rotation(const glm::vec3& value) { 
        m_rotation = value; 

        // 오일러 -> 쿼터니언
        m_orientation =
            glm::angleAxis(m_rotation.y, glm::vec3(0, 1, 0)) *
            glm::angleAxis(m_rotation.z, glm::vec3(0, 0, 1)) *
            glm::angleAxis(m_rotation.x, glm::vec3(1, 0, 0));

        _update_matrix(); 
    }
    void set_orientation(const glm::quat& value) {
        m_orientation = value;

        // 쿼터니언 -> 오일러
        glm::mat4 m = glm::toMat4(value);
        glm::extractEulerAngleYZX(m,
            m_rotation.y, m_rotation.z, m_rotation.x
        );

        _update_matrix();
    }
    void set_scale(const glm::vec3& value) { m_scale = value; _update_matrix(); }

저희는 3차원 회전을 표현할 때,

오일러 각의 직관성과

쿼터니언의 안정성 & 효율성을 둘 다 챙기기 위해서

set_rotation(EulerAngle)set_orientation(Quaternion) 을 둘 다 구현할 겁니다.

여기서 중요한 건,

오일러 각이 변하면 쿼터니언이 싱크되고,

반대로 쿼터니언이 변하면 오일러 각이 싱크되도록

적절히 동기화를 시켜주어야 한다는 것입니다.

먼저 set_rotation() 의 경우,

오일러 각을 Y-Z-X 축 순서로 쿼터니언을 합성하여

m_orientation을 덮어씁니다.

set_orientation() 의 경우,

쿼터니언을 회전 행렬로 변환하여

Y, Z, X 오일러 각 값을 추출해줍니다.

여기서 두 시스템에 상호변환에는

반드시 똑같은 축 적용 순서가 사용되어야 합니다.

(glm::extractEulerAngle### 함수들을 사용하여

웬만한 순서에 대해 추출할 수 있습니다)

마지막으로 getter 와 _update_matrix() 입니다.

public:
    const glm::mat4& get_matrix() const { return m_matrix; }
    const glm::vec3& get_position() const { return m_position; }
    const glm::vec3& get_rotation() const { return m_rotation; }
    const glm::quat& get_orientation() const { return m_orientation; }
    const glm::vec3& get_scale() const { return m_scale; }
private:
    void _update_matrix() {
        auto scaling = glm::scale(glm::mat4{ 1.0f }, m_scale);
        //auto rotation =
        //    glm::rotate(glm::mat4(1.0f), m_rotation.y, { 0.0f, 1.0f, 0.0f });
        //rotation = glm::rotate(rotation, m_rotation.z, { 0.0f, 0.0f, 1.0f });
        //rotation = glm::rotate(rotation, m_rotation.x, { 1.0f, 0.0f, 0.0f });

        auto rotation = glm::toMat4(m_orientation);

        auto translation = glm::translate(glm::mat4{ 1.0f }, m_position);
        m_matrix = translation * rotation * scaling;
    }
};

_update_matrix의 다른 점은 모두 같지만,

회전 행렬을 구성할 때는 오일러 각 대신

쿼터니언을 사용해 주세요.

계산량이 훨씬 적어집니다.

또한 Transform3Dset_orientation() 만을 사용하여

위에서 구현했던 쿼터니언 누적 방식으로

"짐벌락 방지를 위해 쿼터니언만을 사용하는" 경우를 고려하여

행렬 만들 때는 쿼터니언을 사용하는 것이 낫습니다.

쿼터니언으로 큐브 회전시키기

루프 안에서 큐브를 회전시키는 코드를

다음과 같이 수정해 보세요.

            // 오일러각을 쓴다면?
            //world_mat.set_rotation(world_mat.get_rotation() + glm::vec3(0.0f, 0.01f, 0.0f));

            // 쿼터니언으로, 회전을 누적해가기!
            auto q = glm::angleAxis(0.01f, glm::vec3{ 0.0f, 1.0f, 0.0f });
            world_mat.set_orientation(world_mat.get_orientation() * q);

이제 set_orientation을 사용하여

오일러 각 대신에,

쿼터니언을 사용하여 회전을 누적할 수 있게 되었습니다.


번외 : 2D 카메라 만들기

Camera3D 를 구현했으니,

Camera2D도 빠르게 구현해봅시다.

다음같이 간단히 구현해주면 됩니다.

class Camera2D {
private:
    ViewMatrix2D m_view_mat{};
    ProjectionMatrix2D m_proj_mat{};
public:
    Camera2D() = default;
    ~Camera2D() = default;
public:
    void set_position(const glm::vec2& value) { m_view_mat.set_position(value); }
    void set_rotation(const float& value) { m_view_mat.set_rotation(value); }
    void set_zoom(const glm::vec2& value) { m_view_mat.set_zoom(value); }
    void set_frustrum_size(const glm::uvec2& value) { m_proj_mat.set_frustrum_size(value); }
public:
    const glm::vec2& get_position() const { return m_view_mat.get_position(); }
    const float& get_rotation() const { return m_view_mat.get_rotation(); }
    const glm::vec2& get_zoom() const { return m_view_mat.get_zoom(); }
    const glm::uvec2& get_frustrum_size()const { return m_proj_mat.get_frustrum_size(); }
public:
    const ViewMatrix2D& get_view_matrix() const { return m_view_mat; }
    const ProjectionMatrix2D& get_projection_matrix() const { return m_proj_mat; }
};

3차원 카메라와 마찬가지로 두 클래스를 래핑하게 됩니다.


좋습니다.

실행시키면 다음과 같이 3D 카메라를 자유롭게 조종할 수 있을 겁니다.

8_2.png

여기까지 오셨다면,

3차원 그래픽스 프로그래밍을 시작할 준비가 끝났습니다.

날아댕기는 카메라만 구현했는데도

벌써 재미있지 않나요?


전체 코드는 하단에 있습니다.

다음 글에서는 TextureCubemap 클래스를 구현하고,

게임 엔진에서 흔히 '스카이박스' 라고 불리는 것을 구현해보겠습니다.

전체 코드 보기

   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
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <cassert>

#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/ext.hpp>

#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>

#include <iostream>
#include <vector>
#include <optional>
#include <array>
#include <unordered_map>

const char* s_vertex_shader_src =
R"""(// 모든 GLSL 코드는 #version [버전] [core(선택)] 이라는 전처리기로 시작합니다.
#version 460 core

//     이제 3차원 정점이므로 vec3으로 받아야 합니다.
layout (location = 0) in vec3 aPos; 
layout (location = 1) in vec2 aTexCoord; 

layout (location = 0) uniform vec3 uSize = vec3(64, 64, 64);

layout (location = 1) uniform mat4 uProj;
layout (location = 2) uniform mat4 uView;
layout (location = 3) uniform mat4 uWorld;

layout (location = 0) out vec2 TexCoord;

// GLSL도 셰이더 1개당 진입점을 하나씩 가집니다.
// C++ 처럼 에러 코드를 반환하지는 않지만, 
//      버텍스 셰이더에서는 'gl_Position 이라는 내부 변수에 값을 쓰는 것' 이 핵심입니다.
//          gl_Position 은 버텍스 셰이더 내에서 읽고 쓰기가 가능한 vec4 타입의 변수이며,
//          이름 그대로 GPU에 넘겨질 정점을 뜻합니다. 왜 vec4이고 마지막에 1을 넣는지는 다다음 장을 참고해주세요.
void main() {
    vec3 pos = (aPos * uSize);

    gl_Position = uProj * uView * uWorld * vec4(pos, 1);
    TexCoord = aTexCoord;
}
)""";

const char* s_fragment_shader_src =
R"""(#version 460 core

// 위의 코드에서 정점을 in 으로 받은 것과 다르게, 
// 이번에는 프래그먼트 셰이더가 'RGBA 색상을 출력' 한다는 것을 표현하기 위해 
// out 을 사용합니다.
// FragColor 라는 변수에 값을 쓴다는 것은, 최종적으로 화면에 그려질 픽셀의 색상을 결정하는 것과 같습니다.
layout (location = 0) out vec4 FragColor;

layout (location = 0) in vec2 TexCoord;

layout (location = 4) uniform sampler2D uTexture;

void main() {
    FragColor = texture(uTexture, TexCoord);
}
)""";


class Transform2D final {
private:
    glm::vec2 m_position{ 0.0f, 0.0f };
    float     m_rotation{ 0.0f };
    glm::vec2 m_scale{ 1.0f, 1.0f };
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    Transform2D() {
        this->_update_matrix();
    }
    Transform2D(const glm::vec2& pos, const float& rot, const glm::vec2& scl)
        : m_position(pos), m_rotation(rot), m_scale(scl) {
        this->_update_matrix();
    }
    ~Transform2D() = default;
public:
    const glm::mat4& get_matrix() const { return m_matrix; }
public:
    void set_position(const glm::vec2& value) { m_position = value; this->_update_matrix(); }
    void set_rotation(const float& value) { m_rotation = value; this->_update_matrix(); }
    void set_scale(const glm::vec2& value) { m_scale = value; this->_update_matrix(); }
public:
    const glm::vec2& get_position() const { return m_position; }
    const float& get_rotation() const { return m_rotation; }
    const glm::vec2& get_scale() const { return m_scale; }
private:
    void _update_matrix() {
        m_matrix = glm::mat4{ 1.0f };
        m_matrix = glm::translate(m_matrix, { m_position.x, -m_position.y, 0.0f });
        m_matrix = glm::rotate(m_matrix, m_rotation, { 0.0f, 0.0f, 1.0f });
        m_matrix = glm::scale(m_matrix, { m_scale.x, m_scale.y, 1.0f });
    }
};

class Transform3D final {
private:
    glm::vec3 m_position{ 0.0f, 0.0f, 0.0f };
private:
    glm::vec3 m_rotation{ 0.0f, 0.0f, 0.0f }; // 라디안입니다
private:
    glm::quat m_orientation{ 1.0f, 0.0f, 0.0f, 0.0f };
private:
    glm::vec3 m_scale{ 1.0f, 1.0f, 1.0f };
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    Transform3D() {
        this->_update_matrix();
    }
    Transform3D(const glm::vec3& pos, const glm::vec3& rot, const glm::vec3& scl)
        : m_position(pos), m_rotation(rot), m_scale(scl)
    {
        _update_matrix();
    }
    ~Transform3D() = default;
public:
    void set_position(const glm::vec3& value) { m_position = value; _update_matrix(); }
    void set_rotation(const glm::vec3& value) { 
        m_rotation = value; 

        // 오일러 -> 쿼터니언
        m_orientation =
            glm::angleAxis(m_rotation.y, glm::vec3(0, 1, 0)) *
            glm::angleAxis(m_rotation.z, glm::vec3(0, 0, 1)) *
            glm::angleAxis(m_rotation.x, glm::vec3(1, 0, 0));

        _update_matrix(); 
    }
    void set_orientation(const glm::quat& value) {
        m_orientation = value;

        // 쿼터니언 -> 오일러
        glm::mat4 m = glm::toMat4(value);
        glm::extractEulerAngleYZX(m,
            m_rotation.y, m_rotation.z, m_rotation.x
        );

        _update_matrix();
    }
    void set_scale(const glm::vec3& value) { m_scale = value; _update_matrix(); }
public:
    const glm::mat4& get_matrix() const { return m_matrix; }
    const glm::vec3& get_position() const { return m_position; }
    const glm::vec3& get_rotation() const { return m_rotation; }
    const glm::quat& get_orientation() const { return m_orientation; }
    const glm::vec3& get_scale() const { return m_scale; }
private:
    void _update_matrix() {
        auto scaling = glm::scale(glm::mat4{ 1.0f }, m_scale);
        //auto rotation =
        //    glm::rotate(glm::mat4(1.0f), m_rotation.y, { 0.0f, 1.0f, 0.0f });
        //rotation = glm::rotate(rotation, m_rotation.z, { 0.0f, 0.0f, 1.0f });
        //rotation = glm::rotate(rotation, m_rotation.x, { 1.0f, 0.0f, 0.0f });

        auto rotation = glm::toMat4(m_orientation);

        auto translation = glm::translate(glm::mat4{ 1.0f }, m_position);
        m_matrix = translation * rotation * scaling;
    }
};

class ViewMatrix2D final {
private:
    glm::vec2 m_position{ 0.0f, 0.0f };
    float     m_rotation{ 0.0f };
    glm::vec2 m_zoom{ 1.0f, 1.0f };
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    ViewMatrix2D() { this->_update_matrix(); }
    ViewMatrix2D(const glm::vec2& pos, const float& rot, const glm::vec2& zoom)
        : m_position(pos), m_rotation(rot), m_zoom(zoom) {
        this->_update_matrix();
    }
    ~ViewMatrix2D() = default;
public:
    void set_position(const glm::vec2& value) { m_position = value; this->_update_matrix(); }
    void set_rotation(const float& value) { m_rotation = value; this->_update_matrix(); }
    void set_zoom(const glm::vec2& value) { m_zoom = value; this->_update_matrix(); }
public:
    const glm::vec2& get_position() const { return m_position; }
    const float& get_rotation() const { return m_rotation; }
    const glm::vec2& get_zoom() const { return m_zoom; }
    const glm::mat4& get_matrix() const { return m_matrix; }
private:
    void _update_matrix() {
        m_matrix = glm::mat4{ 1.0f };

        m_matrix = glm::scale(m_matrix, { m_zoom.x, m_zoom.y, 1.0f });
        m_matrix = glm::rotate(m_matrix, -m_rotation, { 0.0f, 0.0f, 1.0f });
        m_matrix = glm::translate(m_matrix, { -m_position.x, m_position.y, 0.0f });
    }
};

//class ViewMatrix3D final {
class ViewMatrix3D_EulerAngle final {
private:
    glm::vec3 m_position{ 0.0f, 0.0f, 0.0f };
private:
    float m_yaw = 0.0f;   // Y축(업벡터) 기준
    float m_pitch = 0.0f; // right 축기준
private:
    glm::vec3 m_target{ 0.0f, 0.0f, -1.0f };
    glm::vec3 m_up{ 0.0f, 1.0f, 0.0f };
    glm::vec3 m_right{ 1.0f, 0.0f, 0.0f };
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    ViewMatrix3D_EulerAngle() {
        this->_update_matrix();
    }
    void set_position(const glm::vec3& pos) {
        m_position = pos;
        this->_update_matrix();
    }
    void add_yaw(const float& value) {
        m_yaw += value;
        this->_update_matrix();
    }
    void add_pitch(const float& value) {
        m_pitch += value;
        m_pitch = glm::clamp(m_pitch, -glm::radians(89.0f), glm::radians(89.0f));
        this->_update_matrix();
    }
public:
    glm::vec3 get_front_vector() const {
        return m_target;
    }
    glm::vec3 get_right_vector() const {
        return m_right;
    }
    glm::vec3 get_up_vector() const {
        return m_up;
    }
public:
    const glm::vec3& get_position() const { return m_position; }
    const glm::mat4& get_matrix() const { return m_matrix; }
private:
    void _update_matrix() {
        const glm::vec3 world_upvec = { 0.0f, 1.0f, 0.0f };

        glm::vec3 forward = {
            std::sin(m_yaw),
            0.0f,
            -std::cos(m_yaw)
        };
        forward = glm::normalize(forward);
        m_right = glm::normalize(glm::cross(forward, world_upvec));

        glm::mat4 pitch_rotmat = glm::rotate(glm::mat4(1.0f), m_pitch, m_right);
        m_target = glm::normalize(glm::vec3(pitch_rotmat * glm::vec4(forward, 0.0f)));

        m_up = glm::normalize(glm::cross(m_right, m_target));

        m_matrix = glm::lookAt(m_position, m_position + m_target, m_up);
    }
};


class ViewMatrix3D_Quaternion final {
private:
    glm::vec3 m_position{ 0.0f, 0.0f, 0.0f };
    glm::quat m_orientation{ 1.0f, 0.0f, 0.0f, 0.0f };
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    ViewMatrix3D_Quaternion() {
        this->_update_matrix();
    }
    void set_position(const glm::vec3& pos) {
        m_position = pos;
        this->_update_matrix();
    }
    void add_yaw(const float& value) {
        // 월드 up 기준 회전
        //  사원수를 '누적' 해야 함.
        glm::quat q = glm::angleAxis(-value, glm::vec3(0, 1, 0));
        m_orientation = glm::normalize(q * m_orientation);

        this->_update_matrix();
    }
    void add_pitch(const float& value) {
        glm::vec3 front = get_front_vector();
        // 단위원에서 r=1 이므로
        // sin(theta) = (y / 1) = y, 
        // theta = arcsin(y)
        float pitch = std::asin(glm::clamp(front.y, -1.0f, 1.0f));
        float newpitch = glm::clamp(pitch + value, -glm::radians(89.0f), glm::radians(89.0f));
        float delta = (newpitch - pitch);

        glm::vec3 right = get_right_vector();
        glm::quat q = glm::angleAxis(delta, right);
        m_orientation = glm::normalize(q * m_orientation);

        this->_update_matrix();
    }
public:
    glm::vec3 get_front_vector() const {
        return m_orientation * glm::vec3(0.0f, 0.0f, -1.0f);
    }
    glm::vec3 get_right_vector() const {
        return m_orientation * glm::vec3(1.0f, 0.0f, 0.0f);
    }
    glm::vec3 get_up_vector() const {
        return m_orientation * glm::vec3(0.0f, 1.0f, 0.0f);
    }
public:
    const glm::vec3& get_position() const { return m_position; }
    const glm::mat4& get_matrix() const { return m_matrix; }
private:
    void _update_matrix() {
        glm::quat orien_rev = glm::conjugate(m_orientation);
        glm::mat4 rotation = glm::toMat4(orien_rev);
        // 통째로 반전해서 넣자.
        glm::mat4 translation = glm::translate( glm::mat4{ 1.0f }, -m_position );

        m_matrix = rotation * translation;
    }
};

//using ViewMatrix3D = ViewMatrix3D_EulerAngle;
using ViewMatrix3D = ViewMatrix3D_Quaternion;

class ProjectionMatrix2D final {
private:
    glm::uvec2 m_frustrum_size{ 1280, 720 };
    float m_near = -1.0f;
    float m_far = 1.0f;
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    ProjectionMatrix2D() {
        this->_update_matrix();
    }
    ProjectionMatrix2D(const glm::uvec2& frustrum_size, const float& proj_near, const float& proj_far)
        : m_frustrum_size(frustrum_size), m_near(proj_near), m_far(proj_far)
    {
        this->_update_matrix();
    }
    ~ProjectionMatrix2D() = default;
public:
    void set_frustrum_size(const glm::uvec2& value) { m_frustrum_size = value; this->_update_matrix(); }
    void set_near(const float& value) { m_near = value; this->_update_matrix(); }
    void set_far(const float& value) { m_far = value; this->_update_matrix(); }
public:
    const glm::uvec2& get_frustrum_size() const { return m_frustrum_size; }
    const float& get_near() const { return m_near; }
    const float& get_far() const { return m_far; }
public:
    const glm::mat4& get_matrix() const { return m_matrix; }
private:
    void _update_matrix() {
        const float fwidth = static_cast<float>(m_frustrum_size.x);
        const float fheight = static_cast<float>(m_frustrum_size.y);

        //m_matrix = {
        //    2.0f / fwidth, 0.0f,           0.0f,                      0.0f,
        //    0.0f,          2.0f / fheight, 0.0f,                      0.0f,
        //    0.0f,          0.0f,           -2.0f / (m_far - m_near),  0.0f,
        //    0.0f,          0.0f,           -(m_far + m_near) / (m_far - m_near), 1.0f
        //};


        //m_matrix = {
        //    2.0f / fwidth,  0.0f,           0.0f,                     0.0f, //  -(right+left)/(right-left)
        //    0.0f,           2.0f / fheight, 0.0f,                     0.0f, //  -(top+bottom)/(top-bottom)
        //    0.0f,           0.0f,           -2.0f / (m_far - m_near), -(m_far + m_near) / (m_far - m_near),
        //    0.0f,           0.0f,           0.0f,                     1.0f
        //};

        //m_matrix = glm::ortho(-640.0f, 640.0f, -360.0f, 360.0f, -1.0f, 1.0f);
        float width_half = (fwidth / 2.0f);
        float height_half = (fheight / 2.0f);
        m_matrix = glm::ortho(-width_half, width_half, -height_half, height_half, m_near, m_far);
    }
};

enum class ProjectionType {
    Perspective,
    Ortho,
};

class ProjectionMatrix3D final {
private:
    glm::uvec2 m_frustrum_size{ /* 0 */ 1280, /* 0 */ 720 };
    float m_near = 0.1f;
    float m_far = 1000.0f;
private:
    float m_fov{ glm::radians(50.0f) };
private:
    ProjectionType m_projection_type = ProjectionType::Perspective;
private:
    glm::mat4 m_matrix{ 1.0f };
public:
    ProjectionMatrix3D() {
        this->_update_matrix();
    }
    ProjectionMatrix3D(const glm::uvec2& frustrum_size, const float& near, const float& far, const float& fov)
        : m_frustrum_size(frustrum_size),
        m_near(near),
        m_far(far),
        m_fov(fov)
    {
        this->_update_matrix();
    }
    ~ProjectionMatrix3D() = default;
public:
    void set_projection_type(const ProjectionType& type) {
        const auto last_type = m_projection_type;
        m_projection_type = type;
        if (last_type != m_projection_type) {
            this->_update_matrix();
        }
    }
    void set_frustrum_size(const glm::uvec2& value) {
        m_frustrum_size = value;

        this->_update_matrix();
    }
    void set_near(const float& value) {
        assert(value != 0.0f);
        m_near = value;
        this->_update_matrix();
    }
    void set_far(const float& value) {
        m_far = value;
        this->_update_matrix();
    }
    void set_fov(const float& value) {
        m_fov = value;

        this->_update_matrix();
    }
public:
    const ProjectionType& get_projection_type() const { return m_projection_type; }
    const glm::uvec2& get_frustrum_size() const { return m_frustrum_size; }
    const float& get_near() const { return m_near; }
    const float& get_far() const { return m_far; }
    const float& get_fov() const { return m_fov; }
public:
    const glm::mat4& get_matrix() const { return m_matrix; }
private:
    void _update_matrix() {
        if (m_projection_type == ProjectionType::Perspective) {
            assert(m_near > 0.0f);
            assert(m_far > 0.0f);
            m_matrix = glm::perspective(m_fov, float(m_frustrum_size.x) / float(m_frustrum_size.y), m_near, m_far);
        }
        else {
            float width_half = (float(m_frustrum_size.x) / 2.0f);
            float height_half = (float(m_frustrum_size.y) / 2.0f);
            m_matrix = glm::ortho(-width_half, width_half, -height_half, height_half, m_near, m_far);
        }
    }
};

class BufferData final {
private:
    std::vector<unsigned char> m_data{};
public:
    BufferData() = default;
    ~BufferData() = default;
    BufferData(const BufferData& other) = default;
    BufferData& operator=(const BufferData& other) = default;
public:
    BufferData(const void* data, const size_t& len) {
        assert(data != nullptr && len > 0);

        const auto* bytes = static_cast<const unsigned char*>(data);
        m_data.assign(bytes, bytes + len);
    }
public:
    void swap(std::vector<unsigned char>&& data) {
        m_data = std::move(data);
    }
private:
    void _add(const unsigned char* value, size_t count) {
        size_t old_size = m_data.size();
        m_data.resize(old_size + count);
        std::memcpy(m_data.data() + old_size, value, count);
    }
public:
    template <typename T, typename std::enable_if_t<std::is_trivially_copyable_v<T>, int> = 0>
    void add_pod(const T& value) {
        _add(reinterpret_cast<const unsigned char*>(&value), sizeof(T));
    }
    template <typename T, typename std::enable_if_t<std::is_trivially_copyable_v<T>, int> = 0>
    void add_vec(const T& v) {
        _add(reinterpret_cast<const unsigned char*>(&v), sizeof(T));
    }
public:
    void add_int32(int32_t v) { add_pod(v); }
    void add_uint32(uint32_t v) { add_pod(v); }
    void add_float(float v) { add_pod(v); }
public:
    void add_vec2i(const glm::ivec2& v) { add_vec(v); }
    void add_vec3i(const glm::ivec3& v) { add_vec(v); }
    void add_vec4i(const glm::ivec4& v) { add_vec(v); }
    void add_vec2u(const glm::uvec2& v) { add_vec(v); }
    void add_vec3u(const glm::uvec3& v) { add_vec(v); }
    void add_vec4u(const glm::uvec4& v) { add_vec(v); }
    void add_vec2(const glm::vec2& v) { add_vec(v); }
    void add_vec3(const glm::vec3& v) { add_vec(v); }
    void add_vec4(const glm::vec4& v) { add_vec(v); }
public:
    void reserve(const size_t& size) { m_data.reserve(size); }
public:
    const void* get_pointer() const { return m_data.data(); }
    size_t get_length() const { return m_data.size(); }
};

enum class BufferAccessType : GLenum {
    ReadOnly = GL_READ_ONLY,
    WriteOnly = GL_WRITE_ONLY,
    ReadAndWrite = GL_READ_WRITE,
};


enum class TransformFeedbackCaptureMode : GLenum {
    InterleavedAttribs = GL_INTERLEAVED_ATTRIBS,
    SeparateAttribs = GL_SEPARATE_ATTRIBS
};

enum class UniformType : GLenum {
    Sampler2D = GL_SAMPLER_2D,
    Sampler2DArray = GL_SAMPLER_2D_ARRAY,
    Sampler2DRect = GL_SAMPLER_2D_RECT,
    Sampler3D = GL_SAMPLER_3D,
    SamplerCube = GL_SAMPLER_CUBE,

    Int = GL_INT,
    Float = GL_FLOAT,
    Vec2f = GL_FLOAT_VEC2,
    Vec3f = GL_FLOAT_VEC3,
    Vec4f = GL_FLOAT_VEC4,

    Mat2f = GL_FLOAT_MAT2,
    Mat3f = GL_FLOAT_MAT3,
    Mat4f = GL_FLOAT_MAT4,

    Double = GL_DOUBLE,
    Vec2d = GL_DOUBLE_VEC2,
    Vec3d = GL_DOUBLE_VEC3,
    Vec4d = GL_DOUBLE_VEC4,

    Uint = GL_UNSIGNED_INT,
    Vec2u = GL_UNSIGNED_INT_VEC2,
    Vec3u = GL_UNSIGNED_INT_VEC3,
    Vec4u = GL_UNSIGNED_INT_VEC4,

    Bool = GL_BOOL,
    Vec2b = GL_BOOL_VEC2,
    Vec3b = GL_BOOL_VEC3,
    Vec4b = GL_BOOL_VEC4,

    Mat2x3f = GL_FLOAT_MAT2x3,
    Mat2x4f = GL_FLOAT_MAT2x4,
    Mat3x2f = GL_FLOAT_MAT3x2,
    Mat3x4f = GL_FLOAT_MAT3x4,
    Mat4x2f = GL_FLOAT_MAT4x2,
    Mat4x3f = GL_FLOAT_MAT4x3,

    Mat2d = GL_DOUBLE_MAT2,
    Mat3d = GL_DOUBLE_MAT3,
    Mat4d = GL_DOUBLE_MAT4,

    Mat2x3d = GL_DOUBLE_MAT2x3,
    Mat2x4d = GL_DOUBLE_MAT2x4,
    Mat3x2d = GL_DOUBLE_MAT3x2,
    Mat3x4d = GL_DOUBLE_MAT3x4,
    Mat4x2d = GL_DOUBLE_MAT4x2,
    Mat4x3d = GL_DOUBLE_MAT4x3,

};

enum class BufferUsage : GLenum {
    StreamDraw = GL_STREAM_DRAW, // 주기적으로 업로드
    StreamRead = GL_STREAM_READ,
    StreamCopy = GL_STREAM_COPY,

    StaticDraw = GL_STATIC_DRAW, // 초기에 한번만 업로드
    StaticRead = GL_STATIC_READ,
    StaticCopy = GL_STATIC_COPY,

    DynamicDraw = GL_DYNAMIC_DRAW, // 렌더링할때마다 버퍼 내용물을 재업로드
    DynamicRead = GL_DYNAMIC_READ,
    DynamicCopy = GL_DYNAMIC_COPY
};

enum class BufferStorageFlag : GLenum {
    MapRead = GL_MAP_READ_BIT,
    MapWrite = GL_MAP_WRITE_BIT,
    MapPersistent = GL_MAP_PERSISTENT_BIT,
    MapCoherent = GL_MAP_COHERENT_BIT,
    DynamicStorage = GL_DYNAMIC_STORAGE_BIT,
    ClientStorage = GL_CLIENT_STORAGE_BIT,
};


enum class BufferMappingFlag : GLenum {
    // 이 넷중에 하나는 필수
    Read = GL_MAP_READ_BIT, // 읽기전용
    Write = GL_MAP_WRITE_BIT, // 쓰기전용
    Persistent = GL_MAP_PERSISTENT_BIT, // 
    Coherent = GL_MAP_COHERENT_BIT,

    // 이 네개는 옵션
    //      이 세개중에 하나라도 켜지면 Read는 불가
    InvalidateRange = GL_MAP_INVALIDATE_RANGE_BIT, // 기존 버퍼의 범위(glMapRange) 를 무효화
    InvalidateBuffer = GL_MAP_INVALIDATE_BUFFER_BIT, // 기존 버퍼 전체를 무효화

    // 동기화 X, 성능 우선
    /*
    *   이거 쓰고 동기화하려면,
        glFinish() -> glUnmapBuffer() 순으로 불러야함
            (또는 glMemoryBarrier(),
             또는 glClientWaitSync 이후에 unmap)
    */
    Unsynchronized = GL_MAP_UNSYNCHRONIZED_BIT,

    FlushExplicit = GL_MAP_FLUSH_EXPLICIT_BIT, // 이게 켜지면 Write는 필수
};


enum class WrappingType : GLenum {
    ClampToEdge = GL_CLAMP_TO_EDGE,
    ClampToBorder = GL_CLAMP_TO_BORDER,
    Repeat = GL_REPEAT,
    MirroredRepeat = GL_MIRRORED_REPEAT
};

enum class FilterType : GLenum {
    Nearest = GL_NEAREST,
    Linear = GL_LINEAR,
    NearestMipmapNearest = GL_NEAREST_MIPMAP_NEAREST,
    LinearMipmapNearest = GL_LINEAR_MIPMAP_NEAREST,
    NearestMipmapLinear = GL_NEAREST_MIPMAP_LINEAR,
    LinearMipmapLinear = GL_LINEAR_MIPMAP_LINEAR
};

enum class InternalFormat : GLenum {
    CompressedRed = GL_COMPRESSED_RED,
    CompressedRedRGTC1 = GL_COMPRESSED_RED_RGTC1,
    CompressedRG = GL_COMPRESSED_RG,
    CompressedRGB = GL_COMPRESSED_RGB,
    CompressedRGBA = GL_COMPRESSED_RGBA,
    CompressedRGRGTC2 = GL_COMPRESSED_RG_RGTC2,
    CompressedSignedRedRGTC1 = GL_COMPRESSED_SIGNED_RED_RGTC1,
    CompressedSignedRGRGTC2 = GL_COMPRESSED_SIGNED_RG_RGTC2,
    CompressedSRGB = GL_COMPRESSED_SRGB,
    DepthStencil = GL_DEPTH_STENCIL,
    Depth24Stencil8 = GL_DEPTH24_STENCIL8,
    Depth32FStencil8 = GL_DEPTH32F_STENCIL8,
    DepthComponent = GL_DEPTH_COMPONENT,
    DepthComponent16 = GL_DEPTH_COMPONENT16,
    DepthComponent24 = GL_DEPTH_COMPONENT24,
    DepthComponent32F = GL_DEPTH_COMPONENT32F,
    R16F = GL_R16F,
    R16I = GL_R16I,
    R16SNorm = GL_R16_SNORM,
    R16UI = GL_R16UI,
    R32F = GL_R32F,
    R32I = GL_R32I,
    R32UI = GL_R32UI,
    R3G3B2 = GL_R3_G3_B2,
    R8 = GL_R8,
    R8I = GL_R8I,
    R8SNorm = GL_R8_SNORM,
    R8UI = GL_R8UI,
    Red = GL_RED,
    RG = GL_RG,
    RG16 = GL_RG16,
    RG16F = GL_RG16F,
    RG16SNorm = GL_RG16_SNORM,
    RG32F = GL_RG32F,
    RG32I = GL_RG32I,
    RG32UI = GL_RG32UI,
    RG8 = GL_RG8,
    RG8I = GL_RG8I,
    RG8SNorm = GL_RG8_SNORM,
    RG8UI = GL_RG8UI,
    RGB = GL_RGB,
    RGB10 = GL_RGB10,
    RGB10A2 = GL_RGB10_A2,
    RGB12 = GL_RGB12,
    RGB16 = GL_RGB16,
    RGB16F = GL_RGB16F,
    RGB16I = GL_RGB16I,
    RGB16UI = GL_RGB16UI,
    RGB32F = GL_RGB32F,
    RGB32I = GL_RGB32I,
    RGB32UI = GL_RGB32UI,
    RGB4 = GL_RGB4,
    RGB5 = GL_RGB5,
    RGB5A1 = GL_RGB5_A1,
    RGB8 = GL_RGB8,
    RGB8I = GL_RGB8I,
    RGB8UI = GL_RGB8UI,
    RGB9E5 = GL_RGB9_E5,
    RGBA = GL_RGBA,
    RGBA12 = GL_RGBA12,
    RGBA16 = GL_RGBA16,
    RGBA16F = GL_RGBA16F,
    RGBA16I = GL_RGBA16I,
    RGBA16UI = GL_RGBA16UI,
    RGBA2 = GL_RGBA2,
    RGBA32F = GL_RGBA32F,
    RGBA32I = GL_RGBA32I,
    RGBA32UI = GL_RGBA32UI,
    RGBA4 = GL_RGBA4,
    RGBA8 = GL_RGBA8,
    RGBA8UI = GL_RGBA8UI,
    SRGB8 = GL_SRGB8,
    SRGB8A8 = GL_SRGB8_ALPHA8,
    SRGBA = GL_SRGB_ALPHA,

    R11FG11FB10F = GL_R11F_G11F_B10F,
};

enum class PixelFormat : GLenum {
    Red = GL_RED,
    Green = GL_GREEN,
    Blue = GL_BLUE,
    Alpha = GL_ALPHA,
    RGB = GL_RGB,
    RGBA = GL_RGBA,
    BGR = GL_BGR,
    BGRA = GL_BGRA,
    RG = GL_RG,
    RedInteger = GL_RED_INTEGER,
    RGInteger = GL_RG_INTEGER,
    RGBInteger = GL_RGB_INTEGER,
    BGRInteger = GL_BGR_INTEGER,
    RGBAInteger = GL_RGBA_INTEGER,
    BGRAInteger = GL_BGRA_INTEGER,
    StencilIndex = GL_STENCIL_INDEX,
    DepthComponent = GL_DEPTH_COMPONENT,
    DepthStencil = GL_DEPTH_STENCIL
};

enum class DataType : GLenum {
    Byte = GL_BYTE,
    UnsignedByte = GL_UNSIGNED_BYTE,
    Short = GL_SHORT,
    UnsignedShort = GL_UNSIGNED_SHORT,
    Int = GL_INT,
    UnsignedInt = GL_UNSIGNED_INT,
    Float = GL_FLOAT,
    Double = GL_DOUBLE,

    UnsignedByte332 = GL_UNSIGNED_BYTE_3_3_2,
    UnsignedByte233Rev = GL_UNSIGNED_BYTE_2_3_3_REV,
    UnsignedShort565 = GL_UNSIGNED_SHORT_5_6_5,
    UnsignedShort565Rev = GL_UNSIGNED_SHORT_5_6_5_REV,
    UnsignedShort4444 = GL_UNSIGNED_SHORT_4_4_4_4,
    UnsignedShort4444Rev = GL_UNSIGNED_SHORT_4_4_4_4_REV,
    UnsignedShort5551 = GL_UNSIGNED_SHORT_5_5_5_1,
    UnsignedShort1555Rev = GL_UNSIGNED_SHORT_1_5_5_5_REV,
    UnsignedInt8888 = GL_UNSIGNED_INT_8_8_8_8,
    UnsignedInt8888Rev = GL_UNSIGNED_INT_8_8_8_8_REV,
    UnsignedInt101010102 = GL_UNSIGNED_INT_10_10_10_2
};

class VertexLayout {
private:
    std::vector<std::pair<DataType, uint32_t>> m_attribs{ };
public:
    VertexLayout() = default;
    ~VertexLayout() = default;
public:
    void push_attrib(const DataType& type, const uint32_t& count) {
        m_attribs.emplace_back(type, count);
    }
public:
    const auto& get_attribs() const { return m_attribs; }
public:
    uint32_t get_vertex_size() const {
        uint32_t result = 0;
        for (const auto& attrib : m_attribs) {
            result += static_cast<uint32_t>(VertexLayout::get_data_size(attrib.first) * attrib.second);
        }
        return result;
    }
public:
    static size_t get_data_size(const DataType& type) {
        size_t result = 0;

        switch (type) {
        case (DataType::Byte): { result = sizeof(char); break; }
        case (DataType::UnsignedByte332): [[fallthrough]];
        case (DataType::UnsignedByte233Rev): [[fallthrough]];
        case (DataType::UnsignedByte): { result = sizeof(unsigned char); break; }
        case (DataType::Short): { result = sizeof(short); break; }
        case (DataType::UnsignedShort565): [[fallthrough]];
        case (DataType::UnsignedShort565Rev): [[fallthrough]];
        case (DataType::UnsignedShort4444): [[fallthrough]];
        case (DataType::UnsignedShort4444Rev): [[fallthrough]];
        case (DataType::UnsignedShort5551): [[fallthrough]];
        case (DataType::UnsignedShort1555Rev): [[fallthrough]];
        case (DataType::UnsignedShort): { result = sizeof(unsigned short); break; }
        case (DataType::Int): { result = sizeof(int); break; }
        case (DataType::UnsignedInt8888): [[fallthrough]];
        case (DataType::UnsignedInt8888Rev): [[fallthrough]];
        case (DataType::UnsignedInt101010102): [[fallthrough]];
        case (DataType::UnsignedInt): { result = sizeof(unsigned int); break; }
        case (DataType::Float): { result = sizeof(float); break; }
        case (DataType::Double): { result = sizeof(double); break; }
        default: { assert(false); break; }
        };
        return result;
    }
};

enum class ShaderType : uint32_t {
    Vertex = GL_VERTEX_SHADER,
    TessellationControl = GL_TESS_CONTROL_SHADER,
    TessellationEvaluation = GL_TESS_EVALUATION_SHADER,
    Geometry = GL_GEOMETRY_SHADER,
    Fragment = GL_FRAGMENT_SHADER,
    Compute = GL_COMPUTE_SHADER,
};

struct ShaderTypeHash {
    template <typename T>
    std::size_t operator()(T t) const {
        return static_cast<std::size_t>(t);
    }
};

class Buffer final {
private:
    GLuint m_ID = 0;
public:
    Buffer() {
        glCreateBuffers(1, &m_ID);
    }
    ~Buffer() {
        glDeleteBuffers(1, &m_ID);
    }
public:
    void upload_data(const BufferData& data, const BufferUsage& usage) const {
        glNamedBufferData(m_ID,
            data.get_length(),
            data.get_pointer(),
            (GLenum)(usage)
        );
    }
    void upload_empty_data(const size_t& size, const BufferUsage& usage) const {
        glNamedBufferData(m_ID,
            size,
            nullptr,
            (GLenum)(usage)
        );
    }
    void upload_sub_data(const uint32_t& offset, const BufferData& data) const {
        glNamedBufferSubData(
            m_ID,
            offset,
            data.get_length(), data.get_pointer()
        );
    }
    void download_sub_data(const uint32_t& offset, void* dst, const size_t& size) const {
        glGetNamedBufferSubData(
            m_ID,
            offset,
            size, dst
        );
    }
public:
    void* map(const BufferAccessType& type) const {
        return glMapNamedBuffer(m_ID,
            (GLenum)(type)
        );
    }
    void* map_range(const uint32_t& offset, const size_t& size, const BufferMappingFlag& flag) const {
        return glMapNamedBufferRange(
            m_ID, offset, size, (GLenum)(flag));
    }
    void flush_mapped_range(const uint32_t& offset, const size_t& size) const {
        glFlushMappedNamedBufferRange(
            m_ID,
            offset,
            size
        );
    }
    void unmap() const {
        glUnmapNamedBuffer(m_ID);
    }
public:
    void copy_from(const Buffer& src, const uint32_t& read_offset, const uint32_t& write_offset, const size_t& size) const {
        glCopyNamedBufferSubData(
            src.get_opengl_id(), m_ID,
            read_offset, write_offset, size
        );
    }
    void copy_to(const Buffer& dst, const uint32_t& read_offset, const uint32_t& write_offset, const size_t& size) const {
        glCopyNamedBufferSubData(
            m_ID, dst.get_opengl_id(),
            read_offset, write_offset, size
        );
    }
public:
    void clear_data(const InternalFormat& iformat, const PixelFormat& format, const DataType& data_type, const void* data /* 배열 아님. 보통 0임 */) const {
        glClearNamedBufferData(
            m_ID,
            (GLenum)(iformat),
            (GLenum)(format),
            (GLenum)(data_type), data
        );
    }
    void clear_sub_data(const InternalFormat& iformat, const uint32_t& offset, const size_t& size, const PixelFormat& format, const DataType& data_type, const void* data /* 배열 아님, 보통0 */) const {
        glClearNamedBufferSubData(
            m_ID,
            (GLenum)(iformat),
            offset, size,
            (GLenum)(format),
            (GLenum)(data_type),
            data
        );
    }
public:
    void upload_storage(const BufferData& data, const BufferStorageFlag& flag) const {
        glNamedBufferStorage(
            m_ID,
            data.get_length(), data.get_pointer(),
            (GLenum)(flag)
        );
    }
    void upload_storage(const size_t& size, const BufferStorageFlag& flag) const {
        glNamedBufferStorage(
            m_ID,
            size, nullptr,
            (GLenum)(flag)
        );
    }
public:
    const GLuint& get_opengl_id() const { return m_ID; }
};

class VertexArray final {
private:
    GLuint m_ID = 0;
public:
    VertexArray() {
        glCreateVertexArrays(1, &m_ID);

    }
    ~VertexArray() {
        glDeleteBuffers(1, &m_ID);

    }
public:
    void bind() const {
        glBindVertexArray(m_ID);

    }
public:
    void bind_vertex_buffer(const uint32_t& binding_idx, const Buffer* buffer, const uint32_t& offset, const VertexLayout& layout) const {
        auto vbo_id = buffer->get_opengl_id();
        glVertexArrayVertexBuffer(
            m_ID, binding_idx, vbo_id,
            offset, layout.get_vertex_size()
        );

        const auto& vertex_size = layout.get_vertex_size();
        const auto& attribs = layout.get_attribs();

        int attrib_index = 0;
        uint32_t offset_ptr = 0;

        for (const auto& attrib : attribs) {
            glEnableVertexArrayAttrib(m_ID, attrib_index);

            glVertexArrayAttribFormat(
                m_ID, attrib_index, attrib.second, (GLenum)(attrib.first), GL_FALSE, offset_ptr
            );

            glVertexArrayAttribBinding(
                m_ID,
                attrib_index,
                binding_idx
            );

            offset_ptr += static_cast<uint32_t>(VertexLayout::get_data_size(attrib.first)) * attrib.second;
            attrib_index++;
        }
    }
    void bind_element_buffer(const Buffer* buffer) const {
        glVertexArrayElementBuffer(m_ID, buffer->get_opengl_id());
    }
public:
    void set_divisor(const uint32_t& binding_idx, const uint32_t& divisor) const {
        glVertexArrayBindingDivisor(
            m_ID,
            binding_idx, divisor
        );
    }
public:
    const GLuint& get_opengl_id() const { return m_ID; }
};


class ShaderProgram final {
private:
    std::unordered_map<std::string, UniformType>
        m_uniform_type_map{ };
private:
    GLuint m_ID = 0;
private:
    std::unordered_map<ShaderType, GLuint, ShaderTypeHash> m_shader_map{ };
    std::unordered_map<std::string, int> m_uniform_location_map{ };
private:
private:
    // 서브루틴 기능은 OpenGL에만 있다.
    struct SubroutineInfo {
        // 타겟 uniform 서브루틴 이름 -->  해당 셰이더에서의 인덱스
        std::unordered_map<std::string, GLuint> location_map{ };
        // 특정 서브루틴 이름         -->  해당 서브루틴의 인덱스
        std::unordered_map<std::string, GLuint> index_map{ };
        // 이걸 전부 glUniformSubroutinesuiv에 전달.
        std::vector<GLuint> storage{};
    };
    mutable std::unordered_map<ShaderType, SubroutineInfo, ShaderTypeHash> m_subroutine_info_map{ };
public:
    ShaderProgram() {
        m_ID = glCreateProgram();
    }
    ~ShaderProgram() {
        for (const auto& [type, id] : m_shader_map) {
            glDetachShader(m_ID, id);
            glDeleteShader(id);
        }
        glDeleteProgram(m_ID);
    }
public:
    void use() const {
        glUseProgram(m_ID);
    }
public:
    void attach_shader(const ShaderType& type, const std::string_view& src) {
        assert(m_shader_map.find(type) == m_shader_map.end());
        uint32_t id = glCreateShader((GLenum)(type));
        const auto* ptr = src.data();
        glShaderSource(id, 1, &ptr, NULL);
        glCompileShader(id);
        int success = 0;
        glGetShaderiv(id, GL_COMPILE_STATUS, &success);
        if (!success) {
            char buffer[1024] = { 0, };
            glGetShaderInfoLog(id, 1024, NULL, buffer);
            std::cout << "failed to compile shader : " << buffer << "\n";
            assert(false);
        }
        m_shader_map[type] = id;
        glAttachShader(m_ID, id);
    }
    void link() const {
        glLinkProgram(m_ID);
        int success = 0;
        glGetProgramiv(m_ID, GL_LINK_STATUS, &success);
        if (!success) {
            char buffer[1024] = { 0, };
            glGetProgramInfoLog(m_ID, 1024, NULL, &buffer[0]);
            std::cout << "failed to link program : " << buffer << "\n";
            assert(false);
        }
    }
public:
    void set_transform_feedback_varyings(const std::vector<std::string_view>& varyings, const TransformFeedbackCaptureMode& capture_mode) const {
        std::vector<const char*> strs{};
        strs.reserve(varyings.size());
        for (const auto& s : varyings) { strs.emplace_back(s.data()); }
        glTransformFeedbackVaryings(
            m_ID, static_cast<GLsizei>(strs.size()), strs.data(),
            (GLenum)(capture_mode)
        );
    }
    void get_varying(const uint32_t& index, std::string& out_name, uint32_t& out_size /* 배열이면 out_size > 1 */, UniformType& out_type) const {
        char name[64] = { 0, };
        GLsizei length = 0, size = 0;
        GLenum type = 0;

        glGetTransformFeedbackVarying(
            m_ID,
            index,
            64,
            &length,
            &size,
            &type,
            name
        );

        out_name = name;
        out_size = size;
        out_type = (UniformType)(type);
    }
public:
    void upload_uniform_bool(const std::string& name, const bool& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Bool);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), value);
    }
    void upload_uniform_int(const std::string& name, const int& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Int);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), value);
    }
    void upload_uniform_float(const std::string& name, const float& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Float);
        glProgramUniform1f(m_ID, m_uniform_location_map.at(name), value);
    }
    void upload_uniform_vec2f(const std::string& name, const glm::vec2& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Vec2f);
        glProgramUniform2f(m_ID, m_uniform_location_map.at(name), value.x, value.y);
    }
    void upload_uniform_vec3f(const std::string& name, const glm::vec3& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Vec3f);
        glProgramUniform3f(m_ID, m_uniform_location_map.at(name), value.x, value.y, value.z);
    }
    void upload_uniform_vec4f(const std::string& name, const glm::vec4& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Vec4f);
        glProgramUniform4f(m_ID, m_uniform_location_map.at(name), value.x, value.y, value.z, value.w);
    }
    void upload_uniform_mat4f(const std::string& name, const glm::mat4& value) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Mat4f);
        glProgramUniformMatrix4fv(m_ID, m_uniform_location_map.at(name), 1, GL_FALSE, &value[0][0]);
    }
    void upload_uniform_sampler2d(const std::string& name, const int& slot) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Sampler2D);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), slot);
    }
    void upload_uniform_sampler2d_array(const std::string& name, const int& slot) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::Sampler2DArray);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), slot);
    }
    void upload_uniform_sampler_cube(const std::string& name, const int& slot) const {
        assert(m_uniform_location_map.find(name) != m_uniform_location_map.end());
        assert(m_uniform_type_map.at(name) == UniformType::SamplerCube);
        glProgramUniform1i(m_ID, m_uniform_location_map.at(name), slot);
    }
public:
    void upload_uniform_subroutine(const ShaderType& type, const std::string& target_name, const std::string& subroutine_fn_name) const {
        auto& info = m_subroutine_info_map.at(type);
        GLuint loc = info.location_map.at(target_name);
        GLuint index = info.index_map.at(subroutine_fn_name);
        // 기록 하고? 다시 갱신해주는거임.
        info.storage.at(loc) = index;
        glUniformSubroutinesuiv(
            (GLenum)(type),
            info.storage.size(),
            info.storage.data()
        );
    }
public:
    void register_uniform(const std::string& name, const UniformType& type) {

        assert(m_uniform_type_map.find(name) == m_uniform_type_map.end());
        m_uniform_type_map[name] = type;

        auto loc = glGetUniformLocation(m_ID, name.c_str());

        // GLSL컴파일러가 너무 똑똑해서 안쓰는건 다 없애버리기에 
        // 이걸 해놓으면 (디버깅이) 귀찮아짐
        //assert(loc != -1);
        m_uniform_location_map[name] = loc;

        if (loc == -1) { return; }

        {
            const GLchar* str = name.c_str();
            const GLchar* const arr[] = { str };

            // 주의 : 컴파일단에서 안쓰이는거 없어진 경우
            //      여기서 INVALID_INDEX뜸..
            GLuint gl_index{};
            glGetUniformIndices(m_ID, 1, arr, &gl_index);

            assert(gl_index != GL_INVALID_INDEX);

            GLint gl_type{};
            glGetActiveUniformsiv(m_ID, 1, &gl_index, GL_UNIFORM_TYPE, &gl_type);

            assert((GLenum)type == (gl_type));
        }
    }
public:
    void set_uniform_block_binding(const uint32_t& block_index, const uint32_t& binding) const {
        glUniformBlockBinding(m_ID, block_index, binding);
    }
    uint32_t get_uniform_block_index(const std::string& name) const {
        return glGetUniformBlockIndex(m_ID, name.c_str());
    }
public:
    const uint32_t& get_opengl_id() const { return m_ID; }
private:
    void _register_subroutines() {

        GLenum interfaces[] = {
            GL_VERTEX_SUBROUTINE,
            GL_GEOMETRY_SUBROUTINE,
            GL_TESS_CONTROL_SUBROUTINE,
            GL_TESS_EVALUATION_SUBROUTINE,
            GL_FRAGMENT_SUBROUTINE,
            GL_COMPUTE_SUBROUTINE
        };
        ShaderType shader_stages[] = {
            ShaderType::Vertex,
            ShaderType::Geometry,
            ShaderType::TessellationControl,
            ShaderType::TessellationEvaluation,
            ShaderType::Fragment,
            ShaderType::Compute
        };

        GLint interfaces_count = std::size(interfaces);

        for (GLint i = 0; i < interfaces_count; ++i) {
            /* Get all active subroutines */
            GLenum program_interface = interfaces[i];

            // 해당 셰이더에 정의된 subroutine의 개수
            GLint num_subroutines = 0;
            glGetProgramInterfaceiv(m_ID, program_interface, GL_ACTIVE_RESOURCES, &num_subroutines);

            const GLenum properties[] = { GL_NAME_LENGTH };
            const GLint properties_size = sizeof(properties) / sizeof(properties[0]);

            // 해당 셰이더에 얼만큼 크기의 서브루틴배열을 넘겨야 하는가??
            GLint count_subroutine_locations = 0;
            glGetProgramStageiv(m_ID, (GLenum)(shader_stages[i]), GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS, &count_subroutine_locations);
            m_subroutine_info_map[shader_stages[i]]
                .storage.resize(count_subroutine_locations);

            // location_map 채우기
            std::vector<std::string> uniform_names{};
            GLint count = 0;
            glGetProgramInterfaceiv(m_ID, program_interface, GL_ACTIVE_RESOURCES, &count);
            for (GLint i = 0; i < count; ++i) {
                char name[256];
                GLsizei length = 0;
                glGetProgramResourceName(
                    m_ID,
                    program_interface,
                    i,
                    sizeof(name),
                    &length,
                    name
                );
                uniform_names.push_back(std::string(name));
            }
            for (const auto& name : uniform_names) {
                GLuint location = glGetSubroutineUniformLocation(
                    m_ID,
                    (GLenum)(shader_stages[i]),
                    name.c_str()
                );

                m_subroutine_info_map[shader_stages[i]]
                    .location_map.at(name) = location;
            }

            // index_map 채우기
            for (GLint j = 0; j < num_subroutines; ++j) {
                GLint values[properties_size];
                GLint length = 0;
                glGetProgramResourceiv(m_ID, program_interface, j, properties_size, properties, properties_size, &length, values);

                std::vector<char> name_data(values[0]);
                glGetProgramResourceName(m_ID, program_interface, j, name_data.size(), nullptr, &name_data[0]);
                std::string subroutine_name(name_data.begin(), name_data.end() - 1);

                GLuint subroutine_index = glGetSubroutineIndex(m_ID, (GLenum)(shader_stages[i]), subroutine_name.c_str());

                m_subroutine_info_map[shader_stages[i]]
                    .index_map[subroutine_name] = subroutine_index;
            }
        }
    }
};

struct TextureDesc {
    FilterType MagFilter = FilterType::Linear;
    FilterType MinFilter = FilterType::Linear;
    WrappingType WrappingS = WrappingType::Repeat;
    WrappingType WrappingT = WrappingType::Repeat;
    WrappingType WrappingR = WrappingType::Repeat;
    InternalFormat FormatInternal = InternalFormat::RGBA8;
    PixelFormat FormatPixel = PixelFormat::RGBA;
    DataType FormatData = DataType::UnsignedByte;
    bool     MipmapGeneration = false;
    // 해당 텍스쳐의 밉맵을 몇 개나 생성할 건지.
    std::optional<int>   MipmapLevel = std::nullopt;
};


class Texture2D final {
private:
    mutable glm::uvec2 m_size{};
private:
    mutable TextureDesc m_desc{};
private:
    GLuint m_ID = 0;
public:
    Texture2D() {
        glCreateTextures(GL_TEXTURE_2D, 1, &m_ID);
    }
    ~Texture2D() {
        glDeleteTextures(1, &m_ID);
    }
public:
    void initialize_empty(const glm::uvec2& size, const TextureDesc& desc) const {
        m_size = size;
        m_desc = desc;

        // 밉맵 최대 레벨이 1이면 밉맵X, 기본 1개만 사용
        int mip_level_count = 1;
        if (desc.MipmapGeneration == true) {
            if (desc.MipmapLevel.has_value()) {
                mip_level_count = desc.MipmapLevel.value();
            }
            else {
                mip_level_count = 1 + static_cast<int>(std::floor(std::log2(std::max(size.x, size.y))));
            }
        }
        glTextureStorage2D(m_ID, mip_level_count,
            (GLenum)desc.FormatInternal,
            static_cast<int>(size.x), static_cast<int>(size.y)
        );

        glTextureParameteri(this->m_ID, GL_TEXTURE_MIN_FILTER, (GLenum)desc.MinFilter);
        glTextureParameteri(this->m_ID, GL_TEXTURE_MAG_FILTER, (GLenum)desc.MagFilter);
        glTextureParameteri(this->m_ID, GL_TEXTURE_WRAP_S, (GLenum)desc.WrappingS);
        glTextureParameteri(this->m_ID, GL_TEXTURE_WRAP_T, (GLenum)desc.WrappingT);

        glClearTexImage(m_ID, 0,
            (GLenum)desc.FormatPixel,
            (GLenum)desc.FormatData,
            nullptr
        );

        // 앞에서 0으로 mipmap레벨 0을 초기화했으므로
        //      이 명령은 유효하다
        if (desc.MipmapGeneration == true) {
            glGenerateTextureMipmap(m_ID);
        }
    }
    void initialize_by_bytes(const glm::uvec2& size, const void* data, const TextureDesc& desc) const {
        m_size = size;

        // 밉맵 최대 레벨이 1이면 밉맵X, 기본 1개만 사용
        int mip_level_count = 1;

        if (desc.MipmapGeneration == true) {
            if (desc.MipmapLevel.has_value()) {
                mip_level_count = desc.MipmapLevel.value();
            }
            else {
                mip_level_count = 1 + static_cast<int>(std::floor(std::log2(std::max(size.x, size.y))));
            }
        }

        glTextureStorage2D(m_ID, mip_level_count,
            (GLenum)desc.FormatInternal,
            static_cast<int>(size.x), static_cast<int>(size.y)
        );

        glTextureParameteri(m_ID, GL_TEXTURE_MIN_FILTER, (GLenum)desc.MinFilter);
        glTextureParameteri(m_ID, GL_TEXTURE_MAG_FILTER, (GLenum)desc.MagFilter);
        glTextureParameteri(m_ID, GL_TEXTURE_WRAP_S, (GLenum)desc.WrappingS);
        glTextureParameteri(m_ID, GL_TEXTURE_WRAP_T, (GLenum)desc.WrappingT);

        // 그냥 여기서 레벨 0만 초기화하고,
        //      glGenerateTextureMipmap()  불러주면 자동으로 채워짐.
        glTextureSubImage2D(
            m_ID,
            0, // 레벨 0만 초기화
            0, 0, // 오프셋
            static_cast<int>(size.x),
            static_cast<int>(size.y),
            (GLenum)desc.FormatPixel,
            (GLenum)desc.FormatData,
            data
        );

        if (desc.MipmapGeneration == true) {
            glGenerateTextureMipmap(m_ID);
        }
    }
public:
    void upload_sub_image(const glm::ivec2& offset, const glm::uvec2& mipmap_size, const int& mip_lvl, const void* ptr) const {

        // 이미 init이 되어 있다고 가정
        //      -> texStorage 이미 끝남....
        glTextureSubImage2D(
            m_ID,
            mip_lvl, // 타겟팅하는 밉맵 레벨
            offset.x, offset.y, // 오프셋
            static_cast<int>(mipmap_size.x), // 해당 밉맵 크기
            static_cast<int>(mipmap_size.y), // 해당 밉맵 크기
            (GLenum)m_desc.FormatPixel,
            (GLenum)m_desc.FormatData,
            ptr
        );
    }
public:
    void bind_unit(const uint32_t& slot) const {
        glBindTextureUnit(slot, m_ID);
    }
public:
    const GLuint& get_opengl_id() const { return m_ID; }
};

class Camera2D {
private:
    ViewMatrix2D m_view_mat{};
    ProjectionMatrix2D m_proj_mat{};
public:
    Camera2D() = default;
    ~Camera2D() = default;
public:
    void set_position(const glm::vec2& value) { m_view_mat.set_position(value); }
    void set_rotation(const float& value) { m_view_mat.set_rotation(value); }
    void set_zoom(const glm::vec2& value) { m_view_mat.set_zoom(value); }
    void set_frustrum_size(const glm::uvec2& value) { m_proj_mat.set_frustrum_size(value); }
public:
    const glm::vec2& get_position() const { return m_view_mat.get_position(); }
    const float& get_rotation() const { return m_view_mat.get_rotation(); }
    const glm::vec2& get_zoom() const { return m_view_mat.get_zoom(); }
    const glm::uvec2& get_frustrum_size()const { return m_proj_mat.get_frustrum_size(); }
public:
    const ViewMatrix2D& get_view_matrix() const { return m_view_mat; }
    const ProjectionMatrix2D& get_projection_matrix() const { return m_proj_mat; }
};

class Camera3D {
private:
    ViewMatrix3D m_view_mat{};
    ProjectionMatrix3D m_proj_mat{};
public:
    Camera3D() = default;
    ~Camera3D() = default;
public:
    void look_up(const float& value) { m_view_mat.add_pitch(value); }
    void look_right(const float& value) { m_view_mat.add_yaw(value); }
public:
    void set_position(const glm::vec3& value) { m_view_mat.set_position(value); }
    void set_frustrum_size(const glm::uvec2& value) { m_proj_mat.set_frustrum_size(value); }
    void set_fov(const float& value) { m_proj_mat.set_fov(value); }
public:
    glm::vec3 get_front_vector() const {
        return m_view_mat.get_front_vector();
    }
    glm::vec3 get_right_vector() const {
        return m_view_mat.get_right_vector();
    }
    glm::vec3 get_up_vector() const {
        return m_view_mat.get_up_vector();
    }
public:
    const glm::vec3& get_position() const { return m_view_mat.get_position(); }
    const glm::uvec2& get_frustrum_size()const { return m_proj_mat.get_frustrum_size(); }
    const float& get_fov()const { return m_proj_mat.get_fov(); }
public:
    const ViewMatrix3D& get_view_matrix() const { return m_view_mat; }
    const ProjectionMatrix3D& get_projection_matrix() const { return m_proj_mat; }
};

//float dt = 0.0f;
Camera3D cam3d{};

static void on_cursor(GLFWwindow* window, double xpos, double ypos) {
    static bool firstin = true;
    static glm::vec2 last{ 0, 0 };

    static glm::vec2 accel{};
    static glm::vec2 vel{};

    if (firstin) {
        last = { xpos, ypos };
        firstin = false;
        return;
    }

    glm::vec2 delta = { xpos - last.x, ypos - last.y };
    delta *= 0.001f;

    accel += delta;
    vel += accel;

    //cam3d.look_up(-delta.y * dt);
    //cam3d.look_right(delta.x * dt);
    //cam3d.look_up(-vel.y * dt);
    //cam3d.look_right(vel.x * dt);
    cam3d.look_up(-vel.y);
    cam3d.look_right(vel.x);

    vel *= 0.8f;
    accel = {};

    last = { xpos, ypos };
}

int main() {
    glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(1280, 720, "Camera and Quaternion", nullptr, nullptr);

    // 3D 카메라설정!!
    glfwSetCursorPosCallback(window, on_cursor);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    if (glfwRawMouseMotionSupported()) {
        glfwSetInputMode(window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
    }

    glfwMakeContextCurrent(window);
    assert(gladLoadGL() != 0);

    // 정점 데이터 (vec3 position + vec2 uv)
    BufferData vertices_data{}; {
        // Front (+Z)
        vertices_data.add_vec3({ -0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });

        // Back (-Z)
        vertices_data.add_vec3({ 0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });

        // Left (-X)
        vertices_data.add_vec3({ -0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });

        // Right (+X)
        vertices_data.add_vec3({ 0.5f,  0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f,  0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });

        // Top (+Y)
        vertices_data.add_vec3({ -0.5f, 0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, 0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, 0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, 0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });

        // Bottom (-Y)
        vertices_data.add_vec3({ -0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 0.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f,  0.5f }); vertices_data.add_vec2({ 1.0f, 1.0f });
        vertices_data.add_vec3({ 0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 1.0f, 0.0f });
        vertices_data.add_vec3({ -0.5f, -0.5f, -0.5f }); vertices_data.add_vec2({ 0.0f, 0.0f });
    }

    // 인덱스 데이터 (각 면 CCW)
    BufferData indices_data{}; {
        for (uint32_t i = 0; i < 6; ++i) {
            uint32_t base = i * 4;

            indices_data.add_uint32(base + 0);
            indices_data.add_uint32(base + 3);
            indices_data.add_uint32(base + 1);

            indices_data.add_uint32(base + 1);
            indices_data.add_uint32(base + 3);
            indices_data.add_uint32(base + 2);
        }
    }

    VertexArray va{};
    Buffer vb{}, eb{};

    vb.upload_data(vertices_data, BufferUsage::StaticDraw);
    eb.upload_data(indices_data, BufferUsage::StaticDraw);

    VertexLayout va_layout{}; {
        va_layout.push_attrib(DataType::Float, 3);
        va_layout.push_attrib(DataType::Float, 2);
    }

    va.bind_vertex_buffer(0, &vb, 0, va_layout);
    va.bind_element_buffer(&eb);

    ShaderProgram program{};
    program.attach_shader(ShaderType::Vertex, s_vertex_shader_src);
    program.attach_shader(ShaderType::Fragment, s_fragment_shader_src);
    program.link();
    program.register_uniform("uSize", UniformType::Vec3f);
    program.register_uniform("uProj", UniformType::Mat4f);
    program.register_uniform("uView", UniformType::Mat4f);
    program.register_uniform("uWorld", UniformType::Mat4f);
    program.register_uniform("uTexture", UniformType::Sampler2D);

    Texture2D tex{};
    {
        TextureDesc desc{ };
        int w{}, h{}, c{};
        stbi_set_flip_vertically_on_load(true);
        auto* data = stbi_load("C:/cat.png", &w, &h, &c, 0);
        assert(data != nullptr);
        assert(c == 4);

        tex.initialize_by_bytes({ w, h }, data, desc);

        stbi_image_free(data);
    }

    //ProjectionMatrix2D proj_mat{ {1280, 720}, -1.0f, 1.0f };
    //ViewMatrix2D view_mat{};
    //view_mat.set_position({ 640, 360 });
    //Transform2D world_mat{};
    //world_mat.set_position({ 640, 360 });

    //ProjectionMatrix3D proj_mat{ {1280, 720}, 0.1f, 1000.0f, glm::radians(45.0f) };
    //ViewMatrix3D view_mat{};
    //view_mat.set_position({ 0.0f, 0.0f, 100.0f });
    cam3d.set_fov(glm::radians(60.0f));
    cam3d.set_position({ 0.0f, 0.0f, 100.0f });

    Transform3D world_mat{};
    world_mat.set_position({ 0.0f, 0.0f, 0.0f });

    while (glfwWindowShouldClose(window) == false) {
        //static float last = 0.0f;
        //float current = static_cast<float>(glfwGetTime());
        //dt = (current - last);
        //last = current;

        glfwPollEvents();
        {
            // 카메라로
            float speed = 2.0f;
            if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() - cam3d.get_right_vector() * speed);
            }
            if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() + cam3d.get_right_vector() * speed);
            }
            if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() + cam3d.get_front_vector() * speed);
            }
            if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() - cam3d.get_front_vector() * speed);
            }
            if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() + cam3d.get_up_vector() * speed);
            }
            if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) {
                cam3d.set_position(cam3d.get_position() - cam3d.get_up_vector() * speed);
            }
        }
        {
            // 오일러각 쓴다면?
            //world_mat.set_rotation(world_mat.get_rotation() + glm::vec3(0.0f, 0.01f, 0.0f));

            // 쿼터니언으로, 회전을 누적해가기!
            auto q = glm::angleAxis(0.01f, glm::vec3{ 0.0f, 1.0f, 0.0f });
            world_mat.set_orientation(world_mat.get_orientation() * q);
        }
        {
            // 화면 초기화 색상을 초록색으로 정하고, 컬러 버퍼와 깊이 버퍼를 초기화합니다.
            glClearColor(0.2f, 0.3f, 0.1f, 1.0f);
            glClearDepth(1.0f);   // 깊이 버퍼 초기화 값을 1(가장 큰 뎁스)로.
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            glEnable(GL_DEPTH_TEST); // 뎁스 테스트 활성화
            glDepthFunc(GL_LESS); // 새 픽셀의 뎁스가 기존 뎁스보다 작을 경우 (더 앞에 있을 경우) 통과
            glDepthMask(GL_TRUE); // 뎁스 테스트 이후, 뎁스 쓰기(갱신)를 활성화

            glEnable(GL_CULL_FACE);  // 백페이스 컬링 활성화
            glFrontFace(GL_CCW); // 삼각형을 CCW 방향으로 묶은 면이 앞면
            glCullFace(GL_BACK); // 뒷면을 컬링


            // 정점 배열과 프로그램을 지정합니다.
            //     glDraw* 함수를 부르려면 이 두 코드가 꼭 필요합니다.
            va.bind();
            program.use();

            program.upload_uniform_vec3f("uSize", { 30.0f, 30.0f, 30.0f });
            program.upload_uniform_mat4f("uProj", cam3d.get_projection_matrix().get_matrix());
            program.upload_uniform_mat4f("uView", cam3d.get_view_matrix().get_matrix());
            program.upload_uniform_mat4f("uWorld", world_mat.get_matrix());
            tex.bind_unit(0);
            program.upload_uniform_sampler2d("uTexture", 0);

            // glDrawElements 는 인덱스 버퍼를 사용한다는 가정 하에 쓰이는 렌더 콜입니다.
            // 첫번째 인자 : 프리미티브를 지정합니다. 이 경우에서는 GL_TRIANGLES, 즉 삼각형을 그립니다.
            // 두번째 인자 : 인덱스의 개수를 지정합니다. 아까 인덱스 데이터의 개수는 3개였습니다.
            // 세번째 인자 : 인덱스 데이터의 형태를 지정합니다. 아까 인덱스 데이터의 형은 uint32_t 형이었습니다.
            // 네번째 인자 : 인덱스 데이터의 오프셋을 지정합니다. 보통은 0으로 둡니다.
            glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
        }
        glfwSwapBuffers(window);
    }

    glfwDestroyWindow(window);

    glfwTerminate();
}