void drawframe(GLFWwindow* window) { int width = 0, height = 0; float view[4], cx, cy, hw, hh, aspect, px; NSVGshape* shape; NSVGpath* path; glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); glClearColor(220.0f/255.0f, 220.0f/255.0f, 220.0f/255.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Fit view to bounds cx = g_image->width*0.5f; cy = g_image->height*0.5f; hw = g_image->width*0.5f; hh = g_image->height*0.5f; if (width/hw < height/hh) { aspect = (float)height / (float)width; view[0] = cx - hw * 1.2f; view[2] = cx + hw * 1.2f; view[1] = cy - hw * 1.2f * aspect; view[3] = cy + hw * 1.2f * aspect; } else { aspect = (float)width / (float)height; view[0] = cx - hh * 1.2f * aspect; view[2] = cx + hh * 1.2f * aspect; view[1] = cy - hh * 1.2f; view[3] = cy + hh * 1.2f; } // Size of one pixel. px = (view[2] - view[1]) / (float)width; glOrtho(view[0], view[2], view[3], view[1], -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glColor4ub(255,255,255,255); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); // Draw bounds glColor4ub(0,0,0,64); glBegin(GL_LINE_LOOP); glVertex2f(0, 0); glVertex2f(g_image->width, 0); glVertex2f(g_image->width, g_image->height); glVertex2f(0, g_image->height); glEnd(); for (shape = g_image->shapes; shape != NULL; shape = shape->next) { for (path = shape->paths; path != NULL; path = path->next) { drawPath(path->pts, path->npts, path->closed, px * 1.5f); drawControlPts(path->pts, path->npts); } } glfwSwapBuffers(window); }
// the program starts here void AppMain() { // initialise GLFW glfwSetErrorCallback(OnError); if(!glfwInit()) throw std::runtime_error("glfwInit failed"); // open a window with GLFW glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); gWindow = glfwCreateWindow((int)SCREEN_SIZE.x, (int)SCREEN_SIZE.y, "OpenGL Tutorial", NULL, NULL); if(!gWindow) throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 3.2?"); // GLFW settings glfwSetInputMode(gWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(gWindow, 0, 0); glfwSetScrollCallback(gWindow, OnScroll); glfwMakeContextCurrent(gWindow); // initialise GLEW glewExperimental = GL_TRUE; //stops glew crashing on OSX :-/ if(glewInit() != GLEW_OK) throw std::runtime_error("glewInit failed"); // GLEW throws some errors, so discard all the errors so far while(glGetError() != GL_NO_ERROR) {} // print out some info about the graphics drivers std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl; std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl; // make sure OpenGL version 3.2 API is available if(!GLEW_VERSION_3_2) throw std::runtime_error("OpenGL 3.2 API is not available."); // OpenGL settings glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // initialise the gWoodenCrate asset LoadWoodenCrateAsset(); // create all the instances in the 3D scene based on the gWoodenCrate asset CreateInstances(); // setup gCamera gCamera.setPosition(glm::vec3(-4,0,17)); gCamera.setViewportAspectRatio(SCREEN_SIZE.x / SCREEN_SIZE.y); gCamera.setNearAndFarPlanes(0.5f, 100.0f); // setup gLight gLight.position = gCamera.position(); gLight.intensities = glm::vec3(1,1,1); //white // run while the window is open float lastTime = (float)glfwGetTime(); while(!glfwWindowShouldClose(gWindow)){ // process pending events glfwPollEvents(); // update the scene based on the time elapsed since last update float thisTime = (float)glfwGetTime(); Update(thisTime - lastTime); lastTime = thisTime; // draw one frame Render(); // check for errors GLenum error = glGetError(); if(error != GL_NO_ERROR) std::cerr << "OpenGL Error " << error << std::endl; //exit program if escape key is pressed if(glfwGetKey(gWindow, GLFW_KEY_ESCAPE)) glfwSetWindowShouldClose(gWindow, GL_TRUE); } // clean up and exit glfwTerminate(); }
void UiInit(GLFWwindow* window){ glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, 1); glfwSetInputMode(window, GLFW_STICKY_KEYS, 1); glfwSetCursorPos(window, 1366/2, 768/2); }
void KeyboardController::checkInput(ViewState* viewState) { // initialize controller state static double lastTime(glfwGetTime()); GLFWwindow* window = viewState->getWindow(); // determine time difference double currTime = glfwGetTime(); GLfloat diffTime = static_cast<GLfloat>(currTime - lastTime); lastTime = currTime; // camera movement if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS) { camera_->dolly(moveVelocity_ * diffTime); } else { camera_->translate(glm::vec3(0.0f, 0.0f, -moveVelocity_ * diffTime)); } } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS) { camera_->dolly(-moveVelocity_ * diffTime); } else { camera_->translate(glm::vec3(0.0f, 0.0f, moveVelocity_ * diffTime)); } } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera_->translate(glm::vec3(-moveVelocity_ * diffTime, 0.0f, 0.0f)); } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera_->translate(glm::vec3(moveVelocity_ * diffTime, 0.0f, 0.0f)); } if (glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS) { camera_->translate(glm::vec3(0.0f, moveVelocity_ * diffTime, 0.0f)); } if (glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS) { camera_->translate(glm::vec3(0.0f, -moveVelocity_ * diffTime, 0.0f)); } // camera rotation if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS) { camera_->rotateRoll(-rotateVelocity_ * diffTime); } else { if (isFlyMode_) { camera_->rotateYaw(rotateVelocity_ * diffTime); } else { camera_->rotateAzimuth(-rotateVelocity_ * diffTime); } } } if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) { if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS) { camera_->rotateRoll(rotateVelocity_ * diffTime); } else { if (isFlyMode_) { camera_->rotateYaw(-rotateVelocity_ * diffTime); } else { camera_->rotateAzimuth(rotateVelocity_ * diffTime); } } } if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) { if (isFlyMode_) { camera_->rotatePitch(-rotateVelocity_ * diffTime); } else { camera_->rotateElevation(rotateVelocity_ * diffTime); } } if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) { if (isFlyMode_) { camera_->rotatePitch(rotateVelocity_ * diffTime); } else { camera_->rotateElevation(-rotateVelocity_ * diffTime); } } // continuous flight velocity static bool toggleKeyPageUp = false; if (glfwGetKey(window, GLFW_KEY_PAGE_UP) == GLFW_PRESS && !toggleKeyPageUp) { flightVelocity_ -= flightVelocityStep_; toggleKeyPageUp = true; } if (glfwGetKey(window, GLFW_KEY_PAGE_UP) == GLFW_RELEASE) { toggleKeyPageUp = false; } static bool toggleKeyPageDown = false; if (glfwGetKey(window, GLFW_KEY_PAGE_DOWN) == GLFW_PRESS && !toggleKeyPageDown) { flightVelocity_ += flightVelocityStep_; toggleKeyPageDown = true; } if (glfwGetKey(window, GLFW_KEY_PAGE_DOWN) == GLFW_RELEASE) { toggleKeyPageDown = false; } // toggle fly/examine mode static bool toggleKeySpace = false; if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS && !toggleKeySpace) { static bool prevDrawCenterMode = false; isFlyMode_ = !isFlyMode_; if (isFlyMode_) { // fly mode: restore previous draw center point mode camera_->setDrawCenter(prevDrawCenterMode); } else { // examine mode: draw center point, saving current mode prevDrawCenterMode = camera_->isDrawCenter(); camera_->setDrawCenter(true); } toggleKeySpace = true; } if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_RELEASE) { toggleKeySpace = false; } // toggle frame rate output static bool toggleKeyH = false; if (glfwGetKey(window, GLFW_KEY_H) == GLFW_PRESS && !toggleKeyH) { viewState->setFrameRateOutput(!viewState->isFrameRateOutput()); toggleKeyH = true; } if (glfwGetKey(window, GLFW_KEY_H) == GLFW_RELEASE) { toggleKeyH = false; } // toggle draw center point mode static bool toggleKeyJ = false; if (glfwGetKey(window, GLFW_KEY_J) == GLFW_PRESS && !toggleKeyJ) { camera_->setDrawCenter(!camera_->isDrawCenter()); toggleKeyJ = true; } if (glfwGetKey(window, GLFW_KEY_J) == GLFW_RELEASE) { toggleKeyJ = false; } // toggle visibility of mouse cursor static bool toggleKeyK = false; static double mouseXOld(0), mouseYOld(0); if (glfwGetKey(window, GLFW_KEY_K) == GLFW_PRESS && !toggleKeyK) { viewState->setMouseCursorVisible(!viewState->isMouseCursorVisible()); if (viewState->isMouseCursorVisible()) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); glfwSetCursorPos(window, mouseXOld, mouseYOld); } else { glfwGetCursorPos(window, &mouseXOld, &mouseYOld); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } toggleKeyK = true; } if (glfwGetKey(window, GLFW_KEY_K) == GLFW_RELEASE) { toggleKeyK = false; } // toggle line/fill mode static bool toggleKeyL = false; if (glfwGetKey(window, GLFW_KEY_L) == GLFW_PRESS && !toggleKeyL) { static bool isLineMode = false; isLineMode = !isLineMode; isLineMode ? glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) : glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); toggleKeyL = true; } if (glfwGetKey(window, GLFW_KEY_L) == GLFW_RELEASE) { toggleKeyL = false; } // continuous flight action camera_->translate(glm::vec3(0.0f, 0.0f, flightVelocity_ * diffTime)); }
// The MAIN function, from here we start the application and run the game loop int main() { std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl; // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // Options glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers if (glewInit() != GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; return -1; } // Define the viewport dimensions int screenWidth, screenHeight; glfwGetFramebufferSize(window, &screenWidth, &screenHeight); glViewport(0, 0, screenWidth, screenHeight); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Set to always pass the depth test (same effect as glDisable(GL_DEPTH_TEST)) // Build and compile our shader program Shader shader( "/Users/sun/repos/MyProjects/OpenGL/Learn OpenGL/Learn OpenGL/advanced.vs", "/Users/sun/repos/MyProjects/OpenGL/Learn OpenGL/Learn OpenGL/advanced.frag"); Shader screenShader( "/Users/sun/repos/MyProjects/OpenGL/Learn OpenGL/Learn OpenGL/screen.vs", "/Users/sun/repos/MyProjects/OpenGL/Learn OpenGL/Learn OpenGL/screen.frag"); #pragma region "object_initialization" // Set the object data (buffers, vertex attributes) GLfloat cubeVertices[] = { // Positions // Texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; GLfloat floorVertices[] = { // Positions // Texture Coords (note we set these higher than 1 that together with GL_REPEAT as texture wrapping mode will cause the floor texture to repeat) 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, 5.0f, 0.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, -5.0f, 2.0f, 2.0f }; GLfloat quadVertices[] = { // Vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates. // Positions // TexCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; // Setup cube VAO GLuint cubeVAO, cubeVBO; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &cubeVBO); glBindVertexArray(cubeVAO); glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Setup plane VAO GLuint floorVAO, floorVBO; glGenVertexArrays(1, &floorVAO); glGenBuffers(1, &floorVBO); glBindVertexArray(floorVAO); glBindBuffer(GL_ARRAY_BUFFER, floorVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(floorVertices), &floorVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Setup screen VAO GLuint quadVAO, quadVBO; glGenVertexArrays(1, &quadVAO); glGenBuffers(1, &quadVBO); glBindVertexArray(quadVAO); glBindBuffer(GL_ARRAY_BUFFER, quadVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat))); glBindVertexArray(0); // Load textures GLuint cubeTexture = loadTexture("/Users/sun/repos/MyProjects/OpenGL/Learn OpenGL/Learn OpenGL/container.jpg"); GLuint floorTexture = loadTexture("/Users/sun/repos/MyProjects/OpenGL/Learn OpenGL/Learn OpenGL/awesomeface.png"); // Framebuffers GLuint framebuffer; glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); // Create a color attachment texture GLuint textureColorbuffer = generateAttachmentTexture(false, false); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureColorbuffer, 0); // Create a renderbuffer object for depth and stencil attachment (we won't be sampling these) GLuint rbo; glGenRenderbuffers(1, &rbo); glBindRenderbuffer(GL_RENDERBUFFER, rbo); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, screenWidth, screenHeight); // Use a single renderbuffer object for both a depth AND stencil buffer. glBindRenderbuffer(GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); // Now actually attach it // Now that we actually created the framebuffer and added all attachments we want to check if it is actually complete now if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); #pragma endregion // Game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); do_movement(); ///////////////////////////////////////////////////// // Bind to framebuffer and draw to color texture // as we normally would. // ////////////////////////////////////////////////// glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); // Clear all attached buffers glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // We're not using stencil buffer so why bother with clearing? glEnable(GL_DEPTH_TEST); // Set uniforms shader.Use(); glm::mat4 model; glm::mat4 view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth/(float)screenHeight, 0.1f, 100.0f); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); // Floor glBindVertexArray(floorVAO); glBindTexture(GL_TEXTURE_2D, floorTexture); model = glm::mat4(); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); // Cubes glBindVertexArray(cubeVAO); glBindTexture(GL_TEXTURE_2D, cubeTexture); model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); model = glm::mat4(); model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); ///////////////////////////////////////////////////// // Bind to default framebuffer again and draw the // quad plane with attched screen texture. // ////////////////////////////////////////////////// glBindFramebuffer(GL_FRAMEBUFFER, 0); // Clear all relevant buffers glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Set clear color to white (not really necessery actually, since we won't be able to see behind the quad anyways) glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_DEPTH_TEST); // We don't care about depth information when rendering a single quad // Draw Screen screenShader.Use(); glBindVertexArray(quadVAO); glBindTexture(GL_TEXTURE_2D, textureColorbuffer); // Use the color attachment texture as the texture of the quad plane glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); // Swap the buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &cubeVAO); glDeleteBuffers(1, &cubeVBO); glDeleteVertexArrays(1, &floorVAO); glDeleteBuffers(1, &floorVBO); glDeleteVertexArrays(1, &quadVAO); glDeleteBuffers(1, &quadVAO); // glDeleteBuffers(1, &EBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; }
void Interface::showMouse(bool show) const { if (show) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); else glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); }
void SMELT_IMPL::smSetMouse2f(float x,float y){glfwSetInputMode((GLFWwindow*)hwnd,x,y);}
int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // build and compile shaders // ------------------------- Shader shader("6.lighting.vs", "6.lighting.fs"); Shader hdrShader("6.hdr.vs", "6.hdr.fs"); // load textures // ------------- unsigned int woodTexture = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str(), true); // note that we're loading the texture as an SRGB texture // configure floating point framebuffer // ------------------------------------ unsigned int hdrFBO; glGenFramebuffers(1, &hdrFBO); // create floating point color buffer unsigned int colorBuffer; glGenTextures(1, &colorBuffer); glBindTexture(GL_TEXTURE_2D, colorBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // create depth buffer (renderbuffer) unsigned int rboDepth; glGenRenderbuffers(1, &rboDepth); glBindRenderbuffer(GL_RENDERBUFFER, rboDepth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, SCR_WIDTH, SCR_HEIGHT); // attach buffers glBindFramebuffer(GL_FRAMEBUFFER, hdrFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboDepth); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer not complete!" << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); // lighting info // ------------- // positions std::vector<glm::vec3> lightPositions; lightPositions.push_back(glm::vec3( 0.0f, 0.0f, 49.5f)); // back light lightPositions.push_back(glm::vec3(-1.4f, -1.9f, 9.0f)); lightPositions.push_back(glm::vec3( 0.0f, -1.8f, 4.0f)); lightPositions.push_back(glm::vec3( 0.8f, -1.7f, 6.0f)); // colors std::vector<glm::vec3> lightColors; lightColors.push_back(glm::vec3(200.0f, 200.0f, 200.0f)); lightColors.push_back(glm::vec3(0.1f, 0.0f, 0.0f)); lightColors.push_back(glm::vec3(0.0f, 0.0f, 0.2f)); lightColors.push_back(glm::vec3(0.0f, 0.1f, 0.0f)); // shader configuration // -------------------- shader.use(); shader.setInt("diffuseTexture", 0); hdrShader.use(); hdrShader.setInt("hdrBuffer", 0); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 1. render scene into floating point framebuffer // ----------------------------------------------- glBindFramebuffer(GL_FRAMEBUFFER, hdrFBO); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)SCR_WIDTH / (GLfloat)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); shader.use(); shader.setMat4("projection", projection); shader.setMat4("view", view); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, woodTexture); // set lighting uniforms for (unsigned int i = 0; i < lightPositions.size(); i++) { shader.setVec3("lights[" + std::to_string(i) + "].Position", lightPositions[i]); shader.setVec3("lights[" + std::to_string(i) + "].Color", lightColors[i]); } shader.setVec3("viewPos", camera.Position); // render tunnel glm::mat4 model = glm::mat4(); model = glm::translate(model, glm::vec3(0.0f, 0.0f, 25.0)); model = glm::scale(model, glm::vec3(2.5f, 2.5f, 27.5f)); shader.setMat4("model", model); shader.setInt("inverse_normals", true); renderCube(); glBindFramebuffer(GL_FRAMEBUFFER, 0); // 2. now render floating point color buffer to 2D quad and tonemap HDR colors to default framebuffer's (clamped) color range // -------------------------------------------------------------------------------------------------------------------------- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); hdrShader.use(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, colorBuffer); hdrShader.setInt("hdr", hdr); hdrShader.setFloat("exposure", exposure); renderQuad(); std::cout << "hdr: " << (hdr ? "on" : "off") << "| exposure: " << exposure << std::endl; // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; }
// The MAIN function, from here we start our application and run our Game loop int main() { // Init GLFW glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); // Windowed glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // Options glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Initialize GLEW to setup the OpenGL Function pointers glewExperimental = GL_TRUE; glewInit(); // Define the viewport dimensions glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); // Setup and compile our shaders Shader shader("advanced_lighting.vs", "advanced_lighting.frag"); GLfloat planeVertices[] = { // Positions // Normals // Texture Coords 8.0f, -0.5f, 8.0f, 0.0f, 1.0f, 0.0f, 5.0f, 0.0f, -8.0f, -0.5f, 8.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -8.0f, -0.5f, -8.0f, 0.0f, 1.0f, 0.0f, 0.0f, 5.0f, 8.0f, -0.5f, 8.0f, 0.0f, 1.0f, 0.0f, 5.0f, 0.0f, -8.0f, -0.5f, -8.0f, 0.0f, 1.0f, 0.0f, 0.0f, 5.0f, 8.0f, -0.5f, -8.0f, 0.0f, 1.0f, 0.0f, 5.0f, 5.0f }; // Setup plane VAO GLuint planeVAO, planeVBO; glGenVertexArrays(1, &planeVAO); glGenBuffers(1, &planeVBO); glBindVertexArray(planeVAO); glBindBuffer(GL_ARRAY_BUFFER, planeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glBindVertexArray(0); // Light source glm::vec3 lightPos(0.0f, 0.0f, 0.0f); // Load textures GLuint floorTexture = loadTexture("../../../resources/textures/wood.png"); // Game loop while(!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); Do_Movement(); // Clear the colorbuffer glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw objects shader.Use(); glm::mat4 view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); // Set light uniforms glUniform3fv(glGetUniformLocation(shader.Program, "lightPos"), 1, &lightPos[0]); glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]); glUniform1i(glGetUniformLocation(shader.Program, "blinn"), blinn); // Floor glBindVertexArray(planeVAO); glBindTexture(GL_TEXTURE_2D, floorTexture); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); std::cout << (blinn ? "true" : "false") << std::endl; // Swap the buffers glfwSwapBuffers(window); } glfwTerminate(); return 0; }
int main(int argc, char** argv) { if(argc < 2) { std::cerr << "usage: " << argv[0] << " " << "config\n"; return EXIT_FAILURE; } if(!glfwInit()) exit(EXIT_FAILURE); GLFWwindow* window = glfwCreateWindow(xSize, ySize, "Scene Graph", NULL, NULL); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glfwMakeContextCurrent(window); glewInit(); // Set the color which clears the screen between frames glClearColor(0, 0, 0, 1); // Enable and clear the depth buffer glEnable(GL_DEPTH_TEST); glClearDepth(1.0); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // initialize the scene std::ifstream in(argv[1]); if(!in) { std::cout << "couldn't open config " << argv[1] << "\n"; return EXIT_FAILURE; } Config sceneConf(in); scene = new Scene(sceneConf); in.close(); // get the render order nodeList = scene->nodeList(); if(nodeList.size() > 0) { std::string sel = nodeList.front(); scene->bindShader(sel, "contour"); } glfwSetWindowSizeCallback(window, resize); glfwSetKeyCallback(window, keypress); glfwSetCursorPosCallback(window, mousepos); glfwSetScrollCallback(window, scroll); int nbFrames = 0; double lastTime = glfwGetTime(); while(!glfwWindowShouldClose(window)) { // Clear the screen so that we only see newly drawn images glfwSetCursorPos(window, xSize/2, ySize/2); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); scene->draw("diffuse"); scene->draw("contour"); // Move the rendering we just made onto the screen glfwSwapBuffers(window); glfwPollEvents(); double currentTime = glfwGetTime(); nbFrames++; if (currentTime - lastTime >= 1.0){ printf("%f ms/frame\n", 1000.0/double(nbFrames)); nbFrames = 0; lastTime += 1.0; } // Check for any GL errors that have happened recently printGLErrorLog(); } glfwDestroyWindow(window); glfwTerminate(); delete scene; return EXIT_SUCCESS; }
int main(void){ /* Initialize the library */ if (!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_CORE_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); window = glfwCreateWindow(800, 600, "Hello World!", NULL, NULL); if (!window){ glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); /* Setup some glfw callbacks */ glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetWindowSizeCallback(window, onresize); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); /* Initalize glew */ glewExperimental = GL_TRUE; if(glewInit() != GLEW_OK){ std::cout << "Error loading glew" << std::endl; } printf("OpenGL %s, GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); /* Set some OpenGL state values */ glClearColor(0.4f, 0.6f, 0.9f, 0.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); /* Setup the game */ Setup(); double newTime = glfwGetTime(); double lastTime = newTime; deltaTime = newTime - lastTime; std::string title = patch::to_string(deltaTime); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)){ newTime = glfwGetTime(); if(((newTime - lastTime) * 1000) < (1000.0f / 60.0f)){ // dont do anything }else{ Update(); Render(); glfwSwapBuffers(window); glfwPollEvents(); deltaTime = newTime - lastTime; lastTime = newTime; } } Cleanup(); glfwTerminate(); return 0; }
Viewer::Viewer(int width, int height, const std::string title) : window(NULL), close(false), color_index(0), nb_faces(0), azimut(0.0), elevation(0.0), twist(0.0), distance(0.0), draw_normals(false), draw_mode(DRAW_MODE::TRIANGLES), smooth_mode(SMOOTH_MODE::NO_SMOOTH), lighting_mode(LIGHTING_MODE::CONSTANT) { std::cout << "Constructor !!\n" << std::endl; if(!glfwInit()) { std::cerr << "Error initialisaing GLFW" << std::endl; return ; } window = glfwCreateWindow(width, height,title.c_str(), NULL, NULL); if(!window) { std::cerr << "Error creating window" << std::endl; glfwTerminate(); return ; } glfwMakeContextCurrent(window); GLenum state = glewInit(); if(state != GLEW_OK) { std::cerr<<"Error initializing OpenGL" << std::endl; return ; } std::cout << "width = " << width << std::endl; std::cout << "height = " << height << std::endl; glViewport(0,0,width,height); this->setPerspective(90,1.0,0.1,50); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); this->polarView(10,45,45,0); //gluLookAt(2,2,2,0,0,0,0,0,1); //glTranslatef(0.0,0.0,-10.0); /*float azimut = 45.0; float elevation = 45.0; float twist = 0.0; Matrixh mat1; mat1.setRotationZ(PI/2-TO_RADIANS(azimut)); Matrixh mat2; mat2.setRotationX(-PI/2-TO_RADIANS(elevation)); Matrixh mat3; glfwTerminate(); mat3.setRotationY(PI); Matrixh mat4; mat4.setTranslation(0.0,0.0,-10.0); //Matrixh res = mat1 * mat2 * mat3 * mat4; Matrixh res = mat4 * mat3 * mat2 * mat1; glMultMatrixf(res.toColMajorMatrix()); std::cout << "mymatrix = " << res; */ /*float temp[16]; glTranslatef(0.0,0.0,-10.0); glRotatef(TO_DEGRES(PI),0.0,1.0,0.0); glGetFloatv(GL_MODELVIEW_MATRIX,temp); Matrixh mata; mata.fromColMajorMatrix(temp); std::cout << "gl matrix = " << mata; glLoadIdentity(); glRotatef(TO_DEGRES(-PI/2)-elevation,1.0,0.0,0.0); glGetFloatv(GL_MODELVIEW_MATRIX,temp); Matrixh mat; mat.fromColMajorMatrix(temp); std::cout << "gl matrix = " << mat; std::cout << "cos(-3pi/4) = " << cos(TO_RADIANS(TO_DEGRES(-PI/2-PI/4))) << std::endl; glRotatef(TO_DEGRES(PI/2)-azimut,0.0,0.0,1.0); */ /* ======test ========== float temp[16]; glMatrixMode(GL_MODELVIEW_MATRIX); glLoadIdentity(); glRotatef(45,1,0,0); glRotatef(45,0,1,0); glGetFloatv(GL_MODELVIEW_MATRIX,temp); print(temp); Matrixh mx; mx.setRotationX(TO_RADIANS(45)); Matrixh my; my.setRotationY(TO_RADIANS(45)); Matrixh mm = mx * my; std::cout << mm; ------------------------- */ glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // ---------------test lighting -------------- //GLfloat mat_ambient[] = { 0.0, 0.0, 0.0, 1.0 }; //GLfloat mat_diffuse[] = { 0.9, 0.2, 0.1, 1.0 }; //GLfloat mat_specular[] = { 0.9, 0.9, 0.9, 1.0 }; //GLfloat mat_emission[] = { 0.0, 0.0, 0.0, 0.0}; // // //glMaterialfv(GL_FRONT, GL_AMBIENT,mat_ambient); //glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); //glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); //glMaterialfv(GL_FRONT, GL_EMISSION, mat_emission); //glMaterialf(GL_FRONT, GL_SHININESS, 100.0); GLfloat light_ambient[] = {0.4,0.4,0.4,1.0}; GLfloat light_diffuse[] = {0.4,0.4,0.4,1.0}; GLfloat light_specular[] = {0.4,0.4,0.4,1.0}; GLfloat light_position[] = {0,0,50,1}; GLfloat light_direction[] = {0,0,-1,1}; glLightfv(GL_LIGHT0,GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 90.0); glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 10); glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, light_direction); glEnable(GL_LIGHT0); glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_TRUE); glfwSetInputMode(window,GLFW_STICKY_KEYS,GL_FALSE); glfwSetWindowUserPointer(window,this); //store this viewer // use C function as callback and they call instance methods glfwSetWindowSizeCallback(window,reshape_callback); glfwSetScrollCallback(window, zoom_callback); glfwSetMouseButtonCallback(window,mouse_button_callback); glfwSetKeyCallback(window, key_callback); /* ---- init colors ----- */ color_tab[0] = 1.0; color_tab[1] = 0.0; color_tab[2] = 0.0; color_tab[3] = 1.0; color_tab[4] = 1.0; color_tab[5] = 1.0; color_tab[6] = 1.0; color_tab[7] = 1.0; color_tab[8] = 0.0; color_tab[9] = 0.0; color_tab[10] = 1.0; color_tab[11] = 1.0; color_tab[12] = 1.0; color_tab[13] = 0.0; color_tab[14] = 1.0; }
int main() { // Initialize GLFW and set some hints that will create an OpenGL 3.3 context // using core profile. glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a fixed 800x600 window that is not resizable. GLFWwindow* window = glfwCreateWindow(kWindowWidth, kWindowHeight, "LearnGL", nullptr, nullptr); if (window == nullptr) { std::cerr << "Failed to created GLFW window" << std::endl; glfwTerminate(); return 1; } // Create an OpenGL context and pass callbacks to GLFW. glfwMakeContextCurrent(window); glfwSetKeyCallback(window, keyCallback); glfwSetCursorPosCallback(window, mouseCallback); glfwSetScrollCallback(window, scrollCallback); // Lock the mouse in the window. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cerr << "Failed to initialize GLEW" << std::endl; glfwTerminate(); return 1; } // Create a viewport the same size as the window. glfwGetFramebufferSize is // used rather than the size constants since some windowing systems have a // discrepancy between window size and framebuffer size // (e.g HiDPi screen coordinates), int fbWidth, fbHeight; glfwGetFramebufferSize(window, &fbWidth, &fbHeight); glViewport(0, 0, fbWidth, fbHeight); // Enable use of the depth buffer since we're working on 3D and want to // prevent overlapping polygon artifacts. glEnable(GL_DEPTH_TEST); // Read and compile the vertex and fragment shaders using // the shader helper class. Shader shader("glsl/vertex.glsl", "glsl/fragment.glsl", "glsl/geometry.glsl"); Shader lampShader("glsl/lampvertex.glsl", "glsl/lampfragment.glsl"); Shader postShader("glsl/post_vert.glsl", "glsl/post_frag.glsl"); Shader gsShader("glsl/gs_vert.glsl", "glsl/gs_frag.glsl", "glsl/gs_geo.glsl"); GLuint containerTexture = loadTexture("assets/container2.png"); GLuint containerSpecular = loadTexture("assets/container2_specular.png"); GLuint containerEmission = loadTexture("assets/matrix.jpg"); // Create and bind a framebuffer. GLuint FBO; glGenFramebuffers(1, &FBO); glBindFramebuffer(GL_FRAMEBUFFER, FBO); // Create an empty texture to be attached to the framebuffer. // Give a null pointer to glTexImage2D since we want an empty texture. GLuint frameColorBuffer; glGenTextures(1, &frameColorBuffer); glBindTexture(GL_TEXTURE_2D, frameColorBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, fbWidth, fbHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); // Attach the texture to the framebuffer. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, frameColorBuffer, 0); // Create a renderbuffer to hold our depth and stencil buffers with a size // of the window's framebuffer size. GLuint RBO; glGenRenderbuffers(1, &RBO); glBindRenderbuffer(GL_RENDERBUFFER, RBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, fbWidth, fbHeight); glBindRenderbuffer(GL_RENDERBUFFER, 0); // Attach the render buffer (provides depth and stencil) to the framebuffer. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, RBO); // Panic if the framebuffer is somehow incomplete at this stage. This should // never happen if we attached the texture but it's good practice to check. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cerr << "ERROR: Framebuffer is not complete!" << std::endl; glfwTerminate(); return 1; } // Unbind the framebuffer since we want the main scene to be drawn // to be drawn to the main window. glBindFramebuffer(GL_FRAMEBUFFER, 0); // Container mesh data. GLfloat vertices[] = { // Vertices // Normals // UVs -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; // Points for the geometry shader tutorial. GLfloat points[] = { -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // Top-left 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // Top-right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right -0.5f, -0.5f, 1.0f, 1.0f, 0.0f // Bottom-left }; // Positions all containers glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3( 2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3( 1.3f, -2.0f, -2.5f), glm::vec3( 1.5f, 2.0f, -2.5f), glm::vec3( 1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; // Create a VBO to store the vertex data, an EBO to store indice data, and // create a VAO to retain our vertex attribute pointers. GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // Fill the VBO and set vertex attributes. glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glBindVertexArray(0); // Create a lamp box thing using the existing container VBO. GLuint lightVAO; glGenVertexArrays(1, &lightVAO); // Use the container's VBO and set vertex attributes. glBindVertexArray(lightVAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindVertexArray(0); // Vertex attributes for the frame quad in NDC. GLfloat frameVertices[] = { // Positions // UVs -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; // Create a VBO and VAO for the post-processing step. GLuint frameVBO, frameVAO; glGenVertexArrays(1, &frameVAO); glGenBuffers(1, &frameVBO); glBindVertexArray(frameVAO); glBindBuffer(GL_ARRAY_BUFFER, frameVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(frameVertices), frameVertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindVertexArray(0); // Create a VBO and VAO for the geometry shader test. The VBO will contain // only the position. GLuint pointsVBO, pointsVAO; glGenVertexArrays(1, &pointsVAO); glGenBuffers(1, &pointsVBO); glBindVertexArray(pointsVAO); glBindBuffer(GL_ARRAY_BUFFER, pointsVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindVertexArray(0); // Create a perspective camera to fit the viewport. screenWidth = (GLfloat)fbWidth; screenHeight = (GLfloat)fbHeight; camera = PerspectiveCamera( glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0.0f, glm::radians(-90.0f), 0.0f), glm::radians(45.0f), screenWidth / screenHeight, 0.1f, 100.0f ); GLfloat delta = 0.0f; GLfloat lastFrame = 0.0f; // Light information. const glm::vec3 directionalLightDir(0.0f, 1.0f, 0.0f); const glm::vec3 pointLightPositions[] = { glm::vec3( 0.7f, 0.2f, 2.0f), glm::vec3( 2.3f, -3.3f, -4.0f), glm::vec3(-4.0f, 2.0f, -12.0f), glm::vec3( 0.0f, 0.0f, -3.0f) }; // Render loop. while (!glfwWindowShouldClose(window)) { GLfloat currentFrame = glfwGetTime(); delta = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events. glfwPollEvents(); move(delta); // Bind the off screen framebuffer (for post-processing) and clear the // screen to a nice blue color. glBindFramebuffer(GL_FRAMEBUFFER, FBO); glClearColor(0.1f, 0.15f, 0.15f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); const GLfloat limitTime = 1.0f; fovTime += delta; if (fovTime > limitTime) { fovTime = limitTime; } // Update the perspective to account for changes in fov. camera.fov = easeOutQuart(fovTime, startFov, (startFov - targetFov) * -1, limitTime); camera.update(); // Bind the VAO and shader. glBindVertexArray(VAO); shader.use(); // Pass the view and projection matrices from the camera. GLuint viewMatrix = glGetUniformLocation(shader.program, "view"); glUniformMatrix4fv(viewMatrix, 1, GL_FALSE, glm::value_ptr(camera.view)); GLuint projectionMatrix = glGetUniformLocation(shader.program, "projection"); glUniformMatrix4fv(projectionMatrix, 1, GL_FALSE, glm::value_ptr(camera.projection)); // Generate light colors. glm::vec3 lightColor(1.0f, 1.0f, 1.0f); // Directional light glUniform3f(glGetUniformLocation(shader.program, "dirLight.direction"), -0.2f, -1.0f, -0.3f); glUniform3f(glGetUniformLocation(shader.program, "dirLight.ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(shader.program, "dirLight.diffuse"), 0.4f, 0.4f, 0.4f); glUniform3f(glGetUniformLocation(shader.program, "dirLight.specular"), 0.5f, 0.5f, 0.5f); // Point light 1 glUniform3f(glGetUniformLocation(shader.program, "pointLights[0].position"), pointLightPositions[0].x, pointLightPositions[0].y, pointLightPositions[0].z); glUniform3f(glGetUniformLocation(shader.program, "pointLights[0].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(shader.program, "pointLights[0].diffuse"), 1.0f, 0.0f, 0.0f); glUniform3f(glGetUniformLocation(shader.program, "pointLights[0].specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(shader.program, "pointLights[0].constant"), 1.0f); glUniform1f(glGetUniformLocation(shader.program, "pointLights[0].linear"), 0.09); glUniform1f(glGetUniformLocation(shader.program, "pointLights[0].quadratic"), 0.032); // Point light 2 glUniform3f(glGetUniformLocation(shader.program, "pointLights[1].position"), pointLightPositions[1].x, pointLightPositions[1].y, pointLightPositions[1].z); glUniform3f(glGetUniformLocation(shader.program, "pointLights[1].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(shader.program, "pointLights[1].diffuse"), 0.0f, 1.0f, 0.0f); glUniform3f(glGetUniformLocation(shader.program, "pointLights[1].specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(shader.program, "pointLights[1].constant"), 1.0f); glUniform1f(glGetUniformLocation(shader.program, "pointLights[1].linear"), 0.09); glUniform1f(glGetUniformLocation(shader.program, "pointLights[1].quadratic"), 0.032); // Point light 3 glUniform3f(glGetUniformLocation(shader.program, "pointLights[2].position"), pointLightPositions[2].x, pointLightPositions[2].y, pointLightPositions[2].z); glUniform3f(glGetUniformLocation(shader.program, "pointLights[2].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(shader.program, "pointLights[2].diffuse"), 0.0f, 0.0f, 1.0f); glUniform3f(glGetUniformLocation(shader.program, "pointLights[2].specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(shader.program, "pointLights[2].constant"), 1.0f); glUniform1f(glGetUniformLocation(shader.program, "pointLights[2].linear"), 0.09); glUniform1f(glGetUniformLocation(shader.program, "pointLights[2].quadratic"), 0.032); // Point light 4 glUniform3f(glGetUniformLocation(shader.program, "pointLights[3].position"), pointLightPositions[3].x, pointLightPositions[3].y, pointLightPositions[3].z); glUniform3f(glGetUniformLocation(shader.program, "pointLights[3].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(shader.program, "pointLights[3].diffuse"), 0.8f, 0.8f, 0.8f); glUniform3f(glGetUniformLocation(shader.program, "pointLights[3].specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(shader.program, "pointLights[3].constant"), 1.0f); glUniform1f(glGetUniformLocation(shader.program, "pointLights[3].linear"), 0.09); glUniform1f(glGetUniformLocation(shader.program, "pointLights[3].quadratic"), 0.032); // Sport light 1 glUniform3f(glGetUniformLocation(shader.program, "spotLights[0].position"), camera.position.x, camera.position.y, camera.position.z); glUniform3f(glGetUniformLocation(shader.program, "spotLights[0].direction"), camera.front.x, camera.front.y, camera.front.z); glUniform3f(glGetUniformLocation(shader.program, "spotLights[0].ambient"), 0.0f, 0.0f, 0.0f); glUniform3f(glGetUniformLocation(shader.program, "spotLights[0].diffuse"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(shader.program, "spotLights[0].specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(shader.program, "spotLights[0].constant"), 1.0f); glUniform1f(glGetUniformLocation(shader.program, "spotLights[0].linear"), 0.09); glUniform1f(glGetUniformLocation(shader.program, "spotLights[0].quadratic"), 0.032); glUniform1f(glGetUniformLocation(shader.program, "spotLights[0].cutoff"), glm::cos(glm::radians(12.5f))); glUniform1f(glGetUniformLocation(shader.program, "spotLights[0].outerCutoff"), glm::cos(glm::radians(15.5f))); // Pass material values. GLuint materialShininess = glGetUniformLocation(shader.program, "material.shininess"); GLuint materialDiffuse = glGetUniformLocation(shader.program, "material.diffuse"); GLuint materialSpecular = glGetUniformLocation(shader.program, "material.specular"); GLuint materialEmission = glGetUniformLocation(shader.program, "material.emission"); glUniform1f(materialShininess, 64.0f); glUniform1i(materialDiffuse, 0); glUniform1i(materialSpecular, 1); glUniform1i(materialEmission, 2); // Misc values. GLuint viewPos = glGetUniformLocation(shader.program, "viewPos"); glUniform3f(viewPos, camera.position.x, camera.position.y, camera.position.z); GLuint time = glGetUniformLocation(shader.program, "time"); glUniform1f(time, glfwGetTime()); // Bind the textures. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, containerTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, containerSpecular); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, containerEmission); // Draw multiple containers! GLuint modelMatrix = glGetUniformLocation(shader.program, "model"); GLuint normalMatrix = glGetUniformLocation(shader.program, "normalMatrix"); for (GLuint i = 0; i < 10; i++) { // Apply world transformations. model = glm::mat4(); model = glm::translate(model, cubePositions[i]); model = glm::rotate(model, i * 20.0f, glm::vec3(1.0f, 0.3f, 0.5f)); glUniformMatrix4fv(modelMatrix, 1, GL_FALSE, glm::value_ptr(model)); // Calculate the normal matrix on the CPU (keep them normals perpendicular). normal = glm::mat3(glm::transpose(glm::inverse(model))); glUniformMatrix3fv(normalMatrix, 1, GL_FALSE, glm::value_ptr(normal)); // Draw the container. glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); // Bind the VAO and shader. glBindVertexArray(lightVAO); lampShader.use(); // Pass the view and projection matrices from the camera. viewMatrix = glGetUniformLocation(lampShader.program, "view"); glUniformMatrix4fv(viewMatrix, 1, GL_FALSE, glm::value_ptr(camera.view)); projectionMatrix = glGetUniformLocation(lampShader.program, "projection"); glUniformMatrix4fv(projectionMatrix, 1, GL_FALSE, glm::value_ptr(camera.projection)); for (GLuint i = 0; i < 4; i++) { // Apply world transformations. model = glm::mat4(); model = glm::translate(model, pointLightPositions[i]); model = glm::scale(model, glm::vec3(0.2f)); modelMatrix = glGetUniformLocation(lampShader.program, "model"); glUniformMatrix4fv(modelMatrix, 1, GL_FALSE, glm::value_ptr(model)); // Draw the lamp. glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); // Draw something with the geometry shader program. //glDisable(GL_DEPTH_TEST); //gsShader.use(); //glBindVertexArray(pointsVAO); //glDrawArrays(GL_POINTS, 0, 4); //glBindVertexArray(0); //glEnable(GL_DEPTH_TEST); // Unbind the offscreen framebuffer containing the unprocessed frame. glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_DEPTH_TEST); postShader.use(); glBindVertexArray(frameVAO); // Send the texture sampler to the shader. GLuint frameTexture = glGetUniformLocation(postShader.program, "frameTexture"); time = glGetUniformLocation(postShader.program, "time"); glUniform1i(frameTexture, 0); glUniform1f(time, glfwGetTime()); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, frameColorBuffer); // Render the color buffer in the framebuffer to the quad with post shader. glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); // Swap buffers used for double buffering. glfwSwapBuffers(window); } // Destroy the off screen framebuffer. glBindFramebuffer(GL_FRAMEBUFFER, 0); glDeleteFramebuffers(1, &FBO); // Properly deallocate the VBO and VAO. glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW and clean any resources before exiting. glfwTerminate(); return 0; }
int main(int argc, char** argv) { if (!glfwInit()) // 初始化glfw库 { std::cout << "Error::GLFW could not initialize GLFW!" << std::endl; return -1; } // 开启OpenGL 3.3 core profile std::cout << "Start OpenGL core profile version 3.3" << std::endl; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // 创建窗口 GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo of geometry shader(explode effect)", NULL, NULL); if (!window) { std::cout << "Error::GLFW could not create winddow!" << std::endl; glfwTerminate(); std::system("pause"); return -1; } // 创建的窗口的context指定为当前context glfwMakeContextCurrent(window); // 注册窗口键盘事件回调函数 glfwSetKeyCallback(window, key_callback); // 注册鼠标事件回调函数 glfwSetCursorPosCallback(window, mouse_move_callback); // 注册鼠标滚轮事件回调函数 glfwSetScrollCallback(window, mouse_scroll_callback); // 鼠标捕获 停留在程序内 glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // 初始化GLEW 获取OpenGL函数 glewExperimental = GL_TRUE; // 让glew获取所有拓展函数 GLenum status = glewInit(); if (status != GLEW_OK) { std::cout << "Error::GLEW glew version:" << glewGetString(GLEW_VERSION) << " error string:" << glewGetErrorString(status) << std::endl; glfwTerminate(); std::system("pause"); return -1; } // 设置视口参数 glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); //Section1 加载模型数据 为了方便更换模型 我们从文件读取模型文件路径 Model objModel; std::ifstream modelPath("modelPath.txt"); if (!modelPath) { std::cerr << "Error::could not read model path file." << std::endl; glfwTerminate(); std::system("pause"); return -1; } std::string modelFilePath; std::getline(modelPath, modelFilePath); if (modelFilePath.empty()) { std::cerr << "Error::model path empty." << std::endl; glfwTerminate(); std::system("pause"); return -1; } if (!objModel.loadModel(modelFilePath)) { glfwTerminate(); std::system("pause"); return -1; } // Section2 准备着色器程序 Shader shader("model.vertex", "model.frag", "model.gs"); // 添加了几何着色器 glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); // 开始游戏主循环 while (!glfwWindowShouldClose(window)) { GLfloat currentFrame = (GLfloat)glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); // 处理例如鼠标 键盘等事件 do_movement(); // 根据用户操作情况 更新相机属性 // 清除颜色缓冲区 重置为指定颜色 glClearColor(0.18f, 0.04f, 0.14f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shader.use(); glm::mat4 projection = glm::perspective(camera.mouse_zoom, (GLfloat)(WINDOW_WIDTH) / WINDOW_HEIGHT, 1.0f, 100.0f); // 投影矩阵 glm::mat4 view = camera.getViewMatrix(); // 视变换矩阵 glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"), 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 model; model = glm::translate(model, glm::vec3(0.0f, -1.0f, -1.0f)); // 适当调整位置 model = glm::scale(model, glm::vec3(0.25f, 0.25f, 0.25f)); // 适当缩小模型 glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"), 1, GL_FALSE, glm::value_ptr(model)); glUniform1f(glGetUniformLocation(shader.programId, "time"), glfwGetTime()); // 这里填写场景绘制代码 objModel.draw(shader); // 绘制物体 glBindVertexArray(0); glUseProgram(0); glfwSwapBuffers(window); // 交换缓存 } // 释放资源 glfwTerminate(); return 0; }
void frame(GLFWwindow* window) { int width = 0, height = 0; int i,j,k; static float globalTime=0.0f; float x,y; globalTime += 1.0f/60.0f; glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); glClearColor(20.0f/255.0f, 20.0f/255.0f, 90.0f/255.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(viewbounds[0], viewbounds[1], viewbounds[2], viewbounds[3], viewbounds[4], viewbounds[5]); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glColor4ub(255,255,255,255); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); if ( glfwGetKey(window,GLFW_KEY_1)==GLFW_PRESS ) { glPointSize(4.0f); cpoly_marchingsq_nointerp(g_circles,MAXCIRCLES,sizeof(sCircle),SQSIDE); glLineWidth(1.0f); glColor4f(1,1,0,1); k=0; for (i=0;i<cpoly_pool_icount[CPOLY_IPOOL_0];++i) { glBegin(GL_LINE_LOOP); for (j=k;j<cpoly_pool_get_index(CPOLY_IPOOL_0,i);++j ) { cpoly_pool_get_vertex(j,&x,&y); glVertex2f(x,y); } glEnd(); k=j; } // cpoly_convex_hull(cpoly_pool_v,cpoly_pool_get_index(CPOLY_IPOOL_0,0),sizeof(float)*2); // glColor4ub(0,255,0,255); // glBegin(GL_LINE_LOOP); // for ( i=0; i < cpoly_pool_icount[CPOLY_IPOOL_0]; ++i ) // { // j = cpoly_pool_get_index(CPOLY_IPOOL_0,i); // cpoly_pool_get_vertex(j,&x,&y); // glVertex2f( x,y ); // } // glEnd(); } //else { for (i=0;i<MAXCIRCLES;++i) { drawCircle(g_circles[i].x, g_circles[i].y, g_circles[i].r, WHITE, 0, 0, 16.0f); } } drawgrid(); // glPointSize(15.0f); // glColor4ub(255,255,0,255); // glBegin(GL_POINTS); // glVertex2f(0,0); // glEnd(); glfwSwapBuffers(window); }
int main(int argc, char** argv) { int ch, width, height; thrd_t physics_thread = 0; GLFWwindow* window; GLFWmonitor* monitor = NULL; if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); exit(EXIT_FAILURE); } while ((ch = getopt(argc, argv, "fh")) != -1) { switch (ch) { case 'f': monitor = glfwGetPrimaryMonitor(); break; case 'h': usage(); exit(EXIT_SUCCESS); } } if (monitor) { 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); width = mode->width; height = mode->height; } else { width = 640; height = 480; } window = glfwCreateWindow(width, height, "Particle Engine", monitor, NULL); if (!window) { fprintf(stderr, "Failed to create GLFW window\n"); glfwTerminate(); exit(EXIT_FAILURE); } if (monitor) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwMakeContextCurrent(window); glfwSwapInterval(1); glfwSetWindowSizeCallback(window, resize_callback); glfwSetKeyCallback(window, key_callback); // Set initial aspect ratio glfwGetWindowSize(window, &width, &height); resize_callback(window, width, height); // Upload particle texture glGenTextures(1, &particle_tex_id); glBindTexture(GL_TEXTURE_2D, particle_tex_id); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, P_TEX_WIDTH, P_TEX_HEIGHT, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, particle_texture); // Upload floor texture glGenTextures(1, &floor_tex_id); glBindTexture(GL_TEXTURE_2D, floor_tex_id); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, F_TEX_WIDTH, F_TEX_HEIGHT, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, floor_texture); if (glfwExtensionSupported("GL_EXT_separate_specular_color")) { glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SEPARATE_SPECULAR_COLOR_EXT); } // Set filled polygon mode as default (not wireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); wireframe = 0; // Set initial times thread_sync.t = 0.0; thread_sync.dt = 0.001f; thread_sync.p_frame = 0; thread_sync.d_frame = 0; mtx_init(&thread_sync.particles_lock, mtx_timed); cnd_init(&thread_sync.p_done); cnd_init(&thread_sync.d_done); if (thrd_create(&physics_thread, physics_thread_main, window) != thrd_success) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetTime(0.0); while (!glfwWindowShouldClose(window)) { draw_scene(window, glfwGetTime()); glfwSwapBuffers(window); glfwPollEvents(); } thrd_join(physics_thread, NULL); glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
// The MAIN function, from here the application starts and runs the Game loop int main() { //PDB Vertex Spotter glm::vec3 *atomPositions; std::vector<std::string> atom_Location; atomLineFinder(atom_Location); GLfloat scaleFactor = 0.0; int numb_atoms = atom_Location.size(); atomPositions = new glm::vec3[numb_atoms]; gly_finder(atom_Location, numb_atoms, atomPositions, scaleFactor); // Init GLFW glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "NanoVR", nullptr, nullptr); // Windowed glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); // Options glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); // Initialize GLEW to setup the OpenGL Function pointers glewExperimental = GL_TRUE; glewInit(); // Define the viewport dimensions glViewport(0, 0, screenWidth, screenHeight); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); // Setup and compile our shaders Shader shader("default.vs", "default.frag"); // Load models Model ourModel("C:/Users/Taylor/Documents/Build Dir/Third Part Lib/Models/sphere.obj"); // Draw in wireframe //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // Game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); Do_Movement(); // Clear the colorbuffer glClearColor(0.05f, 0.05f, 0.05f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shader.Use(); // Transformation matrices glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth / (float)screenHeight, 0.1f, 100.0f); //glm::mat4 view = camera.GetViewMatrix(); glm::mat4 view = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0., 0., 0.), glm::vec3(0., 1., 0.)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); // Draw the loaded model for (GLuint i = 0; i < 800; i++) { // Calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model; model = glm::scale(model, glm::vec3(scaleFactor, scaleFactor, scaleFactor)); model = glm::translate(model, atomPositions[i]); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); ourModel.Draw(shader); } /* glm::mat4 model; model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f)); // It's a bit too big for our scene, so scale it down glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); ourModel.Draw(shader); */ // Swap the buffers glfwSwapBuffers(window); } glfwTerminate(); return 0; }
// The MAIN function, from here we start our application and run our Game loop int main() { // Init GLFW glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_SAMPLES, 4); GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "This is an awesome motherfucking Window!", nullptr, nullptr); // Windowed glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // Options glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Initialize GLEW to setup the OpenGL Function pointers glewExperimental = GL_TRUE; glewInit(); // Define the viewport dimensions glViewport(0, 0, screenWidth, screenHeight); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); // Setup and compile our shaders Shader ourShader("Shaders/vertex.vert", "Shaders/fragment.frag"); Model ourModel("objects/nanosuit/nanosuit.obj"); // Game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); Do_Movement(); // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ourShader.Use(); glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth / (float)screenHeight, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); glUniformMatrix4fv(glGetUniformLocation(ourShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(ourShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); // Draw the loaded model glm::mat4 model; model = glm::translate(model, glm::vec3(0.0f, -1.75f, 0.0f)); // Translate it down a bit so it's at the center of the scene model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f)); // It's a bit too big for our scene, so scale it downž float angle = glfwGetTime() * 25.0f; model = glm::rotate(model, angle, glm::vec3(0.0f, 1.0f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(ourShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); ourModel.Draw(ourShader); glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glfwTerminate(); return 0; }
int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // build and compile shaders // ------------------------- Shader shader("2.gamma_correction.vs", "2.gamma_correction.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float planeVertices[] = { // positions // normals // texcoords 10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 0.0f, -10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 10.0f, 10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 0.0f, -10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 10.0f, 10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 10.0f }; // plane VAO unsigned int planeVAO, planeVBO; glGenVertexArrays(1, &planeVAO); glGenBuffers(1, &planeVBO); glBindVertexArray(planeVAO); glBindBuffer(GL_ARRAY_BUFFER, planeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), planeVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glBindVertexArray(0); // load textures // ------------- unsigned int floorTexture = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str(), false); unsigned int floorTextureGammaCorrected = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str(), true); // shader configuration // -------------------- shader.use(); shader.setInt("floorTexture", 0); // lighting info // ------------- glm::vec3 lightPositions[] = { glm::vec3(-3.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3 (1.0f, 0.0f, 0.0f), glm::vec3 (3.0f, 0.0f, 0.0f) }; glm::vec3 lightColors[] = { glm::vec3(0.25), glm::vec3(0.50), glm::vec3(0.75), glm::vec3(1.00) }; // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw objects shader.use(); glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); shader.setMat4("projection", projection); shader.setMat4("view", view); // set light uniforms glUniform3fv(glGetUniformLocation(shader.ID, "lightPositions"), 4, &lightPositions[0][0]); glUniform3fv(glGetUniformLocation(shader.ID, "lightColors"), 4, &lightColors[0][0]); shader.setVec3("viewPos", camera.Position); shader.setInt("gamma", gammaEnabled); // floor glBindVertexArray(planeVAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, gammaEnabled ? floorTextureGammaCorrected : floorTexture); glDrawArrays(GL_TRIANGLES, 0, 6); std::cout << (gammaEnabled ? "Gamma enabled" : "Gamma disabled") << std::endl; // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &planeVAO); glDeleteBuffers(1, &planeVBO); glfwTerminate(); return 0; }
int main( void ) { GLFWwindow *window; // Initialize the library if ( !glfwInit( ) ) { return -1; } //glfwWindowHint(GLFW_SAMPLES, 2); // antialiasing // Create a windowed mode window and its OpenGL context window = glfwCreateWindow( SCREEN_WIDTH, SCREEN_HEIGHT, "Hello World", NULL, NULL ); if ( !window ) { glfwTerminate( ); return -1; } // Make the window's context current glfwMakeContextCurrent( window ); glfwSetKeyCallback( window, keyCallback ); glfwSetInputMode( window, GLFW_STICKY_KEYS, 1 ); glViewport( 0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT ); // specifies the part of the window to which OpenGL will draw (in pixels), convert from normalised to pixels glMatrixMode( GL_PROJECTION ); // projection matrix defines the properties of the camera that views the objects in the world coordinate frame. Here you typically set the zoom factor, aspect ratio and the near and far clipping planes glLoadIdentity( ); // replace the current matrix with the identity matrix and starts us a fresh because matrix transforms such as glOrpho and glRotate cumulate, basically puts us at (0, 0, 0) glOrtho( 0, SCREEN_WIDTH, 0, SCREEN_HEIGHT, -1000, 1000 ); // essentially set coordinate system glMatrixMode( GL_MODELVIEW ); // (default matrix mode) modelview matrix defines how your objects are transformed (meaning translation, rotation and scaling) in your world glLoadIdentity( ); // same as above comment // Enable depth test glEnable( GL_DEPTH_TEST ); // Accept fragment if it closer to the camera than the former one // glDepthFunc( GL_LESS ); // glDepthMask(GL_FALSE); GLfloat rotation = 0.0f; GLfloat halfScreenWidth = SCREEN_WIDTH / 2; GLfloat halfScreenHeight = SCREEN_HEIGHT / 2; GLHelper::Shapes3D::Cube cube; cube.SetCenterPosition(halfScreenWidth, halfScreenHeight, 0); cube.SetEdgeLength( 250); cube.SetColour(COLOUR_YELLOW); cube.SetWireframe(true); std::cout << cube.GetColourGreen() << std::endl; // Loop until the user closes the window while ( !glfwWindowShouldClose( window ) ) { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glPushMatrix(); glTranslatef(halfScreenWidth, halfScreenHeight, 0); //glRotatef(rotation, 1, 1, 1); glRotatef( translationX, 1, 0, 0 ); glRotatef( translationY, 0, 1, 0 ); glTranslatef(-halfScreenWidth, -halfScreenHeight, 0); //GLHelper::Shapes3D::Cube::DrawCube(halfScreenWidth, halfScreenHeight, 0.0f, 150, WIREFRAME_ON, COLOUR_RED ); //cube.Draw(); GLHelper::Shapes2D::Circle circle; circle.SetRadius( 175 ); circle.SetColour(COLOUR_GREEN); circle.SetWireframe(true); circle.SetCenterPosition(halfScreenWidth, halfScreenHeight, 0); circle.Draw( ); glPopMatrix(); rotation += 2; // Swap front and back buffers glfwSwapBuffers( window ); // Poll for and process events glfwPollEvents( ); } glDisable( GL_DEPTH_TEST ); glfwTerminate( ); return 0; }
void SMELT_IMPL::smSetMouseGrab(bool enabled){glfwSetInputMode((GLFWwindow*)hwnd,GLFW_CURSOR,enabled?GLFW_CURSOR_DISABLED:GLFW_CURSOR_NORMAL);}
int main(int argc, char **argv) { srand(time(NULL)); rand(); if (!glfwInit()) { return -1; } create_window(); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSwapInterval(VSYNC); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetKeyCallback(window, on_key); glfwSetMouseButtonCallback(window, on_mouse_button); #ifndef __APPLE__ if (glewInit() != GLEW_OK) { return -1; } #endif if (db_init()) { return -1; } glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_LINE_SMOOTH); glLogicOp(GL_INVERT); glClearColor(0.53, 0.81, 0.92, 1.00); GLuint vertex_array; glGenVertexArrays(1, &vertex_array); glBindVertexArray(vertex_array); GLuint texture; glGenTextures(1, &texture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); load_png_texture("texture.png"); GLuint block_program = load_program( "shaders/block_vertex.glsl", "shaders/block_fragment.glsl"); GLuint matrix_loc = glGetUniformLocation(block_program, "matrix"); GLuint camera_loc = glGetUniformLocation(block_program, "camera"); GLuint sampler_loc = glGetUniformLocation(block_program, "sampler"); GLuint timer_loc = glGetUniformLocation(block_program, "timer"); GLuint position_loc = glGetAttribLocation(block_program, "position"); GLuint normal_loc = glGetAttribLocation(block_program, "normal"); GLuint uv_loc = glGetAttribLocation(block_program, "uv"); GLuint line_program = load_program( "shaders/line_vertex.glsl", "shaders/line_fragment.glsl"); GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix"); GLuint line_position_loc = glGetAttribLocation(line_program, "position"); GLuint item_position_buffer = 0; GLuint item_normal_buffer = 0; GLuint item_uv_buffer = 0; int previous_block_type = 0; Chunk chunks[MAX_CHUNKS]; int chunk_count = 0; FPS fps = {0, 0}; float matrix[16]; float x = (rand_double() - 0.5) * 10000; float z = (rand_double() - 0.5) * 10000; float y = 0; float dy = 0; float rx = 0; float ry = 0; double px = 0; double py = 0; int loaded = db_load_state(&x, &y, &z, &rx, &ry); ensure_chunks(chunks, &chunk_count, floorf(roundf(x) / CHUNK_SIZE), floorf(roundf(z) / CHUNK_SIZE), 1); if (!loaded) { y = highest_block(chunks, chunk_count, x, z) + 2; } glfwGetCursorPos(window, &px, &py); double previous = glfwGetTime(); while (!glfwWindowShouldClose(window)) { update_fps(&fps, SHOW_FPS); double now = glfwGetTime(); double dt = MIN(now - previous, 0.2); previous = now; if (exclusive && (px || py)) { double mx, my; glfwGetCursorPos(window, &mx, &my); float m = 0.0025; rx += (mx - px) * m; ry -= (my - py) * m; if (rx < 0) { rx += RADIANS(360); } if (rx >= RADIANS(360)){ rx -= RADIANS(360); } ry = MAX(ry, -RADIANS(90)); ry = MIN(ry, RADIANS(90)); px = mx; py = my; } else { glfwGetCursorPos(window, &px, &py); } if (left_click) { left_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (hy > 0 && is_destructable(hw)) { set_block(chunks, chunk_count, hx, hy, hz, 0); } } if (right_click) { right_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 1, x, y, z, rx, ry, &hx, &hy, &hz); if (is_obstacle(hw)) { if (!player_intersects_block(2, x, y, z, hx, hy, hz)) { set_block(chunks, chunk_count, hx, hy, hz, block_type); } } } int sz = 0; int sx = 0; ortho = glfwGetKey(window, 'F'); fov = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) ? 15.0 : 65.0; if (glfwGetKey(window, 'Q')) break; if (glfwGetKey(window, 'W')) sz--; if (glfwGetKey(window, 'S')) sz++; if (glfwGetKey(window, 'A')) sx--; if (glfwGetKey(window, 'D')) sx++; if (dy == 0 && glfwGetKey(window, GLFW_KEY_SPACE)) { dy = 8; } float vx, vy, vz; get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz); if (glfwGetKey(window, 'Z')) { vx = -1; vy = 0; vz = 0; } if (glfwGetKey(window, 'X')) { vx = 1; vy = 0; vz = 0; } if (glfwGetKey(window, 'C')) { vx = 0; vy = -1; vz = 0; } if (glfwGetKey(window, 'V')) { vx = 0; vy = 1; vz = 0; } if (glfwGetKey(window, 'B')) { vx = 0; vy = 0; vz = -1; } if (glfwGetKey(window, 'N')) { vx = 0; vy = 0; vz = 1; } float speed = flying ? 20 : 5; int step = 8; float ut = dt / step; vx = vx * ut * speed; vy = vy * ut * speed; vz = vz * ut * speed; for (int i = 0; i < step; i++) { if (flying) { dy = 0; } else { dy -= ut * 25; dy = MAX(dy, -250); } x += vx; y += vy + dy * ut; z += vz; if (collide(chunks, chunk_count, 2, &x, &y, &z)) { dy = 0; } } int p = floorf(roundf(x) / CHUNK_SIZE); int q = floorf(roundf(z) / CHUNK_SIZE); ensure_chunks(chunks, &chunk_count, p, q, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); update_matrix_3d(matrix, x, y, z, rx, ry); // render chunks glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, x, y, z); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); for (int i = 0; i < chunk_count; i++) { Chunk *chunk = chunks + i; if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) { continue; } if (!chunk_visible(chunk, matrix)) { continue; } draw_chunk(chunk, position_loc, normal_loc, uv_loc); } // render focused block wireframe int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (is_obstacle(hw)) { glUseProgram(line_program); glLineWidth(1); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint buffer = make_cube_buffer(hx, hy, hz, 0.51); draw_lines(buffer, line_position_loc, 3, 48); glDeleteBuffers(1, &buffer); glDisable(GL_COLOR_LOGIC_OP); } update_matrix_2d(matrix); // render crosshairs glUseProgram(line_program); glLineWidth(4); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint buffer = make_line_buffer(); draw_lines(buffer, line_position_loc, 2, 4); glDeleteBuffers(1, &buffer); glDisable(GL_COLOR_LOGIC_OP); // render selected item update_matrix_item(matrix); if (block_type != previous_block_type) { previous_block_type = block_type; make_single_cube( &item_position_buffer, &item_normal_buffer, &item_uv_buffer, block_type); } glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, 0, 0, 5); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); glDisable(GL_DEPTH_TEST); draw_single_cube( item_position_buffer, item_normal_buffer, item_uv_buffer, position_loc, normal_loc, uv_loc); glEnable(GL_DEPTH_TEST); glfwSwapBuffers(window); glfwPollEvents(); } db_save_state(x, y, z, rx, ry); db_close(); glfwTerminate(); return 0; }
// The MAIN function, from here we start our application and run our Game loop int main() { // Init GLFW glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Windowed GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // Options glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Initialize GLEW to setup the OpenGL Function pointers glewExperimental = GL_TRUE; glewInit(); // Define the viewport dimensions glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); // Setup and compile our shaders Shader shader("Shaders/shader.vert", "Shaders/shader.frag"); Shader simpleDepthShader("Shaders/shadow_mapping_depth.vs", "Shaders/shadow_mapping_depth.frag"); Shader lampShader("Shaders/lamp.vs", "Shaders/lamp.frag"); // Load models Model ourModel("Obj/nanosuit.obj"); Model lightBulb("Obj/geodesic_dome.obj"); GLfloat planeVertices[] = { // Positions // Normals // Texture Coords 25.0f, -0.5f, 25.0f, 0.0f, 1.0f, 0.0f, 25.0f, 0.0f, -25.0f, -0.5f, -25.0f, 0.0f, 1.0f, 0.0f, 0.0f, 25.0f, -25.0f, -0.5f, 25.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 25.0f, -0.5f, 25.0f, 0.0f, 1.0f, 0.0f, 25.0f, 0.0f, 25.0f, -0.5f, -25.0f, 0.0f, 1.0f, 0.0f, 25.0f, 25.0f, -25.0f, -0.5f, -25.0f, 0.0f, 1.0f, 0.0f, 0.0f, 25.0f }; glm::vec3 pointLightPositions[] = { glm::vec3(-2.0f, 4.0f, 0.0f), glm::vec3(-2.0f, 4.0f, 0.0f) }; // Setup plane VAO GLuint planeVBO; glGenVertexArrays(1, &planeVAO); glGenBuffers(1, &planeVBO); glBindVertexArray(planeVAO); glBindBuffer(GL_ARRAY_BUFFER, planeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glBindVertexArray(0); // Light source glm::vec3 lightPos(-2.0f, 4.0f, -1.0f); // Load textures woodTexture = loadTexture("Textures/wood.png"); rockTexture = loadTexture("Textures/rock.jpg"); glCullFace(GL_FRONT); // Configure depth map FBO const GLuint SHADOW_WIDTH = 1024, SHADOW_HEIGHT = 1024; GLuint depthMapFBO; glGenFramebuffers(1, &depthMapFBO); // - Create depth texture GLuint depthMap; glGenTextures(1, &depthMap); glBindTexture(GL_TEXTURE_2D, depthMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); GLfloat borderColor[] = { 1.0, 1.0, 1.0, 1.0 }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor); glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0); glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER, 0); glCullFace(GL_BACK); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); // Game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); Do_Movement(); // Set texture samples shader.Use(); glUniform1i(glGetUniformLocation(shader.Program, "material.texture_diffuse1"), 0); glUniform1i(glGetUniformLocation(shader.Program, "shadowMap"), 1); // Change light position over time lightPos.x = sin(glfwGetTime() * 0.5f) * 6.0f; lightPos.z = 0; lightPos.y = cos(glfwGetTime() * 0.5f) * 6.0f; // 1. Render depth of scene to texture (from light's perspective) // - Get light projection/view matrix. glm::mat4 lightProjection, lightView; glm::mat4 lightSpaceMatrix; GLfloat near_plane = 0.5f, far_plane = 20.0f; lightProjection = glm::ortho(-10.0f, 10.0f, -10.0f, 10.0f, near_plane, far_plane); //lightProjection = glm::perspective(45.0f, (GLfloat)SHADOW_WIDTH / (GLfloat)SHADOW_HEIGHT, near_plane, far_plane); // Note that if you use a perspective projection matrix you'll have to change the light position as the current light position isn't enough to reflect the whole scene. lightView = glm::lookAt(lightPos, glm::vec3(0.0f), glm::vec3(1.0)); lightSpaceMatrix = lightProjection * lightView; // - now render scene from light's point of view simpleDepthShader.Use(); glUniformMatrix4fv(glGetUniformLocation(simpleDepthShader.Program, "lightSpaceMatrix"), 1, GL_FALSE, glm::value_ptr(lightSpaceMatrix)); glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT); glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); glClear(GL_DEPTH_BUFFER_BIT); RenderScene(simpleDepthShader); glm::mat4 model; model = glm::translate(model, glm::vec3(0.1f, -0.5f, 1.0f)); // Translate it down a bit so it's at the center of the scene model = glm::scale(model, glm::vec3(0.15f, 0.15f, 0.15f)); glUniformMatrix4fv(glGetUniformLocation(simpleDepthShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); ourModel.Draw(simpleDepthShader); glBindFramebuffer(GL_FRAMEBUFFER, 0); // 2. Render scene as normal glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shader.Use(); glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); // Set light uniforms glUniform3f(glGetUniformLocation(shader.Program, "viewPos"), camera.Position.x, camera.Position.y, camera.Position.z); // Point light 1 glUniform3f(glGetUniformLocation(shader.Program, "pointLights[0].position"), pointLightPositions[0].x, pointLightPositions[0].y, pointLightPositions[0].z); glUniform3f(glGetUniformLocation(shader.Program, "pointLights[0].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(shader.Program, "pointLights[0].diffuse"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(shader.Program, "pointLights[0].specular"), 0.5f, 0.5f, 0.5f); glUniform1f(glGetUniformLocation(shader.Program, "pointLights[0].constant"), 1.0f); glUniform1f(glGetUniformLocation(shader.Program, "pointLights[0].linear"), 0.009); glUniform1f(glGetUniformLocation(shader.Program, "pointLights[0].quadratic"), 0.0032); // Point light 2 glUniform3f(glGetUniformLocation(shader.Program, "pointLights[1].position"), pointLightPositions[1].x, pointLightPositions[1].y, pointLightPositions[1].z); glUniform3f(glGetUniformLocation(shader.Program, "pointLights[1].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(shader.Program, "pointLights[1].diffuse"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(shader.Program, "pointLights[1].specular"), 0.5f, 0.5f, 0.5f); glUniform1f(glGetUniformLocation(shader.Program, "pointLights[1].constant"), 1.0f); glUniform1f(glGetUniformLocation(shader.Program, "pointLights[1].linear"), 0.009); glUniform1f(glGetUniformLocation(shader.Program, "pointLights[1].quadratic"), 0.0032); glUniform3fv(glGetUniformLocation(shader.Program, "ViewPos"), 1, &camera.Position[0]); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "lightSpaceMatrix"), 1, GL_FALSE, glm::value_ptr(lightSpaceMatrix)); // Enable/Disable shadows by pressing 'SPACE' glUniform1i(glGetUniformLocation(shader.Program, "shadows"), shadows); glUniform1i(glGetUniformLocation(shader.Program, "pointLightCount"), 2); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, woodTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, depthMap); RenderScene(shader); glActiveTexture(GL_TEXTURE15); glBindTexture(GL_TEXTURE_2D, woodTexture); glUniform1i(glGetUniformLocation(shader.Program, "material.texture_diffuse1"), 1); glActiveTexture(GL_TEXTURE16); glBindTexture(GL_TEXTURE_2D, depthMap); glUniform1i(glGetUniformLocation(shader.Program, "shadowMap"), 16); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); ourModel.Draw(shader); // Draw the lamps lampShader.Use(); glUniformMatrix4fv(glGetUniformLocation(lampShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(lampShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); for (GLuint i = 0; i < 2; i++) { model = glm::mat4(); model = glm::translate(model, pointLightPositions[i]); if (i == 1) model = glm::rotate(model, glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.3f, 0.3f, 0.3f)); // Downscale lamp object (a bit too large) glUniformMatrix4fv(glGetUniformLocation(lampShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); GLfloat camX = sin(glfwGetTime() * 0.5f) * 10.0f; GLfloat camZ = 0; GLfloat camY = cos(glfwGetTime() * 0.5f) * 10.0f; glm::vec4 light; if (camY <= 0.0) light = glm::vec4(1.0f, 1.0f, 0.0f, 1.0f); else light = glm::vec4(1.0f); glUniform4f(glGetUniformLocation(lampShader.Program, "light"), light.x, light.y, light.z, light.w); GLint modelLoc = glGetUniformLocation(lampShader.Program, "model"); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); pointLightPositions[i] = glm::vec3(camX, camY, camZ); lightBulb.Draw(lampShader); } // Swap the buffers glfwSwapBuffers(window); } glfwTerminate(); return 0; }
int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; return -1; } glViewport(0, 0, WIDTH, HEIGHT); glEnable(GL_DEPTH_TEST); Shader lightingShader("./lighting.vs", "./lighting.frag"); Shader lampShader("./lamp.vs", "./lamp.frag"); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Normals // Texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; GLuint VBO, containerVAO; glGenVertexArrays(1, &containerVAO); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindVertexArray(containerVAO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glBindVertexArray(0); GLuint lightVAO; glGenVertexArrays(1, &lightVAO); glBindVertexArray(lightVAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindVertexArray(0); GLuint diffuseMap; glGenTextures(1, &diffuseMap); int height, width; unsigned char* image; image = SOIL_load_image("container2.png", &width, &height, 0, SOIL_LOAD_RGB); glBindTexture(GL_TEXTURE_2D, diffuseMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); GLuint specularMap; glGenTextures(1, &specularMap); image = SOIL_load_image("container2_specular.png", &width, &height, 0, SOIL_LOAD_RGB); glBindTexture(GL_TEXTURE_2D, specularMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); GLuint emissionMap; glGenTextures(1, &emissionMap); image = SOIL_load_image("matrix.jpg", &width, &height, 0, SOIL_LOAD_RGB); glBindTexture(GL_TEXTURE_2D, emissionMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); // Set texture units lightingShader.Use(); glUniform1i(glGetUniformLocation(lightingShader.Program, "material.diffuse"), 0); glUniform1i(glGetUniformLocation(lightingShader.Program, "material.specular"), 1); glUniform1i(glGetUniformLocation(lightingShader.Program, "material.emission"), 2); while(!glfwWindowShouldClose(window)) { GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); do_movement(); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); lightingShader.Use(); GLint lightLoc = glGetUniformLocation(lightingShader.Program, "light.position"); GLint viewPosLoc = glGetUniformLocation(lightingShader.Program, "viewPos"); glUniform3f(lightLoc, lightPos.x, lightPos.y, lightPos.z); glUniform3f(viewPosLoc, camera.Position.x, camera.Position.y, camera.Position.z); glUniform3f(glGetUniformLocation(lightingShader.Program, "light.ambient"), 0.2f, 0.2f, 0.2f); glUniform3f(glGetUniformLocation(lightingShader.Program, "light.diffuse"), 0.5f, 0.5f, 0.5f); glUniform3f(glGetUniformLocation(lightingShader.Program, "light.specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "material.shininess"), 32.0f); glm::mat4 view; view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f); GLint modelLoc = glGetUniformLocation(lightingShader.Program, "model"); GLint viewLoc = glGetUniformLocation(lightingShader.Program, "view"); GLint projLoc = glGetUniformLocation(lightingShader.Program, "projection"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuseMap); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, specularMap); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, emissionMap); glBindVertexArray(containerVAO); glm::mat4 model; glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); // Also draw the lamp object, again binding the appropriate shader lampShader.Use(); // Get location objects for the matrices on the lamp shader (these could be different on a different shader) modelLoc = glGetUniformLocation(lampShader.Program, "model"); viewLoc = glGetUniformLocation(lampShader.Program, "view"); projLoc = glGetUniformLocation(lampShader.Program, "projection"); // Set matrices glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); model = glm::mat4(); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(0.2f)); // Make it a smaller cube glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); // Draw the light object (using light's vertex attributes) glBindVertexArray(lightVAO); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glfwSwapBuffers(window); } glDeleteVertexArrays(1, &containerVAO); glDeleteVertexArrays(1, &lightVAO); glDeleteBuffers(1, &VBO); glfwTerminate(); return 0; }
int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // build and compile our shader zprogram // ------------------------------------ Shader lightingShader("1.colors.vs", "1.colors.fs"); Shader lampShader("1.lamp.vs", "1.lamp.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, }; // first, configure the cube's VAO (and VBO) unsigned int VBO, cubeVAO; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindVertexArray(cubeVAO); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // second, configure the light's VAO (VBO stays the same; the vertices are the same for the light object which is also a 3D cube) unsigned int lightVAO; glGenVertexArrays(1, &lightVAO); glBindVertexArray(lightVAO); // we only need to bind to the VBO (to link it with glVertexAttribPointer), no need to fill it; the VBO's data already contains all we need (it's already bound, but we do it again for educational purposes) glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // be sure to activate shader when setting uniforms/drawing objects lightingShader.use(); lightingShader.setVec3("objectColor", 1.0f, 0.5f, 0.31f); lightingShader.setVec3("lightColor", 1.0f, 1.0f, 1.0f); // view/projection transformations glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); lightingShader.setMat4("projection", projection); lightingShader.setMat4("view", view); // world transformation glm::mat4 model = glm::mat4(1.0f); lightingShader.setMat4("model", model); // render the cube glBindVertexArray(cubeVAO); glDrawArrays(GL_TRIANGLES, 0, 36); // also draw the lamp object lampShader.use(); lampShader.setMat4("projection", projection); lampShader.setMat4("view", view); model = glm::mat4(1.0f); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(0.2f)); // a smaller cube lampShader.setMat4("model", model); glBindVertexArray(lightVAO); glDrawArrays(GL_TRIANGLES, 0, 36); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &cubeVAO); glDeleteVertexArrays(1, &lightVAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
int main() { #pragma region Initialize GLFW if(!glfwInit()) { std::cerr << clog::err << "Failed to initialize GLFW." << std::endl; std::cin.get(); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(windowWidth, windowHeight, "GLTEST", NULL, NULL); if(window == NULL) { std::cerr << clog::err << "Failed to open GLFW window." << std::endl; std::cin.get(); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); #pragma endregion Creating an OpenGL rendering context #pragma region Initialize GLEW if(glewInit() != GLEW_OK) { std::cerr << clog::err << "Failed to initialize GLEW." << std::endl; std::cin.get(); return -1; } #pragma endregion Initializing the extension entry points #pragma region Display version info std::cout << glGetString(GL_RENDERER) << " | " << glGetString(GL_VENDOR) << std::endl; std::cout << "OpenGL v." << glGetString(GL_VERSION) << std::endl; std::cout << "GLSL v." << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << std::endl; #pragma endregion Displaying renderer, vendor of implementation, versions glPlay::initialize(); do { glPlay::draw(); glfwSwapBuffers(window); glfwPollEvents(); } while(!glfwWindowShouldClose(window)); glPlay::clean(); glfwTerminate(); return 0; }
// uiloop void uiloop() { auto ok = glfwInit(); error_if_not(ok, "glfw init error"); // setting an error callback glfwSetErrorCallback([](int ecode, const char* msg){ return error(msg); }); // glfwWindowHint(GLFW_SAMPLES, scene->image_samples*scene->image_samples); auto window = glfwCreateWindow(scene->image_width, scene->image_height, "graphics14 | model", NULL, NULL); error_if_not(window, "glfw window error"); glfwMakeContextCurrent(window); glfwSetCharCallback(window, [](GLFWwindow* window, unsigned int key) { switch (key) { case 's': scene->draw_captureimage = true; break; case 'w': scene->draw_wireframe = ! scene->draw_wireframe; break; } }); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); #ifdef _WIN32 auto ok1 = glewInit(); error_if_not(GLEW_OK == ok1, "glew init error"); #endif auto state = new ShadeState(); init_shaders(state); init_textures(scene,state); auto mouse_last_x = -1.0; auto mouse_last_y = -1.0; while(! glfwWindowShouldClose(window)) { glfwGetFramebufferSize(window, &scene->image_width, &scene->image_height); scene->camera->width = (scene->camera->height * scene->image_width) / scene->image_height; shade(scene,state); if(glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT)) { double x, y; glfwGetCursorPos(window, &x, &y); if (mouse_last_x < 0 || mouse_last_y < 0) { mouse_last_x = x; mouse_last_y = y; } auto delta_x = x - mouse_last_x, delta_y = y - mouse_last_y; set_view_turntable(scene->camera, delta_x*0.01, -delta_y*0.01, 0, 0, 0); mouse_last_x = x; mouse_last_y = y; } else { mouse_last_x = -1; mouse_last_y = -1; } if(scene->draw_captureimage) { auto image = image3f(scene->image_width,scene->image_height); glReadPixels(0, 0, scene->image_width, scene->image_height, GL_RGB, GL_FLOAT, &image.at(0,0)); write_png(image_filename, image, true); scene->draw_captureimage = false; } glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); delete state; }
// The MAIN function, from here we start our application and run our Game loop int main() { // Init GLFW glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); // Windowed glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // Options glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Initialize GLEW to setup the OpenGL Function pointers glewExperimental = GL_TRUE; glewInit(); // Define the viewport dimensions glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); // Setup and compile our shaders Shader shaderGeometryPass("g_buffer.vs", "g_buffer.frag"); Shader shaderLightingPass("deferred_shading.vs", "deferred_shading.frag"); Shader shaderLightBox("deferred_light_box.vs", "deferred_light_box.frag"); // Set samplers shaderLightingPass.Use(); glUniform1i(glGetUniformLocation(shaderLightingPass.Program, "gPosition"), 0); glUniform1i(glGetUniformLocation(shaderLightingPass.Program, "gNormal"), 1); glUniform1i(glGetUniformLocation(shaderLightingPass.Program, "gAlbedoSpec"), 2); // Models Model cyborg(FileSystem::getPath("resources/objects/nanosuit/nanosuit.obj").c_str()); std::vector<glm::vec3> objectPositions; objectPositions.push_back(glm::vec3(-3.0, -3.0, -3.0)); objectPositions.push_back(glm::vec3(0.0, -3.0, -3.0)); objectPositions.push_back(glm::vec3(3.0, -3.0, -3.0)); objectPositions.push_back(glm::vec3(-3.0, -3.0, 0.0)); objectPositions.push_back(glm::vec3(0.0, -3.0, 0.0)); objectPositions.push_back(glm::vec3(3.0, -3.0, 0.0)); objectPositions.push_back(glm::vec3(-3.0, -3.0, 3.0)); objectPositions.push_back(glm::vec3(0.0, -3.0, 3.0)); objectPositions.push_back(glm::vec3(3.0, -3.0, 3.0)); // - Colors const GLuint NR_LIGHTS = 32; std::vector<glm::vec3> lightPositions; std::vector<glm::vec3> lightColors; srand(13); for (GLuint i = 0; i < NR_LIGHTS; i++) { // Calculate slightly random offsets GLfloat xPos = ((rand() % 100) / 100.0) * 6.0 - 3.0; GLfloat yPos = ((rand() % 100) / 100.0) * 6.0 - 4.0; GLfloat zPos = ((rand() % 100) / 100.0) * 6.0 - 3.0; lightPositions.push_back(glm::vec3(xPos, yPos, zPos)); // Also calculate random color GLfloat rColor = ((rand() % 100) / 200.0f) + 0.5; // Between 0.5 and 1.0 GLfloat gColor = ((rand() % 100) / 200.0f) + 0.5; // Between 0.5 and 1.0 GLfloat bColor = ((rand() % 100) / 200.0f) + 0.5; // Between 0.5 and 1.0 lightColors.push_back(glm::vec3(rColor, gColor, bColor)); } // Set up G-Buffer // 3 textures: // 1. Positions (RGB) // 2. Color (RGB) + Specular (A) // 3. Normals (RGB) GLuint gBuffer; glGenFramebuffers(1, &gBuffer); glBindFramebuffer(GL_FRAMEBUFFER, gBuffer); GLuint gPosition, gNormal, gAlbedoSpec; // - Position color buffer glGenTextures(1, &gPosition); glBindTexture(GL_TEXTURE_2D, gPosition); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gPosition, 0); // - Normal color buffer glGenTextures(1, &gNormal); glBindTexture(GL_TEXTURE_2D, gNormal); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gNormal, 0); // - Color + Specular color buffer glGenTextures(1, &gAlbedoSpec); glBindTexture(GL_TEXTURE_2D, gAlbedoSpec); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gAlbedoSpec, 0); // - Tell OpenGL which color attachments we'll use (of this framebuffer) for rendering GLuint attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; glDrawBuffers(3, attachments); // - Create and attach depth buffer (renderbuffer) GLuint rboDepth; glGenRenderbuffers(1, &rboDepth); glBindRenderbuffer(GL_RENDERBUFFER, rboDepth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, SCR_WIDTH, SCR_HEIGHT); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboDepth); // - Finally check if framebuffer is complete if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer not complete!" << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); Do_Movement(); glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_LINE : GL_FILL); // 1. Geometry Pass: render scene's geometry/color data into gbuffer glBindFramebuffer(GL_FRAMEBUFFER, gBuffer); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)SCR_WIDTH / (GLfloat)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); glm::mat4 model; shaderGeometryPass.Use(); glUniformMatrix4fv(glGetUniformLocation(shaderGeometryPass.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(shaderGeometryPass.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); for (GLuint i = 0; i < objectPositions.size(); i++) { model = glm::mat4(); model = glm::translate(model, objectPositions[i]); model = glm::scale(model, glm::vec3(0.25f)); glUniformMatrix4fv(glGetUniformLocation(shaderGeometryPass.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); cyborg.Draw(shaderGeometryPass); } glBindFramebuffer(GL_FRAMEBUFFER, 0); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // 2. Lighting Pass: calculate lighting by iterating over a screen filled quad pixel-by-pixel using the gbuffer's content. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shaderLightingPass.Use(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, gPosition); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, gNormal); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, gAlbedoSpec); // Also send light relevant uniforms for (GLuint i = 0; i < lightPositions.size(); i++) { glUniform3fv(glGetUniformLocation(shaderLightingPass.Program, ("lights[" + std::to_string(i) + "].Position").c_str()), 1, &lightPositions[i][0]); glUniform3fv(glGetUniformLocation(shaderLightingPass.Program, ("lights[" + std::to_string(i) + "].Color").c_str()), 1, &lightColors[i][0]); // Update attenuation parameters and calculate radius const GLfloat constant = 1.0; // Note that we don't send this to the shader, we assume it is always 1.0 (in our case) const GLfloat linear = 0.7; const GLfloat quadratic = 1.8; glUniform1f(glGetUniformLocation(shaderLightingPass.Program, ("lights[" + std::to_string(i) + "].Linear").c_str()), linear); glUniform1f(glGetUniformLocation(shaderLightingPass.Program, ("lights[" + std::to_string(i) + "].Quadratic").c_str()), quadratic); // Then calculate radius of light volume/sphere const GLfloat lightThreshold = 5.0; // 5 / 256 const GLfloat maxBrightness = std::fmaxf(std::fmaxf(lightColors[i].r, lightColors[i].g), lightColors[i].b); GLfloat radius = (-linear + static_cast<float>(std::sqrt(linear * linear - 4 * quadratic * (constant - (256.0 / lightThreshold) * maxBrightness)))) / (2 * quadratic); glUniform1f(glGetUniformLocation(shaderLightingPass.Program, ("lights[" + std::to_string(i) + "].Radius").c_str()), radius); } glUniform3fv(glGetUniformLocation(shaderLightingPass.Program, "viewPos"), 1, &camera.Position[0]); glUniform1i(glGetUniformLocation(shaderLightingPass.Program, "draw_mode"), draw_mode); RenderQuad(); // 2.5. Copy content of geometry's depth buffer to default framebuffer's depth buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, gBuffer); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); // Write to default framebuffer // blit to default framebuffer. Note that this may or may not work as the internal formats of both the FBO and default framebuffer have to match. // the internal formats are implementation defined. This works on all of my systems, but if it doesn't on yours you'll likely have to write to the // depth buffer in another stage (or somehow see to match the default framebuffer's internal format with the FBO's internal format). glBlitFramebuffer(0, 0, SCR_WIDTH, SCR_HEIGHT, 0, 0, SCR_WIDTH, SCR_HEIGHT, GL_DEPTH_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_FRAMEBUFFER, 0); // 3. Render lights on top of scene, by blitting shaderLightBox.Use(); glUniformMatrix4fv(glGetUniformLocation(shaderLightBox.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(shaderLightBox.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); for (GLuint i = 0; i < lightPositions.size(); i++) { model = glm::mat4(); model = glm::translate(model, lightPositions[i]); model = glm::scale(model, glm::vec3(0.25f)); glUniformMatrix4fv(glGetUniformLocation(shaderLightBox.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glUniform3fv(glGetUniformLocation(shaderLightBox.Program, "lightColor"), 1, &lightColors[i][0]); RenderCube(); } // Swap the buffers glfwSwapBuffers(window); } glfwTerminate(); return 0; }
// The MAIN function, from here we start the application and run the game loop int main() { // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // GLFW Options glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions glViewport(0, 0, WIDTH, HEIGHT); // OpenGL options glEnable(GL_DEPTH_TEST); // Build and compile our shader program Shader lightingShader("materials.vs", "materials.frag"); Shader lampShader("lamp.vs", "lamp.frag"); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f }; // First, set the container's VAO (and VBO) GLuint VBO, containerVAO; glGenVertexArrays(1, &containerVAO); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindVertexArray(containerVAO); // Position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // Normal attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindVertexArray(0); // Then, we set the light's VAO (VBO stays the same. After all, the vertices are the same for the light object (also a 3D cube)) GLuint lightVAO; glGenVertexArrays(1, &lightVAO); glBindVertexArray(lightVAO); // We only need to bind to the VBO (to link it with glVertexAttribPointer), no need to fill it; the VBO's data already contains all we need. glBindBuffer(GL_ARRAY_BUFFER, VBO); // Set the vertex attributes (only position data for the lamp)) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); // Note that we skip over the normal vectors glEnableVertexAttribArray(0); glBindVertexArray(0); // Game loop while (!glfwWindowShouldClose(window)) { // Calculate deltatime of current frame GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); do_movement(); // Clear the colorbuffer glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Use cooresponding shader when setting uniforms/drawing objects lightingShader.Use(); GLint lightPosLoc = glGetUniformLocation(lightingShader.Program, "light.position"); GLint viewPosLoc = glGetUniformLocation(lightingShader.Program, "viewPos"); glUniform3f(lightPosLoc, lightPos.x, lightPos.y, lightPos.z); glUniform3f(viewPosLoc, camera.Position.x, camera.Position.y, camera.Position.z); // Set lights properties glm::vec3 lightColor; lightColor.x = sin(glfwGetTime() * 2.0f); lightColor.y = sin(glfwGetTime() * 0.7f); lightColor.z = sin(glfwGetTime() * 1.3f); glm::vec3 diffuseColor = lightColor * glm::vec3(0.5f); // Decrease the influence glm::vec3 ambientColor = diffuseColor * glm::vec3(0.2f); // Low influence glUniform3f(glGetUniformLocation(lightingShader.Program, "light.ambient"), ambientColor.x, ambientColor.y, ambientColor.z); glUniform3f(glGetUniformLocation(lightingShader.Program, "light.diffuse"), diffuseColor.x, diffuseColor.y, diffuseColor.z); glUniform3f(glGetUniformLocation(lightingShader.Program, "light.specular"), 1.0f, 1.0f, 1.0f); // Set material properties glUniform3f(glGetUniformLocation(lightingShader.Program, "material.ambient"), 1.0f, 0.5f, 0.31f); glUniform3f(glGetUniformLocation(lightingShader.Program, "material.diffuse"), 1.0f, 0.5f, 0.31f); glUniform3f(glGetUniformLocation(lightingShader.Program, "material.specular"), 0.5f, 0.5f, 0.5f); // Specular doesn't have full effect on this object's material glUniform1f(glGetUniformLocation(lightingShader.Program, "material.shininess"), 32.0f); // Create camera transformations glm::mat4 view; view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f); // Get the uniform locations GLint modelLoc = glGetUniformLocation(lightingShader.Program, "model"); GLint viewLoc = glGetUniformLocation(lightingShader.Program, "view"); GLint projLoc = glGetUniformLocation(lightingShader.Program, "projection"); // Pass the matrices to the shader glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); // Draw the container (using container's vertex attributes) glBindVertexArray(containerVAO); glm::mat4 model; glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); // Also draw the lamp object, again binding the appropriate shader lampShader.Use(); // Get location objects for the matrices on the lamp shader (these could be different on a different shader) modelLoc = glGetUniformLocation(lampShader.Program, "model"); viewLoc = glGetUniformLocation(lampShader.Program, "view"); projLoc = glGetUniformLocation(lampShader.Program, "projection"); // Set matrices glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); model = glm::mat4(); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(0.2f)); // Make it a smaller cube glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); // Draw the light object (using light's vertex attributes) glBindVertexArray(lightVAO); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); // Swap the screen buffers glfwSwapBuffers(window); } // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; }
// The MAIN function, from here we start the application and run the game loop int main() { // Init GLFW glfwInit(); GLFWmonitor* primary = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(primary); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_SAMPLES, 4); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(mode->width, mode->height, "LearnOpenGL", primary, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // Options glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions glViewport(0, 0, mode->width, mode->height); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); Scene scene = Scene("default"); // Build and compile our shader program Shader defaultShader("default.vs", "default.frag", "default.gs"); Shader alternateShader("alternate.vs", "alternate.frag", "alternate.gs"); Shader* currentShader = &defaultShader; Shader skyboxShader("skybox.vs", "skybox.frag"); #pragma region "object_initialization" GLfloat skyboxVertices[] = { // Positions -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, 10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, 10.0f, 10.0f, -10.0f, -10.0f, 10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, -10.0f, 10.0f, -10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, -10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, 10.0f, -10.0f, 10.0f, 10.0f, -10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, -10.0f, 10.0f, 10.0f, -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, -10.0f, -10.0f, -10.0f, 10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, -10.0f, 10.0f, 10.0f, -10.0f, 10.0f }; //wVertex data GLfloat vertices[] = { //positions //colors -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // Top-left 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // Top-right 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, // Bottom-right -0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f // Bottom-left }; /*GLfloat* floatVertices = scene.getVertices(); GLfloat vertices[sizeof(floatVertices)/sizeof(GLfloat)]; for (int i = 0; i < 24 ; i++) { vertices[i] = floatVertices[i]; }*/ glGenBuffers(1, &VBO); glGenVertexArrays(1, &VAO); //// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); //// Position attribute //setAttributeData(0, 3, 6, 0); //// Color attribute //setAttributeData(1, 3, 6, 3); // Position attribute std::vector<int> va = scene.getVecAtrib(); setAttributeData(va[0], va[1], va[2], va[3]); // Color attribute std::vector<int> ca = scene.getColAtrib(); setAttributeData(ca[0], ca[1], ca[2], ca[3]); // Unbind VAO glBindVertexArray(0); // Setup skybox VAO GLuint skyboxVAO, skyboxVBO; glGenVertexArrays(1, &skyboxVAO); glGenBuffers(1, &skyboxVBO); glBindVertexArray(skyboxVAO); glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glBindVertexArray(0); #pragma endregion // Cubemap (Skybox) std::vector<const GLchar*> faces = scene.getFaces(); /*faces.push_back("Resources/skybox/right.jpg"); faces.push_back("Resources/skybox/left.jpg"); faces.push_back("Resources/skybox/top.jpg"); faces.push_back("Resources/skybox/bottom.jpg"); faces.push_back("Resources/skybox/back.jpg"); faces.push_back("Resources/skybox/front.jpg");*/ GLuint cubemapTexture = loadCubemap(faces); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // Game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); Input_Switch_Shader(¤tShader, &defaultShader, &alternateShader); Do_Movement(); // Check camera position and see if it reaches the boundary of the room // reset the camera to the other side of the room when it crosses the boundary glm::vec3 camPos = camera.getPostion(); if (abs(camPos.x) > 5.0f) { camPos.x = -1 * camPos.x; camera.setPosition(camPos); Switch_Shader(¤tShader, &defaultShader, &alternateShader); } if (abs(camPos.y) > 5.0f) { camPos.y = -1 * camPos.y; camera.setPosition(camPos); Switch_Shader(¤tShader, &defaultShader, &alternateShader); } if (abs(camPos.z) > 5.0f) { camPos.z = -1 * camPos.z; camera.setPosition(camPos); Switch_Shader(¤tShader, &defaultShader, &alternateShader); } // Render // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw the scene currentShader->Use(); // Create camera transformation glm::mat4 view = camera.GetViewMatrix(); GLint viewLoc = glGetUniformLocation(currentShader->Program, "view"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); // Calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model; GLint modelLoc = glGetUniformLocation(currentShader->Program, "model"); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glm::mat4 projection = glm::perspective(camera.Zoom, (float)mode->width / (float)mode->height, 0.1f, 1000.0f); //currentShader->Use(); GLint projLoc = glGetUniformLocation(currentShader->Program, "projection"); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); glBindVertexArray(VAO); glDrawArrays(GL_POINTS, 0, 4); glBindVertexArray(0); //Draw skybox as last glDepthFunc(GL_LEQUAL); // Change depth function so depth test passes when values are equal to depth buffer's content skyboxShader.Use(); view = glm::mat4(glm::mat3(camera.GetViewMatrix())); // Remove any translation component of the view matrix glUniformMatrix4fv(glGetUniformLocation(skyboxShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(skyboxShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); // skybox cube glBindVertexArray(skyboxVAO); glActiveTexture(GL_TEXTURE0); glUniform1i(glGetUniformLocation(skyboxShader.Program, "skybox"), 0); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glDepthFunc(GL_LESS); // Set depth function back to default // Swap the screen buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; }