source: opengl-game/new-game.cpp@ 93462c6

feature/imgui-sdl points-test
Last change on this file since 93462c6 was 93462c6, checked in by Dmitry Portnoy <dmp1488@…>, 6 years ago

-Create State and Event enums
-Create the main menu and game states
-Create renderScene() and renderGui() functions for each state
-Create the main menu UI and hook up the event handlers to enable

switching between the main menu and game states

  • Property mode set to 100644
File size: 30.9 KB
RevLine 
[22b2c37]1#include "logger.h"
[5272b6b]2
[485424b]3#include "stb_image.h"
4
[4e0b82b]5// I think this was for the OpenGL 4 book font file tutorial
6//#define STB_IMAGE_WRITE_IMPLEMENTATION
7//#include "stb_image_write.h"
8
[1099b95]9#define _USE_MATH_DEFINES
[c62eee6]10#define GLM_SWIZZLE
[1099b95]11
[5c9d193]12// This is to fix a non-alignment issue when passing vec4 params.
13// Check if it got fixed in a later version of GLM
14#define GLM_FORCE_PURE
15
[c62eee6]16#include <glm/mat4x4.hpp>
[7ee66ea]17#include <glm/gtc/matrix_transform.hpp>
18#include <glm/gtc/type_ptr.hpp>
19
[c1ca5b5]20#include "IMGUI/imgui.h"
21#include "imgui_impl_glfw_gl3.h"
22
[5272b6b]23#include <GL/glew.h>
24#include <GLFW/glfw3.h>
25
[22b2c37]26#include <cstdio>
27#include <iostream>
[ec4456b]28#include <fstream>
[93baa0e]29#include <cmath>
[1099b95]30#include <string>
[19c9338]31#include <array>
[df652d5]32#include <vector>
[93462c6]33#include <queue>
[22b2c37]34
[5272b6b]35using namespace std;
[7ee66ea]36using namespace glm;
37
38#define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444
[c62eee6]39
[df652d5]40struct SceneObject {
[d9f99b2]41 unsigned int id;
[df652d5]42 mat4 model_mat;
[baa5848]43 GLuint shader_program;
[05e43cf]44 unsigned int num_points;
[07ed460]45 GLvoid* vertex_vbo_offset;
46 GLvoid* texture_vbo_offset;
47 vector<GLfloat> points;
48 vector<GLfloat> colors;
49 vector<GLfloat> texcoords;
[9dd2eb7]50 vector<GLfloat> normals;
[07ed460]51 vector<GLfloat> selected_colors;
[df652d5]52};
53
[93462c6]54enum State {
55 STATE_MAIN_MENU,
56 STATE_GAME,
57};
58
59enum Event {
60 EVENT_GO_TO_MAIN_MENU,
61 EVENT_GO_TO_GAME,
62 EVENT_QUIT,
63};
64
[485424b]65const bool FULLSCREEN = false;
[c62eee6]66int width = 640;
67int height = 480;
68
[c1ca5b5]69double fps;
70
[c62eee6]71vec3 cam_pos;
72
73mat4 view_mat;
74mat4 proj_mat;
[5272b6b]75
[df652d5]76vector<SceneObject> objects;
[93462c6]77queue<Event> events;
[df652d5]78
[147ac6d]79SceneObject* clickedObject = NULL;
[baa5848]80SceneObject* selectedObject;
[147ac6d]81
[c1ca5b5]82float NEAR_CLIP = 0.1f;
83float FAR_CLIP = 100.0f;
84
[5b3462b]85// Should really have some array or struct of UI-related variables
86bool isRunning = true;
87
[c1ca5b5]88ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
[046ce72]89
[d9f99b2]90bool faceClicked(array<vec3, 3> points, SceneObject* obj, vec4 world_ray, vec4 cam, vec4& click_point);
[5c9d193]91bool insideTriangle(vec3 p, array<vec3, 3> triangle_points);
[33a9664]92
[ec4456b]93GLuint loadShader(GLenum type, string file);
[485424b]94GLuint loadShaderProgram(string vertexShaderPath, string fragmentShaderPath);
95unsigned char* loadImage(string file_name, int* x, int* y);
[ec4456b]96
[d12d003]97void printVector(string label, vec3 v);
[b73cb3b]98void print4DVector(string label, vec4 v);
[d12d003]99
[93462c6]100void renderMainMenu();
101void renderMainMenuGui();
102
103void renderScene(vector<SceneObject>& objects,
104 GLuint shader_program1, GLuint shader_program2,
105 GLuint vao1, GLuint vao2,
106 GLuint shader1_mat_loc, GLuint shader2_mat_loc,
107 GLuint points_vbo, GLuint normals_vbo,
108 GLuint colors_vbo, GLuint texcoords_vbo, GLuint selected_colors_vbo,
109 SceneObject* selectedObject);
110void renderSceneGui();
[d12d003]111
[ec4456b]112void glfw_error_callback(int error, const char* description) {
113 gl_log_err("GLFW ERROR: code %i msg: %s\n", error, description);
114}
115
[c62eee6]116void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
[33a9664]117 double mouse_x, mouse_y;
118 glfwGetCursorPos(window, &mouse_x, &mouse_y);
119
120 if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
121 cout << "Mouse clicked (" << mouse_x << "," << mouse_y << ")" << endl;
[147ac6d]122 selectedObject = NULL;
[33a9664]123
124 float x = (2.0f*mouse_x) / width - 1.0f;
125 float y = 1.0f - (2.0f*mouse_y) / height;
[d12d003]126
[33a9664]127 cout << "x: " << x << ", y: " << y << endl;
128
[b73cb3b]129 vec4 ray_clip = vec4(x, y, -1.0f, 1.0f);
130 vec4 ray_eye = inverse(proj_mat) * ray_clip;
131 ray_eye = vec4(ray_eye.xy(), -1.0f, 1.0f);
[5c9d193]132 vec4 ray_world = inverse(view_mat) * ray_eye;
[33a9664]133
[b73cb3b]134 vec4 cam_pos_temp = vec4(cam_pos, 1.0f);
[33a9664]135
[e82692b]136 vec4 click_point;
[b73cb3b]137 vec3 closest_point = vec3(0.0f, 0.0f, -FAR_CLIP); // Any valid point will be closer than the far clipping plane, so initial value to that
[d9f99b2]138 SceneObject* closest_object = NULL;
139
140 SceneObject* obj;
141 for (vector<SceneObject>::iterator it = objects.begin(); it != objects.end(); it++) {
142 obj = &*it;
143
[4e0b82b]144 for (unsigned int p_idx = 0; p_idx < it->points.size(); p_idx += 9) {
[d9f99b2]145 if (faceClicked({
146 vec3(it->points[p_idx], it->points[p_idx + 1], it->points[p_idx + 2]),
147 vec3(it->points[p_idx + 3], it->points[p_idx + 4], it->points[p_idx + 5]),
148 vec3(it->points[p_idx + 6], it->points[p_idx + 7], it->points[p_idx + 8]),
149 },
150 obj, ray_world, cam_pos_temp, click_point)) {
151 click_point = view_mat * click_point;
152
153 if (-NEAR_CLIP >= click_point.z && click_point.z > -FAR_CLIP && click_point.z > closest_point.z) {
154 closest_point = click_point.xyz();
155 closest_object = obj;
156 }
[e82692b]157 }
[5c9d193]158 }
159 }
[d12d003]160
[d9f99b2]161 if (closest_object == NULL) {
[5c9d193]162 cout << "No object was clicked" << endl;
[e82692b]163 } else {
[d9f99b2]164 clickedObject = closest_object;
165 cout << "Clicked object: " << clickedObject->id << endl;
[147ac6d]166 }
[c62eee6]167 }
168}
169
[c1ca5b5]170int main(int argc, char* argv[]) {
[5272b6b]171 cout << "New OpenGL Game" << endl;
172
[ec4456b]173 if (!restart_gl_log()) {}
174 gl_log("starting GLFW\n%s\n", glfwGetVersionString());
[22b2c37]175
[ec4456b]176 glfwSetErrorCallback(glfw_error_callback);
[5272b6b]177 if (!glfwInit()) {
178 fprintf(stderr, "ERROR: could not start GLFW3\n");
179 return 1;
[be246ad]180 }
181
182#ifdef __APPLE__
183 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
184 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
185 glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
186 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
187#endif
[5272b6b]188
[ec4456b]189 glfwWindowHint(GLFW_SAMPLES, 4);
190
191 GLFWwindow* window = NULL;
[e856d62]192 GLFWmonitor* mon = NULL;
[ec4456b]193
194 if (FULLSCREEN) {
[e856d62]195 mon = glfwGetPrimaryMonitor();
[ec4456b]196 const GLFWvidmode* vmode = glfwGetVideoMode(mon);
197
198 width = vmode->width;
199 height = vmode->height;
[e856d62]200 cout << "Fullscreen resolution " << vmode->width << "x" << vmode->height << endl;
[ec4456b]201 }
[e856d62]202 window = glfwCreateWindow(width, height, "New OpenGL Game", mon, NULL);
[ec4456b]203
[5272b6b]204 if (!window) {
205 fprintf(stderr, "ERROR: could not open window with GLFW3\n");
206 glfwTerminate();
207 return 1;
208 }
[c62eee6]209
[644a2e4]210 glfwMakeContextCurrent(window);
[5272b6b]211 glewExperimental = GL_TRUE;
212 glewInit();
213
[c1ca5b5]214 // Setup Dear ImGui binding
215 IMGUI_CHECKVERSION();
216 ImGui::CreateContext();
217 ImGuiIO& io = ImGui::GetIO(); (void)io;
218 //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
219 //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
220 ImGui_ImplGlfwGL3_Init(window, true);
221
222 // Setup style
223 ImGui::StyleColorsDark();
224 //ImGui::StyleColorsClassic();
225
226 glfwSetMouseButtonCallback(window, mouse_button_callback);
227
[5272b6b]228 const GLubyte* renderer = glGetString(GL_RENDERER);
229 const GLubyte* version = glGetString(GL_VERSION);
230 printf("Renderer: %s\n", renderer);
231 printf("OpenGL version supported %s\n", version);
[93baa0e]232
[5272b6b]233 glEnable(GL_DEPTH_TEST);
234 glDepthFunc(GL_LESS);
[516668e]235
[93baa0e]236 glEnable(GL_CULL_FACE);
237 // glCullFace(GL_BACK);
238 // glFrontFace(GL_CW);
239
[485424b]240 int x, y;
241 unsigned char* texImage = loadImage("test.png", &x, &y);
242 if (texImage) {
243 cout << "Yay, I loaded an image!" << endl;
244 cout << x << endl;
245 cout << y << endl;
[e856d62]246 printf("first 4 bytes are: %i %i %i %i\n", texImage[0], texImage[1], texImage[2], texImage[3]);
[485424b]247 }
248
249 GLuint tex = 0;
250 glGenTextures(1, &tex);
251 glActiveTexture(GL_TEXTURE0);
252 glBindTexture(GL_TEXTURE_2D, tex);
253 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, texImage);
254
255 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
256 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
257 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
258 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
259
[07ed460]260 mat4 T_model, R_model;
261
262 // triangle
263 objects.push_back(SceneObject());
[d9f99b2]264 objects[0].id = 0;
[07ed460]265 objects[0].shader_program = 0;
266 objects[0].vertex_vbo_offset = (GLvoid*) (0 * sizeof(float) * 3);
267 objects[0].texture_vbo_offset = (GLvoid*)(0 * sizeof(float) * 2);
268 objects[0].points = {
[d12d003]269 0.0f, 0.5f, 0.0f,
270 -0.5f, -0.5f, 0.0f,
271 0.5f, -0.5f, 0.0f,
272 0.5f, -0.5f, 0.0f,
273 -0.5f, -0.5f, 0.0f,
274 0.0f, 0.5f, 0.0f,
[516668e]275 };
[07ed460]276 objects[0].colors = {
277 1.0f, 0.0f, 0.0f,
278 0.0f, 0.0f, 1.0f,
279 0.0f, 1.0f, 0.0f,
280 0.0f, 1.0f, 0.0f,
281 0.0f, 0.0f, 1.0f,
282 1.0f, 0.0f, 0.0f,
[93baa0e]283 };
[07ed460]284 objects[0].texcoords = {
285 1.0f, 1.0f,
286 0.0f, 1.0f,
287 0.0f, 0.0f,
288 1.0f, 1.0f,
289 0.0f, 0.0f,
290 1.0f, 0.0f
[33a9664]291 };
[9dd2eb7]292 objects[0].normals = {
293 0.0f, 0.0f, 1.0f,
294 0.0f, 0.0f, 1.0f,
295 0.0f, 0.0f, 1.0f,
296 0.0f, 0.0f, -1.0f,
297 0.0f, 0.0f, -1.0f,
298 0.0f, 0.0f, -1.0f,
299 };
[07ed460]300 objects[0].selected_colors = {
301 0.0f, 1.0f, 0.0f,
302 0.0f, 1.0f, 0.0f,
303 0.0f, 1.0f, 0.0f,
304 0.0f, 1.0f, 0.0f,
305 0.0f, 1.0f, 0.0f,
306 0.0f, 1.0f, 0.0f,
307 };
308 objects[0].num_points = objects[0].points.size() / 3;
309
310 T_model = translate(mat4(), vec3(0.45f, 0.0f, 0.0f));
311 R_model = rotate(mat4(), 0.0f, vec3(0.0f, 1.0f, 0.0f));
312 objects[0].model_mat = T_model*R_model;
[33a9664]313
[07ed460]314 // square
315 objects.push_back(SceneObject());
[d9f99b2]316 objects[1].id = 1;
[07ed460]317 objects[1].shader_program = 0;
318 objects[1].vertex_vbo_offset = (GLvoid*) (6 * sizeof(float) * 3);
319 objects[1].texture_vbo_offset = (GLvoid*)(6 * sizeof(float) * 2);
320 objects[1].points = {
[b73cb3b]321 0.5f, 0.5f, 0.0f,
[d12d003]322 -0.5f, 0.5f, 0.0f,
323 -0.5f, -0.5f, 0.0f,
[b73cb3b]324 0.5f, 0.5f, 0.0f,
[d12d003]325 -0.5f, -0.5f, 0.0f,
[b73cb3b]326 0.5f, -0.5f, 0.0f,
[64a70f4]327 };
[07ed460]328 objects[1].colors = {
329 1.0f, 0.0f, 0.0f,
330 0.0f, 0.0f, 1.0f,
331 0.0f, 1.0f, 0.0f,
332 0.0f, 1.0f, 0.0f,
333 0.0f, 0.0f, 1.0f,
334 1.0f, 0.0f, 0.0f,
[485424b]335 };
[07ed460]336 objects[1].texcoords = {
[64a70f4]337 1.0f, 1.0f,
338 0.0f, 1.0f,
[07ed460]339 0.0f, 0.0f,
340 1.0f, 1.0f,
341 0.0f, 0.0f,
342 1.0f, 0.0f
[485424b]343 };
[9dd2eb7]344 objects[1].normals = {
345 0.0f, 0.0f, 1.0f,
346 0.0f, 0.0f, 1.0f,
347 0.0f, 0.0f, 1.0f,
348 0.0f, 0.0f, 1.0f,
349 0.0f, 0.0f, 1.0f,
350 0.0f, 0.0f, 1.0f,
351 };
[07ed460]352 objects[1].selected_colors = {
[9f4986b]353 0.0f, 0.6f, 0.9f,
354 0.0f, 0.6f, 0.9f,
355 0.0f, 0.6f, 0.9f,
356 0.0f, 0.6f, 0.9f,
357 0.0f, 0.6f, 0.9f,
358 0.0f, 0.6f, 0.9f,
[19c9338]359 };
[07ed460]360 objects[1].num_points = objects[1].points.size() / 3;
[df652d5]361
[b73cb3b]362 T_model = translate(mat4(), vec3(-0.5f, 0.0f, -1.00f));
363 R_model = rotate(mat4(), 0.5f, vec3(0.0f, 1.0f, 0.0f));
[df652d5]364 objects[1].model_mat = T_model*R_model;
365
[07ed460]366 vector<SceneObject>::iterator obj_it;
367 GLsizeiptr offset;
[19c9338]368
[07ed460]369 GLsizeiptr points_buffer_size = 0;
370 GLsizeiptr textures_buffer_size = 0;
371
372 for (obj_it = objects.begin(); obj_it != objects.end(); obj_it++) {
373 points_buffer_size += obj_it->points.size() * sizeof(GLfloat);
374 textures_buffer_size += obj_it->texcoords.size() * sizeof(GLfloat);
375 }
[19c9338]376
[8b7cfcf]377 GLuint points_vbo = 0;
378 glGenBuffers(1, &points_vbo);
379 glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
[07ed460]380 glBufferData(GL_ARRAY_BUFFER, points_buffer_size, NULL, GL_DYNAMIC_DRAW);
[05e43cf]381
[07ed460]382 offset = 0;
383 for (obj_it = objects.begin(); obj_it != objects.end(); obj_it++) {
384 glBufferSubData(GL_ARRAY_BUFFER, offset, obj_it->points.size() * sizeof(GLfloat), &obj_it->points[0]);
385 offset += obj_it->points.size() * sizeof(GLfloat);
386 }
[516668e]387
[8b7cfcf]388 GLuint colors_vbo = 0;
389 glGenBuffers(1, &colors_vbo);
390 glBindBuffer(GL_ARRAY_BUFFER, colors_vbo);
[07ed460]391 glBufferData(GL_ARRAY_BUFFER, points_buffer_size, NULL, GL_DYNAMIC_DRAW);
392
393 offset = 0;
394 for (obj_it = objects.begin(); obj_it != objects.end(); obj_it++) {
395 glBufferSubData(GL_ARRAY_BUFFER, offset, obj_it->colors.size() * sizeof(GLfloat), &obj_it->colors[0]);
396 offset += obj_it->colors.size() * sizeof(GLfloat);
397 }
398
399 GLuint selected_colors_vbo = 0;
400 glGenBuffers(1, &selected_colors_vbo);
401 glBindBuffer(GL_ARRAY_BUFFER, selected_colors_vbo);
402 glBufferData(GL_ARRAY_BUFFER, points_buffer_size, NULL, GL_DYNAMIC_DRAW);
403
404 offset = 0;
405 for (obj_it = objects.begin(); obj_it != objects.end(); obj_it++) {
406 glBufferSubData(GL_ARRAY_BUFFER, offset, obj_it->selected_colors.size() * sizeof(GLfloat), &obj_it->selected_colors[0]);
407 offset += obj_it->selected_colors.size() * sizeof(GLfloat);
408 }
409
410 GLuint texcoords_vbo = 0;
411 glGenBuffers(1, &texcoords_vbo);
412 glBindBuffer(GL_ARRAY_BUFFER, texcoords_vbo);
413 glBufferData(GL_ARRAY_BUFFER, textures_buffer_size, NULL, GL_DYNAMIC_DRAW);
414
415 offset = 0;
416 for (obj_it = objects.begin(); obj_it != objects.end(); obj_it++) {
417 glBufferSubData(GL_ARRAY_BUFFER, offset, obj_it->texcoords.size() * sizeof(GLfloat), &obj_it->texcoords[0]);
418 offset += obj_it->texcoords.size() * sizeof(GLfloat);
419 }
[8b7cfcf]420
[9dd2eb7]421 GLuint normals_vbo = 0;
422 glGenBuffers(1, &normals_vbo);
423 glBindBuffer(GL_ARRAY_BUFFER, normals_vbo);
424 glBufferData(GL_ARRAY_BUFFER, points_buffer_size, NULL, GL_DYNAMIC_DRAW);
425
426 offset = 0;
427 for (obj_it = objects.begin(); obj_it != objects.end(); obj_it++) {
428 glBufferSubData(GL_ARRAY_BUFFER, offset, obj_it->normals.size() * sizeof(GLfloat), &obj_it->normals[0]);
429 offset += obj_it->normals.size() * sizeof(GLfloat);
430 }
431
[644a2e4]432 GLuint vao = 0;
[516668e]433 glGenVertexArrays(1, &vao);
434 glBindVertexArray(vao);
435
[8b7cfcf]436 glEnableVertexAttribArray(0);
437 glEnableVertexAttribArray(1);
[9dd2eb7]438 glEnableVertexAttribArray(2);
[644a2e4]439
[485424b]440 GLuint vao2 = 0;
441 glGenVertexArrays(1, &vao2);
442 glBindVertexArray(vao2);
[644a2e4]443
[485424b]444 glEnableVertexAttribArray(0);
445 glEnableVertexAttribArray(1);
[9dd2eb7]446 glEnableVertexAttribArray(2);
[8b7cfcf]447
[1a530df]448 // I can create a vbo to store all points for all models,
449 // and another vbo to store all colors for all models, but how do I allow alternating between
450 // using colors and textures for each model?
451 // Do I create a third vbo for texture coordinates and change which vertex attribute array I have bound
452 // when I want to draw a textured model?
453 // Or do I create one vao with vertices and colors and another with vertices and textures and switch between the two?
454 // Since I would have to switch shader programs to toggle between using colors or textures,
455 // I think I should use one vao for both cases and have a points vbo, a colors vbo, and a textures vbo
456 // One program will use the points and colors, and the other will use the points and texture coords
457 // Review how to bind vbos to vertex attributes in the shader.
458 //
459 // Binding vbos is done using glVertexAttribPointer(...) on a per-vao basis and is not tied to any specific shader.
460 // This means, I could create two vaos, one for each shader and have one use points+colors, while the other
461 // uses points+texxcoords.
462 //
463 // At some point, when I have lots of objects, I want to group them by shader when drawing them.
464 // I'd probably create some sort of set per shader and have each set contain the ids of all objects currently using that shader
465 // Most likely, I'd want to implement each set using a bit field. Makes it constant time for updates and iterating through them
466 // should not be much of an issue either.
467 // Assuming making lots of draw calls instead of one is not innefficient, I should be fine.
468 // I might also want to use one glDrawElements call per shader to draw multiple non-memory-adjacent models
469 //
470 // DECISION: Use a glDrawElements call per shader since I use a regular array to specify the elements to draw
471 // Actually, this will only work once I get UBOs working since each object will have a different model matrix
472 // For now, I could implement this with a glDrawElements call per object and update the model uniform for each object
473
[485424b]474 GLuint shader_program = loadShaderProgram("./color.vert", "./color.frag");
475 GLuint shader_program2 = loadShaderProgram("./texture.vert", "./texture.frag");
[644a2e4]476
[93baa0e]477 float speed = 1.0f;
478 float last_position = 0.0f;
479
[7ee66ea]480 float cam_speed = 1.0f;
[201e2f8]481 float cam_yaw_speed = 60.0f*ONE_DEG_IN_RAD;
[7ee66ea]482
[b73cb3b]483 // glm::lookAt can create the view matrix
484 // glm::perspective can create the projection matrix
485
486 cam_pos = vec3(0.0f, 0.0f, 2.0f);
[64a70f4]487 float cam_yaw = 0.0f * 2.0f * 3.14159f / 360.0f;
[7ee66ea]488
[c62eee6]489 mat4 T = translate(mat4(), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z));
[7ee66ea]490 mat4 R = rotate(mat4(), -cam_yaw, vec3(0.0f, 1.0f, 0.0f));
[c62eee6]491 view_mat = R*T;
[7ee66ea]492
493 float fov = 67.0f * ONE_DEG_IN_RAD;
494 float aspect = (float)width / (float)height;
495
[d12d003]496 float range = tan(fov * 0.5f) * NEAR_CLIP;
497 float Sx = NEAR_CLIP / (range * aspect);
498 float Sy = NEAR_CLIP / range;
499 float Sz = -(FAR_CLIP + NEAR_CLIP) / (FAR_CLIP - NEAR_CLIP);
500 float Pz = -(2.0f * FAR_CLIP * NEAR_CLIP) / (FAR_CLIP - NEAR_CLIP);
[7ee66ea]501
[c62eee6]502 float proj_arr[] = {
[7ee66ea]503 Sx, 0.0f, 0.0f, 0.0f,
504 0.0f, Sy, 0.0f, 0.0f,
505 0.0f, 0.0f, Sz, -1.0f,
506 0.0f, 0.0f, Pz, 0.0f,
507 };
[c62eee6]508 proj_mat = make_mat4(proj_arr);
[7ee66ea]509
[93462c6]510 GLuint model_test_loc = glGetUniformLocation(shader_program, "model");
511 GLuint view_test_loc = glGetUniformLocation(shader_program, "view");
512 GLuint proj_test_loc = glGetUniformLocation(shader_program, "proj");
[7ee66ea]513
[93462c6]514 GLuint model_mat_loc = glGetUniformLocation(shader_program2, "model");
515 GLuint view_mat_loc = glGetUniformLocation(shader_program2, "view");
516 GLuint proj_mat_loc = glGetUniformLocation(shader_program2, "proj");
[19c9338]517
[7ee66ea]518 glUseProgram(shader_program);
[df652d5]519 glUniformMatrix4fv(model_test_loc, 1, GL_FALSE, value_ptr(objects[0].model_mat));
[19c9338]520 glUniformMatrix4fv(view_test_loc, 1, GL_FALSE, value_ptr(view_mat));
[c62eee6]521 glUniformMatrix4fv(proj_test_loc, 1, GL_FALSE, value_ptr(proj_mat));
[485424b]522
523 glUseProgram(shader_program2);
[df652d5]524 glUniformMatrix4fv(model_mat_loc, 1, GL_FALSE, value_ptr(objects[1].model_mat));
[19c9338]525 glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, value_ptr(view_mat));
[c62eee6]526 glUniformMatrix4fv(proj_mat_loc, 1, GL_FALSE, value_ptr(proj_mat));
[7ee66ea]527
[baa5848]528 objects[0].shader_program = shader_program;
529 objects[1].shader_program = shader_program2;
530
[7ee66ea]531 bool cam_moved = false;
532
[046ce72]533 int frame_count = 0;
[f70ab75]534 double elapsed_seconds_fps = 0.0f;
[93baa0e]535 double previous_seconds = glfwGetTime();
[046ce72]536
[9dd2eb7]537 // This draws wireframes. Useful for seeing separate faces and occluded objects.
538 //glPolygonMode(GL_FRONT, GL_LINE);
539
[1c81bf0]540 // disable vsync to see real framerate
541 //glfwSwapInterval(0);
542
[93462c6]543 State curState = STATE_MAIN_MENU;
544
[5b3462b]545 while (!glfwWindowShouldClose(window) && isRunning) {
[93baa0e]546 double current_seconds = glfwGetTime();
547 double elapsed_seconds = current_seconds - previous_seconds;
548 previous_seconds = current_seconds;
549
[046ce72]550 elapsed_seconds_fps += elapsed_seconds;
551 if (elapsed_seconds_fps > 0.25f) {
552 fps = (double)frame_count / elapsed_seconds_fps;
553 cout << "FPS: " << fps << endl;
554
555 frame_count = 0;
556 elapsed_seconds_fps = 0.0f;
557 }
558
559 frame_count++;
560
[93baa0e]561 if (fabs(last_position) > 1.0f) {
562 speed = -speed;
563 }
564
[baa5848]565 // Handle events (Ideally, move all event-handling code
566 // before the render code)
567
568 clickedObject = NULL;
569 glfwPollEvents();
570
[93462c6]571 while (!events.empty()) {
572 switch (events.front()) {
573 case EVENT_GO_TO_MAIN_MENU:
574 curState = STATE_MAIN_MENU;
575 break;
576 case EVENT_GO_TO_GAME:
577 curState = STATE_GAME;
578 break;
579 case EVENT_QUIT:
580 isRunning = false;
581 break;
582 }
583 events.pop();
[147ac6d]584 }
[93462c6]585
586 if (curState == STATE_GAME) {
587 if (clickedObject == &objects[0]) {
588 selectedObject = &objects[0];
589 }
590 if (clickedObject == &objects[1]) {
591 selectedObject = &objects[1];
592 }
[baa5848]593 }
[33a9664]594
[baa5848]595 if (selectedObject == &objects[1] &&
596 objects[1].shader_program == shader_program2) {
597 objects[1].shader_program = shader_program;
598 } else if (selectedObject != &objects[1] &&
599 objects[1].shader_program == shader_program) {
600 objects[1].shader_program = shader_program2;
[147ac6d]601 }
[baa5848]602
[7ee66ea]603 /*
[93baa0e]604 model[12] = last_position + speed*elapsed_seconds;
605 last_position = model[12];
[7ee66ea]606 */
[93baa0e]607
608 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
[485424b]609
[93462c6]610 switch (curState) {
611 case STATE_MAIN_MENU:
612 renderMainMenu();
613 renderMainMenuGui();
614 break;
615 case STATE_GAME:
616 renderScene(objects,
617 shader_program, shader_program2,
618 vao, vao2,
619 model_test_loc, model_mat_loc,
620 points_vbo, normals_vbo,
621 colors_vbo, texcoords_vbo, selected_colors_vbo,
622 selectedObject);
623 renderSceneGui();
624 break;
[baa5848]625 }
[df652d5]626
[644a2e4]627 glfwSwapBuffers(window);
[ec4456b]628
629 if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE)) {
630 glfwSetWindowShouldClose(window, 1);
631 }
[7ee66ea]632
633 float dist = cam_speed * elapsed_seconds;
634 if (glfwGetKey(window, GLFW_KEY_A)) {
[c62eee6]635 cam_pos.x -= cos(cam_yaw)*dist;
636 cam_pos.z += sin(cam_yaw)*dist;
[7ee66ea]637 cam_moved = true;
638 }
639 if (glfwGetKey(window, GLFW_KEY_D)) {
[c62eee6]640 cam_pos.x += cos(cam_yaw)*dist;
641 cam_pos.z -= sin(cam_yaw)*dist;
[7ee66ea]642 cam_moved = true;
643 }
644 if (glfwGetKey(window, GLFW_KEY_W)) {
[c62eee6]645 cam_pos.x -= sin(cam_yaw)*dist;
646 cam_pos.z -= cos(cam_yaw)*dist;
[7ee66ea]647 cam_moved = true;
648 }
649 if (glfwGetKey(window, GLFW_KEY_S)) {
[c62eee6]650 cam_pos.x += sin(cam_yaw)*dist;
651 cam_pos.z += cos(cam_yaw)*dist;
[7ee66ea]652 cam_moved = true;
653 }
654 if (glfwGetKey(window, GLFW_KEY_LEFT)) {
655 cam_yaw += cam_yaw_speed * elapsed_seconds;
656 cam_moved = true;
657 }
658 if (glfwGetKey(window, GLFW_KEY_RIGHT)) {
659 cam_yaw -= cam_yaw_speed * elapsed_seconds;
660 cam_moved = true;
661 }
662 if (cam_moved) {
[c62eee6]663 T = translate(mat4(), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z));
[7ee66ea]664 R = rotate(mat4(), -cam_yaw, vec3(0.0f, 1.0f, 0.0f));
[267c4c5]665 view_mat = R*T;
[7ee66ea]666
[267c4c5]667 glUseProgram(shader_program);
668 glUniformMatrix4fv(view_test_loc, 1, GL_FALSE, value_ptr(view_mat));
669
670 glUseProgram(shader_program2);
[7ee66ea]671 glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, value_ptr(view_mat));
[267c4c5]672
[7ee66ea]673 cam_moved = false;
674 }
[644a2e4]675 }
676
[c1ca5b5]677 ImGui_ImplGlfwGL3_Shutdown();
678 ImGui::DestroyContext();
679
680 glfwDestroyWindow(window);
[5272b6b]681 glfwTerminate();
[c1ca5b5]682
[5272b6b]683 return 0;
684}
[ec4456b]685
686GLuint loadShader(GLenum type, string file) {
687 cout << "Loading shader from file " << file << endl;
688
689 ifstream shaderFile(file);
690 GLuint shaderId = 0;
691
692 if (shaderFile.is_open()) {
693 string line, shaderString;
694
695 while(getline(shaderFile, line)) {
696 shaderString += line + "\n";
697 }
698 shaderFile.close();
699 const char* shaderCString = shaderString.c_str();
700
701 shaderId = glCreateShader(type);
702 glShaderSource(shaderId, 1, &shaderCString, NULL);
703 glCompileShader(shaderId);
704
705 cout << "Loaded successfully" << endl;
706 } else {
[e856d62]707 cout << "Failed to load the file" << endl;
[ec4456b]708 }
709
710 return shaderId;
711}
[485424b]712
713GLuint loadShaderProgram(string vertexShaderPath, string fragmentShaderPath) {
714 GLuint vs = loadShader(GL_VERTEX_SHADER, vertexShaderPath);
715 GLuint fs = loadShader(GL_FRAGMENT_SHADER, fragmentShaderPath);
716
717 GLuint shader_program = glCreateProgram();
718 glAttachShader(shader_program, vs);
719 glAttachShader(shader_program, fs);
720
721 glLinkProgram(shader_program);
722
723 return shader_program;
724}
725
726unsigned char* loadImage(string file_name, int* x, int* y) {
727 int n;
[e856d62]728 int force_channels = 4; // This forces RGBA (4 bytes per pixel)
[485424b]729 unsigned char* image_data = stbi_load(file_name.c_str(), x, y, &n, force_channels);
[e856d62]730
731 int width_in_bytes = *x * 4;
732 unsigned char *top = NULL;
733 unsigned char *bottom = NULL;
734 unsigned char temp = 0;
735 int half_height = *y / 2;
736
737 // flip image upside-down to account for OpenGL treating lower-left as (0, 0)
738 for (int row = 0; row < half_height; row++) {
739 top = image_data + row * width_in_bytes;
740 bottom = image_data + (*y - row - 1) * width_in_bytes;
741 for (int col = 0; col < width_in_bytes; col++) {
742 temp = *top;
743 *top = *bottom;
744 *bottom = temp;
745 top++;
746 bottom++;
747 }
748 }
749
[485424b]750 if (!image_data) {
751 fprintf(stderr, "ERROR: could not load %s\n", file_name.c_str());
752 }
[e856d62]753
754 // Not Power-of-2 check
755 if ((*x & (*x - 1)) != 0 || (*y & (*y - 1)) != 0) {
756 fprintf(stderr, "WARNING: texture %s is not power-of-2 dimensions\n", file_name.c_str());
757 }
758
[485424b]759 return image_data;
760}
[33a9664]761
[d9f99b2]762bool faceClicked(array<vec3, 3> points, SceneObject* obj, vec4 world_ray, vec4 cam, vec4& click_point) {
[5c9d193]763 // LINE EQUATION: P = O + Dt
[b73cb3b]764 // O = cam
[5c9d193]765 // D = ray_world
766
[b73cb3b]767 // PLANE EQUATION: P dot n + d = 0
768 // n is the normal vector
769 // d is the offset from the origin
[5c9d193]770
771 // Take the cross-product of two vectors on the plane to get the normal
[d9f99b2]772 vec3 v1 = points[1] - points[0];
773 vec3 v2 = points[2] - points[0];
[5c9d193]774
775 vec3 normal = vec3(v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x);
[b73cb3b]776
777 print4DVector("Full world ray", world_ray);
[5c9d193]778
779 vec3 local_ray = (inverse(obj->model_mat) * world_ray).xyz();
780 vec3 local_cam = (inverse(obj->model_mat) * cam).xyz();
781
[b73cb3b]782 local_ray = local_ray - local_cam;
[5c9d193]783
[d9f99b2]784 float d = -glm::dot(points[0], normal);
[5c9d193]785 cout << "d: " << d << endl;
786
787 float t = -(glm::dot(local_cam, normal) + d) / glm::dot(local_ray, normal);
788 cout << "t: " << t << endl;
789
790 vec3 intersection = local_cam + t*local_ray;
791 printVector("Intersection", intersection);
792
[d9f99b2]793 if (insideTriangle(intersection, points)) {
[e82692b]794 click_point = obj->model_mat * vec4(intersection, 1.0f);
795 return true;
796 } else {
797 return false;
798 }
[5c9d193]799}
800bool insideTriangle(vec3 p, array<vec3, 3> triangle_points) {
[d9f99b2]801 vec3 v21 = triangle_points[1] - triangle_points[0];
802 vec3 v31 = triangle_points[2] - triangle_points[0];
803 vec3 pv1 = p - triangle_points[0];
[33a9664]804
805 float y = (pv1.y*v21.x - pv1.x*v21.y) / (v31.y*v21.x - v31.x*v21.y);
806 float x = (pv1.x-y*v31.x) / v21.x;
807
808 return x > 0.0f && y > 0.0f && x+y < 1.0f;
809}
[d12d003]810
811void printVector(string label, vec3 v) {
812 cout << label << " -> (" << v.x << "," << v.y << "," << v.z << ")" << endl;
813}
[b73cb3b]814
815void print4DVector(string label, vec4 v) {
816 cout << label << " -> (" << v.x << "," << v.y << "," << v.z << "," << v.w << ")" << endl;
817}
[c1ca5b5]818
[93462c6]819void renderScene(vector<SceneObject>& objects,
820 GLuint shader_program1, GLuint shader_program2,
821 GLuint vao1, GLuint vao2,
822 GLuint shader1_mat_loc, GLuint shader2_mat_loc,
823 GLuint points_vbo, GLuint normals_vbo,
824 GLuint colors_vbo, GLuint texcoords_vbo, GLuint selected_colors_vbo,
825 SceneObject* selectedObject) {
826 if (selectedObject == &objects[1]) {
827 objects[1].shader_program = shader_program1;
828 } else if (selectedObject != &objects[1]) {
829 objects[1].shader_program = shader_program2;
830 }
831
832 vector<int> program1_objects, program2_objects;
833
834 // group scene objects by shader
835 for (unsigned int i = 0; i < objects.size(); i++) {
836 if (objects[i].shader_program == shader_program1) {
837 program1_objects.push_back(i);
838 }
839 else if (objects[i].shader_program == shader_program2) {
840 program2_objects.push_back(i);
841 }
842 }
843
844 vector<int>::iterator it;
845
846 glUseProgram(shader_program1);
847 glBindVertexArray(vao1);
848
849 for (it = program1_objects.begin(); it != program1_objects.end(); it++) {
850 glUniformMatrix4fv(shader1_mat_loc, 1, GL_FALSE, value_ptr(objects[*it].model_mat));
851
852 glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
853 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vertex_vbo_offset);
854
855 if (selectedObject == &objects[*it]) {
856 glBindBuffer(GL_ARRAY_BUFFER, selected_colors_vbo);
857 } else {
858 glBindBuffer(GL_ARRAY_BUFFER, colors_vbo);
859 }
860 glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vertex_vbo_offset);
861
862 glBindBuffer(GL_ARRAY_BUFFER, normals_vbo);
863 glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vertex_vbo_offset);
864
865 glDrawArrays(GL_TRIANGLES, 0, objects[*it].num_points);
866 }
867
868 glUseProgram(shader_program2);
869 glBindVertexArray(vao2);
870
871 for (it = program2_objects.begin(); it != program2_objects.end(); it++) {
872 glUniformMatrix4fv(shader2_mat_loc, 1, GL_FALSE, value_ptr(objects[*it].model_mat));
873
874 glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
875 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vertex_vbo_offset);
876
877 glBindBuffer(GL_ARRAY_BUFFER, texcoords_vbo);
878 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, objects[*it].texture_vbo_offset);
879
880 glBindBuffer(GL_ARRAY_BUFFER, normals_vbo);
881 glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vertex_vbo_offset);
882
883 glDrawArrays(GL_TRIANGLES, 0, objects[*it].num_points);
884 }
885}
886
887void renderSceneGui() {
[c1ca5b5]888 ImGui_ImplGlfwGL3_NewFrame();
889
890 // 1. Show a simple window.
891 // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
[5b3462b]892 /*
[c1ca5b5]893 {
894 static float f = 0.0f;
895 static int counter = 0;
896 ImGui::Text("Hello, world!"); // Display some text (you can use a format string too)
897 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
898 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
899
900 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our windows open/close state
901 ImGui::Checkbox("Another Window", &show_another_window);
902
903 if (ImGui::Button("Button")) // Buttons return true when clicked (NB: most widgets return true when edited/activated)
904 counter++;
905 ImGui::SameLine();
906 ImGui::Text("counter = %d", counter);
907
908 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
909 }
[5b3462b]910 */
[c1ca5b5]911
[5b3462b]912 {
913 ImGui::SetNextWindowSize(ImVec2(85, 22), ImGuiCond_Once);
914 ImGui::SetNextWindowPos(ImVec2(10, 50), ImGuiCond_Once);
[f0cc877]915 ImGui::Begin("WndStats", NULL,
916 ImGuiWindowFlags_NoTitleBar |
917 ImGuiWindowFlags_NoResize |
918 ImGuiWindowFlags_NoMove);
[5b3462b]919 ImGui::Text("Score: ???");
[c1ca5b5]920 ImGui::End();
921 }
922
[5b3462b]923 {
924 ImGui::SetNextWindowPos(ImVec2(380, 10), ImGuiCond_Once);
925 ImGui::SetNextWindowSize(ImVec2(250, 35), ImGuiCond_Once);
[f0cc877]926 ImGui::Begin("WndMenubar", NULL,
927 ImGuiWindowFlags_NoTitleBar |
[5b3462b]928 ImGuiWindowFlags_NoResize |
929 ImGuiWindowFlags_NoMove);
[93462c6]930 ImGui::InvisibleButton("", ImVec2(155, 18));
[5b3462b]931 ImGui::SameLine();
[93462c6]932 if (ImGui::Button("Main Menu")) {
933 events.push(EVENT_GO_TO_MAIN_MENU);
[5b3462b]934 }
935 ImGui::End();
[c1ca5b5]936 }
937
[93462c6]938 ImGui::Render();
939 ImGui_ImplGlfwGL3_RenderDrawData(ImGui::GetDrawData());
940}
941
942void renderMainMenu() {
943}
944
945void renderMainMenuGui() {
946 ImGui_ImplGlfwGL3_NewFrame();
947
[f0cc877]948 {
949 int padding = 4;
950 ImGui::SetNextWindowPos(ImVec2(-padding, -padding), ImGuiCond_Once);
[93462c6]951 ImGui::SetNextWindowSize(ImVec2(width + 2 * padding, height + 2 * padding), ImGuiCond_Once);
[f0cc877]952 ImGui::Begin("WndMain", NULL,
953 ImGuiWindowFlags_NoTitleBar |
954 ImGuiWindowFlags_NoResize |
955 ImGuiWindowFlags_NoMove);
[93462c6]956
957 ImGui::InvisibleButton("", ImVec2(10, 80));
958 ImGui::InvisibleButton("", ImVec2(285, 18));
959 ImGui::SameLine();
960 if (ImGui::Button("New Game")) {
961 events.push(EVENT_GO_TO_GAME);
962 }
963
964 ImGui::InvisibleButton("", ImVec2(10, 15));
965 ImGui::InvisibleButton("", ImVec2(300, 18));
966 ImGui::SameLine();
967 if (ImGui::Button("Quit")) {
968 events.push(EVENT_QUIT);
969 }
970
[f0cc877]971 ImGui::End();
972 }
973
[c1ca5b5]974 ImGui::Render();
975 ImGui_ImplGlfwGL3_RenderDrawData(ImGui::GetDrawData());
976}
Note: See TracBrowser for help on using the repository browser.