source: opengl-game/new-game.cpp@ 54b6d6b

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

Add an ImGui example project

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