quick backup
[demo] / src / opengl / opengl.cc
1 #include <GL/glew.h>
2 #include <GLFW/glfw3.h>
3 #include <stdio.h>
4
5 #include "gfxapi.h"
6 #include "opengl/opengl.h"
7
8 extern GLFWwindow *win;
9 extern int win_h;
10 extern int win_w;
11
12 static void clear(float r, float g, float b);
13 static void viewport(int x, int y, int width, int height);
14 static void zbuffer(bool enable);
15 static void cull_face(Gfx_cull_face cf);
16 static void reshape(int width, int height) {}
17 static void wireframe(bool enable);
18
19 bool init_opengl()
20 {
21         if(!glfwInit()) {
22                 fprintf(stderr, "Failed to initialize GLFW.\n");
23                 return false;
24         }
25
26         glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
27         glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
28         glfwWindowHint(GLFW_SRGB_CAPABLE, GLFW_TRUE);
29
30         if(!(win = glfwCreateWindow(win_w, win_h, "glcow", 0, 0))) {
31                 fprintf(stderr, "Failed to create window.\n");
32                 return false;
33         }
34         glfwMakeContextCurrent(win);
35
36         glewInit();
37
38         glEnable(GL_DEPTH_TEST);
39         glEnable(GL_CULL_FACE);
40         glEnable(GL_FRAMEBUFFER_SRGB); // linear colorspace
41
42         gfx_clear = clear;
43         gfx_viewport = viewport;
44         gfx_zbuffer = zbuffer;
45         gfx_cull_face = cull_face;
46         gfx_reshape = reshape;
47         gfx_wireframe = wireframe;
48
49         // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
50         return true;
51 }
52
53 void cleanup_opengl()
54 {
55         if(win) {
56                 glfwDestroyWindow(win);
57         }
58         glfwTerminate();
59 }
60
61 static void clear(float r, float g, float b)
62 {
63         glClearColor(r, g, b, 1.0);
64         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
65 }
66
67 static void viewport(int x, int y, int width, int height)
68 {
69         glViewport(x, y, width, height);
70 }
71
72 static void zbuffer(bool enable)
73 {
74         if(enable)
75                 glEnable(GL_DEPTH_TEST);
76         else
77                 glDisable(GL_DEPTH_TEST);
78 }
79
80 static void cull_face(Gfx_cull_face cf)
81 {
82         switch(cf) {
83         case GFX_CULL_NONE:
84                 glDisable(GL_CULL_FACE);
85                 break;
86         case GFX_CULL_FRONT:
87                 glEnable(GL_CULL_FACE);
88                 glCullFace(GL_FRONT);
89                 break;
90         case GFX_CULL_BACK:
91                 glEnable(GL_CULL_FACE);
92                 glCullFace(GL_BACK);
93                 break;
94         }
95 }
96
97 static void wireframe(bool enabled)
98 {
99         if(enabled)
100                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
101         else
102                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
103 }