Visualizer/src/Application.cpp

103 lines
2.1 KiB
C++
Raw Normal View History

2021-12-20 03:31:44 +00:00
#include "Application.hpp"
#include <stdexcept>
#include <sstream>
2021-12-20 03:50:23 +00:00
#include <glad/glad.h>
2021-12-20 03:31:44 +00:00
#include <GLFW/glfw3.h>
Application::~Application()
{
2021-12-20 23:51:18 +00:00
if (cube != nullptr)
delete cube;
2021-12-20 03:31:44 +00:00
if (window != nullptr)
{
glfwDestroyWindow(window);
window = nullptr;
}
glfwTerminate();
}
void Application::Init(int width, int height, const std::string& title)
{
2021-12-20 03:50:23 +00:00
// Initialize GLFW
2021-12-20 23:51:18 +00:00
if (window == nullptr)
2021-12-20 03:31:44 +00:00
glfwInit();
2021-12-20 22:12:34 +00:00
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
2021-12-20 03:50:23 +00:00
// Create GLFW window
2021-12-20 22:12:34 +00:00
window = glfwCreateWindow(mode->width, mode->height, title.c_str(), monitor, NULL);
2021-12-20 03:31:44 +00:00
if (window == nullptr)
{
const char* errorbuf;
int errorcode = glfwGetError(&errorbuf);
glfwTerminate();
std::stringstream errorstream;
errorstream << "Failed to create GLFWwindow (" << errorcode << "): \n" << errorbuf << std::endl;
throw std::runtime_error(errorstream.str());
}
glfwMakeContextCurrent(window);
2021-12-20 03:50:23 +00:00
// Set up OpenGL
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
glfwDestroyWindow(window);
window = nullptr;
glfwTerminate();
throw std::runtime_error("Failed to initialize GLAD");
}
2021-12-20 22:12:34 +00:00
glViewport(0, 0, mode->width, mode->height);
2021-12-20 23:51:18 +00:00
glEnable(GL_DEPTH_TEST);
2021-12-20 03:50:23 +00:00
// Register GLFW callbacks
2021-12-20 23:51:18 +00:00
glfwSetFramebufferSizeCallback(window,
2021-12-20 03:50:23 +00:00
[](GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
);
2021-12-20 18:09:52 +00:00
2021-12-20 22:12:34 +00:00
glfwSetKeyCallback(window,
[](GLFWwindow* window, int key, int scancode, int action, int mods)
{
// Close window when pressing ESC
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
{
glfwSetWindowShouldClose(window, true);
}
}
);
2021-12-20 23:51:18 +00:00
cube = new Cuboid();
2021-12-20 03:31:44 +00:00
}
void Application::Launch()
{
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
2021-12-20 15:58:47 +00:00
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
2021-12-20 23:51:18 +00:00
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2021-12-20 03:50:23 +00:00
2021-12-20 23:51:18 +00:00
cube->Render();
2021-12-20 18:09:52 +00:00
2021-12-20 03:31:44 +00:00
glfwSwapBuffers(window);
}
}