learn-opengl/17-refactor-bug-fix/src/main.cpp

122 lines
2.9 KiB
C++

#define _USE_MATH_DEFINES
#include <stb_image.h>
#include "scene.hpp"
#include "utils.hpp"
void framebuffer_size_callback(GLFWwindow *window, int width, int height);
void init_glfw() {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
}
void framebuffer_size_callback(GLFWwindow *, int width, int height) {
glViewport(0, 0, width, height);
}
void mouse_callback(GLFWwindow *window, double xpos, double ypos) {
Camera* camera = static_cast<Camera*>(glfwGetWindowUserPointer(window));
camera->mouse_move(xpos, ypos);
}
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) {
Camera* camera = static_cast<Camera*>(glfwGetWindowUserPointer(window));
camera->mouse_scroll(xoffset, yoffset);
}
GLFWwindow* create_window() {
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
dbc::check(window != NULL, "failed to open window");
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
auto good = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
dbc::check(good, "failed to load GLAD");
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
return window;
}
void process_input(GLFWwindow *window, Scene& scene) {
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
}
if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
scene.camera.forward();
}
if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
scene.camera.back();
}
if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
scene.camera.left();
}
if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
scene.camera.right();
}
if(glfwGetKey(window, GLFW_KEY_L) == GLFW_PRESS) {
for(auto& light : scene.light.directional) {
light.adjust(-0.01f);
}
}
if(glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS) {
for(auto& light : scene.light.directional) {
light.adjust(0.01f);
}
}
}
Scene setup() {
glEnable(GL_DEPTH_TEST);
components::Scene config = utils::load_scene_config("config.json");
Scene scene(config);
return scene;
}
void update(GLFWwindow* window, Scene& scene) {
glfwPollEvents();
process_input(window, scene);
scene.update();
}
void render(GLFWwindow* window, Scene& scene) {
scene.render(window);
glfwSwapBuffers(window);
}
void quit(GLFWwindow* window, Scene& scene) {
scene.cleanup();
glfwTerminate();
}
int main() {
init_glfw();
auto window = create_window();
auto scene = setup();
glfwSetWindowUserPointer(window, &scene.camera);
while(!glfwWindowShouldClose(window)) {
update(window, scene);
render(window, scene);
}
quit(window, scene);
return 0;
}