#include "logger.h" #include "stb_image.h" // I think this was for the OpenGL 4 book font file tutorial //#define STB_IMAGE_WRITE_IMPLEMENTATION //#include "stb_image_write.h" #define _USE_MATH_DEFINES #include #include #include #include "IMGUI/imgui.h" #include "imgui_impl_glfw_gl3.h" #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using namespace glm; struct SceneObject { unsigned int id; // Currently, model_transform should only have translate, and rotation and scale need to be done in model_base since // they need to be done when the object is at the origin. I should change this to have separate scale, rotate, and translate // matrices for each object that can be updated independently and then applied to the object in that order. mat4 model_mat, model_base, model_transform; mat4 translate_mat; // beginning of doing what's mentioned above GLuint shader_program; unsigned int num_points; GLuint vertex_vbo_offset; GLuint ubo_offset; vector points; vector colors; vector texcoords; vector normals; vector selected_colors; bool deleted; vec3 bounding_center; GLfloat bounding_radius; }; struct BufferInfo { unsigned int vbo_base; unsigned int vbo_offset; unsigned int vbo_capacity; unsigned int ubo_base; unsigned int ubo_offset; unsigned int ubo_capacity; }; enum State { STATE_MAIN_MENU, STATE_GAME, }; enum Event { EVENT_GO_TO_MAIN_MENU, EVENT_GO_TO_GAME, EVENT_QUIT, }; void glfw_error_callback(int error, const char* description); void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); bool faceClicked(array points, SceneObject* obj, vec4 world_ray, vec4 cam, vec4& click_point); bool insideTriangle(vec3 p, array triangle_points); GLuint loadShader(GLenum type, string file); GLuint loadShaderProgram(string vertexShaderPath, string fragmentShaderPath); unsigned char* loadImage(string file_name, int* x, int* y); void printVector(string label, vec3 v); void print4DVector(string label, vec4 v); void addObjectToSceneDuringInit(SceneObject& obj); void addObjectToScene(SceneObject& obj, map& shaderBufferInfo, GLuint points_vbo, GLuint colors_vbo, GLuint selected_colors_vbo, GLuint texcoords_vbo, GLuint normals_vbo, GLuint ubo, GLuint model_mat_idx_vbo); void removeObjectFromScene(SceneObject& obj, GLuint ubo); void calculateObjectBoundingBox(SceneObject& obj); void initializeBuffers( GLuint* points_vbo, GLuint* colors_vbo, GLuint* selected_colors_vbo, GLuint* texcoords_vbo, GLuint* normals_vbo, GLuint* ubo, GLuint* model_mat_idx_vbo); void populateBuffers(vector& objects, map& shaderBufferInfo, GLuint points_vbo, GLuint colors_vbo, GLuint selected_colors_vbo, GLuint texcoords_vbo, GLuint normals_vbo, GLuint ubo, GLuint model_mat_idx_vbo); void copyObjectDataToBuffers(SceneObject& obj, map& shaderBufferInfo, GLuint points_vbo, GLuint colors_vbo, GLuint selected_colors_vbo, GLuint texcoords_vbo, GLuint normals_vbo, GLuint ubo, GLuint model_mat_idx_vbo); void transformObject(SceneObject& obj, const mat4& transform, GLuint ubo); void renderMainMenu(); void renderMainMenuGui(); void renderScene(vector& objects, GLuint color_sp, GLuint texture_sp, GLuint vao1, GLuint vao2, GLuint points_vbo, GLuint normals_vbo, GLuint colors_vbo, GLuint texcoords_vbo, GLuint selected_colors_vbo, SceneObject* selectedObject, map& shaderBufferInfo); void renderSceneGui(); void spawnAsteroid(vec3 pos, GLuint shader, map& shaderBufferInfo, GLuint points_vbo, GLuint colors_vbo, GLuint selected_colors_vbo, GLuint texcoords_vbo, GLuint normals_vbo, GLuint ubo, GLuint model_mat_idx_vbo); float getRandomNum(float low, float high); #define NUM_KEYS (512) #define ONE_DEG_IN_RAD ((2.0f * M_PI) / 360.0f) // 0.017444444 (maybe make this a const instead) const int KEY_STATE_UNCHANGED = -1; const bool FULLSCREEN = false; const bool SHOW_FPS = false; const bool DISABLE_VSYNC = false; // disable vsync to see real framerate unsigned int MAX_UNIFORMS = 0; // Requires OpenGL constants only available at runtime, so it can't be const int key_state[NUM_KEYS]; bool key_pressed[NUM_KEYS]; int width = 640; int height = 480; double fps; vec3 cam_pos; mat4 view_mat; mat4 proj_mat; // TODO: Consider using a list instead since it will make element deletion more efficient vector objects; queue events; SceneObject* clickedObject = NULL; SceneObject* selectedObject = NULL; float NEAR_CLIP = 0.1f; float FAR_CLIP = 100.0f; // TODO: Should really have some array or struct of UI-related variables bool isRunning = true; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); int main(int argc, char* argv[]) { cout << "New OpenGL Game" << endl; if (!restart_gl_log()) {} gl_log("starting GLFW\n%s\n", glfwGetVersionString()); glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) { fprintf(stderr, "ERROR: could not start GLFW3\n"); return 1; } #ifdef __APPLE__ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif glfwWindowHint(GLFW_SAMPLES, 4); GLFWwindow* window = NULL; GLFWmonitor* mon = NULL; if (FULLSCREEN) { mon = glfwGetPrimaryMonitor(); const GLFWvidmode* vmode = glfwGetVideoMode(mon); width = vmode->width; height = vmode->height; cout << "Fullscreen resolution " << vmode->width << "x" << vmode->height << endl; } window = glfwCreateWindow(width, height, "New OpenGL Game", mon, NULL); if (!window) { fprintf(stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; glewInit(); srand(time(0)); /* * RENDERING ALGORITHM NOTES: * * Basically, I need to split my objects into groups, so that each group fits into * GL_MAX_UNIFORM_BLOCK_SIZE. I need to have an offset and a size for each group. * Getting the offset is straitforward. The size may as well be GL_MAX_UNIFORM_BLOCK_SIZE * for each group, since it seems that smaller sizes just round up to the nearest GL_MAX_UNIFORM_BLOCK_SIZE * * I'll need to have a loop inside my render loop that calls glBindBufferRange(GL_UNIFORM_BUFFER, ... * for every 1024 objects and then draws all those objects with one glDraw call. * * Since I currently have very few objects, I'll wait to implement this until I have * a reasonable number of objects always using the same shader. */ GLint UNIFORM_BUFFER_OFFSET_ALIGNMENT, MAX_UNIFORM_BLOCK_SIZE; glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &UNIFORM_BUFFER_OFFSET_ALIGNMENT); glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &MAX_UNIFORM_BLOCK_SIZE); MAX_UNIFORMS = MAX_UNIFORM_BLOCK_SIZE / sizeof(mat4); cout << "UNIFORM_BUFFER_OFFSET_ALIGNMENT: " << UNIFORM_BUFFER_OFFSET_ALIGNMENT << endl; cout << "MAX_UNIFORMS: " << MAX_UNIFORMS << endl; // Setup Dear ImGui binding IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls ImGui_ImplGlfwGL3_Init(window, true); // Setup style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetKeyCallback(window, key_callback); const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* version = glGetString(GL_VERSION); printf("Renderer: %s\n", renderer); printf("OpenGL version supported %s\n", version); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); // glCullFace(GL_BACK); // glFrontFace(GL_CW); int x, y; unsigned char* texImage = loadImage("test.png", &x, &y); if (texImage) { cout << "Yay, I loaded an image!" << endl; cout << x << endl; cout << y << endl; printf("first 4 bytes are: %i %i %i %i\n", texImage[0], texImage[1], texImage[2], texImage[3]); } GLuint tex = 0; glGenTextures(1, &tex); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, texImage); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); /* RENDERING ALGORITHM * * Create a separate vbo for each of the following things: * - points * - colors * - texture coordinates * - selected colors * - normals * - indices into a ubo that stores a model matrix for each object * * Also, make a model matrix ubo, the entirety of which will be passed to the vertex shader. * The vbo containing the correct index into the ubo (mentioned above) will be used to select * the right model matrix for each point. The index in the vbo will be the saem for all points * of any given object. * * There will be two shader programs for now, one for draing colored objects, and another for * drawing textured ones. The points, normals, and model mat ubo indices will be passed to both * shaders, while the colors vbo will only be passed to the colors shader, and the texcoords vbo * only to the texture shader. * * Right now, the currently selected object is drawn using one color (specified in the selected * colors vbo) regardless of whether it is normally rendering using colors or a texture. The selected * object is rendering by binding the selected colors vbo in place of the colors vbo and using the colors * shader. Then, the selected object is redrawn along with all other objects, but the depth buffer test * prevents the unselected version of the object from appearing on the screen. This lets me render all the * objects that use a particular shader using one glDrawArrays() call. */ map shaderBufferInfo; GLuint color_sp = loadShaderProgram("./color.vert", "./color.frag"); GLuint texture_sp = loadShaderProgram("./texture.vert", "./texture.frag"); shaderBufferInfo[color_sp] = BufferInfo(); shaderBufferInfo[texture_sp] = BufferInfo(); SceneObject obj; mat4 T_model, R_model; /* // triangle obj = SceneObject(); obj.shader_program = color_sp; obj.points = { 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f, }; obj.colors = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, }; obj.texcoords = { 0.0f }; obj.selected_colors = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; T_model = translate(mat4(1.0f), vec3(0.45f, -1.5f, 0.0f)); R_model = rotate(mat4(1.0f), 0.0f, vec3(0.0f, 1.0f, 0.0f)); obj.model_base = T_model*R_model; addObjectToSceneDuringInit(obj); // square obj = SceneObject(); obj.shader_program = texture_sp; obj.points = { 0.5f, 0.5f, 0.0f, -0.5f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, }; obj.colors = { 0.0f }; obj.texcoords = { 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f }; obj.selected_colors = { 0.0f, 0.6f, 0.9f, 0.0f, 0.6f, 0.9f, 0.0f, 0.6f, 0.9f, 0.0f, 0.6f, 0.9f, 0.0f, 0.6f, 0.9f, 0.0f, 0.6f, 0.9f, }; T_model = translate(mat4(1.0f), vec3(-0.5f, -1.5f, -1.00f)); R_model = rotate(mat4(1.0f), 0.5f, vec3(0.0f, 1.0f, 0.0f)); obj.model_base = T_model*R_model; addObjectToSceneDuringInit(obj); */ // player ship obj = SceneObject(); obj.shader_program = color_sp; obj.points = { //back -0.5f, 0.3f, 0.0f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, -0.5f, 0.3f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f, 0.3f, 0.0f, // left back -0.5f, 0.3f, -2.0f, -0.5f, 0.0f, -2.0f, -0.5f, 0.0f, 0.0f, -0.5f, 0.3f, -2.0f, -0.5f, 0.0f, 0.0f, -0.5f, 0.3f, 0.0f, // right back 0.5f, 0.3f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, -2.0f, 0.5f, 0.3f, 0.0f, 0.5f, 0.0f, -2.0f, 0.5f, 0.3f, -2.0f, // left mid -0.25f, 0.3f, -3.0f, -0.25f, 0.0f, -3.0f, -0.5f, 0.0f, -2.0f, -0.25f, 0.3f, -3.0f, -0.5f, 0.0f, -2.0f, -0.5f, 0.3f, -2.0f, // right mid 0.5f, 0.3f, -2.0f, 0.5f, 0.0f, -2.0f, 0.25f, 0.0f, -3.0f, 0.5f, 0.3f, -2.0f, 0.25f, 0.0f, -3.0f, 0.25f, 0.3f, -3.0f, // left front 0.0f, 0.0f, -3.5f, -0.25f, 0.0f, -3.0f, -0.25f, 0.3f, -3.0f, // right front 0.25f, 0.3f, -3.0f, 0.25f, 0.0f, -3.0f, 0.0f, 0.0f, -3.5f, // top back -0.5f, 0.3f, -2.0f, -0.5f, 0.3f, 0.0f, 0.5f, 0.3f, 0.0f, -0.5f, 0.3f, -2.0f, 0.5f, 0.3f, 0.0f, 0.5f, 0.3f, -2.0f, // bottom back -0.5f, 0.0f, 0.0f, -0.5f, 0.0f, -2.0f, 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, -0.5f, 0.0f, -2.0f, 0.5f, 0.0f, -2.0f, // top mid -0.25f, 0.3f, -3.0f, -0.5f, 0.3f, -2.0f, 0.5f, 0.3f, -2.0f, -0.25f, 0.3f, -3.0f, 0.5f, 0.3f, -2.0f, 0.25f, 0.3f, -3.0f, // bottom mid -0.5f, 0.0f, -2.0f, -0.25f, 0.0f, -3.0f, 0.5f, 0.0f, -2.0f, 0.5f, 0.0f, -2.0f, -0.25f, 0.0f, -3.0f, 0.25f, 0.0f, -3.0f, // top front -0.25f, 0.3f, -3.0f, 0.25f, 0.3f, -3.0f, 0.0f, 0.0f, -3.5f, // bottom front 0.25f, 0.0f, -3.0f, -0.25f, 0.0f, -3.0f, 0.0f, 0.0f, -3.5f, // left wing start back -1.5f, 0.3f, 0.0f, -1.5f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, -1.5f, 0.3f, 0.0f, -0.5f, 0.0f, 0.0f, -0.5f, 0.3f, 0.0f, // left wing start top -0.5f, 0.3f, -0.3f, -1.3f, 0.3f, -0.3f, -1.5f, 0.3f, 0.0f, -0.5f, 0.3f, -0.3f, -1.5f, 0.3f, 0.0f, -0.5f, 0.3f, 0.0f, // left wing start front -0.5f, 0.3f, -0.3f, -0.5f, 0.0f, -0.3f, -1.3f, 0.0f, -0.3f, -0.5f, 0.3f, -0.3f, -1.3f, 0.0f, -0.3f, -1.3f, 0.3f, -0.3f, // left wing start bottom -0.5f, 0.0f, 0.0f, -1.5f, 0.0f, 0.0f, -1.3f, 0.0f, -0.3f, -0.5f, 0.0f, 0.0f, -1.3f, 0.0f, -0.3f, -0.5f, 0.0f, -0.3f, // left wing end outside -1.5f, 0.3f, 0.0f, -2.2f, 0.15f, -0.8f, -1.5f, 0.0f, 0.0f, // left wing end top -1.3f, 0.3f, -0.3f, -2.2f, 0.15f, -0.8f, -1.5f, 0.3f, 0.0f, // left wing end front -1.3f, 0.0f, -0.3f, -2.2f, 0.15f, -0.8f, -1.3f, 0.3f, -0.3f, // left wing end bottom -1.5f, 0.0f, 0.0f, -2.2f, 0.15f, -0.8f, -1.3f, 0.0f, -0.3f, // right wing start back 1.5f, 0.0f, 0.0f, 1.5f, 0.3f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 1.5f, 0.3f, 0.0f, 0.5f, 0.3f, 0.0f, // right wing start top 1.3f, 0.3f, -0.3f, 0.5f, 0.3f, -0.3f, 1.5f, 0.3f, 0.0f, 1.5f, 0.3f, 0.0f, 0.5f, 0.3f, -0.3f, 0.5f, 0.3f, 0.0f, // right wing start front 0.5f, 0.0f, -0.3f, 0.5f, 0.3f, -0.3f, 1.3f, 0.0f, -0.3f, 1.3f, 0.0f, -0.3f, 0.5f, 0.3f, -0.3f, 1.3f, 0.3f, -0.3f, // right wing start bottom 1.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 1.3f, 0.0f, -0.3f, 1.3f, 0.0f, -0.3f, 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, -0.3f, // right wing end outside 2.2f, 0.15f, -0.8f, 1.5f, 0.3f, 0.0f, 1.5f, 0.0f, 0.0f, // right wing end top 2.2f, 0.15f, -0.8f, 1.3f, 0.3f, -0.3f, 1.5f, 0.3f, 0.0f, // right wing end front 2.2f, 0.15f, -0.8f, 1.3f, 0.0f, -0.3f, 1.3f, 0.3f, -0.3f, // right wing end bottom 2.2f, 0.15f, -0.8f, 1.5f, 0.0f, 0.0f, 1.3f, 0.0f, -0.3f, }; obj.colors = { 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.3f, }; obj.texcoords = { 0.0f }; obj.selected_colors = { 0.0f }; T_model = translate(mat4(1.0f), vec3(0.0f, -1.2f, 1.8f)); R_model = rotate(mat4(1.0f), 20.0f * (float)ONE_DEG_IN_RAD, vec3(1.0f, 0.0f, 0.0f)); R_model = mat4(1.0f); obj.model_base = T_model * R_model * scale(mat4(1.0f), vec3(0.1f, 0.1f, 0.1f)); obj.translate_mat = T_model; addObjectToSceneDuringInit(obj); vector::iterator obj_it; GLuint points_vbo, colors_vbo, selected_colors_vbo, texcoords_vbo, normals_vbo, ubo, model_mat_idx_vbo; initializeBuffers( &points_vbo, &colors_vbo, &selected_colors_vbo, &texcoords_vbo, &normals_vbo, &ubo, &model_mat_idx_vbo); populateBuffers(objects, shaderBufferInfo, points_vbo, colors_vbo, selected_colors_vbo, texcoords_vbo, normals_vbo, ubo, model_mat_idx_vbo); GLuint vao = 0; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, points_vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, normals_vbo); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, model_mat_idx_vbo); glVertexAttribIPointer(3, 1, GL_UNSIGNED_INT, 0, 0); GLuint vao2 = 0; glGenVertexArrays(1, &vao2); glBindVertexArray(vao2); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, points_vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, texcoords_vbo); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, normals_vbo); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, model_mat_idx_vbo); glVertexAttribIPointer(3, 1, GL_UNSIGNED_INT, 0, 0); float cam_speed = 1.0f; float cam_yaw_speed = 60.0f*ONE_DEG_IN_RAD; float cam_pitch_speed = 60.0f*ONE_DEG_IN_RAD; // glm::lookAt can create the view matrix // glm::perspective can create the projection matrix cam_pos = vec3(0.0f, 0.0f, 2.0f); //cam_pos = vec3(-2.1f, -1.5f, -1.5f); // Good position for checking ship faces float cam_yaw = 0.0f * 2.0f * 3.14159f / 360.0f; float cam_pitch = -50.0f * 2.0f * 3.14159f / 360.0f; mat4 T = translate(mat4(1.0f), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z)); mat4 yaw_mat = rotate(mat4(1.0f), -cam_yaw, vec3(0.0f, 1.0f, 0.0f)); mat4 pitch_mat = rotate(mat4(1.0f), -cam_pitch, vec3(1.0f, 0.0f, 0.0f)); mat4 R = pitch_mat * yaw_mat; view_mat = R*T; float fov = 67.0f * ONE_DEG_IN_RAD; float aspect = (float)width / (float)height; float range = tan(fov * 0.5f) * NEAR_CLIP; float Sx = NEAR_CLIP / (range * aspect); float Sy = NEAR_CLIP / range; float Sz = -(FAR_CLIP + NEAR_CLIP) / (FAR_CLIP - NEAR_CLIP); float Pz = -(2.0f * FAR_CLIP * NEAR_CLIP) / (FAR_CLIP - NEAR_CLIP); float proj_arr[] = { Sx, 0.0f, 0.0f, 0.0f, 0.0f, Sy, 0.0f, 0.0f, 0.0f, 0.0f, Sz, -1.0f, 0.0f, 0.0f, Pz, 0.0f, }; proj_mat = make_mat4(proj_arr); GLuint ub_binding_point = 0; GLuint view_test_loc = glGetUniformLocation(color_sp, "view"); GLuint proj_test_loc = glGetUniformLocation(color_sp, "proj"); GLuint color_sp_ub_index = glGetUniformBlockIndex(color_sp, "models"); GLuint view_mat_loc = glGetUniformLocation(texture_sp, "view"); GLuint proj_mat_loc = glGetUniformLocation(texture_sp, "proj"); GLuint texture_sp_ub_index = glGetUniformBlockIndex(texture_sp, "models"); glUseProgram(color_sp); glUniformMatrix4fv(view_test_loc, 1, GL_FALSE, value_ptr(view_mat)); glUniformMatrix4fv(proj_test_loc, 1, GL_FALSE, value_ptr(proj_mat)); glUniformBlockBinding(color_sp, color_sp_ub_index, ub_binding_point); glBindBufferRange(GL_UNIFORM_BUFFER, ub_binding_point, ubo, 0, GL_MAX_UNIFORM_BLOCK_SIZE); glUseProgram(texture_sp); glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, value_ptr(view_mat)); glUniformMatrix4fv(proj_mat_loc, 1, GL_FALSE, value_ptr(proj_mat)); glUniformBlockBinding(texture_sp, texture_sp_ub_index, ub_binding_point); glBindBufferRange(GL_UNIFORM_BUFFER, ub_binding_point, ubo, 0, GL_MAX_UNIFORM_BLOCK_SIZE); bool cam_moved = false; int frame_count = 0; double elapsed_seconds_fps = 0.0f; double elapsed_seconds_spawn = 0.0f; double previous_seconds = glfwGetTime(); // This draws wireframes. Useful for seeing separate faces and occluded objects. //glPolygonMode(GL_FRONT, GL_LINE); if (DISABLE_VSYNC && SHOW_FPS) { glfwSwapInterval(0); } State curState = STATE_MAIN_MENU; while (!glfwWindowShouldClose(window) && isRunning) { double current_seconds = glfwGetTime(); double elapsed_seconds = current_seconds - previous_seconds; previous_seconds = current_seconds; if (SHOW_FPS) { elapsed_seconds_fps += elapsed_seconds; if (elapsed_seconds_fps > 0.25f) { fps = (double)frame_count / elapsed_seconds_fps; cout << "FPS: " << fps << endl; frame_count = 0; elapsed_seconds_fps = 0.0f; } frame_count++; } // Handle events clickedObject = NULL; // reset the all key states to KEY_STATE_UNCHANGED (something the GLFW key callback can never return) // so that GLFW_PRESS and GLFW_RELEASE are only detected once // TODO: Change this if we ever need to act on GLFW_REPEAT (which is when a key is held down // continuously for a period of time) fill(key_state, key_state + NUM_KEYS, KEY_STATE_UNCHANGED); glfwPollEvents(); while (!events.empty()) { switch (events.front()) { case EVENT_GO_TO_MAIN_MENU: curState = STATE_MAIN_MENU; break; case EVENT_GO_TO_GAME: curState = STATE_GAME; break; case EVENT_QUIT: isRunning = false; break; } events.pop(); } if (curState == STATE_GAME) { elapsed_seconds_spawn += elapsed_seconds; if (elapsed_seconds_spawn > 0.5f) { spawnAsteroid(vec3(getRandomNum(-1.3f, 1.3f), getRandomNum(-3.0f, -1.0f), getRandomNum(-5.5f, -4.5f)), color_sp, shaderBufferInfo, points_vbo, colors_vbo, selected_colors_vbo, texcoords_vbo, normals_vbo, ubo, model_mat_idx_vbo); elapsed_seconds_spawn -= 0.5f; } /* if (clickedObject == &objects[0]) { selectedObject = &objects[0]; } if (clickedObject == &objects[1]) { selectedObject = &objects[1]; } */ /* if (key_state[GLFW_KEY_SPACE] == GLFW_PRESS) { transformObject(objects[1], translate(mat4(1.0f), vec3(0.3f, 0.0f, 0.0f)), ubo); } if (key_pressed[GLFW_KEY_RIGHT]) { transformObject(objects[2], translate(mat4(1.0f), vec3(0.01f, 0.0f, 0.0f)), ubo); } if (key_pressed[GLFW_KEY_LEFT]) { transformObject(objects[2], translate(mat4(1.0f), vec3(-0.01f, 0.0f, 0.0f)), ubo); } */ if (key_pressed[GLFW_KEY_RIGHT]) { transformObject(objects[0], translate(mat4(1.0f), vec3(0.01f, 0.0f, 0.0f)), ubo); } if (key_pressed[GLFW_KEY_LEFT]) { transformObject(objects[0], translate(mat4(1.0f), vec3(-0.01f, 0.0f, 0.0f)), ubo); } for (int i = 1; i < objects.size(); i++) { if (!objects[i].deleted) { transformObject(objects[i], translate(mat4(1.0f), vec3(0.0f, 0.0f, 0.04f)), ubo); vec3 obj_center = vec3(view_mat * vec4(objects[i].bounding_center, 1.0f)); if ((obj_center.z - objects[i].bounding_radius) > -NEAR_CLIP) { removeObjectFromScene(objects[i], ubo); } } } if (key_state[GLFW_KEY_SPACE] == GLFW_PRESS) { removeObjectFromScene(objects[0], ubo); } } if (key_state[GLFW_KEY_ESCAPE] == GLFW_PRESS) { glfwSetWindowShouldClose(window, 1); } float dist = cam_speed * elapsed_seconds; if (key_pressed[GLFW_KEY_A]) { vec3 dir = vec3(inverse(R) * vec4(-1.0f, 0.0f, 0.0f, 1.0f)); cam_pos += dir * dist; cam_moved = true; } if (key_pressed[GLFW_KEY_D]) { vec3 dir = vec3(inverse(R) * vec4(1.0f, 0.0f, 0.0f, 1.0f)); cam_pos += dir * dist; cam_moved = true; } if (key_pressed[GLFW_KEY_W]) { vec3 dir = vec3(inverse(R) * vec4(0.0f, 0.0f, -1.0f, 1.0f)); cam_pos += dir * dist; cam_moved = true; } if (key_pressed[GLFW_KEY_S]) { vec3 dir = vec3(inverse(R) * vec4(0.0f, 0.0f, 1.0f, 1.0f)); cam_pos += dir * dist; cam_moved = true; } /* if (key_pressed[GLFW_KEY_LEFT]) { cam_yaw += cam_yaw_speed * elapsed_seconds; cam_moved = true; } if (key_pressed[GLFW_KEY_RIGHT]) { cam_yaw -= cam_yaw_speed * elapsed_seconds; cam_moved = true; } if (key_pressed[GLFW_KEY_UP]) { cam_pitch += cam_pitch_speed * elapsed_seconds; cam_moved = true; } if (key_pressed[GLFW_KEY_DOWN]) { cam_pitch -= cam_pitch_speed * elapsed_seconds; cam_moved = true; } */ if (cam_moved) { T = translate(mat4(1.0f), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z)); mat4 yaw_mat = rotate(mat4(1.0f), -cam_yaw, vec3(0.0f, 1.0f, 0.0f)); mat4 pitch_mat = rotate(mat4(1.0f), -cam_pitch, vec3(1.0f, 0.0f, 0.0f)); R = pitch_mat * yaw_mat; view_mat = R * T; //printVector("cam pos", cam_pos); glUseProgram(color_sp); glUniformMatrix4fv(view_test_loc, 1, GL_FALSE, value_ptr(view_mat)); glUseProgram(texture_sp); glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, value_ptr(view_mat)); cam_moved = false; } // Render scene glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); switch (curState) { case STATE_MAIN_MENU: renderMainMenu(); renderMainMenuGui(); break; case STATE_GAME: renderScene(objects, color_sp, texture_sp, vao, vao2, points_vbo, normals_vbo, colors_vbo, texcoords_vbo, selected_colors_vbo, selectedObject, shaderBufferInfo); renderSceneGui(); break; } glfwSwapBuffers(window); } ImGui_ImplGlfwGL3_Shutdown(); ImGui::DestroyContext(); glfwDestroyWindow(window); glfwTerminate(); return 0; } void glfw_error_callback(int error, const char* description) { gl_log_err("GLFW ERROR: code %i msg: %s\n", error, description); } void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { double mouse_x, mouse_y; glfwGetCursorPos(window, &mouse_x, &mouse_y); if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { cout << "Mouse clicked (" << mouse_x << "," << mouse_y << ")" << endl; selectedObject = NULL; float x = (2.0f*mouse_x) / width - 1.0f; float y = 1.0f - (2.0f*mouse_y) / height; cout << "x: " << x << ", y: " << y << endl; vec4 ray_clip = vec4(x, y, -1.0f, 1.0f); vec4 ray_eye = inverse(proj_mat) * ray_clip; ray_eye = vec4(vec2(ray_eye), -1.0f, 1.0f); vec4 ray_world = inverse(view_mat) * ray_eye; vec4 cam_pos_temp = vec4(cam_pos, 1.0f); vec4 click_point; 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 SceneObject* closest_object = NULL; for (vector::iterator it = objects.begin(); it != objects.end(); it++) { for (unsigned int p_idx = 0; p_idx < it->points.size(); p_idx += 9) { if (faceClicked( { vec3(it->points[p_idx], it->points[p_idx + 1], it->points[p_idx + 2]), vec3(it->points[p_idx + 3], it->points[p_idx + 4], it->points[p_idx + 5]), vec3(it->points[p_idx + 6], it->points[p_idx + 7], it->points[p_idx + 8]), }, &*it, ray_world, cam_pos_temp, click_point )) { click_point = view_mat * click_point; if (-NEAR_CLIP >= click_point.z && click_point.z > -FAR_CLIP && click_point.z > closest_point.z) { closest_point = vec3(click_point); closest_object = &*it; } } } } if (closest_object == NULL) { cout << "No object was clicked" << endl; } else { clickedObject = closest_object; cout << "Clicked object: " << clickedObject->id << endl; } } } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { key_state[key] = action; // should be true for GLFW_PRESS and GLFW_REPEAT key_pressed[key] = (action != GLFW_RELEASE); } GLuint loadShader(GLenum type, string file) { cout << "Loading shader from file " << file << endl; ifstream shaderFile(file); GLuint shaderId = 0; if (shaderFile.is_open()) { string line, shaderString; while(getline(shaderFile, line)) { shaderString += line + "\n"; } shaderFile.close(); const char* shaderCString = shaderString.c_str(); shaderId = glCreateShader(type); glShaderSource(shaderId, 1, &shaderCString, NULL); glCompileShader(shaderId); cout << "Loaded successfully" << endl; } else { cout << "Failed to load the file" << endl; } return shaderId; } GLuint loadShaderProgram(string vertexShaderPath, string fragmentShaderPath) { GLuint vs = loadShader(GL_VERTEX_SHADER, vertexShaderPath); GLuint fs = loadShader(GL_FRAGMENT_SHADER, fragmentShaderPath); GLuint shader_program = glCreateProgram(); glAttachShader(shader_program, vs); glAttachShader(shader_program, fs); glLinkProgram(shader_program); return shader_program; } unsigned char* loadImage(string file_name, int* x, int* y) { int n; int force_channels = 4; // This forces RGBA (4 bytes per pixel) unsigned char* image_data = stbi_load(file_name.c_str(), x, y, &n, force_channels); int width_in_bytes = *x * 4; unsigned char *top = NULL; unsigned char *bottom = NULL; unsigned char temp = 0; int half_height = *y / 2; // flip image upside-down to account for OpenGL treating lower-left as (0, 0) for (int row = 0; row < half_height; row++) { top = image_data + row * width_in_bytes; bottom = image_data + (*y - row - 1) * width_in_bytes; for (int col = 0; col < width_in_bytes; col++) { temp = *top; *top = *bottom; *bottom = temp; top++; bottom++; } } if (!image_data) { fprintf(stderr, "ERROR: could not load %s\n", file_name.c_str()); } // Not Power-of-2 check if ((*x & (*x - 1)) != 0 || (*y & (*y - 1)) != 0) { fprintf(stderr, "WARNING: texture %s is not power-of-2 dimensions\n", file_name.c_str()); } return image_data; } bool faceClicked(array points, SceneObject* obj, vec4 world_ray, vec4 cam, vec4& click_point) { // LINE EQUATION: P = O + Dt // O = cam // D = ray_world // PLANE EQUATION: P dot n + d = 0 // n is the normal vector // d is the offset from the origin // Take the cross-product of two vectors on the plane to get the normal vec3 v1 = points[1] - points[0]; vec3 v2 = points[2] - points[0]; 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); vec3 local_ray = vec3(inverse(obj->model_mat) * world_ray); vec3 local_cam = vec3(inverse(obj->model_mat) * cam); local_ray = local_ray - local_cam; float d = -glm::dot(points[0], normal); float t = -(glm::dot(local_cam, normal) + d) / glm::dot(local_ray, normal); vec3 intersection = local_cam + t*local_ray; if (insideTriangle(intersection, points)) { click_point = obj->model_mat * vec4(intersection, 1.0f); return true; } else { return false; } } bool insideTriangle(vec3 p, array triangle_points) { vec3 v21 = triangle_points[1] - triangle_points[0]; vec3 v31 = triangle_points[2] - triangle_points[0]; vec3 pv1 = p - triangle_points[0]; float y = (pv1.y*v21.x - pv1.x*v21.y) / (v31.y*v21.x - v31.x*v21.y); float x = (pv1.x-y*v31.x) / v21.x; return x > 0.0f && y > 0.0f && x+y < 1.0f; } void printVector(string label, vec3 v) { cout << label << " -> (" << v.x << "," << v.y << "," << v.z << ")" << endl; } void print4DVector(string label, vec4 v) { cout << label << " -> (" << v.x << "," << v.y << "," << v.z << "," << v.w << ")" << endl; } void addObjectToSceneDuringInit(SceneObject& obj) { // Each objects must have at least 3 points, so the size of // the points array must be a positive multiple of 9 if (obj.points.size() == 0 || (obj.points.size() % 9) != 0) { return; } obj.id = objects.size(); // currently unused obj.num_points = obj.points.size() / 3; obj.model_transform = mat4(1.0f); obj.deleted = false; obj.normals.reserve(obj.points.size()); for (int i = 0; i < obj.points.size(); i += 9) { vec3 point1 = vec3(obj.points[i], obj.points[i + 1], obj.points[i + 2]); vec3 point2 = vec3(obj.points[i + 3], obj.points[i + 4], obj.points[i + 5]); vec3 point3 = vec3(obj.points[i + 6], obj.points[i + 7], obj.points[i + 8]); vec3 normal = normalize(cross(point2 - point1, point3 - point1)); // Add the same normal for all 3 points for (int j = 0; j < 3; j++) { obj.normals.push_back(normal.x); obj.normals.push_back(normal.y); obj.normals.push_back(normal.z); } } calculateObjectBoundingBox(obj); obj.bounding_center = vec3(obj.translate_mat * vec4(obj.bounding_center, 1.0f)); objects.push_back(obj); } void addObjectToScene(SceneObject& obj, map& shaderBufferInfo, GLuint points_vbo, GLuint colors_vbo, GLuint selected_colors_vbo, GLuint texcoords_vbo, GLuint normals_vbo, GLuint ubo, GLuint model_mat_idx_vbo) { addObjectToSceneDuringInit(obj); BufferInfo* bufferInfo = &shaderBufferInfo[obj.shader_program]; // Check if the buffers aren't large enough to fit the new object and, if so, call // populateBuffers() to resize and repopupulate them if (bufferInfo->vbo_capacity < (bufferInfo->ubo_offset + obj.num_points) || bufferInfo->ubo_capacity < (bufferInfo->ubo_offset + 1)) { populateBuffers(objects, shaderBufferInfo, points_vbo, colors_vbo, selected_colors_vbo, texcoords_vbo, normals_vbo, ubo, model_mat_idx_vbo); } else { copyObjectDataToBuffers(objects.back(), shaderBufferInfo, points_vbo, colors_vbo, selected_colors_vbo, texcoords_vbo, normals_vbo, ubo, model_mat_idx_vbo); } } void removeObjectFromScene(SceneObject& obj, GLuint ubo) { if (!obj.deleted) { // Move the object outside the render bounds of the scene so it doesn't get rendered // TODO: Find a better way of hiding the object until the next time buffers are repopulated transformObject(obj, translate(mat4(1.0f), vec3(0.0f, 0.0f, FAR_CLIP * 1000.0f)), ubo); obj.deleted = true; } } void calculateObjectBoundingBox(SceneObject& obj) { GLfloat min_x = obj.points[0]; GLfloat max_x = obj.points[0]; GLfloat min_y = obj.points[1]; GLfloat max_y = obj.points[1]; GLfloat min_z = obj.points[2]; GLfloat max_z = obj.points[2]; // start from the second point for (int i = 3; i < obj.points.size(); i += 3) { if (min_x > obj.points[i]) { min_x = obj.points[i]; } else if (max_x < obj.points[i]) { max_x = obj.points[i]; } if (min_y > obj.points[i + 1]) { min_y = obj.points[i + 1]; } else if (max_y < obj.points[i + 1]) { max_y = obj.points[i + 1]; } if (min_z > obj.points[i + 2]) { min_z = obj.points[i + 2]; } else if (max_z < obj.points[i + 2]) { max_z = obj.points[i + 2]; } } obj.bounding_center = vec3((min_x + max_x) / 2.0f, (min_y + max_y) / 2.0f, (min_z + max_z) / 2.0f); GLfloat radius_x = max_x - obj.bounding_center.x; GLfloat radius_y = max_y - obj.bounding_center.y; GLfloat radius_z = max_z - obj.bounding_center.z; // This actually underestimates the radius. Might need to be fixed at some point. obj.bounding_radius = radius_x; if (obj.bounding_radius < radius_y) obj.bounding_radius = radius_y; if (obj.bounding_radius < radius_z) obj.bounding_radius = radius_z; for (int i = 0; i < obj.points.size(); i += 3) { obj.points[i] -= obj.bounding_center.x; obj.points[i + 1] -= obj.bounding_center.y; obj.points[i + 2] -= obj.bounding_center.z; } obj.bounding_center = vec3(0.0f, 0.0f, 0.0f); } void initializeBuffers( GLuint* points_vbo, GLuint* colors_vbo, GLuint* selected_colors_vbo, GLuint* texcoords_vbo, GLuint* normals_vbo, GLuint* ubo, GLuint* model_mat_idx_vbo) { *points_vbo = 0; glGenBuffers(1, points_vbo); *colors_vbo = 0; glGenBuffers(1, colors_vbo); *selected_colors_vbo = 0; glGenBuffers(1, selected_colors_vbo); *texcoords_vbo = 0; glGenBuffers(1, texcoords_vbo); *normals_vbo = 0; glGenBuffers(1, normals_vbo); *ubo = 0; glGenBuffers(1, ubo); *model_mat_idx_vbo = 0; glGenBuffers(1, model_mat_idx_vbo); } void populateBuffers(vector& objects, map& shaderBufferInfo, GLuint points_vbo, GLuint colors_vbo, GLuint selected_colors_vbo, GLuint texcoords_vbo, GLuint normals_vbo, GLuint ubo, GLuint model_mat_idx_vbo) { GLsizeiptr points_buffer_size = 0; GLsizeiptr textures_buffer_size = 0; GLsizeiptr ubo_buffer_size = 0; GLsizeiptr model_mat_idx_buffer_size = 0; map shaderCounts; map shaderUboCounts; vector::iterator it; /* Find all shaders that need to be used and the number of objects and * number of points for each shader. Construct a map from shader id to count * of points being drawn using that shader (for thw model matrix ubo, we * need object counts instead). These will be used to get offsets into the * vertex buffer for each shader. */ for (it = objects.begin(); it != objects.end();) { if (it->deleted) { it = objects.erase(it); } else { points_buffer_size += it->num_points * sizeof(GLfloat) * 3; textures_buffer_size += it->num_points * sizeof(GLfloat) * 2; ubo_buffer_size += 16 * sizeof(GLfloat); model_mat_idx_buffer_size += it->num_points * sizeof(GLuint); if (shaderCounts.count(it->shader_program) == 0) { shaderCounts[it->shader_program] = it->num_points; shaderUboCounts[it->shader_program] = 1; } else { shaderCounts[it->shader_program] += it->num_points; shaderUboCounts[it->shader_program]++; } it++; } } // double the buffer sizes to leave room for new objects points_buffer_size *= 2; textures_buffer_size *= 2; ubo_buffer_size *= 2; model_mat_idx_buffer_size *= 2; map::iterator shaderIt; unsigned int lastShaderCount = 0; unsigned int lastShaderUboCount = 0; /* * The counts calculated above can be used to get the starting offset of * each shader in the vertex buffer. Create a map of base offsets to mark * where the data for the first object using a given shader begins. Also, * create a map of current offsets to mark where to copy data for the next * object being added. */ for (shaderIt = shaderCounts.begin(); shaderIt != shaderCounts.end(); shaderIt++) { shaderBufferInfo[shaderIt->first].vbo_base = lastShaderCount * 2; shaderBufferInfo[shaderIt->first].ubo_base = lastShaderUboCount * 2; cout << "shader: " << shaderIt->first << endl; cout << "point counts: " << shaderCounts[shaderIt->first] << endl; cout << "object counts: " << shaderUboCounts[shaderIt->first] << endl; cout << "vbo_base: " << shaderBufferInfo[shaderIt->first].vbo_base << endl; cout << "ubo_base: " << shaderBufferInfo[shaderIt->first].ubo_base << endl; shaderBufferInfo[shaderIt->first].vbo_offset = 0; shaderBufferInfo[shaderIt->first].ubo_offset = 0; shaderBufferInfo[shaderIt->first].vbo_capacity = shaderCounts[shaderIt->first] * 2; shaderBufferInfo[shaderIt->first].ubo_capacity = shaderUboCounts[shaderIt->first] * 2; lastShaderCount += shaderCounts[shaderIt->first]; lastShaderUboCount += shaderUboCounts[shaderIt->first]; } // Allocate all the buffers using the counts calculated above glBindBuffer(GL_ARRAY_BUFFER, points_vbo); glBufferData(GL_ARRAY_BUFFER, points_buffer_size, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colors_vbo); glBufferData(GL_ARRAY_BUFFER, points_buffer_size, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, selected_colors_vbo); glBufferData(GL_ARRAY_BUFFER, points_buffer_size, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, texcoords_vbo); glBufferData(GL_ARRAY_BUFFER, textures_buffer_size, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, normals_vbo); glBufferData(GL_ARRAY_BUFFER, points_buffer_size, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, ubo); glBufferData(GL_UNIFORM_BUFFER, ubo_buffer_size, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, model_mat_idx_vbo); glBufferData(GL_ARRAY_BUFFER, model_mat_idx_buffer_size, NULL, GL_DYNAMIC_DRAW); for (it = objects.begin(); it != objects.end(); it++) { copyObjectDataToBuffers(*it, shaderBufferInfo, points_vbo, colors_vbo, selected_colors_vbo, texcoords_vbo, normals_vbo, ubo, model_mat_idx_vbo); } } void copyObjectDataToBuffers(SceneObject& obj, map& shaderBufferInfo, GLuint points_vbo, GLuint colors_vbo, GLuint selected_colors_vbo, GLuint texcoords_vbo, GLuint normals_vbo, GLuint ubo, GLuint model_mat_idx_vbo) { BufferInfo* bufferInfo = &shaderBufferInfo[obj.shader_program]; obj.vertex_vbo_offset = bufferInfo->vbo_base + bufferInfo->vbo_offset; obj.ubo_offset = bufferInfo->ubo_base + bufferInfo->ubo_offset; glBindBuffer(GL_ARRAY_BUFFER, points_vbo); glBufferSubData(GL_ARRAY_BUFFER, obj.vertex_vbo_offset * sizeof(GLfloat) * 3, obj.points.size() * sizeof(GLfloat), &obj.points[0]); glBindBuffer(GL_ARRAY_BUFFER, colors_vbo); glBufferSubData(GL_ARRAY_BUFFER, obj.vertex_vbo_offset * sizeof(GLfloat) * 3, obj.colors.size() * sizeof(GLfloat), &obj.colors[0]); glBindBuffer(GL_ARRAY_BUFFER, selected_colors_vbo); glBufferSubData(GL_ARRAY_BUFFER, obj.vertex_vbo_offset * sizeof(GLfloat) * 3, obj.selected_colors.size() * sizeof(GLfloat), &obj.selected_colors[0]); glBindBuffer(GL_ARRAY_BUFFER, texcoords_vbo); glBufferSubData(GL_ARRAY_BUFFER, obj.vertex_vbo_offset * sizeof(GLfloat) * 2, obj.texcoords.size() * sizeof(GLfloat), &obj.texcoords[0]); glBindBuffer(GL_ARRAY_BUFFER, normals_vbo); glBufferSubData(GL_ARRAY_BUFFER, obj.vertex_vbo_offset * sizeof(GLfloat) * 3, obj.normals.size() * sizeof(GLfloat), &obj.normals[0]); glBindBuffer(GL_ARRAY_BUFFER, model_mat_idx_vbo); for (int i = 0; i < obj.num_points; i++) { glBufferSubData(GL_ARRAY_BUFFER, (obj.vertex_vbo_offset + i) * sizeof(GLuint), sizeof(GLuint), &obj.ubo_offset); } obj.model_mat = obj.model_transform * obj.model_base; glBindBuffer(GL_UNIFORM_BUFFER, ubo); glBufferSubData(GL_UNIFORM_BUFFER, obj.ubo_offset * sizeof(mat4), sizeof(mat4), value_ptr(obj.model_mat)); bufferInfo->vbo_offset += obj.num_points; bufferInfo->ubo_offset++; } void transformObject(SceneObject& obj, const mat4& transform, GLuint ubo) { obj.model_transform = transform * obj.model_transform; obj.model_mat = obj.model_transform * obj.model_base; obj.bounding_center = vec3(transform * vec4(obj.bounding_center, 1.0f)); glBindBuffer(GL_UNIFORM_BUFFER, ubo); glBufferSubData(GL_UNIFORM_BUFFER, obj.ubo_offset * sizeof(mat4), sizeof(mat4), value_ptr(obj.model_mat)); } void renderScene(vector& objects, GLuint color_sp, GLuint texture_sp, GLuint vao1, GLuint vao2, GLuint points_vbo, GLuint normals_vbo, GLuint colors_vbo, GLuint texcoords_vbo, GLuint selected_colors_vbo, SceneObject* selectedObject, map& shaderBufferInfo) { glUseProgram(color_sp); glBindVertexArray(vao1); if (selectedObject != NULL) { glBindBuffer(GL_ARRAY_BUFFER, selected_colors_vbo); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_TRIANGLES, selectedObject->vertex_vbo_offset, selectedObject->num_points); } glBindBuffer(GL_ARRAY_BUFFER, colors_vbo); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_TRIANGLES, shaderBufferInfo[color_sp].vbo_base, shaderBufferInfo[color_sp].vbo_offset); glUseProgram(texture_sp); glBindVertexArray(vao2); glDrawArrays(GL_TRIANGLES, shaderBufferInfo[texture_sp].vbo_base, shaderBufferInfo[texture_sp].vbo_offset); } void renderSceneGui() { ImGui_ImplGlfwGL3_NewFrame(); // 1. Show a simple window. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug". /* { static float f = 0.0f; static int counter = 0; ImGui::Text("Hello, world!"); // Display some text (you can use a format string too) ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our windows open/close state ImGui::Checkbox("Another Window", &show_another_window); if (ImGui::Button("Button")) // Buttons return true when clicked (NB: most widgets return true when edited/activated) counter++; ImGui::SameLine(); ImGui::Text("counter = %d", counter); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } */ { ImGui::SetNextWindowSize(ImVec2(85, 22), ImGuiCond_Once); ImGui::SetNextWindowPos(ImVec2(10, 50), ImGuiCond_Once); ImGui::Begin("WndStats", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); ImGui::Text("Score: ???"); ImGui::End(); } { ImGui::SetNextWindowPos(ImVec2(380, 10), ImGuiCond_Once); ImGui::SetNextWindowSize(ImVec2(250, 35), ImGuiCond_Once); ImGui::Begin("WndMenubar", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); ImGui::InvisibleButton("", ImVec2(155, 18)); ImGui::SameLine(); if (ImGui::Button("Main Menu")) { events.push(EVENT_GO_TO_MAIN_MENU); } ImGui::End(); } ImGui::Render(); ImGui_ImplGlfwGL3_RenderDrawData(ImGui::GetDrawData()); } void renderMainMenu() { } void renderMainMenuGui() { ImGui_ImplGlfwGL3_NewFrame(); { int padding = 4; ImGui::SetNextWindowPos(ImVec2(-padding, -padding), ImGuiCond_Once); ImGui::SetNextWindowSize(ImVec2(width + 2 * padding, height + 2 * padding), ImGuiCond_Once); ImGui::Begin("WndMain", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); ImGui::InvisibleButton("", ImVec2(10, 80)); ImGui::InvisibleButton("", ImVec2(285, 18)); ImGui::SameLine(); if (ImGui::Button("New Game")) { events.push(EVENT_GO_TO_GAME); } ImGui::InvisibleButton("", ImVec2(10, 15)); ImGui::InvisibleButton("", ImVec2(300, 18)); ImGui::SameLine(); if (ImGui::Button("Quit")) { events.push(EVENT_QUIT); } ImGui::End(); } ImGui::Render(); ImGui_ImplGlfwGL3_RenderDrawData(ImGui::GetDrawData()); } void spawnAsteroid(vec3 pos, GLuint shader, map& shaderBufferInfo, GLuint points_vbo, GLuint colors_vbo, GLuint selected_colors_vbo, GLuint texcoords_vbo, GLuint normals_vbo, GLuint ubo, GLuint model_mat_idx_vbo) { SceneObject obj = SceneObject(); obj.shader_program = shader; obj.points = { // front 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, // top 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // bottom 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, // back 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, // right 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, // left -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, }; obj.colors = { // front 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, // top 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, // bottom 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, // back 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, // right 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, // left 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, }; obj.texcoords = { 0.0f }; obj.selected_colors = { 0.0f }; mat4 T = translate(mat4(1.0f), pos); mat4 R = rotate(mat4(1.0f), 60.0f * (float)ONE_DEG_IN_RAD, vec3(1.0f, 1.0f, -1.0f)); obj.model_base = T * R * scale(mat4(1.0f), vec3(0.1f, 0.1f, 0.1f)); obj.translate_mat = T; addObjectToScene(obj, shaderBufferInfo, points_vbo, colors_vbo, selected_colors_vbo, texcoords_vbo, normals_vbo, ubo, model_mat_idx_vbo); } float getRandomNum(float low, float high) { return low + ((float)rand()/RAND_MAX) * (high-low); }