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

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

Remove imgui_example.cpp from the Visual Studio project and add commented-out code to disable vsync.

  • Property mode set to 100644
File size: 27.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>
[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
[1c81bf0]517 // disable vsync to see real framerate
518 //glfwSwapInterval(0);
519
[644a2e4]520 while (!glfwWindowShouldClose(window)) {
[93baa0e]521 double current_seconds = glfwGetTime();
522 double elapsed_seconds = current_seconds - previous_seconds;
523 previous_seconds = current_seconds;
524
[046ce72]525 elapsed_seconds_fps += elapsed_seconds;
526 if (elapsed_seconds_fps > 0.25f) {
527 fps = (double)frame_count / elapsed_seconds_fps;
528 cout << "FPS: " << fps << endl;
529
530 frame_count = 0;
531 elapsed_seconds_fps = 0.0f;
532 }
533
534 frame_count++;
535
[93baa0e]536 if (fabs(last_position) > 1.0f) {
537 speed = -speed;
538 }
539
[baa5848]540 program1_objects.clear();
541 program2_objects.clear();
542
543 // Handle events (Ideally, move all event-handling code
544 // before the render code)
545
546 clickedObject = NULL;
547 glfwPollEvents();
548
[147ac6d]549 if (clickedObject == &objects[0]) {
550 selectedObject = &objects[0];
551 }
[baa5848]552 if (clickedObject == &objects[1]) {
553 selectedObject = &objects[1];
554 }
[33a9664]555
[baa5848]556 if (selectedObject == &objects[1] &&
557 objects[1].shader_program == shader_program2) {
558 objects[1].shader_program = shader_program;
559 } else if (selectedObject != &objects[1] &&
560 objects[1].shader_program == shader_program) {
561 objects[1].shader_program = shader_program2;
[147ac6d]562 }
[baa5848]563
564 // group scene objects by shader
[4e0b82b]565 for (unsigned int i=0; i < objects.size(); i++) {
[baa5848]566 if (objects[i].shader_program == shader_program) {
567 program1_objects.push_back(i);
568 } else if (objects[i].shader_program == shader_program2) {
569 program2_objects.push_back(i);
570 }
[64a70f4]571 }
[33a9664]572
[7ee66ea]573 /*
[93baa0e]574 model[12] = last_position + speed*elapsed_seconds;
575 last_position = model[12];
[7ee66ea]576 */
[93baa0e]577
578 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
[485424b]579
580 glUseProgram(shader_program);
[644a2e4]581 glBindVertexArray(vao);
[93baa0e]582
[baa5848]583 for (it=program1_objects.begin(); it != program1_objects.end(); it++) {
584 glUniformMatrix4fv(model_test_loc, 1, GL_FALSE, value_ptr(objects[*it].model_mat));
[ec4456b]585
[05e43cf]586 glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
[07ed460]587 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vertex_vbo_offset);
[05e43cf]588
[baa5848]589 if (selectedObject == &objects[*it]) {
[07ed460]590 glBindBuffer(GL_ARRAY_BUFFER, selected_colors_vbo);
[baa5848]591 } else {
592 glBindBuffer(GL_ARRAY_BUFFER, colors_vbo);
593 }
[07ed460]594 glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vertex_vbo_offset);
[05e43cf]595
[9dd2eb7]596 glBindBuffer(GL_ARRAY_BUFFER, normals_vbo);
597 glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vertex_vbo_offset);
598
[05e43cf]599 glDrawArrays(GL_TRIANGLES, 0, objects[*it].num_points);
[64a70f4]600 }
[485424b]601
[baa5848]602 glUseProgram(shader_program2);
603 glBindVertexArray(vao2);
[485424b]604
[baa5848]605 for (it = program2_objects.begin(); it != program2_objects.end(); it++) {
606 glUniformMatrix4fv(model_mat_loc, 1, GL_FALSE, value_ptr(objects[*it].model_mat));
607
[05e43cf]608 glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
[07ed460]609 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vertex_vbo_offset);
[05e43cf]610
[07ed460]611 glBindBuffer(GL_ARRAY_BUFFER, texcoords_vbo);
612 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, objects[*it].texture_vbo_offset);
[05e43cf]613
[9dd2eb7]614 glBindBuffer(GL_ARRAY_BUFFER, normals_vbo);
615 glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vertex_vbo_offset);
616
[05e43cf]617 glDrawArrays(GL_TRIANGLES, 0, objects[*it].num_points);
[baa5848]618 }
[df652d5]619
[c1ca5b5]620 renderGui();
621
[644a2e4]622 glfwSwapBuffers(window);
[ec4456b]623
624 if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE)) {
625 glfwSetWindowShouldClose(window, 1);
626 }
[7ee66ea]627
628 float dist = cam_speed * elapsed_seconds;
629 if (glfwGetKey(window, GLFW_KEY_A)) {
[c62eee6]630 cam_pos.x -= cos(cam_yaw)*dist;
631 cam_pos.z += sin(cam_yaw)*dist;
[7ee66ea]632 cam_moved = true;
633 }
634 if (glfwGetKey(window, GLFW_KEY_D)) {
[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_W)) {
[c62eee6]640 cam_pos.x -= sin(cam_yaw)*dist;
641 cam_pos.z -= cos(cam_yaw)*dist;
[7ee66ea]642 cam_moved = true;
643 }
644 if (glfwGetKey(window, GLFW_KEY_S)) {
[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_LEFT)) {
650 cam_yaw += cam_yaw_speed * elapsed_seconds;
651 cam_moved = true;
652 }
653 if (glfwGetKey(window, GLFW_KEY_RIGHT)) {
654 cam_yaw -= cam_yaw_speed * elapsed_seconds;
655 cam_moved = true;
656 }
657 if (cam_moved) {
[c62eee6]658 T = translate(mat4(), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z));
[7ee66ea]659 R = rotate(mat4(), -cam_yaw, vec3(0.0f, 1.0f, 0.0f));
[267c4c5]660 view_mat = R*T;
[7ee66ea]661
[267c4c5]662 glUseProgram(shader_program);
663 glUniformMatrix4fv(view_test_loc, 1, GL_FALSE, value_ptr(view_mat));
664
665 glUseProgram(shader_program2);
[7ee66ea]666 glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, value_ptr(view_mat));
[267c4c5]667
[7ee66ea]668 cam_moved = false;
669 }
[644a2e4]670 }
671
[c1ca5b5]672 ImGui_ImplGlfwGL3_Shutdown();
673 ImGui::DestroyContext();
674
675 glfwDestroyWindow(window);
[5272b6b]676 glfwTerminate();
[c1ca5b5]677
[5272b6b]678 return 0;
679}
[ec4456b]680
681GLuint loadShader(GLenum type, string file) {
682 cout << "Loading shader from file " << file << endl;
683
684 ifstream shaderFile(file);
685 GLuint shaderId = 0;
686
687 if (shaderFile.is_open()) {
688 string line, shaderString;
689
690 while(getline(shaderFile, line)) {
691 shaderString += line + "\n";
692 }
693 shaderFile.close();
694 const char* shaderCString = shaderString.c_str();
695
696 shaderId = glCreateShader(type);
697 glShaderSource(shaderId, 1, &shaderCString, NULL);
698 glCompileShader(shaderId);
699
700 cout << "Loaded successfully" << endl;
701 } else {
[e856d62]702 cout << "Failed to load the file" << endl;
[ec4456b]703 }
704
705 return shaderId;
706}
[485424b]707
708GLuint loadShaderProgram(string vertexShaderPath, string fragmentShaderPath) {
709 GLuint vs = loadShader(GL_VERTEX_SHADER, vertexShaderPath);
710 GLuint fs = loadShader(GL_FRAGMENT_SHADER, fragmentShaderPath);
711
712 GLuint shader_program = glCreateProgram();
713 glAttachShader(shader_program, vs);
714 glAttachShader(shader_program, fs);
715
716 glLinkProgram(shader_program);
717
718 return shader_program;
719}
720
721unsigned char* loadImage(string file_name, int* x, int* y) {
722 int n;
[e856d62]723 int force_channels = 4; // This forces RGBA (4 bytes per pixel)
[485424b]724 unsigned char* image_data = stbi_load(file_name.c_str(), x, y, &n, force_channels);
[e856d62]725
726 int width_in_bytes = *x * 4;
727 unsigned char *top = NULL;
728 unsigned char *bottom = NULL;
729 unsigned char temp = 0;
730 int half_height = *y / 2;
731
732 // flip image upside-down to account for OpenGL treating lower-left as (0, 0)
733 for (int row = 0; row < half_height; row++) {
734 top = image_data + row * width_in_bytes;
735 bottom = image_data + (*y - row - 1) * width_in_bytes;
736 for (int col = 0; col < width_in_bytes; col++) {
737 temp = *top;
738 *top = *bottom;
739 *bottom = temp;
740 top++;
741 bottom++;
742 }
743 }
744
[485424b]745 if (!image_data) {
746 fprintf(stderr, "ERROR: could not load %s\n", file_name.c_str());
747 }
[e856d62]748
749 // Not Power-of-2 check
750 if ((*x & (*x - 1)) != 0 || (*y & (*y - 1)) != 0) {
751 fprintf(stderr, "WARNING: texture %s is not power-of-2 dimensions\n", file_name.c_str());
752 }
753
[485424b]754 return image_data;
755}
[33a9664]756
[d9f99b2]757bool faceClicked(array<vec3, 3> points, SceneObject* obj, vec4 world_ray, vec4 cam, vec4& click_point) {
[5c9d193]758 // LINE EQUATION: P = O + Dt
[b73cb3b]759 // O = cam
[5c9d193]760 // D = ray_world
761
[b73cb3b]762 // PLANE EQUATION: P dot n + d = 0
763 // n is the normal vector
764 // d is the offset from the origin
[5c9d193]765
766 // Take the cross-product of two vectors on the plane to get the normal
[d9f99b2]767 vec3 v1 = points[1] - points[0];
768 vec3 v2 = points[2] - points[0];
[5c9d193]769
770 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]771
772 print4DVector("Full world ray", world_ray);
[5c9d193]773
774 vec3 local_ray = (inverse(obj->model_mat) * world_ray).xyz();
775 vec3 local_cam = (inverse(obj->model_mat) * cam).xyz();
776
[b73cb3b]777 local_ray = local_ray - local_cam;
[5c9d193]778
[d9f99b2]779 float d = -glm::dot(points[0], normal);
[5c9d193]780 cout << "d: " << d << endl;
781
782 float t = -(glm::dot(local_cam, normal) + d) / glm::dot(local_ray, normal);
783 cout << "t: " << t << endl;
784
785 vec3 intersection = local_cam + t*local_ray;
786 printVector("Intersection", intersection);
787
[d9f99b2]788 if (insideTriangle(intersection, points)) {
[e82692b]789 click_point = obj->model_mat * vec4(intersection, 1.0f);
790 return true;
791 } else {
792 return false;
793 }
[5c9d193]794}
795bool insideTriangle(vec3 p, array<vec3, 3> triangle_points) {
[d9f99b2]796 vec3 v21 = triangle_points[1] - triangle_points[0];
797 vec3 v31 = triangle_points[2] - triangle_points[0];
798 vec3 pv1 = p - triangle_points[0];
[33a9664]799
800 float y = (pv1.y*v21.x - pv1.x*v21.y) / (v31.y*v21.x - v31.x*v21.y);
801 float x = (pv1.x-y*v31.x) / v21.x;
802
803 return x > 0.0f && y > 0.0f && x+y < 1.0f;
804}
[d12d003]805
806void printVector(string label, vec3 v) {
807 cout << label << " -> (" << v.x << "," << v.y << "," << v.z << ")" << endl;
808}
[b73cb3b]809
810void print4DVector(string label, vec4 v) {
811 cout << label << " -> (" << v.x << "," << v.y << "," << v.z << "," << v.w << ")" << endl;
812}
[c1ca5b5]813
814void renderGui() {
815 bool show_demo_window = true;
816 bool show_another_window = true;
817
818 ImGui_ImplGlfwGL3_NewFrame();
819
820 // 1. Show a simple window.
821 // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
822 {
823 static float f = 0.0f;
824 static int counter = 0;
825 ImGui::Text("Hello, world!"); // Display some text (you can use a format string too)
826 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
827 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
828
829 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our windows open/close state
830 ImGui::Checkbox("Another Window", &show_another_window);
831
832 if (ImGui::Button("Button")) // Buttons return true when clicked (NB: most widgets return true when edited/activated)
833 counter++;
834 ImGui::SameLine();
835 ImGui::Text("counter = %d", counter);
836
837 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
838 }
839
840 // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name your windows.
841 if (show_another_window) {
842 ImGui::Begin("Another Window", &show_another_window);
843 ImGui::Text("Hello from another window!");
844 if (ImGui::Button("Close Me"))
845 show_another_window = false;
846 ImGui::End();
847 }
848
849 // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow(). Read its code to learn more about Dear ImGui!
850 if (show_demo_window) {
851 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!
852 ImGui::ShowDemoWindow(&show_demo_window);
853 }
854
855 ImGui::Render();
856 ImGui_ImplGlfwGL3_RenderDrawData(ImGui::GetDrawData());
857}
Note: See TracBrowser for help on using the repository browser.