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

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

Design an algorithm for rendering objects using colors or shaders and try to use a ubo for storing model matrices

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