summaryrefslogtreecommitdiffstats
path: root/src/main.c
blob: 0241e8f2f78854c05c7155bde00ebf995dbf1a3e (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
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
#define GL_SILENCE_DEPRECATION
#define GLFW_INCLUDE_GLCOREARB
#include <GLFW/glfw3.h>

#include <stdio.h>
#include <stdlib.h>

#include "shorthand.h"

//
// Callbacks.
//

void
glfw_error_callback(int error, const char* description) {
    (void)error;
    fprintf(stderr, "error: %s\n", description);
}

void
glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
    (void)mods;
    (void)scancode;
    if (action == GLFW_PRESS &&
            (key == GLFW_KEY_ESCAPE || key == GLFW_KEY_CAPS_LOCK)) {
        glfwSetWindowShouldClose(window, GLFW_TRUE);
    }
}

typedef struct Context {
    GLFWwindow *window;
    u32 gl_version_major;
    u32 gl_version_minor;
    s32 win_width;
    s32 win_height;
    char win_title[256];
    bool win_resizable;

    struct {
        f64 prev;
        f64 elapsed;
        size_t n_frames;
    } frame_time;
} Context;

u32
compile_program(Context *ctx, const char *vert_src, const char *frag_src) {
    // Compile vertex shader.
    u32 vert_shader = glCreateShader(GL_VERTEX_SHADER);
    {
        glShaderSource(vert_shader, 1, &vert_src, NULL);
        glCompileShader(vert_shader);
        int success = 0;
        glGetShaderiv(vert_shader, GL_COMPILE_STATUS, &success);
        if (!success) {
            fprintf(stderr, "error: vertex shader compilation failed\n");
            glfwDestroyWindow(ctx->window);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }
    }

    // Compile fragment shader.
    u32 frag_shader = glCreateShader(GL_FRAGMENT_SHADER);
    {
        glShaderSource(frag_shader, 1, &frag_src, NULL);
        glCompileShader(frag_shader);
        int success = 0;
        glGetShaderiv(vert_shader, GL_COMPILE_STATUS, &success);
        if (!success) {
            fprintf(stderr, "error: fragment shader compilation failed\n");
            glfwDestroyWindow(ctx->window);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }
    }

    // Link shader program.
    u32 program = glCreateProgram();
    {
        glAttachShader(program, vert_shader);
        glAttachShader(program, frag_shader);
        glLinkProgram(program);
        int success = 0;
        glGetProgramiv(program, GL_LINK_STATUS, &success);
        if(!success) {
            fprintf(stderr, "error: program shader linking failed\n");
            glfwDestroyWindow(ctx->window);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }
    }

    // Delete unused objects.
    glDeleteShader(vert_shader);
    glDeleteShader(frag_shader);
    return program;
}

void
init_context(Context *ctx) {
    if (!glfwInit()) {
        fprintf(stderr, "error: GLFW initialization failed");
        exit(EXIT_FAILURE);
    }

    // Init window and OpenGL context.
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, ctx->gl_version_major);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, ctx->gl_version_minor);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_RESIZABLE, ctx->win_resizable);
    GLFWwindow* window = glfwCreateWindow(
        ctx->win_width, ctx->win_height, ctx->win_title, NULL, NULL);
    if (!window) {
        fprintf(stderr, "error: couldn't open OpenGL window");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    // Enable current OpenGL context and init GLAD.
    glfwMakeContextCurrent(window);
    // TODO: Working on macOS for now, need to check if this is needed.
    // if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    //     fprintf(stderr, "error: GLAD initialization failed");
    //     glfwDestroyWindow(window);
    //     glfwTerminate();
    //     exit(EXIT_FAILURE);
    // }

    ctx->window = window;
}

void
init_debug_overlay(Context *ctx) {
    // TODO: Add debug text to context and initialize here
    (void)ctx;
}

void
setup_callbacks(Context *ctx) {
    glfwSetErrorCallback(glfw_error_callback);
    glfwSetKeyCallback(ctx->window, glfw_key_callback);
}

void
update_frame_time(Context *ctx) {
    // Measure frame times and fps.
    f64 cur_time = glfwGetTime();
    f64 delta_time = cur_time - ctx->frame_time.prev;
    ctx->frame_time.elapsed += delta_time;
    ctx->frame_time.n_frames++;
    if (ctx->frame_time.elapsed >= 1.0) {
        f64 fps = 0;
        fps = ctx->frame_time.n_frames / ctx->frame_time.elapsed;
        ctx->frame_time.elapsed = 0;
        ctx->frame_time.n_frames = 0;

        // Update title with timing data.
        char title_buf[256 * 2];
        sprintf(title_buf,
                "%s [%.2fms, %.2f FPS]",
                ctx->win_title, delta_time * 1000, fps);
        glfwSetWindowTitle(ctx->window, title_buf);
    }
    ctx->frame_time.prev = cur_time;
}

void
update(Context *ctx) {
    update_frame_time(ctx);
}

void
render(Context *ctx) {
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glfwGetFramebufferSize(ctx->window, &ctx->win_width, &ctx->win_height);
    glViewport(0, 0, ctx->win_width, ctx->win_height);


    // TODO: Only need to be done once on the initialization function.
    // Prepare quad rendering.
    f32 vertices[] = {
        // position    // tex_coords
         1.0f,  1.0f,  1.0f, 1.0f,
         1.0f, -1.0f,  1.0f, 0.0f,
        -1.0f, -1.0f,  0.0f, 0.0f,
        -1.0f,  1.0f,  0.0f, 1.0f,
    };
    GLuint indices[] = {
        0, 1, 3,
        1, 2, 3
    };

    // Vertex array object.
    u32 vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    // Vertex buffer object setup.
    u32 vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(f32), (void*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(f32), (void*)(2 * sizeof(f32)));

    // Element buffer object setup.
    u32 ebo;
    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    // Texture atlas.
    u8 texture[] = {
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
    };
    u32 tex_id;
    glGenTextures(1, &tex_id);
    glBindTexture(GL_TEXTURE_2D, tex_id);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, 16, 8, 0, GL_RED,
            GL_UNSIGNED_BYTE, &texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glBindTexture(GL_TEXTURE_2D, 0);

    // Unbind objects to avoid accidental modifications.
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    const char* vert_src =
"#version 330 core\n"
"layout (location = 0) in vec2 position;\n"
"layout (location = 1) in vec2 tex_coords;\n"
"out vec2 tex;\n"
"void main() {\n"
"    gl_Position = vec4(position.x, position.y, 0.0, 1.0);\n"
"    tex = tex_coords;\n"
"}";

    // Fragment shader.
    const char* frag_src =
"#version 330 core\n"
"in vec2 tex;\n"
"out vec4 frag;\n"
"uniform usampler2D tex_sampler;\n"
"void main() {\n"
"    uint val = texture(tex_sampler, tex).r;\n"
"    frag = vec4(val, val, val, 1.0);\n"
"}\n";

    u32 program = compile_program(ctx, vert_src, frag_src);

    glUseProgram(program);
    glBindVertexArray(vao);
    glBindTexture(GL_TEXTURE_2D, tex_id);

    // TODO: How to pass the parameters for each box?
    // NOTE: We want to render the text as a single draw call if possible.
    // glEnable(GL_BLEND);
    // glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    // // glBlendFunc(GL_ONE, GL_ONE);
    // // glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
    // // glBlendFunc(GL_SRC_ALPHA, GL_ONE);
    // // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    // // glBlendFunc(GL_ONE, GL_ZERO);
    // // glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    // // glBlendFunc(GL_DST_ALPHA,GL_ONE);
    // // glBlendFunc(GL_DST_ALPHA, GL_SRC_ALPHA);
    // // glBlendFunc(GL_DST_ALPHA, GL_DST_ALPHA);
    // // glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
    // // glBlendEquation(GL_FUNC_ADD);
    //
    // glBindTexture(GL_TEXTURE_2D, text_tex); // TODO: Bind the texture atlas.
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    // glDisable(GL_BLEND);

    glfwSwapBuffers(ctx->window);
}

int
main(void) {

    //
    // Initialization.
    //

    Context ctx = (Context){
        .gl_version_major = 3,
        .gl_version_minor = 2,
        .win_width = 800,
        .win_height = 600,
        .win_title = "OpenGL experiments",
    };
    init_context(&ctx);
    setup_callbacks(&ctx);
    init_debug_overlay(&ctx);

    //
    // Main loop.
    //

    ctx.frame_time.prev = glfwGetTime();
    ctx.frame_time.elapsed = 0;
    ctx.frame_time.n_frames = 0;
    while (!glfwWindowShouldClose(ctx.window)) {
        update(&ctx);
        render(&ctx);
        glfwPollEvents(); // constant updates.
        // glfwWaitEvents(); // updates only when input arrives (better cpu usage).
    }

    glfwDestroyWindow(ctx.window);
    glfwTerminate();
    return EXIT_SUCCESS;
}