source: opengl-game/new-game.cpp@ 9dd2eb7

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

Implement Phong shading in the color and texture shaders

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