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

feature/imgui-sdl points-test
Last change on this file since f70ab75 was f70ab75, checked in by Dmitry Portnoy <dmitry.portnoy@…>, 7 years ago

Remove previous_seconds_fps since it's unused

  • 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;
465 double previous_seconds = glfwGetTime();
466
467 while (!glfwWindowShouldClose(window)) {
468 double current_seconds = glfwGetTime();
469 double elapsed_seconds = current_seconds - previous_seconds;
470 previous_seconds = current_seconds;
471
472 elapsed_seconds_fps += elapsed_seconds;
473 if (elapsed_seconds_fps > 0.25f) {
474 fps = (double)frame_count / elapsed_seconds_fps;
475 cout << "FPS: " << fps << endl;
476
477 frame_count = 0;
478 elapsed_seconds_fps = 0.0f;
479 }
480
481 frame_count++;
482
483 if (fabs(last_position) > 1.0f) {
484 speed = -speed;
485 }
486
487 if (clickedObject == &objects[0]) {
488 selectedObject = &objects[0];
489 }
490
491 // At some point, I should change this to only rebind the buffer once per click, not once per frame
492 glBindBuffer(GL_ARRAY_BUFFER, colors_vbo);
493 if (selectedObject == &objects[0]) {
494 glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors_new, GL_STATIC_DRAW);
495 }
496 else {
497 glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
498 }
499
500 /*
501 model[12] = last_position + speed*elapsed_seconds;
502 last_position = model[12];
503 */
504
505 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
506
507 glUseProgram(shader_program);
508
509 // Since every object will have a different model matrix, maybe it shouldn't be a uniform
510
511 // this is temporary.
512 // It's needed to offset the code for the recoloring of the square working during click detection
513 glUniformMatrix4fv(model_test_loc, 1, GL_FALSE, value_ptr(objects[0].model_mat));
514
515 glBindVertexArray(vao);
516
517 glDrawArrays(GL_TRIANGLES, 0, numPoints);
518
519 if (clickedObject == &objects[1]) {
520 selectedObject = &objects[1];
521 }
522
523 if (selectedObject == &objects[1]) {
524 glUseProgram(shader_program);
525
526 // this is temporary.
527 // It's needed to get the recoloring of the square working during click detection
528 glUniformMatrix4fv(model_test_loc, 1, GL_FALSE, value_ptr(objects[1].model_mat));
529
530 glBindVertexArray(vao2);
531
532 glBindBuffer(GL_ARRAY_BUFFER, colors2_vbo);
533 glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
534 } else {
535 glUseProgram(shader_program2);
536
537 glBindVertexArray(vao2);
538
539 glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
540 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, NULL);
541 }
542
543 glDrawArrays(GL_TRIANGLES, 0, numPoints2);
544
545 clickedObject = NULL;
546
547 glfwPollEvents();
548 glfwSwapBuffers(window);
549
550 if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE)) {
551 glfwSetWindowShouldClose(window, 1);
552 }
553
554 float dist = cam_speed * elapsed_seconds;
555 if (glfwGetKey(window, GLFW_KEY_A)) {
556 cam_pos.x -= cos(cam_yaw)*dist;
557 cam_pos.z += sin(cam_yaw)*dist;
558 cam_moved = true;
559 }
560 if (glfwGetKey(window, GLFW_KEY_D)) {
561 cam_pos.x += cos(cam_yaw)*dist;
562 cam_pos.z -= sin(cam_yaw)*dist;
563 cam_moved = true;
564 }
565 if (glfwGetKey(window, GLFW_KEY_W)) {
566 cam_pos.x -= sin(cam_yaw)*dist;
567 cam_pos.z -= cos(cam_yaw)*dist;
568 cam_moved = true;
569 }
570 if (glfwGetKey(window, GLFW_KEY_S)) {
571 cam_pos.x += sin(cam_yaw)*dist;
572 cam_pos.z += cos(cam_yaw)*dist;
573 cam_moved = true;
574 }
575 if (glfwGetKey(window, GLFW_KEY_LEFT)) {
576 cam_yaw += cam_yaw_speed * elapsed_seconds;
577 cam_moved = true;
578 }
579 if (glfwGetKey(window, GLFW_KEY_RIGHT)) {
580 cam_yaw -= cam_yaw_speed * elapsed_seconds;
581 cam_moved = true;
582 }
583 if (cam_moved) {
584 T = translate(mat4(), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z));
585 R = rotate(mat4(), -cam_yaw, vec3(0.0f, 1.0f, 0.0f));
586 view_mat = R*T;
587
588 glUseProgram(shader_program);
589 glUniformMatrix4fv(view_test_loc, 1, GL_FALSE, value_ptr(view_mat));
590
591 glUseProgram(shader_program2);
592 glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, value_ptr(view_mat));
593
594 cam_moved = false;
595 }
596 }
597
598 glfwTerminate();
599 return 0;
600}
601
602GLuint loadShader(GLenum type, string file) {
603 cout << "Loading shader from file " << file << endl;
604
605 ifstream shaderFile(file);
606 GLuint shaderId = 0;
607
608 if (shaderFile.is_open()) {
609 string line, shaderString;
610
611 while(getline(shaderFile, line)) {
612 shaderString += line + "\n";
613 }
614 shaderFile.close();
615 const char* shaderCString = shaderString.c_str();
616
617 shaderId = glCreateShader(type);
618 glShaderSource(shaderId, 1, &shaderCString, NULL);
619 glCompileShader(shaderId);
620
621 cout << "Loaded successfully" << endl;
622 } else {
623 cout << "Failed to load the file" << endl;
624 }
625
626 return shaderId;
627}
628
629GLuint loadShaderProgram(string vertexShaderPath, string fragmentShaderPath) {
630 GLuint vs = loadShader(GL_VERTEX_SHADER, vertexShaderPath);
631 GLuint fs = loadShader(GL_FRAGMENT_SHADER, fragmentShaderPath);
632
633 GLuint shader_program = glCreateProgram();
634 glAttachShader(shader_program, vs);
635 glAttachShader(shader_program, fs);
636
637 glLinkProgram(shader_program);
638
639 return shader_program;
640}
641
642unsigned char* loadImage(string file_name, int* x, int* y) {
643 int n;
644 int force_channels = 4; // This forces RGBA (4 bytes per pixel)
645 unsigned char* image_data = stbi_load(file_name.c_str(), x, y, &n, force_channels);
646
647 int width_in_bytes = *x * 4;
648 unsigned char *top = NULL;
649 unsigned char *bottom = NULL;
650 unsigned char temp = 0;
651 int half_height = *y / 2;
652
653 // flip image upside-down to account for OpenGL treating lower-left as (0, 0)
654 for (int row = 0; row < half_height; row++) {
655 top = image_data + row * width_in_bytes;
656 bottom = image_data + (*y - row - 1) * width_in_bytes;
657 for (int col = 0; col < width_in_bytes; col++) {
658 temp = *top;
659 *top = *bottom;
660 *bottom = temp;
661 top++;
662 bottom++;
663 }
664 }
665
666 if (!image_data) {
667 fprintf(stderr, "ERROR: could not load %s\n", file_name.c_str());
668 }
669
670 // Not Power-of-2 check
671 if ((*x & (*x - 1)) != 0 || (*y & (*y - 1)) != 0) {
672 fprintf(stderr, "WARNING: texture %s is not power-of-2 dimensions\n", file_name.c_str());
673 }
674
675 return image_data;
676}
677
678bool faceClicked(ObjectFace* face, vec4 world_ray, vec4 cam, vec4& click_point) {
679 // LINE EQUATION: P = O + Dt
680 // O = cam
681 // D = ray_world
682
683 // PLANE EQUATION: P dot n + d = 0
684 // n is the normal vector
685 // d is the offset from the origin
686
687 // Take the cross-product of two vectors on the plane to get the normal
688 vec3 v1 = face->points[1] - face->points[0];
689 vec3 v2 = face->points[2] - face->points[0];
690
691 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);
692
693 print4DVector("Full world ray", world_ray);
694
695 SceneObject* obj = &objects[face->object_id];
696 vec3 local_ray = (inverse(obj->model_mat) * world_ray).xyz();
697 vec3 local_cam = (inverse(obj->model_mat) * cam).xyz();
698
699 local_ray = local_ray - local_cam;
700
701 float d = -glm::dot(face->points[0], normal);
702 cout << "d: " << d << endl;
703
704 float t = -(glm::dot(local_cam, normal) + d) / glm::dot(local_ray, normal);
705 cout << "t: " << t << endl;
706
707 vec3 intersection = local_cam + t*local_ray;
708 printVector("Intersection", intersection);
709
710 if (insideTriangle(intersection, face->points)) {
711 click_point = obj->model_mat * vec4(intersection, 1.0f);
712 return true;
713 } else {
714 return false;
715 }
716}
717
718bool insideTriangle(vec3 p, array<vec3, 3> triangle_points) {
719 vec3 v21 = triangle_points[1]- triangle_points[0];
720 vec3 v31 = triangle_points[2]- triangle_points[0];
721 vec3 pv1 = p- triangle_points[0];
722
723 float y = (pv1.y*v21.x - pv1.x*v21.y) / (v31.y*v21.x - v31.x*v21.y);
724 float x = (pv1.x-y*v31.x) / v21.x;
725
726 cout << "(" << x << ", " << y << ")" << endl;
727
728 return x > 0.0f && y > 0.0f && x+y < 1.0f;
729}
730
731void printVector(string label, vec3 v) {
732 cout << label << " -> (" << v.x << "," << v.y << "," << v.z << ")" << endl;
733}
734
735void print4DVector(string label, vec4 v) {
736 cout << label << " -> (" << v.x << "," << v.y << "," << v.z << "," << v.w << ")" << endl;
737}
Note: See TracBrowser for help on using the repository browser.