summary refs log tree commit diff
path: root/src/main.cpp
blob: ad6148e7c9cd42be0c34a9697c5ef0c12d364723 (plain)
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
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include "Window.hpp"
#include "Mesh.hpp"
#include "Binder.hpp"
#include "Shader/ShaderProgram.hpp"

#define APP_NAME "Meowcraft"

#define WINDOW_WIDTH 1000
#define WINDOW_HEIGHT 800

void run();
void render(MC::BindableMesh&);
void setup_gl();
void fix_macos_render(MC::Window&);

int main() {
    glfwInit();

    try {
        run();
    } catch (std::runtime_error& error) {
        std::cout << "An error occurred: " << error.what() << std::endl;
        glfwTerminate();
        return 1;
    }

    glfwTerminate();
    return 0;
}

void run() {
    MC::Window window(APP_NAME, WINDOW_WIDTH, WINDOW_HEIGHT);
    setup_gl();

    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

    MC::Mesh quad({
        {-0.5, -0.5, 0.0},
        {0.5, -0.5, 0.0},
        {-0.5, 0.5, 0.0},

        {0.5, 0.5, 0.0},
        {-0.5, 0.5, 0.0},
        {0.5, -0.5, 0.0},
    });

    auto mesh = MC::Binder::load(quad);

    MC::ShaderProgram program(MC::Shader::create_fragment(), MC::Shader::create_vertex());
    program.bind();

    while (!window.should_close()) {
        window.start_frame();

#ifdef __APPLE__
        fix_macos_render(window);
#endif

        if (window.key(GLFW_KEY_ESCAPE, GLFW_PRESS)) {
            window.close();
        }

        render(mesh);
    }
}

void render(MC::BindableMesh& mesh) {
    glClearColor(0.65f, 0.8f, 0.8f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    mesh.bind();
    glDrawArrays(GL_TRIANGLES, 0, mesh.size());
    mesh.unbind();
}

void setup_gl() {
    GLenum error;
    if ((error = glewInit()) != GLEW_OK) {
        std::string error_string(reinterpret_cast<const char*>(glewGetErrorString(error)));
        throw std::runtime_error("Failed to load GL functions: " + error_string);
    }
}

void fix_macos_render(MC::Window& window) {
    static bool moved = false;

    if(!moved) {
        int x, y;
        glfwGetWindowPos(window.get(), &x, &y);
        glfwSetWindowPos(window.get(), ++x, y);

        moved = true;
    }
}