source: opengl-game/new-game.cpp@ d9f99b2

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

Remove all instances of ObjectFace and just reference the points vector in each SceneObject for face info.

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