source: opengl-game/new-game.cpp@ 4e0b82b

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

Add an ImGui example project

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