-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
323 lines (254 loc) · 10.3 KB
/
main.cpp
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
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <format>
#include <Transformations.h>
#include <GL/glew.h>
#include <SDL3/SDL_keyboard.h>
#include <SDL3/SDL_init.h>
#include "Camera.h"
#include "AppData.h"
#include "InputHandling.h"
#include "data/cube.h"
#include "Matrix4D.h"
const std::string LOCAL_FILE_DIR("data/");
// Vertex Shader source code
std::string FindFileOrThrow(const std::string &strBasename, const std::string &program_id) {
std::string strFilename = LOCAL_FILE_DIR + program_id + '/' + strBasename;
const std::ifstream testFile(strFilename.c_str());
if (testFile.is_open())
return strFilename;
std::cerr << "Could not find the file " + strBasename + " for program with id : " + program_id;
throw;
}
// Function to compile shaders
unsigned int compileShader(unsigned int type, const std::string &source) {
const unsigned int id = glCreateShader(type);
auto source_c_str = source.c_str();
glShaderSource(id, 1, &source_c_str, nullptr);
glCompileShader(id);
int success;
glGetShaderiv(id, GL_COMPILE_STATUS, &success);
if (!success) {
char infoLog[512];
glGetShaderInfoLog(id, 512, nullptr, infoLog);
std::cerr << "Shader compilation failed\n" << infoLog << std::endl;
}
return id;
}
GLuint LoadShader(const GLenum eShaderType, const std::string &strShaderFilename, const std::string &programId) {
const std::string strFilename = FindFileOrThrow(strShaderFilename, programId);
std::ifstream shaderFile(strFilename.c_str());
std::stringstream shaderData;
shaderData << shaderFile.rdbuf();
shaderFile.close();
try {
return compileShader(eShaderType, shaderData.str());
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
throw;
}
}
// Function to link vertex and fragment shaders into a program
unsigned int InitializeProgram(const std::string &program_id) {
std::vector<GLuint> shaders;
shaders.push_back(LoadShader(GL_FRAGMENT_SHADER, "frag.frag", program_id));
shaders.push_back(LoadShader(GL_VERTEX_SHADER, "vert.vert", program_id));
GLuint shaderProgram = glCreateProgram();
std::ranges::for_each(shaders, [shaderProgram](const GLuint &s_id) {
glAttachShader(shaderProgram, s_id);
});
glLinkProgram(shaderProgram);
int success;
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
char infoLog[512];
glGetProgramInfoLog(shaderProgram, 512, nullptr, infoLog);
std::cerr << "Shader linking failed\n" << infoLog << std::endl;
}
std::ranges::for_each(shaders,glDeleteShader);
return shaderProgram;
}
float normalize_coord(const float value, const float max) {
return 2 * value / max - 1;
}
void handle_window_resize(AppData &app_data, const int width, const int height) {
const float new_aspect_ratio = static_cast<float>(width) / static_cast<float>(height);
PerspectiveMatrixUpdate(app_data.perspective_matrix, app_data.FOV, new_aspect_ratio);
app_data.view_dirty = true;
glViewport(0, 0, width, height);
}
void Draw_Cursor(unsigned int cursorProgram, unsigned int cursor_vao) {
glUseProgram(cursorProgram);
glBindVertexArray(cursor_vao);
glDrawArrays(GL_LINES, 0, 8);
glBindVertexArray(0);
glUseProgram(0);
}
void InitializeCursorVBO(const std::array<float, 8> &cursor, unsigned int &cursor_vao, unsigned int &cursor_vbo) {
glGenVertexArrays(1, &cursor_vao);
glGenBuffers(1, &cursor_vbo);
glBindVertexArray(cursor_vao);
// Bind and set VBO
glBindBuffer(GL_ARRAY_BUFFER, cursor_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * cursor.size(), cursor.data(), GL_STATIC_DRAW);
// Define the vertex attributes (position)
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), nullptr);
glEnableVertexAttribArray(0);
// Unbind the VAO
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
int main() {
// Initialize GLFW
if (!SDL_Init(SDL_INIT_VIDEO)) {
std::cerr << SDL_GetError() << std::endl;
return -1;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
constexpr int screenWidth = 800, screenHeight = 600;
// Create window
SDL_Window *window = SDL_CreateWindow("Hello World - VAO and VBO", screenWidth, screenHeight,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!window) {
std::cerr << "Failed to create SDL window. Error :" << SDL_GetError() << std::endl;
SDL_Quit();
return -1;
}
SDL_GLContext open_gl_context = SDL_GL_CreateContext(window);
if (!open_gl_context) {
std::cerr << "Failed to create OpenGL context. Error : " << SDL_GetError() << std::endl;
SDL_DestroyWindow(window);
SDL_Quit();
return -1;
}
// Enable VSync
SDL_GL_SetSwapInterval(1);
GLenum err = glewInit();
if (err != GLEW_OK) {
std::cerr << "glewInitFailed: " << glewGetErrorString(err) << std::endl;
SDL_GL_DestroyContext(open_gl_context);
SDL_DestroyWindow(window);
SDL_Quit();
return -1;
}
Matrix4D world_space_matrix(1);
world_space_matrix[1] = Vector4D(0, 0, 1, 0);
world_space_matrix[2] = Vector4D(0, -1, 0, 0);
world_space_matrix = translate(world_space_matrix, Vector3D(0, 4, 0));
AppData appData;
appData.view_dirty = true;
appData.FOV = 45;
appData.perspective_matrix = PerspectiveMatrix(appData.FOV, 0.1f, 100.f,
static_cast<float>(screenWidth) / static_cast<float>(screenHeight));
appData.camera_matrix = CameraLookAtMatrix(appData.camera);
Matrix4D triangle_model_view_space(1);
appData.view_projection_matrix = appData.perspective_matrix * appData.camera_matrix * world_space_matrix *
triangle_model_view_space;
glViewport(0, 0, 800, 600);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LEQUAL);
glDepthRange(0.0f, 1.0f);
// Build and compile shader program
unsigned int shaderProgram = InitializeProgram("program1");
unsigned int cursorProgram = InitializeProgram("cursor_program");
GLint perspectiveMatrixUnif = glGetUniformLocation(shaderProgram, "perspectiveMatrix");
GLint cursor_color_uniform = glGetUniformLocation(cursorProgram, "cursor_color");
GLint voxel_color = glGetUniformLocation(shaderProgram, "voxel_color");
Vector4D color(1, 0, 0, 1);
glUseProgram(cursorProgram);
glUniform4fv(cursor_color_uniform, 1, &color.x);
cube my_cube;
float centerX = static_cast<float>(screenWidth) / 2.0f;
float centerY = static_cast<float>(screenHeight) / 2.0f;
std::array cursor{
normalize_coord(centerX - 10, static_cast<float>(screenWidth)),
normalize_coord(centerY, static_cast<float>(screenHeight)),
normalize_coord(centerX + 10, static_cast<float>(screenWidth)),
normalize_coord(centerY, static_cast<float>(screenHeight)),
normalize_coord(centerX, static_cast<float>(screenWidth)),
normalize_coord(centerY - 10, static_cast<float>(screenHeight)),
normalize_coord(centerX, static_cast<float>(screenWidth)),
normalize_coord(centerY + 10, static_cast<float>(screenHeight))
};
glUseProgram(shaderProgram);
constexpr Vector4D r(0.5, 0.5, 0.5, 1);
glUniform4fv(voxel_color, 1, &r.x);
glUniformMatrix4fv(perspectiveMatrixUnif, 1,GL_FALSE, &appData.view_projection_matrix[0].x);
GLuint world_vao;
glGenVertexArrays(1, &world_vao);
glBindVertexArray(world_vao);
GLuint cubes_vbo;
glGenBuffers(1, &cubes_vbo);
glBindBuffer(GL_ARRAY_BUFFER, cubes_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(my_cube.vertex_data), my_cube.vertex_data, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
GLuint cubes_vbe;
glGenBuffers(1, &cubes_vbe);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cubes_vbe);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(my_cube.vertex_indices), my_cube.vertex_indices, GL_STATIC_DRAW);
glBindVertexArray(0);
unsigned int cursor_vao;
unsigned int cursor_vbo;
InitializeCursorVBO(cursor, cursor_vao, cursor_vbo);
bool keepRunning = true;
// Rendering loop
while (keepRunning) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_EVENT_WINDOW_RESIZED: {
handle_window_resize(appData, event.window.data1, event.window.data2);
break;
}
case SDL_EVENT_WINDOW_CLOSE_REQUESTED: {
keepRunning = false;
break;
}
case SDL_EVENT_KEY_DOWN: {
KeyDown(event.key.scancode, appData);
break;
}
default: {
break;
}
}
}
// Clear the screen
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(world_vao);
if (appData.view_dirty) {
appData.view_projection_matrix = appData.perspective_matrix * appData.camera_matrix * world_space_matrix
* triangle_model_view_space;
glUniformMatrix4fv(perspectiveMatrixUnif, 1,GL_FALSE, &appData.view_projection_matrix[0].x);
appData.view_dirty = false;
}
glDrawElements(GL_TRIANGLES, 36,GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glUseProgram(0);
Draw_Cursor(cursorProgram, cursor_vao);
SDL_GL_SwapWindow(window);
}
// Cleanup
glDeleteVertexArrays(1, &world_vao);
glDeleteBuffers(1, &cubes_vbo);
glDeleteVertexArrays(1, &cursor_vao);
glDeleteBuffers(1, &cursor_vbo);
SDL_DestroyWindow(window);
SDL_GL_DestroyContext(open_gl_context);
SDL_Quit();
return 0;
}