source: opengl-game/new-game.cpp@ 1a616e6

feature/imgui-sdl points-test
Last change on this file since 1a616e6 was c1ca5b5, checked in by Dmitry Portnoy <dmp1488@…>, 7 years ago

Show the example ImGui gui in the OpenGL game.

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