Skybox
[opengl.git] / skybox.cpp
1 #include "shapes.hpp"
2 #include "skybox.hpp"
3 #include "image.hpp"
4 #include <GL/glew.h>
5 #include <glm/gtc/type_ptr.hpp>
6         
7 Skybox::Skybox(const std::vector<std::string> faces): program("skyboxvert.glsl", "skyboxfrag.glsl") {
8         glUseProgram(program.progId);
9         glGenTextures(1, &texId);
10         glBindTexture(GL_TEXTURE_CUBE_MAP, texId);
11
12         int width, height, numChans;
13         for (int i = 0; i < faces.size(); i++) {
14                 Image img(faces[i]);
15
16                 glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, img.width(), img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.data());
17         }
18
19         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
20         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
21         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
22         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
23         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
24
25         glGenVertexArrays(1, &vao);
26         glBindVertexArray(vao);
27
28         GLuint vbo;
29         glGenBuffers(1, &vbo);
30
31         auto vertices = cube();
32
33         glBindBuffer(GL_ARRAY_BUFFER, vbo);
34         glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
35         
36         GLuint posLoc = glGetAttribLocation(program.progId, "pos");
37         glEnableVertexAttribArray(posLoc);
38         glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
39 }
40 void validatePrograms(GLuint progId) {
41         glValidateProgram(progId);
42         
43         GLint success;
44         glGetProgramiv(progId, GL_VALIDATE_STATUS, &success);
45         if (!success) {
46                 GLchar log[1024];
47                 glGetProgramInfoLog(progId, sizeof(log), NULL, log);
48                 fprintf(stderr, "error: %s\n", log);
49                 exit(1);
50         }
51 }
52
53 void Skybox::draw(glm::mat4 proj, glm::mat4 view) const {
54         glUseProgram(program.progId);
55
56         glDepthMask(GL_FALSE);
57         glDisable(GL_CULL_FACE);
58         glBindVertexArray(vao);
59         validatePrograms(program.progId);
60
61         GLuint projLoc = glGetUniformLocation(program.progId, "projection");
62         glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
63
64         GLuint viewLoc = glGetUniformLocation(program.progId, "view");
65         view = glm::mat4(glm::mat3(view));
66         glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
67
68         glBindTexture(GL_TEXTURE_CUBE_MAP, texId);
69         glDrawArrays(GL_TRIANGLES, 0, 36);
70         glEnable(GL_CULL_FACE);
71         glDepthMask(GL_TRUE);
72 }